Skip to content

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.

Merge batch 11-03 b1822: #2733 #2704 #2756 #2763 #2607 (#2802)

0xken157202d04c1505
diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.ts
index 65969ca54..efee838c0 100644
--- a/backend/integration/superTabBuddies.test.ts
+++ b/backend/integration/superTabBuddies.test.ts
@@ -213,9 +213,14 @@ describe('a Buddy through the store', () => {
priority: 'normal' }, peer, agentId)
const sent = await propose()
const row = await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, id: String(sent.result.messageId) } })
- expect(row).toMatchObject({ conversationId: 'lead', recipientIds: [f.lead], source: { kind: 'buddy-proposal', personId: peer.sub, ownerMessageId: ask },
- text: 'Proposal from peer\'s Buddy, on peer\'s behalf.\n\nGoal: Offline sync\nScope: Desktop only\nPriority: normal' })
- expect(await db.superTabDelivery.count({ where: { tabId: f.tab, messageId: row.id, agentId: f.lead } })).toBe(1)
+ expect(row).toMatchObject({ conversationId: 'lead', recipientIds: [], author: { kind: 'person', id: peer.sub },
+ source: { kind: 'buddy-proposal', personId: peer.sub, buddyId: agentId, ownerMessageId: ask }, text: "Let's build: Offline sync" })
+ const details = await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, thread: row.id, replyTo: row.id } })
+ expect(details).toMatchObject({ author: { kind: 'agent', id: agentId }, recipientIds: [f.lead],
+ text: 'Goal: Offline sync\nScope: Desktop only\nPriority: normal' })
+ expect(await db.superTabDelivery.count({ where: { tabId: f.tab, messageId: details.id, agentId: f.lead } })).toBe(1)
+ const page = await f.store.messages(owner, f.tab, 'lead', {})
+ expect(page.threads).toEqual(expect.arrayContaining([expect.objectContaining({ id: row.id, replies: 1 })]))
await expect(propose()).rejects.toThrow('already sent')
await expect(f.execute({ type: 'message.send', conversationId: 'lead', text: 'Hi PM', replyTo: null, recipientIds: [] }, peer, agentId))
.rejects.toThrow('A Buddy posts only in its own chat')
@@ -412,10 +417,10 @@ describe('a Buddy through the store', () => {
await expect(propose([plan, 'a'.repeat(24), 'b'.repeat(24), 'c'.repeat(24), 'd'.repeat(24), 'e'.repeat(24)])).rejects.toThrow('at most 5 files')
const sent = await propose([plan, shot, log])
const id = String(sent.result.messageId)
- const read = (await f.store.messages(owner, f.tab, 'lead', {}, f.lead)).messages.find(m => m.id === id)
+ const read = (await f.store.messages(owner, f.tab, 'lead', {}, f.lead)).messages.find(m => m.replyTo === id)
expect(read?.attachments?.map(a => [a.name, a.mime, a.url.startsWith('https://cdn.example.test/super-tabs/')])).toEqual([
['plan.md', 'text/markdown', true], ['shot.png', 'image/png', true], ['sync.log', 'text/plain', true]])
- expect((await f.store.messages(owner, f.tab, 'lead', {})).messages.find(m => m.id === id)?.attachments).toHaveLength(3)
+ expect((await f.store.messages(owner, f.tab, 'lead', {})).messages.find(m => m.replyTo === id)?.attachments).toHaveLength(3)
// Each opens from its link as the apps open it: the picture shown in place, the plan and the log as their own text.
// And from the signed link each read adds (fileLinks.ts), as apps that know links open it.
expect(read!.attachments!.map(a => f.files.open(a.link!)?.length)).toEqual(read!.attachments!.map(a => a.size))
@@ -438,8 +443,8 @@ describe('a Buddy through the store', () => {
const [first, second] = [await ask(), await ask()]
const raced = await Promise.allSettled([propose([again], first), propose([again], second)])
expect(raced.map(r => r.status).sort()).toEqual(['fulfilled', 'rejected'])
- expect(await db.superTabMessage.count({ where: { tabId: f.tab, conversationId: 'lead', source: { equals: { kind: 'buddy-proposal', personId: peer.sub, ownerMessageId: first } } } })
- + await db.superTabMessage.count({ where: { tabId: f.tab, conversationId: 'lead', source: { equals: { kind: 'buddy-proposal', personId: peer.sub, ownerMessageId: second } } } })).toBe(1)
+ expect(await db.superTabMessage.count({ where: { tabId: f.tab, conversationId: 'lead', source: { equals: { kind: 'buddy-proposal', personId: peer.sub, buddyId: agentId, ownerMessageId: first } } } })
+ + await db.superTabMessage.count({ where: { tabId: f.tab, conversationId: 'lead', source: { equals: { kind: 'buddy-proposal', personId: peer.sub, buddyId: agentId, ownerMessageId: second } } } })).toBe(1)
const elsewhere = await upload('other.txt', 'text/plain', Buffer.from('project chat'), 'lead', false)
await f.execute({ type: 'message.send', conversationId: 'lead', text: 'FYI', replyTo: null, recipientIds: [], attachmentIds: [elsewhere] }, peer)
await expect(propose([elsewhere])).rejects.toThrow('Upload this file again')
@@ -900,7 +905,7 @@ describe('a Buddy hears how its person\'s requests go, unasked (Diego, 10-29)',
await buddy(f)
expect((await read()).deliveries).toEqual([])
// Ordinary deliveries still show: the proposal's to the PM, its listed recipient.
- const sent = (await f.store.messages(owner, f.tab, 'lead', {})).messages.find(m => m.id === proposal)!
+ const sent = (await f.store.messages(owner, f.tab, 'lead', {})).messages.find(m => m.replyTo === proposal)!
expect(sent.deliveries.map(d => d.agentId)).toEqual([f.lead])
})
diff --git a/backend/integration/superTabProfile.test.ts b/backend/integration/superTabProfile.test.ts
index 8c1ee048b..def4c63dc 100644
--- a/backend/integration/superTabProfile.test.ts
+++ b/backend/integration/superTabProfile.test.ts
@@ -455,8 +455,8 @@ describe('reactions', () => {
describe('the ship moment', () => {
const config = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }
- // The task's own line says it shipped, in place of the Shipped line (taskLine.ts; Quiet Swarm, Dee, 11-02).
- it('edits the task\'s one line in the project chat to shipped when its merge is recorded, once on a retry, waking nobody', async () => {
+ // The task's own thread says it merged, in place of the Shipped line (taskLine.ts; plain chat, Dee, 11-03).
+ it('replies Merged in the task\'s thread when its merge is recorded, once on a retry, waking nobody', async () => {
const tab = await swarm()
await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: randomUUID(), name: 'River', configuration: config, lead: true })
const group = (await run(tab, { type: 'conversation.create', title: 'Avatars', brief: 'Add avatars.',
@@ -481,7 +481,9 @@ describe('the ship moment', () => {
expect(rows.filter(m => (m.source as { kind?: string } | null)?.kind === 'ship')).toEqual([])
const lines = rows.filter(m => (m.source as { kind?: string } | null)?.kind === 'task-line')
expect(lines).toHaveLength(1)
- expect(lines[0]).toMatchObject({ text: 'Avatars · shipped', recipientIds: [], source: { taskId: group, state: 'shipped', builderId: builder } })
- expect(await db.superTabDelivery.count({ where: { tabId: tab, messageId: lines[0]!.id } })).toBe(0)
+ expect(lines[0]).toMatchObject({ text: "Let's build: Avatars", recipientIds: [], source: { taskId: group } })
+ const merges = rows.filter(m => m.thread === lines[0]!.id && m.text.startsWith('Merged'))
+ expect(merges).toEqual([expect.objectContaining({ text: 'Merged: PR #7. Ships in the next release.', recipientIds: [] })])
+ expect(await db.superTabDelivery.count({ where: { tabId: tab, messageId: { in: [lines[0]!.id, merges[0]!.id] } } })).toBe(0)
})
})
diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.ts
index 86bc6de38..8ebb16656 100644
--- a/backend/integration/superTabRead.test.ts
+++ b/backend/integration/superTabRead.test.ts
@@ -676,10 +676,10 @@ describe('a real command through the store by parts (design 4.7)', () => {
expect(written.version).toBeGreaterThan(R)
clock = Date.now()
const seen = (await get(`/api/super-tabs/${s.tabId}/changes?cursor=${cursor}`, peer)).body.data
- // The task's line in its project chat takes the new name too (taskLine.ts): that chat is written in the same commit.
- expect(reply.parts.filter(p => p.kind === 'group').map(p => [p.key, p.version]).sort()).toEqual([['lead', written.version], [s.web, written.version]].sort())
+ // The task's message in its project chat is never edited (plain chat, task #2294): only the task is written.
+ expect(reply.parts.filter(p => p.kind === 'group').map(p => [p.key, p.version])).toEqual([[s.web, written.version]])
expect(seen.groups.map((g: { key: string; version: number; data: { title: string } }) => [g.key, g.version, g.data.title]))
- .toEqual([['lead', written.version, 'Lead'], [s.web, written.version, 'Renamed for real']])
+ .toEqual([[s.web, written.version, 'Renamed for real']])
expect(seen.lastChangedAt).toBe(reply.lastChangedAt)
})
})
diff --git a/backend/integration/superTabSwarmBuddy.test.ts b/backend/integration/superTabSwarmBuddy.test.ts
index 270f7158b..bb13c899e 100644
--- a/backend/integration/superTabSwarmBuddy.test.ts
+++ b/backend/integration/superTabSwarmBuddy.test.ts
@@ -152,9 +152,12 @@ describe('the one Buddy sends a proposal to a project its person reads (Scholes,
const { chat, main } = await buddy(f)
const sent = String((await propose(f, chat, await ask(f, chat), f.web.projectId, main)).result.messageId)
const row = await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, id: sent } })
- expect(row).toMatchObject({ conversationId: f.web.conversationId, recipientIds: [f.pms.web], source: { kind: 'buddy-proposal', personId: peer.sub } })
- expect(await db.superTabDelivery.count({ where: { tabId: f.tab, messageId: sent, agentId: f.pms.web } })).toBe(1)
- expect(row.text).toBe('Proposal from peer\'s Buddy, on peer\'s behalf.\n\nGoal: Offline sync\nScope: Web only\nPriority: normal')
+ expect(row).toMatchObject({ conversationId: f.web.conversationId, recipientIds: [], author: { kind: 'person', id: peer.sub },
+ source: { kind: 'buddy-proposal', personId: peer.sub }, text: "Let's build: Offline sync" })
+ // The full proposal is the root's first reply, from the Buddy: the one row the PM is woken for.
+ const details = await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, thread: sent, replyTo: sent } })
+ expect(details).toMatchObject({ conversationId: f.web.conversationId, recipientIds: [f.pms.web], text: 'Goal: Offline sync\nScope: Web only\nPriority: normal' })
+ expect(await db.superTabDelivery.count({ where: { tabId: f.tab, messageId: details.id, agentId: f.pms.web } })).toBe(1)
for (const elsewhere of ['lead', f.secret.conversationId]) expect(await texts(f, elsewhere, owner)).not.toContain(row.text)
const group = String((await f.execute({ type: 'conversation.create', title: 'Offline sync', brief: '', checks: [], proposalMessageId: sent }, owner, f.pms.web)).result.conversationId)
expect((await f.store.read(owner, f.tab)).state.conversations.find(c => c.id === group)?.requesterId).toBe(peer.sub)
@@ -255,7 +258,8 @@ describe('the one Buddy sends a proposal to a project its person reads (Scholes,
await send(f, chat, 'A secret file', { replyTo: thread, attachmentIds: [secretFile] })
await expect(propose(f, chat, await ask(f, chat), f.web.projectId, main, { attachmentIds: [secretFile] })).rejects.toMatchObject({ code: 'ATTACHMENT_UNAVAILABLE' })
const sent = String((await propose(f, chat, await ask(f, chat), f.web.projectId, main, { attachmentIds: [plan, log] })).result.messageId)
- const read = (await f.store.messages(owner, f.tab, f.web.conversationId, {})).messages.find(m => m.id === sent)
+ // The files go with the full proposal, the root's first reply (plain chat, task #2294).
+ const read = (await f.store.messages(owner, f.tab, f.web.conversationId, { thread: sent })).messages.find(m => m.replyTo === sent)
expect(read?.attachments?.map(a => a.name).sort()).toEqual(['main.log', 'plan.md'])
})
})
@@ -395,7 +399,8 @@ describe('a project session', () => {
const sentId = String((await f.execute({ type: 'buddy.propose', conversationId: chat, ownerMessageId: ask, goal: 'Offline sync', scope: 'Web only',
priority: 'normal' }, peer, agentId)).result.messageId)
const row = await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, id: sentId } })
- expect(row).toMatchObject({ conversationId: f.web.conversationId, recipientIds: [f.pms.web], source: { kind: 'buddy-proposal', personId: peer.sub } })
+ expect(row).toMatchObject({ conversationId: f.web.conversationId, recipientIds: [], source: { kind: 'buddy-proposal', personId: peer.sub } })
+ expect(await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, replyTo: sentId } })).toMatchObject({ recipientIds: [f.pms.web] })
})
/** peer's session proposes in web, the PM opens the group from it and the group's PR merges; the session then ends. */
@@ -495,7 +500,7 @@ describe('a project session', () => {
await expect(f.execute({ type: 'buddy.propose', conversationId: chat, ownerMessageId: mainAsk, projectId: f.web.projectId, goal: 'G', scope: 'S', priority: 'normal' }, peer, agentId))
.rejects.toMatchObject({ code: 'PROPOSAL_UNASKED' })
const sent = String((await f.execute({ type: 'buddy.propose', conversationId: chat, ownerMessageId: ask, projectId: f.web.projectId, goal: 'G', scope: 'S', priority: 'normal' }, peer, agentId)).result.messageId)
- expect(await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, id: sent } })).toMatchObject({ conversationId: f.web.conversationId, recipientIds: [f.pms.web] })
+ expect(await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, replyTo: sent } })).toMatchObject({ conversationId: f.web.conversationId, recipientIds: [f.pms.web] })
// Credited to the person's one Buddy, as a project session's is: a session ends.
const group = String((await f.execute({ type: 'conversation.create', title: 'From the session', brief: '', checks: [], proposalMessageId: sent }, owner, f.pms.web)).result.conversationId)
const row = (await f.store.read(owner, f.tab)).state.conversations.find(c => c.id === group)
diff --git a/backend/integration/superTabTaskLines.test.ts b/backend/integration/superTabTaskLines.test.ts
index 8b7ee3b75..052d3b882 100644
--- a/backend/integration/superTabTaskLines.test.ts
+++ b/backend/integration/superTabTaskLines.test.ts
@@ -10,9 +10,9 @@ import type { AuthUser } from '../src/lib/ssoAuth.js'
import { SuperTabStore } from '../src/superTabs/store.js'
import type { Command } from '../src/superTabs/commands.js'
-// Quiet Swarm 2/6 (task #2191; docs/plans/2026-11-02-quiet-swarm-task-line-plan.md): each task with an Engineer is one
-// message in its project chat, edited in place as the task moves, none for its steps, and a private project's line only
-// for that project's readers. Through the store and a fresh loopback replica set, as the people's apps read it.
+// Plain chat (task #2294; docs/plans/2026-11-03-plain-chat-work-plan.md): each task is one ordinary "Let's build" message in
+// its project chat, never edited, with the PM's replies in its thread as it moves, none for its steps, and a private
+// project's only for that project's readers. Through the store and a fresh loopback replica set, as the people's apps read it.
let replica: MongoMemoryReplSet
let db: PrismaClient
let store: SuperTabStore
@@ -60,45 +60,55 @@ async function swarm() {
}
describe('a task\'s one message in its project chat', () => {
- it('posts one message per task with an Engineer and edits it through each state', async () => {
+ it('opens one immutable ordinary root, then records details and updates as normal thread replies', async () => {
const s = await swarm()
const P = await s.add('Coordinator', 'lead', true)
- const T = String((await s.as(P)({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [] })).result.conversationId)
+ const T = String((await s.as(P)({ type: 'conversation.create', title: 'Offline drafts', requesterId: owner.sub, brief: 'Keep drafts.', checks: [] })).result.conversationId)
+ const first = await s.page('lead')
+ expect(first.lines).toEqual([expect.objectContaining({ text: "Let's build: Offline drafts", recipientIds: [] })])
+ const root = first.lines[0]!.id
+ const readThread = () => store.messages(owner, s.tab, 'lead', { thread: root })
+ expect((await readThread()).messages.map(m => m.text)).toEqual(["Let's build: Offline drafts", 'Keep drafts.'])
const E = await s.add('Engineer', T)
const assignmentId = String((await s.as(P)({ type: 'work.assign', conversationId: T, agentId: E })).result.assignmentId)
- const status = (value: 'working' | 'needs_human' | 'review' | 'done', result: string | null, extra: Record<string, unknown> = {}) =>
- s.as(E)({ type: 'work.status', conversationId: T, assignmentId, status: value, result, ...extra } as Command)
-
- const first = await s.page('lead')
- expect(first.lines).toEqual([expect.objectContaining({ text: 'Offline drafts · planned', recipientIds: [],
- source: expect.objectContaining({ kind: 'task-line', taskId: T, title: 'Offline drafts', state: 'planned', builderId: E }) })])
- const lineId = first.lines[0]!.id
- expect(await db.superTabDelivery.count({ where: { tabId: s.tab, messageId: lineId } })).toBe(0)
+ await s.as(E)({ type: 'work.status', conversationId: T, assignmentId, status: 'working', result: 'Started.' })
+ const beforeRepeated = (await readThread()).messages.length
+ await s.as(E)({ type: 'work.status', conversationId: T, assignmentId, status: 'working', result: 'Halfway.' })
+ expect((await readThread()).messages).toHaveLength(beforeRepeated)
+ // An agent's own post stays in its task's conversation.
+ await s.as(E)({ type: 'message.send', conversationId: T, text: 'Please check the draft.', replyTo: null, recipientIds: [] })
+ const pr = 'https://github.com/example/app/pull/7'
+ await s.as(E)({ type: 'work.status', conversationId: T, assignmentId, status: 'review', result: `Ready: ${pr}` })
+ await s.as(E)({ type: 'work.status', conversationId: T, assignmentId, status: 'done', result: `Checks passed: ${pr}` })
+ await s.as(P)({ type: 'conversation.merged', conversationId: T, pullRequestUrl: pr })
+ await s.as(P)({ type: 'conversation.merged', conversationId: T, pullRequestUrl: pr })
+ const thread = await readThread()
+ expect(thread.messages.map(m => m.text)).toEqual(["Let's build: Offline drafts", 'Keep drafts.', expect.stringMatching(/^On it: \S+ is building it\.$/),
+ 'Ready for review: PR #7', 'Merged: PR #7. Ships in the next release.'])
+ expect(thread.messages.filter(m => m.id !== root).every(m => m.thread === root && m.replyTo === root && (m.author as { id: string }).id === P
+ && m.recipientIds.length === 0)).toBe(true)
+ expect(await db.superTabDelivery.count({ where: { tabId: s.tab, messageId: { in: thread.messages.map(m => m.id) } } })).toBe(0)
+ expect((await s.page('lead')).lines).toEqual(first.lines)
+ const page = await store.messages(owner, s.tab, 'lead', {})
+ expect(page.threads).toEqual(expect.arrayContaining([expect.objectContaining({ id: root, replies: thread.messages.length - 1 })]))
+ })
- let seq = first.reactionSeq
- const steps: Array<[Parameters<typeof status>[0], string | null, Record<string, unknown>, string, Record<string, unknown>]> = [
- ['working', 'Started.', {}, 'Offline drafts · working', { state: 'working' }],
- ['needs_human', 'Keep drafts after a restart?', { ask: { personId: peer.sub, options: ['Keep', 'Drop'], recommended: 0, unblocks: 'The release' } },
- 'Offline drafts · waiting on peer', { state: 'waiting', answerFor: peer.sub }],
- ['review', 'Ready: https://github.com/example/app/pull/7 at abc1234.', {}, 'Offline drafts · in review', { state: 'review' }],
- ['done', 'Review passed: https://github.com/example/app/pull/7.', {}, 'Offline drafts · ready', { state: 'ready' }],
- ]
- for (const [value, result, extra, text, source] of steps) {
- await status(value, result, extra)
- const now = await s.page('lead')
- expect(now.lines).toEqual([expect.objectContaining({ id: lineId, text, source: expect.objectContaining({ taskId: T, ...source }) })])
- if (!('answerFor' in source)) expect(now.lines[0]!.source).not.toHaveProperty('answerFor')
- // The page a reader already shows changed: its counter moved, so the app reads it again.
- expect(now.reactionSeq).toBeGreaterThan(seq)
- seq = now.reactionSeq
- }
- // Shipped once the merge is recorded (PM, review of #2633).
- await s.as(P)({ type: 'conversation.merged', conversationId: T, pullRequestUrl: 'https://github.com/example/app/pull/7' })
- const shipped = await s.page('lead')
- expect(shipped.lines).toEqual([expect.objectContaining({ id: lineId, text: 'Offline drafts · shipped', source: expect.objectContaining({ state: 'shipped' }) })])
- expect(shipped.reactionSeq).toBeGreaterThan(seq)
- // The Shipped line is gone: its line says it.
- expect((await store.messages(owner, s.tab, 'lead', {}) as unknown as { messages: Row[] }).messages.filter(m => m.source?.kind === 'ship')).toEqual([])
+ it('keeps a person\'s own chat message as the task\'s root, and refuses any other message', async () => {
+ const s = await swarm()
+ const P = await s.add('Coordinator', 'lead', true)
+ const asked = String((await run(s.tab, { type: 'message.send', conversationId: 'lead', text: 'Can the phone show who answered?', replyTo: null,
+ recipientIds: [] }, peer)).result.messageId)
+ const T = String((await s.as(P)({ type: 'conversation.create', title: 'Phone shows who answered', brief: 'Show who answered.', checks: [],
+ requestMessageId: asked })).result.conversationId)
+ expect((await s.page('lead')).lines).toEqual([])
+ expect((await store.read(owner, s.tab)).state.conversations.find(c => c.id === T)?.requesterId).toBe(peer.sub)
+ const E = await s.add('Engineer', T)
+ await s.as(P)({ type: 'work.assign', conversationId: T, agentId: E })
+ expect((await store.messages(owner, s.tab, 'lead', { thread: asked })).messages.map(m => m.text))
+ .toEqual(['Can the phone show who answered?', expect.stringMatching(/^On it: \S+ is building it\.$/)])
+ const inTask = String((await run(s.tab, { type: 'message.send', conversationId: T, text: 'Also Desktop?', replyTo: null, recipientIds: [] })).result.messageId)
+ await expect(s.as(P)({ type: 'conversation.create', title: 'Another', brief: '', checks: [], requestMessageId: inTask })).rejects.toThrow('own message')
+ await expect(s.as(P)({ type: 'conversation.create', title: 'Another', brief: '', checks: [], requestMessageId: 'missing' })).rejects.toThrow('own message')
})
it('posts none for a task\'s steps', async () => {
@@ -114,7 +124,7 @@ describe('a task\'s one message in its project chat', () => {
const reviewing = String((await s.as(E)({ type: 'work.assign', conversationId: R, agentId: V })).result.assignmentId)
await s.as(V)({ type: 'work.status', conversationId: R, assignmentId: reviewing, status: 'done', result: 'Ready to merge: Yes.' })
const { lines } = await s.page('lead')
- expect(lines.map(l => [l.source?.taskId, l.source?.state])).toEqual([[T, 'review']])
+ expect(lines.map(l => [l.source?.taskId, l.text])).toEqual([[T, "Let's build: Offline drafts"]])
})
it('shows a private project\'s task line only to that project\'s readers', async () => {
@@ -127,7 +137,7 @@ describe('a task\'s one message in its project chat', () => {
await s.as(E)({ type: 'work.status', conversationId: T, assignmentId, status: 'working', result: 'Started.' })
const mine = await s.page(created.conversationId)
- expect(mine.lines.map(l => [l.source?.taskId, l.source?.state])).toEqual([[T, 'working']])
+ expect(mine.lines.map(l => [l.source?.taskId, l.text])).toEqual([[T, "Let's build: Hidden work"]])
const lineId = mine.lines[0]!.id
// A Swarm member outside the project: no line on the chats they read, and neither the private chat nor the line by id.
expect((await s.page('lead', peer)).lines).toEqual([])
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 7f1459857..e845037bc 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -856,8 +856,8 @@ describe('private swarm projects on the real control API', () => {
const polls = await Promise.all(Array.from({ length: 3 }, () => updates()))
const ids = new Set(polls.flat().map(d => d.id))
expect(ids.size).toBe(1)
- // After the row naming who added the Lead (#2207).
- expect((await chat()).map(m => (m.source as Record<string, unknown>)?.kind)).toEqual(['system', 'update-request'])
+ // After the row naming who added the Lead (#2207), and the task's "Let's build" message with its brief in its thread (#2294).
+ expect((await chat()).map(m => (m.source as Record<string, unknown>)?.kind)).toEqual(['system', 'task-line', 'system', 'update-request'])
await execute({ ...message('New evidence'), conversationId: group } as Command)
now += 900_000
expect((await updates()).map(d => d.id)).toEqual([...ids])
@@ -1241,8 +1241,8 @@ describe('Super Tabs on a real Mongo replica set', () => {
const event = { turnId: randomUUID(), kind: 'prompt' as const, previousEventId: null,
text: 'Change this implementation', truncated: false, interrupted: false }
const typed = await store.native.append(host, tab, contextId, event) as { eventId: string }
- // Besides the rows naming who added each agent (#2207).
- expect((await store.messages(owner, tab, 'lead', {})).messages.filter(m => !memberRow(m))).toHaveLength(0)
+ // Besides the rows naming who added each agent (#2207), only the task's own "Let's build" message (#2294).
+ expect((await store.messages(owner, tab, 'lead', {})).messages.filter(m => !memberRow(m)).map(m => m.text)).toEqual(["Let's build: Implementation"])
expect((await store.messages(owner, tab, group, {})).messages.filter(m => !memberRow(m))).toHaveLength(1)
expect(await store.deliveries(host, tab, worker)).toEqual([])
// A typed prompt names no one (project instructions, phase 4): the coordinator hears only of a gap on the task.
@@ -4895,14 +4895,12 @@ describe('Swarm sweeps', () => {
const previous = (await storedState(tab)).agents.find(a => a.id === agentId)!.configurationVersion ?? null
await run(tab, { type: 'agent.configuration', previousVersion: previous, configuration: { ...config, effort } }, host, agentId)
}
- const before = await db.swarmAgent.findFirstOrThrow({ where: { tabId: tab, key: agentId } })
await run(tab, { type: 'agent.remove', agentId })
- // Past the tombstone's 7 days: its record stays, compacted, and holds the version; nothing purges it.
+ const tombstone = await db.swarmAgent.findFirstOrThrow({ where: { tabId: tab, key: agentId } })
+ expect(tombstone.deleted).toBe(true)
+ // Past the tombstone's 7 days it goes (agentTombstones.ts); the Swarm's agent floor keeps its version.
await sweepSwarms(db, Date.now() + 8 * day)
- const kept = await db.swarmAgent.findFirstOrThrow({ where: { tabId: tab, key: agentId } })
- expect(kept.deleted).toBe(true)
- expect(kept.data).toEqual({})
- expect(kept.version).toBeGreaterThan(before.version)
+ expect(await db.swarmAgent.findFirst({ where: { tabId: tab, key: agentId } })).toBeNull()
await ensurePartExpiry(db)
for (const collection of ['SwarmMember', 'SwarmAgent', 'SwarmMachine']) {
const indexes = await db.$runCommandRaw({ listIndexes: collection }) as { cursor: { firstBatch: Array<{ expireAfterSeconds?: number }> } }
@@ -4911,7 +4909,8 @@ describe('Swarm sweeps', () => {
await add()
const back = await db.swarmAgent.findFirstOrThrow({ where: { tabId: tab, key: agentId } })
expect(back.deleted).toBe(false)
- expect(back.version).toBeGreaterThan(kept.version)
+ // Above the tombstone a Desktop open all along last saw.
+ expect(back.version).toBeGreaterThan(tombstone.version)
const history = await db.superTabConfiguration.findMany({ where: { tabId: tab, agentId }, orderBy: { revision: 'asc' } })
expect(history.at(-1)!.configuration).toMatchObject({ effort: 'high' })
})
diff --git a/backend/integration/swarmAgentTombstones.test.ts b/backend/integration/swarmAgentTombstones.test.ts
new file mode 100644
index 000000000..fd8e987f0
--- /dev/null
+++ b/backend/integration/swarmAgentTombstones.test.ts
@@ -0,0 +1,215 @@
+import { randomUUID } from 'node:crypto'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import type { PrismaClient } from '@prisma/client'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import { listNamedIndexes } from '../src/superTabs/parts/indexed.js'
+import { loadDeliveryParts } from '../src/superTabs/parts/light.js'
+import { guardedWrite } from '../src/superTabs/parts/write.js'
+import { AGENT_RECHECK_MS, purgeAgentTombstones, requeueCompactedAgents } from '../src/superTabs/agentTombstones.js'
+import { planDatabase, plan, profiled, reads } from './plans.test-support.js'
+
+// Prod profile 2026-11-02 (v1.3.86): a Swarm's live-agent read planned on [tabId, changedAt] and examined 1,070 agents to
+// return 40, because about 1,000 removed agents stayed as tombstones. A fresh loopback replica set; never DATABASE_URL.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+let store: SuperTabStore
+const NOW = Date.parse('2026-11-02T13:00:00Z')
+const DAY = 86_400_000
+const maker: AuthUser = { sub: randomUUID().replaceAll('-', '').slice(0, 24), email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const LIVE = 40, REMOVED = 1000
+let busy: string, other: string, empty: string
+
+const agent = (tabId: string, key: string, fields: Record<string, unknown> = {}) => ({ id: `${tabId}:${key}`, tabId, key, version: 1,
+ changedAt: new Date(NOW - 30 * DAY), ordinal: 1, data: { id: key }, machineId: 'm', machineOwnerId: maker.sub, contributorId: maker.sub,
+ deleted: false, purgeAt: null, ...fields })
+const removed = (tabId: string, key: string, purgeAt: Date | null = null) => agent(tabId, key, { deleted: true, purgeAt, data: {} })
+
+beforeAll(async () => {
+ ({ replica, db } = await planDatabase('swarm_agents_test'))
+ store = new SuperTabStore(db, () => NOW)
+ await db.user.create({ data: { id: maker.sub, externalId: `fixture-${maker.sub}`, email: maker.email, autonomousEnv: 'prod' } })
+ busy = (await store.create(maker, randomUUID(), 'Busy')).id
+ other = (await store.create(maker, randomUUID(), 'Other')).id
+ empty = (await store.create(maker, randomUUID(), 'Only tombstones')).id
+ await db.swarmAgent.createMany({ data: [
+ ...Array.from({ length: LIVE }, (_, i) => agent(busy, `live-${i}`)),
+ ...Array.from({ length: REMOVED }, (_, i) => removed(busy, `gone-${i}`)),
+ ...Array.from({ length: 200 }, (_, i) => agent(other, `other-${i}`)),
+ ...Array.from({ length: 50 }, (_, i) => removed(empty, `gone-${i}`)),
+ ] })
+ await listNamedIndexes(db)
+})
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+describe('the live-agent read', () => {
+ it('uses the [tabId, deleted] index and examines only live agents', async () => {
+ let parts: Awaited<ReturnType<typeof loadDeliveryParts>> | undefined
+ const entries = await profiled(db, async () => { parts = await db.$transaction(tx => loadDeliveryParts(tx, busy, [], [])) })
+ expect(parts!.agents.map(a => a.key).sort()).toEqual(Array.from({ length: LIVE }, (_, i) => `live-${i}`).sort())
+ const read = reads(entries, 'SwarmAgent', ['tabId', 'deleted'])
+ expect(read, JSON.stringify(plan(read))).toHaveLength(1)
+ expect(read[0]!.planSummary, JSON.stringify(plan(read))).toMatch(/IXSCAN \{ tabId: 1, deleted: 1 \}/)
+ expect(read[0]!.docsExamined, JSON.stringify(plan(read))).toBe(LIVE)
+ })
+
+ it('returns none for a Swarm of tombstones only, through the same index', async () => {
+ let parts: Awaited<ReturnType<typeof loadDeliveryParts>> | undefined
+ const entries = await profiled(db, async () => { parts = await db.$transaction(tx => loadDeliveryParts(tx, empty, [], [])) })
+ expect(parts!.agents).toEqual([])
+ const read = reads(entries, 'SwarmAgent', ['tabId', 'deleted'])
+ expect(read[0]!.planSummary, JSON.stringify(plan(read))).toMatch(/IXSCAN \{ tabId: 1, deleted: 1 \}/)
+ expect(read[0]!.docsExamined, JSON.stringify(plan(read))).toBe(0)
+ })
+})
+
+describe('an agent added again after its tombstone is gone', () => {
+ const added = (tabId: string, key: string) => db.$transaction(tx => guardedWrite(tx, tabId, { op: 'insert', kind: 'agent', key, ordinal: 1, first: 1,
+ data: { id: key, machineId: 'm', machineOwnerId: maker.sub, contributorId: maker.sub } }, NOW))
+
+ // Desktop keeps the newest version it saw of each part, a tombstone's too, until it reloads (desktop parts.dart _newer): an
+ // agent back at or below its tombstone's version stays hidden there.
+ it('starts above every version its Swarm\'s purged agents reached', async () => {
+ await db.$runCommandRaw({ update: 'SwarmHead', updates: [{ q: { _id: `${other}:head` }, u: { $set: { agentFloor: 900 } } }] })
+ expect(await added(other, 'back')).toBe(901)
+ expect((await db.swarmAgent.findUniqueOrThrow({ where: { id: `${other}:back` } })).version).toBe(901)
+ })
+
+ it('starts at the first version in a Swarm that purged none', async () => {
+ const fresh = (await store.create(maker, randomUUID(), 'Fresh')).id
+ expect(await added(fresh, 'new')).toBe(1)
+ })
+})
+
+describe('the hourly purge of agent tombstones', () => {
+ let tab: string, second: string
+ let first: Awaited<ReturnType<typeof purgeAgentTombstones>>, again: Awaited<ReturnType<typeof purgeAgentTombstones>>
+ let entries: Awaited<ReturnType<typeof profiled>>, repeat: Awaited<ReturnType<typeof profiled>>
+ const due = new Date(NOW - DAY)
+ const group = (key: string, data: Record<string, unknown>, fields: Record<string, unknown> = {}) => ({ id: `${tab}:${key}`, tabId: tab, key,
+ version: 1, changedAt: new Date(NOW - DAY), ordinal: 1, data: { id: key, agentIds: [], leadId: null, ...data },
+ agentIds: (data.agentIds as string[] | undefined) ?? [], lastActivityAt: new Date(NOW - DAY), ...fields })
+ const start = (key: string, agentId: string, fields: Record<string, unknown> = {}) => ({ id: `${tab}:${key}`, tabId: tab, key, version: 1,
+ changedAt: new Date(NOW - DAY), ordinal: 1, data: {}, machineId: 'm', conversationId: 'c', agentId, ...fields })
+ const keysIn = async (tabId: string) => (await db.swarmAgent.findMany({ where: { tabId }, select: { key: true } })).map(a => a.key).sort()
+
+ beforeAll(async () => {
+ tab = (await store.create(maker, randomUUID(), 'Purged')).id
+ second = (await store.create(maker, randomUUID(), 'Purged too')).id
+ await db.swarmAgent.createMany({ data: [
+ ...['unnamed', 'member', 'lead', 'assignee', 'started', 'in-dormant', 'in-removed', 'removed-start'].map(key => removed(tab, key, due)),
+ // The highest versions: a purged one sets its Swarm's floor, a kept one does not.
+ { ...removed(tab, 'purged-high', due), version: 90 }, { ...removed(tab, 'kept-high', due), version: 500 },
+ agent(tab, 'later', { deleted: true, purgeAt: new Date(NOW + DAY) }),
+ ...Array.from({ length: 5 }, (_, i) => agent(tab, `live-${i}`)),
+ removed(second, 'unnamed', due),
+ ] })
+ await db.swarmGroup.createMany({ data: [
+ group('open-1', { agentIds: ['member', 'live-0', 'kept-high'] }), group('open-2', { leadId: 'lead', assignment: { agentId: 'assignee' } }),
+ group('quiet', { agentIds: ['in-dormant'] }, { dormant: true }), group('gone', { agentIds: ['in-removed'] }, { deleted: true }),
+ ] })
+ await db.swarmStart.createMany({ data: [start('s-live', 'started'), start('s-removed', 'removed-start', { deleted: true })] })
+ entries = await profiled(db, async () => { first = await purgeAgentTombstones(db, NOW) })
+ repeat = await profiled(db, async () => { again = await purgeAgentTombstones(db, NOW) })
+ })
+
+ it('deletes only tombstones past their purge time that nothing open names', async () => {
+ expect(first).toEqual({ purged: 6, kept: 5 })
+ expect(await keysIn(tab)).toEqual(['assignee', 'kept-high', 'lead', 'later', ...Array.from({ length: 5 }, (_, i) => `live-${i}`), 'member', 'started'].sort())
+ expect(await keysIn(second)).toEqual([])
+ const later = await db.swarmAgent.findUniqueOrThrow({ where: { id: `${tab}:later` } })
+ expect(later).toMatchObject({ deleted: true, data: { id: 'later' }, purgeAt: new Date(NOW + DAY) })
+ // Other Swarms' agents and tombstones not yet due stay.
+ expect(await db.swarmAgent.count({ where: { tabId: busy } })).toBe(LIVE + REMOVED)
+ })
+
+ it('raises each Swarm\'s agent floor to the highest version it purged, before the tombstones go', async () => {
+ const floor = async (tabId: string) => ((await db.swarmHead.aggregateRaw({ pipeline: [{ $match: { _id: `${tabId}:head` } },
+ { $project: { _id: 0, agentFloor: 1 } }] })) as unknown as Array<{ agentFloor?: number }>)[0]?.agentFloor
+ expect(await floor(tab)).toBe(90)
+ expect(await floor(second)).toBe(1)
+ expect(await floor(busy)).toBeUndefined()
+ })
+
+ it('keeps a tombstone an open conversation or a live start names, compacted, and checks it again a day later', async () => {
+ for (const key of ['member', 'lead', 'assignee', 'started', 'kept-high']) {
+ expect(await db.swarmAgent.findUniqueOrThrow({ where: { id: `${tab}:${key}` } }), key)
+ .toMatchObject({ deleted: true, data: {}, purgeAt: new Date(NOW + AGENT_RECHECK_MS) })
+ }
+ expect(again).toEqual({ purged: 0, kept: 0 })
+ const read = reads(repeat, 'SwarmAgent', ['purgeAt'])
+ expect(read.map(e => e.docsExamined), JSON.stringify(plan(read))).toEqual([0])
+ })
+
+ it('finds due tombstones by the purge index and the names by the open-conversation index', () => {
+ const found = reads(entries, 'SwarmAgent', ['purgeAt']).filter(e => e.op !== 'update' && e.op !== 'remove')
+ expect(found, JSON.stringify(plan(found))).toHaveLength(1)
+ expect(found[0]!.planSummary, JSON.stringify(plan(found))).toMatch(/IXSCAN \{ purgeAt: 1 \}/)
+ expect(found[0]!.docsExamined, JSON.stringify(plan(found))).toBe(11)
+ // One read per Swarm with due tombstones, of its open conversations only.
+ const groups = reads(entries, 'SwarmGroup', ['agentIds'])
+ expect(groups.map(e => e.command?.hint), JSON.stringify(plan(groups))).toEqual([{ tabId: 1, dormant: 1, changedAt: 1 }, { tabId: 1, dormant: 1, changedAt: 1 }])
+ const starts = reads(entries, 'SwarmStart', ['agentId'])
+ expect(starts.map(e => e.planSummary), JSON.stringify(plan(starts))).toEqual(['IXSCAN { tabId: 1, agentId: 1 }', 'IXSCAN { tabId: 1, agentId: 1 }'])
+ })
+})
+
+describe('tombstones compacted before the purge', () => {
+ it('get a purge time, and the next sweep purges them', async () => {
+ await db.swarmMember.create({ data: { id: `${busy}:gone-member`, tabId: busy, key: 'gone-member', version: 1, changedAt: new Date(NOW - 30 * DAY),
+ ordinal: 1, data: {}, deleted: true, purgeAt: null } })
+ let queued = 0
+ const agents = await db.swarmAgent.count()
+ const entries = await profiled(db, async () => { queued = await requeueCompactedAgents(db, NOW) })
+ expect(queued).toBe(REMOVED + 50)
+ const update = reads(entries, 'SwarmAgent', ['deleted', 'purgeAt'])
+ expect(update, JSON.stringify(plan(update))).toHaveLength(1)
+ // One pass, once per worker start: never more than the agents there are.
+ expect(update[0]!.docsExamined, JSON.stringify(plan(update))).toBeLessThanOrEqual(agents)
+ // A member's tombstone keeps its compaction for good.
+ expect((await db.swarmMember.findUniqueOrThrow({ where: { id: `${busy}:gone-member` } })).purgeAt).toBeNull()
+ expect(await purgeAgentTombstones(db, NOW + 1)).toEqual({ purged: REMOVED + 50, kept: 0 })
+ expect(await db.swarmAgent.count({ where: { tabId: busy } })).toBe(LIVE)
+ expect(await db.swarmAgent.count({ where: { tabId: empty } })).toBe(0)
+ expect(await requeueCompactedAgents(db, NOW)).toBe(0)
+ })
+})
+
+describe('the purge when something changes or fails under it', () => {
+ const LATER = NOW + 2 * DAY
+
+ it('leaves a tombstone whose Swarm\'s floor it could not raise, and checks it again a day later instead of every pass', async () => {
+ // No head: the floor's update matches nothing, so the tombstone's version would be lost. A full batch of them must not spin.
+ const headless = `headless-${randomUUID()}`
+ await db.swarmAgent.createMany({ data: Array.from({ length: 500 }, (_, i) => removed(headless, `gone-${i}`, new Date(LATER - DAY))) })
+ // Earlier cases' tombstones fall due by now too; these 500 are among the kept.
+ expect((await purgeAgentTombstones(db, LATER)).kept).toBeGreaterThanOrEqual(500)
+ expect(await db.swarmAgent.count({ where: { tabId: headless } })).toBe(500)
+ expect((await db.swarmAgent.findUniqueOrThrow({ where: { id: `${headless}:gone-0` } })).purgeAt).toEqual(new Date(LATER + AGENT_RECHECK_MS))
+ })
+
+ it('leaves a tombstone revived between its read and its delete, at the version it continued from', async () => {
+ const tabId = (await store.create(maker, randomUUID(), 'Racing')).id
+ await db.swarmAgent.create({ data: { ...removed(tabId, 'back', new Date(LATER - DAY)), version: 7 } })
+ // The agent comes back (parts/write.ts continues from its tombstone) just before the purge deletes.
+ let revived = false
+ const racing = new Proxy(db, { get(target, property, receiver) {
+ if (property !== '$runCommandRaw') return Reflect.get(target, property, receiver)
+ return async (command: Record<string, unknown>) => {
+ if (command.delete === 'SwarmAgent' && !revived) {
+ revived = true
+ await db.$transaction(tx => guardedWrite(tx, tabId, { op: 'insert', kind: 'agent', key: 'back', ordinal: 1, first: 1,
+ data: { id: 'back', machineId: 'm', machineOwnerId: maker.sub, contributorId: maker.sub } }, LATER))
+ }
+ return target.$runCommandRaw(command as never)
+ }
+ } })
+ expect(await purgeAgentTombstones(racing, LATER)).toEqual({ purged: 0, kept: 0 })
+ expect(revived).toBe(true)
+ expect(await db.swarmAgent.findUniqueOrThrow({ where: { id: `${tabId}:back` } })).toMatchObject({ deleted: false, version: 8 })
+ })
+})
diff --git a/backend/integration/swarmSweepPlans.test.ts b/backend/integration/swarmSweepPlans.test.ts
index 2689596bf..82864f544 100644
--- a/backend/integration/swarmSweepPlans.test.ts
+++ b/backend/integration/swarmSweepPlans.test.ts
@@ -71,8 +71,8 @@ afterAll(async () => {
describe('the hourly sweeps', () => {
it('compacts only tombstones past their purge time, each collection by its purge index', async () => {
- expect(result.tombstonesCompacted).toBe(6)
- for (const collection of ['SwarmMember', 'SwarmAgent', 'SwarmMachine']) {
+ expect(result.tombstonesCompacted).toBe(4)
+ for (const collection of ['SwarmMember', 'SwarmMachine']) {
// The due tombstones are found by the purge index, then compacted by id.
const found = reads(entries, collection, ['purgeAt']).filter(e => e.op !== 'update')
expect(found, `${collection}: ${JSON.stringify(plan(found))}`).toHaveLength(1)
@@ -85,6 +85,12 @@ describe('the hourly sweeps', () => {
expect(kept.data).toEqual({ id: 'swarmMember:later' })
})
+ it('deletes agent tombstones past their purge time instead of compacting them (agentTombstones.ts)', async () => {
+ expect(result.agentTombstones).toEqual({ purged: 2, kept: 0 })
+ const left = await db.swarmAgent.findMany({ where: { tabId: tabs[0]!, deleted: true }, select: { key: true } })
+ expect(left.map(a => a.key).sort()).toEqual(['swarmAgent:compacted', 'swarmAgent:later'])
+ })
+
it('never removes a start that has not finished', async () => {
const running = await db.swarmStart.findMany({ where: { tabId: tabs[0]!, key: { startsWith: 'start:running-' } }, select: { key: true, deleted: true } })
expect(running.filter(r => r.deleted).map(r => r.key)).toEqual([])
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 2a8a097ea..3afd618df 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1781,6 +1781,9 @@ model SwarmHead {
visibilityEpoch Int @default(1)
/// The tab revision when it was split into parts (0 for a Swarm born in parts). Every later message sequence is above it.
sequenceBase Int @default(0)
+ /// The highest version of any agent tombstone the sweep purged (superTabs/agentTombstones.ts): an agent added with no
+ /// tombstone starts above it, so its versions never go back. Missing until the first purge.
+ agentFloor Int?
@@unique([tabId, key])
@@index([tabId, changedAt])
@@ -1871,6 +1874,9 @@ model SwarmAgent {
@@unique([tabId, key])
@@index([tabId, changedAt])
+ /// A Swarm's live agents (parts/light.ts, load.ts, read/host.ts): without it the read planned on [tabId, changedAt] and
+ /// examined every tombstone too (prod 2026-11-02: 1,070 examined for 40 returned).
+ @@index([tabId, deleted])
@@index([machineId, deleted])
@@index([tabId, contributorId])
/// One agent's registrations in every Swarm (confidential.ts, sessionScope.ts): host rows read them on every changed tab.
diff --git a/backend/src/superTabs/agentTombstones.ts b/backend/src/superTabs/agentTombstones.ts
new file mode 100644
index 000000000..37f4b2d6e
--- /dev/null
+++ b/backend/src/superTabs/agentTombstones.ts
@@ -0,0 +1,87 @@
+/**
+ * Removed agents' tombstones go 7 days after their removal (prod 2026-11-02: about 1,000 kept for good in one Swarm, read by
+ * every live-agent read). Members and machines keep theirs, compacted (sweeps.ts compactTombstones). Before any goes, its
+ * Swarm's agent floor rises to its version: an agent added with no tombstone starts above it (parts/write.ts), so a client
+ * that saw the tombstone takes the agent again (Desktop keeps the newest version it saw until it reloads).
+ */
+import type { PrismaClient } from '@prisma/client'
+import { groupsBy, readBy } from './parts/indexed.js'
+import { logger } from '../utils/logger.js'
+
+/** How long a tombstone kept because something open names it waits before it is checked again. */
+export const AGENT_RECHECK_MS = 86_400_000
+const BATCH = 500
+
+const at = (ms: number) => ({ $date: new Date(ms).toISOString() })
+
+/** The agents of `keys` that an open conversation (as its member, Lead or assignee) or a live start of the Swarm names. */
+async function namedAgents(db: PrismaClient, tabId: string, keys: string[]): Promise<Set<string>> {
+ const [groups, starts] = await Promise.all([
+ // The open conversations only, by their index (parts/indexed.ts); the names as light.ts undecidedWork reads them.
+ groupsBy(db, 'dormancy', [{ $match: { tabId, deleted: false, dormant: false,
+ $or: [{ agentIds: { $in: keys } }, { 'data.leadId': { $in: keys } }, { 'data.assignment.agentId': { $in: keys } }] } },
+ { $project: { _id: 0, agentIds: 1, 'data.leadId': 1, 'data.assignment.agentId': 1 } }]),
+ readBy(db, 'SwarmStart', 'agents', [{ $match: { tabId, agentId: { $in: keys }, deleted: false } }, { $project: { _id: 0, agentId: 1 } }]),
+ ])
+ const names = [...groups.flatMap(row => {
+ const data = row.data as { leadId?: string | null; assignment?: { agentId?: string } } | undefined
+ return [...row.agentIds as string[] ?? [], data?.leadId, data?.assignment?.agentId]
+ }), ...starts.map(row => row.agentId as string)]
+ return new Set(names.filter((name): name is string => !!name && keys.includes(name)))
+}
+
+/**
+ * Deletes agent tombstones past their purge time, in batches, by the purge index. One an open conversation or a live start
+ * still names, or whose Swarm's floor could not be raised, is compacted and checked again `AGENT_RECHECK_MS` later. Each write repeats the due match, so a tombstone an
+ * agent's return revived since the read stays; a return that read it before the delete fails its guard and runs again.
+ */
+export async function purgeAgentTombstones(db: PrismaClient, now: number): Promise<{ purged: number; kept: number }> {
+ const due = { deleted: true, purgeAt: { $lt: at(now) } }
+ let purged = 0, kept = 0
+ for (;;) {
+ const rows = await readBy(db, 'SwarmAgent', 'purge', [{ $match: due }, { $limit: BATCH }, { $project: { _id: 1, tabId: 1, key: 1, version: 1 } }]) as
+ Array<{ _id: string; tabId: string; key: string; version: number }>
+ if (!rows.length) break
+ const tabs = new Map<string, string[]>()
+ for (const row of rows) tabs.set(row.tabId, [...tabs.get(row.tabId) ?? [], row.key])
+ const named = new Set<string>()
+ for (const [tabId, keys] of tabs) for (const key of await namedAgents(db, tabId, keys)) named.add(`${tabId}\0${key}`)
+ const held = new Set(rows.filter(row => named.has(`${row.tabId}\0${row.key}`)).map(row => row._id))
+ // The floor first: a deleted tombstone's version is never lost. A Swarm whose floor was not written (no head, a write
+ // error) keeps its tombstones, compacted, for the next check. A revival between the two writes continues from the
+ // tombstone, above the floor already.
+ const floors = new Map<string, number>()
+ for (const row of rows) if (!held.has(row._id)) floors.set(row.tabId, Math.max(floors.get(row.tabId) ?? 0, row.version))
+ const raised = new Set<string>()
+ for (const [tabId, version] of floors) {
+ const reply = await db.$runCommandRaw({ update: 'SwarmHead', updates: [{ q: { _id: `${tabId}:head` }, u: { $max: { agentFloor: version } } }] }) as
+ unknown as { n?: number; writeErrors?: unknown[] }
+ if (Number(reply.n ?? 0) === 1 && !reply.writeErrors?.length) raised.add(tabId)
+ else logger.warn('[swarm-sweeps] an agent floor was not written; its tombstones wait a day', { tabId })
+ }
+ const free = rows.filter(row => !held.has(row._id) && raised.has(row.tabId)).map(row => row._id)
+ const wait = rows.filter(row => !free.includes(row._id)).map(row => row._id)
+ const before = purged + kept
+ if (free.length) {
+ const reply = await db.$runCommandRaw({ delete: 'SwarmAgent', deletes: [{ q: { _id: { $in: free }, ...due }, limit: 0 }] }) as unknown as { n?: number }
+ purged += Number(reply.n ?? 0)
+ }
+ if (wait.length) {
+ const reply = await db.$runCommandRaw({ update: 'SwarmAgent', updates: [{ q: { _id: { $in: wait }, ...due },
+ u: { $set: { data: {}, purgeAt: at(now + AGENT_RECHECK_MS) } }, multi: true }] }) as unknown as { nModified?: number }
+ kept += Number(reply.nModified ?? 0)
+ }
+ // A full batch that changed nothing (its writes refused) would be read again at once: stop until the next pass.
+ if (purged + kept === before) break
+ if (rows.length < BATCH) break
+ }
+ return { purged, kept }
+}
+
+/** Tombstones compacted for good before this purge (purge time null) get one now, so the next sweep purges them. Run once
+ * by the worker at startup: one pass over the agents (about 1,300 in prod, 2026-11-02), as no index leads with `deleted`. */
+export async function requeueCompactedAgents(db: PrismaClient, now: number): Promise<number> {
+ const reply = await db.$runCommandRaw({ update: 'SwarmAgent', updates: [{ q: { deleted: true, purgeAt: null }, u: { $set: { purgeAt: at(now) } },
+ multi: true }] }) as unknown as { nModified?: number }
+ return Number(reply.nModified ?? 0)
+}
diff --git a/backend/src/superTabs/buddies.test.ts b/backend/src/superTabs/buddies.test.ts
index b15e4d6b6..64bc03967 100644
--- a/backend/src/superTabs/buddies.test.ts
+++ b/backend/src/superTabs/buddies.test.ts
@@ -546,12 +546,35 @@ describe('a Buddy\'s proposal to the PM', () => {
return { f, propose }
}
- it('posts one message in the project chat, to the PM, written by the server as on its owner\'s behalf', () => {
+ it('posts an ordinary root as its owner and delivers the full first reply from the Buddy', () => {
const { f, propose } = asked()
- const posted = propose().messages
- expect(posted).toEqual([expect.objectContaining({ conversationId: f.app.conversationId, recipients: [f.pm],
- author: expect.objectContaining({ kind: 'agent', id: 'buddy' }), source: { kind: 'buddy-proposal', personId: 'peer', ownerMessageId: 'ask' },
- text: 'Proposal from peer\'s Buddy, on peer\'s behalf.\n\nGoal: Sync edits made offline\nScope: Desktop drafts only; no phone yet\nPriority: high' })])
+ const [root, details] = propose().messages
+ expect(root).toMatchObject({ conversationId: f.app.conversationId, recipients: [], replyTo: null,
+ author: { kind: 'person', id: 'peer', name: '[email protected]', membershipGeneration: 'first' },
+ source: { kind: 'buddy-proposal', personId: 'peer', buddyId: 'buddy', ownerMessageId: 'ask' },
+ text: "Let's build: Sync edits made offline" })
+ expect(details).toMatchObject({ conversationId: f.app.conversationId, recipients: [f.pm], replyTo: root!.id, thread: root!.id,
+ author: { kind: 'agent', id: 'buddy' },
+ text: 'Goal: Sync edits made offline\nScope: Desktop drafts only; no phone yet\nPriority: high' })
+ })
+
+ it.each([
+ [' Offline drafts ', 'Requested by Dee. Save drafts. Keep them.', 'Offline drafts'],
+ [undefined, 'Requested by Dee. Save drafts. Keep them.', 'Save drafts'],
+ [undefined, 'Requested by [email protected] through Harness. Hub reports hide an item from everyone.', 'Hub reports hide an item from everyone'],
+ [undefined, 'Save drafts! Keep them.', 'Save drafts!'],
+ [undefined, 'A'.repeat(100), 'A'.repeat(80)],
+ ])('uses a bounded short name for the root (%s)', (title, goal, name) => {
+ const { f } = asked()
+ const command = commandSchema.parse({ type: 'buddy.propose', conversationId: f.chat, ownerMessageId: 'ask', ...proposal, goal, ...(title ? { title } : {}) })
+ const posted = f.run(command, buddy, { proposalAsk: { id: 'ask', conversationId: f.chat, source: false, createdAt: 900,
+ author: { kind: 'person', id: 'peer', name: 'peer', membershipGeneration: 'first' } } })
+ expect(posted.messages[0]!.text).toBe(`Let's build: ${name}`)
+ })
+
+ it('refuses empty and overlong explicit names before posting', () => {
+ for (const title of [' ', 'A'.repeat(81)]) expect(commandSchema.safeParse({ type: 'buddy.propose', conversationId: 'chat',
+ ownerMessageId: 'ask', ...proposal, title }).success).toBe(false)
})
it('is one per ask: the same message never asks twice', () => {
@@ -577,11 +600,11 @@ describe('a Buddy\'s proposal to the PM', () => {
{ now: 2 * 3_600_000, proposalAsk: { id: 'ask', conversationId: f.chat, source: false, createdAt, newestOwnerMessageId,
author: { kind: 'person', id: 'peer', name: 'peer', membershipGeneration: 'first' } } })
expect(() => send('later', 900)).toThrow('your owner\'s newest message')
- expect(send('ask', 900).messages).toHaveLength(1)
+ expect(send('ask', 900).messages).toHaveLength(2)
const { f: g } = asked()
expect(g.run({ type: 'buddy.propose', conversationId: g.chat, ownerMessageId: 'ask', ...proposal }, buddy,
{ now: 2 * 3_600_000, proposalAsk: { id: 'ask', conversationId: g.chat, source: false, createdAt: 2 * 3_600_000 - 59 * 60_000, newestOwnerMessageId: 'later',
- author: { kind: 'person', id: 'peer', name: 'peer', membershipGeneration: 'first' } } }).messages).toHaveLength(1)
+ author: { kind: 'person', id: 'peer', name: 'peer', membershipGeneration: 'first' } } }).messages).toHaveLength(2)
})
it('carries the files the store found it may send, on the proposal message in the project chat', () => {
@@ -591,8 +614,8 @@ describe('a Buddy\'s proposal to the PM', () => {
const posted = f.run({ type: 'buddy.propose', conversationId: f.chat, ownerMessageId: 'ask', ...proposal, attachmentIds: ['plan', 'shot', 'plan'] }, buddy,
{ proposalAsk: { id: 'ask', conversationId: f.chat, source: false, createdAt: 900,
author: { kind: 'person', id: 'peer', name: 'peer', membershipGeneration: 'first' } }, attachments: files }).messages
- expect(posted).toEqual([expect.objectContaining({ conversationId: f.app.conversationId, attachments: files,
- source: { kind: 'buddy-proposal', personId: 'peer', ownerMessageId: 'ask' } })])
+ expect(posted[0]).not.toHaveProperty('attachments')
+ expect(posted[1]).toMatchObject({ conversationId: f.app.conversationId, attachments: files, replyTo: posted[0]!.id, thread: posted[0]!.id })
expect(propose('ask2').messages[0]).not.toHaveProperty('attachments')
})
@@ -660,7 +683,7 @@ describe('a Swarm-wide Buddy', () => {
expect(() => f.run({ ...named, projectId: 'made-up' }, self, { proposalAsk: ask } as never)).toThrow(expect.objectContaining({ code: 'NOT_FOUND' }))
expect(() => f.run(named, self, { proposalAsk: { ...ask, session: true } } as never)).toThrow(expect.objectContaining({ code: 'PROPOSAL_UNASKED' }))
const rows = f.run(named, self, { proposalAsk: ask } as never).messages
- expect(rows.at(-2)).toMatchObject({ conversationId: f.web.conversationId, source: { kind: 'buddy-proposal', personId: 'peer' } })
+ expect(rows[0]).toMatchObject({ conversationId: f.web.conversationId, source: { kind: 'buddy-proposal', personId: 'peer' } })
expect(rows.at(-1)).toMatchObject({ conversationId: chat, recipients: [], source: { kind: 'buddy-proposal-sent', projectId: f.web.projectId } })
expect(rows.at(-1)!.id).not.toBe(rows.at(-2)!.id)
})
diff --git a/backend/src/superTabs/buddies.ts b/backend/src/superTabs/buddies.ts
index 580119eb5..d763a9a9c 100644
--- a/backend/src/superTabs/buddies.ts
+++ b/backend/src/superTabs/buddies.ts
@@ -202,6 +202,13 @@ export const proposalSentText = (project: string, proposal: { goal: string; scop
`Your Buddy sent this to the ${project} PM for you.\n\nGoal: ${proposal.goal}\nScope: ${proposal.scope}`
/** Written by the server, never the Buddy: who it is for and on whose behalf, then the three parts the PM needs. */
-export function proposalText(owner: string, proposal: { goal: string; scope: string; priority: string }): string {
- return `Proposal from ${owner}'s Buddy, on ${owner}'s behalf.\n\nGoal: ${proposal.goal}\nScope: ${proposal.scope}\nPriority: ${proposal.priority}`
+/** A proposal's first reply in its thread, from the Buddy: its author says whose Buddy sent it. */
+export function proposalText(proposal: { goal: string; scope: string; priority: string }): string {
+ return `Goal: ${proposal.goal}\nScope: ${proposal.scope}\nPriority: ${proposal.priority}`
+}
+
+/** A short opening message, with the complete goal kept in its thread. */
+export function proposalTitle(proposal: { title?: string; goal: string }): string {
+ const goal = proposal.goal.replace(/^Requested by [^\r\n]+?\.(?:\s+|$)/i, '').trim() || proposal.goal.trim()
+ return (proposal.title?.trim() || (goal.match(/^[^.!?。!?\r\n]+[.!?。!?]?/)?.[0] || goal).replace(/[.。]$/, '')).slice(0, 80).trim()
}
diff --git a/backend/src/superTabs/buddyNews.test.ts b/backend/src/superTabs/buddyNews.test.ts
index c89d22e68..f0083cc84 100644
--- a/backend/src/superTabs/buddyNews.test.ts
+++ b/backend/src/superTabs/buddyNews.test.ts
@@ -195,11 +195,10 @@ describe('work the PM opens from a Buddy\'s proposal without naming anyone (grou
// and their Buddy hears it inside the task, once.
const done = f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'done', result: 'Review passed: https://github.com/o/r/pull/7' },
agentActor(worker))
- expect(done.edits).toEqual([expect.objectContaining({ conversationId: f.app.conversationId, source: expect.objectContaining({ kind: TASK_LINE_KIND,
- state: 'ready', requesterId: 'peer' }) })])
+ expect(done.messages.filter(m => m.thread === find().cards!.line!.messageId)).toEqual([])
expect(done.messages.filter(m => m.recipients.includes('buddy'))).toEqual([])
const merged = f.run({ type: 'conversation.merged', conversationId: group, pullRequestUrl: 'https://github.com/o/r/pull/7' }, agentActor(worker))
- expect(merged.edits).toEqual([expect.objectContaining({ source: expect.objectContaining({ state: 'shipped' }) })])
+ expect(merged.messages).toEqual(expect.arrayContaining([expect.objectContaining({ thread: find().cards!.line!.messageId, text: 'Merged: PR #7. Ships in the next release.' })]))
expect(merged.messages.filter(m => m.recipients.includes('buddy'))).toEqual([expect.objectContaining({ conversationId: group,
source: { kind: 'agent-only' }, text: expect.stringContaining('which they requested, shipped') })])
expect(f.run({ type: 'conversation.merged', conversationId: group, pullRequestUrl: 'https://github.com/o/r/pull/7' }, agentActor(worker))
@@ -233,7 +232,8 @@ describe('work the PM opens from a Buddy\'s proposal without naming anyone (grou
const web = f.run({ type: 'project.create', name: 'Web', visibility: 'public', brief: '' }).result as { projectId: string; conversationId: string }
const before = f.state.conversations.length
const wrongs = [{ ...sent, conversationId: web.conversationId }, { ...sent, conversationId: f.chat },
- { ...sent, author: { kind: 'person' as const, id: 'peer', name: 'peer', membershipGeneration: 'first' } },
+ { ...sent, author: { kind: 'person' as const, id: 'owner', name: 'owner', membershipGeneration: 'first' } },
+ { ...sent, source: { ...sent.source, buddyId: f.pm } },
{ ...sent, author: { ...sent.author, id: f.pm } }, { ...sent, source: { kind: 'route', personId: 'peer' } }]
for (const wrong of wrongs) {
expect(() => f.run({ type: 'conversation.create', projectId: f.app.projectId, title: 'Offline', brief: 'Save.',
diff --git a/backend/src/superTabs/cards.test.ts b/backend/src/superTabs/cards.test.ts
index 4b5efdb76..47a3240b8 100644
--- a/backend/src/superTabs/cards.test.ts
+++ b/backend/src/superTabs/cards.test.ts
@@ -37,7 +37,7 @@ describe('live cards', () => {
const f = fixture()
const created = f.create()
const id = created.result.conversationId as string
- expect(f.group(id).cards).toEqual({ task: created.messages[0]!.id })
+ expect(f.group(id).cards).toMatchObject({ task: created.messages[0]!.id })
const defined = f.run({ type: 'work.define', conversationId: id, brief: 'Add round avatars.', checks: [{ description: 'Tests pass', independent: false }] })
expect(f.group(id).cards?.task).toBe(defined.messages[0]!.id)
})
diff --git a/backend/src/superTabs/catchUp.test.ts b/backend/src/superTabs/catchUp.test.ts
index 404d4f34b..12b8a0501 100644
--- a/backend/src/superTabs/catchUp.test.ts
+++ b/backend/src/superTabs/catchUp.test.ts
@@ -69,6 +69,15 @@ describe('catch-up summary of the unread span', () => {
expect(summary([before, row('Thread reply', { author: me, thread: 'm1' })]).needsYou.total).toBe(1)
})
+ it('does not read the chat at a message the server posted in the reader\'s name (plain chat, #2294)', () => {
+ const tagged = row('Dee, which colour?', { mentions: [READER] })
+ const root = row("Let's build: Offline drafts", { author: me, source: { kind: 'task-line', taskId: 't1' } })
+ const proposal = row("Let's build: Sync", { author: me, source: { kind: 'buddy-proposal', personId: READER } })
+ const result = summary([tagged, root, proposal])
+ expect(result.needsYou.items.map(i => i.messageId)).toEqual([tagged.id])
+ expect(result.unread).toBe(3)
+ })
+
it('keeps the five newest items of a list, oldest first, and counts them all', () => {
const rows = Array.from({ length: 7 }, (_, i) => row(`Question ${i + 1}`, { mentions: [READER] }))
const result = summary(rows)
diff --git a/backend/src/superTabs/catchUp.ts b/backend/src/superTabs/catchUp.ts
index a99fef39a..8b6cf9075 100644
--- a/backend/src/superTabs/catchUp.ts
+++ b/backend/src/superTabs/catchUp.ts
@@ -43,7 +43,10 @@ const authorOf = (row: CatchUpRow) => (row.author ?? {}) as RowAuthor
const kindOf = (row: CatchUpRow) => (row.source as { kind?: unknown } | null)?.kind
/** A row of the chat itself: top-level, from before threads, or a reply also sent to the chat (threads.ts). */
const inMainStream = (row: CatchUpRow) => !row.thread || row.thread === row.id || !!row.alsoInChat
+/** A "Let's build" root the server posted in its person's name (taskLine.ts, buddy.propose): not their own writing. */
+const POSTED_FOR_AUTHOR = new Set<unknown>(['task-line', 'buddy-proposal'])
const own = (row: CatchUpRow, personId: string) => authorOf(row).kind === 'person' && authorOf(row).id === personId
+ && !POSTED_FOR_AUTHOR.has(kindOf(row))
function authorName(row: CatchUpRow): string {
const { kind, name, displayName } = authorOf(row)
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index b41244c30..10fa574f9 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -2173,8 +2173,11 @@ describe('cancelling work', () => {
const assignment = f.state.conversations.find(c => c.id === group)!.assignment!
expect(assignment).toMatchObject({ status: 'cancelled', result: 'Duplicate of another task' })
expect(activeWork(f.state.conversations.find(c => c.id === group)!)).toBe(false)
- expect(effects.messages).toHaveLength(1)
- expect(effects.messages[0]).toMatchObject({ recipients: [worker], text: 'lead cancelled this task: Duplicate of another task. Stop working on it.' })
+ // Beside it, only the task's ordinary thread reply in the project chat (taskLine.ts).
+ const inTask = effects.messages.filter(m => m.conversationId === group)
+ expect(inTask).toHaveLength(1)
+ expect(inTask[0]).toMatchObject({ recipients: [worker], text: 'lead cancelled this task: Duplicate of another task. Stop working on it.' })
+ expect(effects.messages.filter(m => m.conversationId !== group)).toEqual([expect.objectContaining({ text: 'Not building this: Duplicate of another task.', recipients: [] })])
expect(f.run(cancel, leadActor).messages).toHaveLength(0)
expect(f.state.agents.find(a => a.id === worker)!.workDecision).toBe('awaiting')
f.run({ type: 'agent.release', agentId: worker, decision: 'keep' }, leadActor)
@@ -2205,8 +2208,9 @@ describe('cancelling work', () => {
expect(f.state.conversations.find(c => c.id === group)!.assignment!.status).toBe('reconciling')
const effects = f.run(cancel, leadActor)
expect(f.state.conversations.find(c => c.id === group)!.assignment).toMatchObject({ status: 'cancelled', result: 'Duplicate of another task' })
- expect(effects.messages).toHaveLength(1)
- expect(effects.messages[0]).toMatchObject({ recipients: [], text: 'lead cancelled this task: Duplicate of another task.' })
+ const inTask = effects.messages.filter(m => m.conversationId === group)
+ expect(inTask).toHaveLength(1)
+ expect(inTask[0]).toMatchObject({ recipients: [], text: 'lead cancelled this task: Duplicate of another task.' })
expect(f.run(cancel, leadActor).messages).toHaveLength(0)
})
it('still refuses the removed worker or a collaborator cancelling its task', () => {
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index df0624c41..940b39942 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -45,7 +45,7 @@ import { recordClosing } from './closedAgents.js'
import { declinedWith, declinedWithout } from './sharing.js'
import { actorLabel, memberChanges, memberRowText, quotedName } from './memberRows.js'
import { BUDDY_SESSION_CAPABILITY, chatOwner, endSessionEntry, entryProject, liveSessions, mainBuddyOf, MAX_SESSION_WAITING, requireChatOwner, SESSION_ENDED_KIND, sessionAgentsOf, sessionOf, setSessions, type SessionEndReason } from './buddySessions.js'
-import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, chosenBuddyName, isBuddy, isBuddyChat, isSwarmBuddy, isSwarmBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, openBuddyChat, openSwarmBuddyChat, PM_LINE_KIND, PROPOSAL_ASK_MS, PROPOSAL_SENT_KIND, proposalSentText, proposalText, renameBuddy, requireBuddyCommand, swarmBuddyChatId } from './buddies.js'
+import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, chosenBuddyName, isBuddy, isBuddyChat, isSwarmBuddy, isSwarmBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, openBuddyChat, openSwarmBuddyChat, PM_LINE_KIND, PROPOSAL_ASK_MS, PROPOSAL_SENT_KIND, proposalSentText, proposalText, proposalTitle, renameBuddy, requireBuddyCommand, swarmBuddyChatId } from './buddies.js'
import { BUDDY_OWN_MACHINE_REFUSAL, CODEX_BUDDY_REFUSAL } from './buddyContract.js'
import { launchRefusedLine, leadJoined, leadOvertaken, leadStartFailed, leadStarting, placeLead } from './leadStart.js'
import { appendRouting, coordinatorNameOf, routingSummary, FIRST_INSTRUCTIONS, FIRST_SUMMARY, instructionsHash, instructionsTextSchema, legacyRoleName, liveNotes, MAX_NOTES, noteTextSchema, roleNameSchema, summarySchema, type PmNote } from './instructions.js'
@@ -203,7 +203,9 @@ export const commandSchema = z.discriminatedUnion('type', [
step: z.string().trim().min(1).max(40).regex(/^[^\u0000-\u001f\u007f]+$/, 'A step name is one line of text.').optional(), checks: z.array(check).max(40),
audience: z.object({ personIds: z.array(id).max(200) }).strict().optional(), requesterId: id.optional(),
// The Buddy's proposal message in the project chat the group comes from (Lead, 2026-10-29): the Buddy earns when it ships.
- proposalMessageId: id.optional() }).strict()
+ proposalMessageId: id.optional(),
+ // A person's own message in the project chat that asked for the work: it stays the task's root (Dee, 2026-11-03).
+ requestMessageId: id.optional() }).strict()
.refine(c => c.task !== undefined || c.brief !== undefined, 'Provide a task or brief.')
.refine(c => !c.task || renderWorkTask(c.task).length <= 8000, 'Keep the rendered task within 8,000 characters.'),
z.object({ type: z.literal('conversation.rename'), conversationId: id, title }).strict(),
@@ -223,7 +225,7 @@ export const commandSchema = z.discriminatedUnion('type', [
// owner's message there asking for it. Its files are its own uploads in that chat, or files its owner sent there (store.ts proposable).
// `projectId` is the project a person's one Buddy sends to (authorizeCommandAccess reads it as its person would); a project
// session or a project chat's Buddy has its own project, and naming another reads as a project that does not exist.
- z.object({ type: z.literal('buddy.propose'), conversationId: id, ownerMessageId: id, projectId: id.optional(), goal: z.string().trim().min(1).max(2000),
+ z.object({ type: z.literal('buddy.propose'), conversationId: id, ownerMessageId: id, projectId: id.optional(), title: z.string().trim().min(1).max(80).optional(), goal: z.string().trim().min(1).max(2000),
scope: z.string().trim().min(1).max(4000), priority: z.enum(['low', 'normal', 'high']),
attachmentIds: z.array(id).max(MAX_PROPOSAL_ATTACHMENTS, `Attach at most ${MAX_PROPOSAL_ATTACHMENTS} files to a proposal.`).optional() }).strict(),
// Without `projectId`, the person's one Buddy (Dee, 10-31); an older app names a project, and removes that same one Buddy.
@@ -329,7 +331,7 @@ export const operationSchema = z.object({ operationId: id, command: commandSchem
* chat row is redacted (terminal.ts). Not a role's skill text, which only its project's owner, Lead and hosts read. */
const WORDS: Partial<Record<Command['type'], readonly string[]>> = {
'message.send': ['text'],
- 'buddy.propose': ['goal', 'scope'],
+ 'buddy.propose': ['title', 'goal', 'scope'],
'member.status': ['status.text'],
'agent.add': ['name', 'initialMessage'],
'agent.start': ['request.name', 'overrideReason'],
@@ -422,6 +424,8 @@ export interface CommandContext {
buddyNames?: import('./buddies.js').ChosenBuddyName[]
/** 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 chat message a new group names as its request (conversation.create requestMessageId), loaded from this tab by the store. */
+ request?: { id: string; conversationId: string; author: Author; source: unknown; replyTo: string | 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
/** Whether it went to a thread session, which the main Buddy never hears: the main Buddy proposes for none of those. */
@@ -690,9 +694,11 @@ function askedByOf(state: SuperTabState, project: SwarmProject, personId: string
* row is the Swarm's own (buddy.propose), so a Buddy removed since still earns for it. */
function proposalOf(state: SuperTabState, project: SwarmProject, proposal: CommandContext['proposal']): { buddyId: string; messageId: string; personId?: string } {
const author = proposal?.author
- const buddy = author?.kind === 'agent' ? state.agents.find(a => a.id === author.id) : undefined
+ const buddyId = author?.kind === 'agent' ? author.id : typeof proposal?.source?.buddyId === 'string' ? proposal.source.buddyId : undefined
+ const buddy = buddyId ? state.agents.find(a => a.id === buddyId) : undefined
+ const attributed = author?.kind === 'agent' || (author?.kind === 'person' && author.id === proposal?.source?.personId && !!buddyId)
if (!proposal || proposal.conversationId !== project.leadConversationId || proposal.source?.kind !== 'buddy-proposal'
- || author?.kind !== 'agent' || (buddy && !isBuddy(buddy))) {
+ || !attributed || (buddy && !isBuddy(buddy))) {
fail('PROPOSAL_UNKNOWN', 'Name a Buddy\'s proposal posted in this project\'s chat, or leave the proposal out.', 400)
}
// The person it was sent for, as buddy.propose recorded them: the Swarm writes this source, never a sender.
@@ -706,7 +712,17 @@ function proposalOf(state: SuperTabState, project: SwarmProject, proposal: Comma
const main = owner && !(buddy && isSwarmBuddy(buddy) && !buddy.buddySession)
? state.agents.find(a => isSwarmBuddy(a) && !a.buddySession && a.buddyOf!.personId === owner.personId && a.buddyOf!.generation === owner.generation)
: undefined
- return { buddyId: main?.id ?? author.id, messageId: proposal.id, ...personId ? { personId } : {} }
+ return { buddyId: main?.id ?? buddyId!, messageId: proposal.id, ...personId ? { personId } : {} }
+}
+/** The person's own top-level message in [project]'s chat that asked for a new group; anything else reads as unknown. */
+function requestOf(state: SuperTabState, project: SwarmProject, request: CommandContext['request']): { messageId: string; personId: string } {
+ const author = request?.author
+ const member = author?.kind === 'person' ? state.people.find(p => p.id === author.id && p.generation === author.membershipGeneration) : undefined
+ if (!request || request.conversationId !== project.leadConversationId || request.replyTo || request.source || !member
+ || !canReadProject(state, { kind: 'person', userId: member.id, email: member.email }, project)) {
+ fail('REQUEST_UNKNOWN', 'Name a person\'s own message in this project\'s chat, or leave the request out.', 400)
+ }
+ return { messageId: request.id, personId: member.id }
}
/** The person a proposal was sent for, while they are still in the Swarm and read [project]; otherwise nobody, so a person
* who left or lost the project is never credited and opening the group still works (the PM is told to name someone). */
@@ -731,8 +747,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// no longer a member (a command that removed them).
let sender: Author | undefined
try { sender = author(effects.state, actor) } catch { sender = undefined }
- syncTaskLines(original, effects, input.type === 'work.status' ? input.conversationId : undefined, sender,
- stableId(original.id, actorKey(actor), context.operationId))
+ syncTaskLines(original, effects, sender, stableId(original.id, actorKey(actor), context.operationId))
return effects
}
@@ -1903,8 +1918,12 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
// Who asked: the person named, else the one a Buddy's proposal was sent for, else a person opening it themselves.
const proposal = command.proposalMessageId ? proposalOf(state, project, context.proposal) : undefined
+ if (command.requestMessageId && (command.proposalMessageId || command.reviewOf || command.audience)) {
+ fail('INVALID_REQUEST', 'A request message opens a task of its own: leave out proposalMessageId, reviewOf and audience.', 400)
+ }
+ const request = command.requestMessageId ? requestOf(state, project, context.request) : undefined
const requesterId = command.requesterId ? requester(state, project, command.requesterId)
- : proposalRequester(state, project, proposal?.personId) ?? (actor.kind === 'person' ? actor.userId : undefined)
+ : proposalRequester(state, project, proposal?.personId) ?? request?.personId ?? (actor.kind === 'person' ? actor.userId : undefined)
const number = nextConversationNumber(state)
state.groupCounter = number
// The agent that opens a task is in it, so an Engineer that opens its own review can post there and pass its checks.
@@ -1926,6 +1945,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
})
recordAsked(state.conversations.at(-1)!, requesterId, context.now)
if (proposal) recordProposal(state.conversations.at(-1)!, { buddyId: proposal.buddyId, messageId: proposal.messageId })
+ // The asker's message is the task's root; its thread takes the task's replies (taskLine.ts).
+ if (request) state.conversations.at(-1)!.cards = { line: { messageId: request.messageId, conversationId: project.leadConversationId } }
result.conversationId = operationId
result.number = number
// A build group an agent opens for nobody credits nobody when it ships: say so, as the PM can still name them.
@@ -2197,8 +2218,14 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
chat.proposals = [...chat.proposals ?? [], command.ownerMessageId].slice(-MAX_PROPOSAL_ASKS)
const project = readProject(state, actor, command.projectId ?? agentProjectId(state, self)), home = conversation(state, project.leadConversationId)
const name = owner.email.split('@')[0]!
- message(home.id, proposalText(name, command), home.leadId && home.agentIds.includes(home.leadId) ? [home.leadId] : [], null,
- { kind: 'buddy-proposal', personId: owner.id, ownerMessageId: command.ownerMessageId }, attachments)
+ message(home.id, `Let's build: ${proposalTitle(command)}`, [], null,
+ { kind: 'buddy-proposal', personId: owner.id, buddyId: self.id, ownerMessageId: command.ownerMessageId })
+ const root = effects.messages.at(-1)!
+ root.author = { kind: 'person', id: owner.id, name: owner.email, membershipGeneration: owner.generation }
+ effects.messages.push({ id: stableId(operationId, 'proposal-details'), conversationId: home.id, author: sender,
+ text: proposalText(command), replyTo: root.id, thread: root.id,
+ recipients: home.leadId && home.agentIds.includes(home.leadId) ? [home.leadId] : [],
+ ...(attachments.length ? { attachments } : {}) })
// Its own id: this command's id is the proposal's, and a second row with it rolls the command back. Marked with its project,
// so it goes from view as a PM's line does when its person loses that project (buddySessions.ts lostProjectRow).
if (isSwarmBuddy(self)) effects.messages.push({ id: stableId('proposal-sent', operationId), conversationId: chat.id, author: sender,
diff --git a/backend/src/superTabs/leaderboard/record.test.ts b/backend/src/superTabs/leaderboard/record.test.ts
index 47af61930..70df809ce 100644
--- a/backend/src/superTabs/leaderboard/record.test.ts
+++ b/backend/src/superTabs/leaderboard/record.test.ts
@@ -166,7 +166,7 @@ describe('when the Lead records a merge', () => {
const effects = f.run(merged(id), lead)
expect(f.group(id).ledger?.shippedAt).toBe(NOW)
expect(f.group(id).pullRequestUrls).toEqual([PR])
- expect(effects.messages.map(m => [m.conversationId, m.text])).toEqual([[id, `Merged ${PR}`]])
+ expect(effects.messages.filter(m => m.conversationId === id).map(m => [m.conversationId, m.text])).toEqual([[id, `Merged ${PR}`]])
expect(shippedFor(f, 'owner')).toMatchObject({ points: 3, shipped: { count: 1 } })
})
@@ -262,7 +262,7 @@ describe('when the Lead records a merge', () => {
expect(f.group(id).ledger?.fixedAfterMergeAt).toBe(NOW + 3 * DAY_MS)
expect(f.group(fix).ledger).toMatchObject({ shippedAt: NOW + 3 * DAY_MS, fixOf: id })
expect(f.group(fix).pullRequestUrls).toEqual([FIX])
- expect(effects.messages.map(m => m.text)).toEqual([`Merged ${FIX}, a fix of ${PR}`])
+ expect(effects.messages.filter(m => m.conversationId === fix).map(m => m.text)).toEqual([`Merged ${FIX}, a fix of ${PR}`])
// The line is the fix's card (cards.ts: a main-chat line's links become cards, the original's too).
expect(f.group(fix).cards?.pullRequests?.[0]).toMatchObject({ url: FIX, messageId: effects.messages[0]!.id, mergedAt: NOW + 3 * DAY_MS })
// Recorded again, or by a second fix later: the first fix stays the one counted.
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 9eee71c46..1e5d2ce82 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -655,8 +655,6 @@ export interface CommandEffects {
instructions?: import('./instructions.js').InstructionsWrite
/** A coordinator's note kept or a note removed, written outside the tab state by the store (instructions.ts). */
notes?: import('./instructions.js').NotesWrite
- /** Stored messages given new words: a task's line as the task moves (taskLine.ts). */
- edits?: import('./taskLine.js').MessageEdit[]
}
/** `details` go to the caller with the code: what it needs to act on the refusal (a stale save's current text). */
export class SuperTabError extends Error {
diff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.ts
index ea2ff3572..f368c1116 100644
--- a/backend/src/superTabs/parts/indexed.ts
+++ b/backend/src/superTabs/parts/indexed.ts
@@ -54,8 +54,9 @@ export const NAMED_INDEX = {
SwarmMember: { changes: { tabId: 1, changedAt: 1 }, purge: { purgeAt: 1 } },
SwarmAgent: { changes: { tabId: 1, changedAt: 1 }, purge: { purgeAt: 1 } },
SwarmMachine: { changes: { tabId: 1, changedAt: 1 }, read: { tabId: 1, readAt: 1 }, purge: { purgeAt: 1 } },
- /** `expiry`: live starts by finish time (the hourly sweep). */
- SwarmStart: { changes: { tabId: 1, changedAt: 1 }, expiry: { deleted: 1, finishedAt: 1 } },
+ /** `expiry`: live starts by finish time (the hourly sweep). `agents`: a Swarm's starts of some agents (agentTombstones.ts):
+ * unnamed, Mongo planned that read on `expiry` and read every live start of every Swarm. */
+ SwarmStart: { changes: { tabId: 1, changedAt: 1 }, expiry: { deleted: 1, finishedAt: 1 }, agents: { tabId: 1, agentId: 1 } },
SwarmProgress: { changes: { tabId: 1, changedAt: 1 } },
SuperTabMessage: {
/** A conversation's page in (sequence, id) order. */
diff --git a/backend/src/superTabs/parts/write.ts b/backend/src/superTabs/parts/write.ts
index facacb3cf..e24db3c0e 100644
--- a/backend/src/superTabs/parts/write.ts
+++ b/backend/src/superTabs/parts/write.ts
@@ -100,6 +100,13 @@ async function keepFinishedAt(tx: Transaction, id: string, fields: Record<string
return row?.finishedAt ? { ...fields, finishedAt: row.finishedAt } : fields
}
+/** Where an agent added with no tombstone starts above: the highest version of its Swarm's purged agent tombstones
+ * (agentTombstones.ts), 0 before any. A client that saw a purged tombstone's version takes the agent again (D6). */
+async function agentFloor(tx: Transaction, tabId: string): Promise<number> {
+ const head = await tx.swarmHead.findUnique({ where: { id: partId(tabId, 'head') }, select: { agentFloor: true } })
+ return head?.agentFloor ?? 0
+}
+
/**
* Writes one part inside the command's transaction, guarded by the version it was read at (design section 3.2). The
* guard checks the committed version at write time, so it holds whatever the transaction's read concern: a part another
@@ -123,7 +130,7 @@ export async function guardedWrite(tx: Transaction, tabId: string, write: PartWr
if (!updated.count) throw new PartConflict(write.kind, write.key)
return prior.version + 1
}
- const version = write.first ?? 1
+ const version = Math.max(write.first ?? 1, write.kind === 'agent' ? await agentFloor(tx, tabId) + 1 : 0)
await model.create({ data: { id, tabId, key: write.key, version, changedAt: new Date(stamp), deleted: false, ordinal: write.ordinal,
data: json(write.data), ...fields } })
return version
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 2e42f88c7..3f9dc145e 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -1554,6 +1554,13 @@ export class SuperTabStore {
if (proposal) context.proposal = { id: proposal.id, conversationId: proposal.conversationId, author: proposal.author as unknown as Author,
source: proposal.source as Record<string, unknown> | null }
}
+ if (command.type === 'conversation.create' && command.requestMessageId) {
+ // By id within this tab: the person's chat message the new group answers (commands.ts requestOf checks where it is).
+ const request = await tx.superTabMessage.findFirst({ where: { id: command.requestMessageId, tabId },
+ select: { id: true, conversationId: true, author: true, source: true, replyTo: true } })
+ if (request) context.request = { id: request.id, conversationId: request.conversationId, author: request.author as unknown as Author,
+ source: request.source, replyTo: request.replyTo }
+ }
if (command.type === 'buddy.propose') {
const asked = await tx.superTabMessage.findFirst({ where: { id: command.ownerMessageId, tabId, conversationId: command.conversationId } })
// The newest message its owner wrote there: the chat's newest rows, the Buddy's and the owner's in turn.
@@ -1819,10 +1826,6 @@ export class SuperTabStore {
}
await recordEvidence(tx, tabId, original, effects.state, context.now)
await this.writeMessages(tx, tabId, effects.state, effects.messages, sequences)
- // A task's line takes its new words in place, keeping its id, place and author (taskLine.ts).
- for (const edit of effects.edits ?? []) {
- await tx.superTabMessage.updateMany({ where: { tabId, conversationId: edit.conversationId, id: edit.id }, data: { text: edit.text, source: json(edit.source) } })
- }
if (effects.lateDeliveries?.length) await this.writeLateDeliveries(tx, tabId, effects.state, effects.lateDeliveries)
if (command.type === 'message.send' && actor.kind === 'person') await resolveByReply(tx, tabId, command.conversationId, actor.userId, context.now)
if (command.type === 'work.assign') await resolveWhenWorked(tx, tabId, command.conversationId, context.now)
diff --git a/backend/src/superTabs/sweeps.ts b/backend/src/superTabs/sweeps.ts
index 5d4d2700e..d7b08de2f 100644
--- a/backend/src/superTabs/sweeps.ts
+++ b/backend/src/superTabs/sweeps.ts
@@ -13,10 +13,12 @@ import { expireEvidence } from './evidence/store.js'
import { sweepThreadMarks } from './readMarks.js'
import { sweepActivity } from './activity.js'
import { sweepChatSettings } from './chatSettings.js'
+import { purgeAgentTombstones } from './agentTombstones.js'
/** Parts whose key is never used twice (conversations, starts, projects' progress) lose their tombstone at `purgeAt`.
- * A person, agent or machine can come back under the same key, so its tombstone is kept for good, compacted to its
- * version (`compactTombstones`): versions never reset (spec ruling 6, review round 1). Run by the singleton worker at
+ * A person or machine can come back under the same key, so its tombstone is kept for good, compacted to its
+ * version (`compactTombstones`): versions never reset (spec ruling 6, review round 1). An agent's goes at `purgeAt` once
+ * nothing open names it (agentTombstones.ts). Run by the singleton worker at
* startup, like the terminal and mention expiry indexes. */
export async function ensurePartExpiry(db: PrismaClient): Promise<void> {
for (const collection of ['SwarmHead', 'SwarmGroup', 'SwarmStart', 'SwarmProgress']) {
@@ -29,7 +31,7 @@ export async function ensurePartExpiry(db: PrismaClient): Promise<void> {
await ensureIndex(db, 'SwarmWorkspaceInvitation', { key: { expiresAt: 1 }, name: 'workspace_invitation_expiry', expireAfterSeconds: 0 })
}
-/** A removed person, agent or machine keeps its tombstone after its 7 days, with its data dropped: the version it holds
+/** A removed person or machine keeps its tombstone after its 7 days, with its data dropped: the version it holds
* is where a part added again under that key continues (parts/write.ts). Readers already passed its removal. */
async function compactTombstones(db: PrismaClient, now: number): Promise<number> {
// Plain matches on the purge index (parts/indexed.ts). Through Prisma, `purgeAt: { lt }` was $expr, which no index bounds
@@ -37,7 +39,7 @@ async function compactTombstones(db: PrismaClient, now: number): Promise<number>
// compacted again, each hour (roadmap Phase 3.6).
const due = { deleted: true, purgeAt: { $lt: { $date: new Date(now).toISOString() } } }
let compacted = 0
- for (const collection of ['SwarmMember', 'SwarmAgent', 'SwarmMachine'] as const) {
+ for (const collection of ['SwarmMember', 'SwarmMachine'] as const) {
for (;;) {
const ids = (await readBy(db, collection, 'purge', [{ $match: due }, { $limit: BATCH }, { $project: { _id: 1 } }])).map(row => row._id as string)
if (!ids.length) break
@@ -195,7 +197,7 @@ export async function chatSettings(db: PrismaClient, now: number) {
/** One pass of every sweep (spec, Archive). Each part it changes is a guarded write, so a command in between wins. */
export async function sweepSwarms(db: PrismaClient, now = Date.now()) {
return { slept: await sleepQuietGroups(db, now), startsExpired: await expireStarts(db, now), invitationsExpired: await expireInvitations(db, now),
- tombstonesCompacted: await compactTombstones(db, now), evidenceExpired: await expireEvidence(db, now), threadMarks: await threadMarks(db, now),
+ tombstonesCompacted: await compactTombstones(db, now), agentTombstones: await purgeAgentTombstones(db, now), evidenceExpired: await expireEvidence(db, now), threadMarks: await threadMarks(db, now),
activity: await activityRows(db, now), chatSettings: await chatSettings(db, now) }
}
diff --git a/backend/src/superTabs/taskLine.test.ts b/backend/src/superTabs/taskLine.test.ts
index 7ec3418a2..f9d501480 100644
--- a/backend/src/superTabs/taskLine.test.ts
+++ b/backend/src/superTabs/taskLine.test.ts
@@ -30,143 +30,174 @@ function fixture() {
return { run, add, as, group, task, status, lines, pm, get state() { return state } }
}
-describe('a task\'s one line in its project chat', () => {
- it('posts one line in the project chat when a task is assigned', () => {
+describe('ordinary task messages and progress replies', () => {
+ it('opens immediately as its requester with the brief first in its ordinary thread', () => {
const f = fixture()
- const id = f.group()
- const builder = f.add('Kai', id)
- const effects = f.run({ type: 'work.assign', conversationId: id, agentId: builder })
- const [line, ...more] = f.lines(effects)
- expect(more).toEqual([])
- expect(line).toMatchObject({ conversationId: 'lead', recipients: [], replyTo: null, text: 'Offline drafts · planned',
- author: { kind: 'agent', id: f.pm },
- source: { kind: TASK_LINE_KIND, taskId: id, number: f.task(id).number, title: 'Offline drafts', state: 'planned', builderId: builder, requesterId: 'owner' } })
- expect(line!.source).not.toHaveProperty('answerFor')
- expect(f.task(id).cards?.line).toMatchObject({ messageId: line!.id, state: 'planned' })
+ const created = f.run({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [] })
+ const id = created.result.conversationId as string
+ const [root] = f.lines(created)
+ expect(root).toMatchObject({ conversationId: 'lead', author: { kind: 'person', id: 'owner', name: '[email protected]' },
+ text: "Let's build: Offline drafts", replyTo: null, recipients: [], source: { kind: TASK_LINE_KIND, taskId: id } })
+ expect(created.messages.filter(m => m.thread === root!.id)).toEqual([expect.objectContaining({ text: 'Keep drafts.',
+ replyTo: root!.id, conversationId: 'lead' })])
+ expect(f.task(id).cards?.line?.messageId).toBe(root!.id)
})
- it('edits the same line through working, waiting, review, ready and shipped', () => {
+ it('uses the project PM when no requester is named, never the machine owner', () => {
const f = fixture()
- const id = f.group()
+ const created = f.run({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [] }, f.as(f.pm))
+ expect(f.lines(created)[0]).toMatchObject({ author: { kind: 'agent', id: f.pm }, text: "Let's build: Offline drafts" })
+ })
+
+ const thread = (effects: CommandEffects, root: string) => effects.messages.filter(m => m.thread === root).map(m => m.text)
+
+ it('replies in the approved words, as the PM, without editing the root', () => {
+ const f = fixture(), id = f.group(), root = f.task(id).cards!.line!.messageId
const builder = f.add('Kai', id)
- const lineId = f.lines(f.run({ type: 'work.assign', conversationId: id, agentId: builder }))[0]!.id
- const seq = () => f.state.conversations.find(c => c.id === 'lead')!.reactionSeq ?? 0
- const steps: Array<[Parameters<typeof f.status>[2], string, Record<string, unknown>, Record<string, unknown>]> = [
- ['working', 'Offline drafts · working', { state: 'working' }, {}],
- ['needs_human', 'Offline drafts · waiting on dee', { state: 'waiting', answerFor: 'owner' },
- { ask: { personId: 'owner', options: ['Keep', 'Drop'], recommended: 0, unblocks: 'The release' } }],
- ['review', 'Offline drafts · in review', { state: 'review' }, {}],
- // Done with its pull request, not merged yet: ready, never shipped (PM, review of #2633).
- ['done', 'Offline drafts · ready', { state: 'ready' }, {}],
- ]
- for (const [value, text, source, extra] of steps) {
- const before = seq()
- const effects = f.status(id, builder, value, value === 'needs_human' ? 'Keep drafts after a restart?' : value === 'done' ? `Review passed: ${PR}` : null, extra)
- expect(f.lines(effects)).toEqual([])
- expect(effects.edits).toEqual([expect.objectContaining({ id: lineId, conversationId: 'lead', text,
- source: expect.objectContaining({ kind: TASK_LINE_KIND, taskId: id, ...source }) })])
- if (!('answerFor' in source)) expect(effects.edits![0]!.source).not.toHaveProperty('answerFor')
- expect(seq()).toBe(before + 1)
- }
- // Shipped once its merge is recorded, and only then.
+ const assigned = f.run({ type: 'work.assign', conversationId: id, agentId: builder })
+ expect(f.lines(assigned)).toEqual([])
+ expect(assigned.messages.filter(m => m.thread === root)).toEqual([expect.objectContaining({ text: 'On it: Kai is building it.', replyTo: root,
+ author: expect.objectContaining({ kind: 'agent', id: f.pm }), recipients: [] })])
+ expect(thread(f.status(id, builder, 'working', 'Started.'), root)).toEqual([])
+ const ready = f.status(id, builder, 'review', `Ready: ${PR}`)
+ expect(ready.messages.filter(m => m.thread === root)).toEqual([expect.objectContaining({ text: 'Ready for review: PR #7',
+ author: expect.objectContaining({ kind: 'agent', id: f.pm }) })])
+ expect(thread(f.status(id, builder, 'working', 'Two findings: the draft is lost on restart.\nSecond line.'), root))
+ .toEqual(['Changes needed: Two findings: the draft is lost on restart. Kai is fixing it.'])
+ expect(thread(f.status(id, builder, 'review', `Fixed: ${PR}`), root)).toEqual(['Ready for review: PR #7'])
+ const done = f.status(id, builder, 'done', `Checks passed: ${PR}`)
+ expect(thread(done, root)).toEqual([])
const merged = f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: PR })
- expect(merged.edits).toEqual([expect.objectContaining({ id: lineId, text: 'Offline drafts · shipped', source: expect.objectContaining({ state: 'shipped' }) })])
- expect(f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: PR }).edits ?? []).toEqual([])
+ expect(thread(merged, root)).toEqual(['Merged: PR #7. Ships in the next release.'])
+ expect(thread(f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: PR }), root)).toEqual([])
})
- it('reads done, never shipped, for work Done with no pull request', () => {
- const f = fixture()
- const id = f.group('Review: PR #2632')
+ it('keeps agents\' posts in the task\'s own conversation and repeats no unchanged status', () => {
+ const f = fixture(), id = f.group(), root = f.task(id).cards!.line!.messageId
const builder = f.add('Kai', id)
- const lineId = f.lines(f.run({ type: 'work.assign', conversationId: id, agentId: builder }))[0]!.id
- const done = f.status(id, builder, 'done', 'Ready to merge: Yes.')
- expect(done.edits).toEqual([expect.objectContaining({ id: lineId, text: 'Review: PR #2632 · done', source: expect.objectContaining({ state: 'done' }) })])
+ f.run({ type: 'work.assign', conversationId: id, agentId: builder })
+ f.status(id, builder, 'working', 'Started.')
+ expect(thread(f.status(id, builder, 'working', 'Halfway.'), root)).toEqual([])
+ const posted = f.run({ type: 'message.send', conversationId: id, text: `Please check ${PR}`, replyTo: null, recipientIds: [] }, f.as(builder))
+ expect(posted.messages.filter(m => m.conversationId === 'lead')).toEqual([])
+ expect(thread(f.status(id, builder, 'review', 'Ready.'), root)).toEqual(['Ready for review.'])
})
- it('writes no Shipped line for a task with a line', () => {
- const f = fixture()
- const id = f.group()
+ it('reports each newly merged pull request once, including a second pull request for the same task', () => {
+ const f = fixture(), id = f.group(), root = f.task(id).cards!.line!.messageId
+ const second = 'https://github.com/example/app/pull/8'
+ for (const [url, n] of [[PR, 7], [second, 8]] as const) {
+ const merged = f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: url })
+ expect(merged.messages.filter(m => m.thread === root)).toEqual([expect.objectContaining({ text: `Merged: PR #${n}. Ships in the next release.`,
+ source: { kind: 'system' } })])
+ expect(thread(f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: url }), root)).toEqual([])
+ }
+ })
+
+ it('says what is stuck and what happens next', () => {
+ const f = fixture(), id = f.group(), root = f.task(id).cards!.line!.messageId
const builder = f.add('Kai', id)
f.run({ type: 'work.assign', conversationId: id, agentId: builder })
- const effects = f.status(id, builder, 'done', `Merged ${PR}`)
- expect(effects.messages.filter(m => m.source?.kind === SHIP_KIND)).toEqual([])
+ f.status(id, builder, 'working', 'Started.')
+ expect(thread(f.status(id, builder, 'blocked', 'The build machine is offline.\nRestart it to unblock.'), root))
+ .toEqual(['Stuck: The build machine is offline. Next: River is looking at it.'])
})
- it('does not edit for a repeated status or a plain message', () => {
+ it('says the PM is looking at what is stuck when its chat has no coordinator, never the agent that is stuck', () => {
const f = fixture()
- const id = f.group()
+ const project = f.run({ type: 'project.create', name: 'Quiet', visibility: 'private', brief: '' }).result.projectId as string
+ const chat = f.state.projects!.find(p => p.id === project)!.leadConversationId
+ expect(f.state.conversations.find(c => c.id === chat)!.leadId ?? null).toBeNull()
+ const id = f.run({ type: 'conversation.create', projectId: project, title: 'Offline drafts', brief: 'Keep drafts.', checks: [] }).result.conversationId as string
+ const root = f.task(id).cards!.line!.messageId
const builder = f.add('Kai', id)
f.run({ type: 'work.assign', conversationId: id, agentId: builder })
f.status(id, builder, 'working', 'Started.')
- const seq = f.state.conversations.find(c => c.id === 'lead')!.reactionSeq
- expect(f.status(id, builder, 'working', 'Halfway.').edits ?? []).toEqual([])
- expect(f.status(id, builder, 'blocked', 'Waiting on CI.').edits ?? []).toEqual([])
- expect(f.run({ type: 'message.send', conversationId: id, text: 'Pushed.', replyTo: null, recipientIds: [] }, f.as(builder)).edits ?? []).toEqual([])
- expect(f.state.conversations.find(c => c.id === 'lead')!.reactionSeq).toBe(seq)
+ expect(thread(f.status(id, builder, 'blocked', 'The build machine is offline.'), root))
+ .toEqual(['Stuck: The build machine is offline. Next: the PM is looking at it.'])
})
- it('gives a step no line and leaves its task\'s line alone', () => {
- const f = fixture()
- const id = f.group()
+ it('tags the person a decision waits on, with its default', () => {
+ const f = fixture(), id = f.group(), root = f.task(id).cards!.line!.messageId
const builder = f.add('Kai', id)
f.run({ type: 'work.assign', conversationId: id, agentId: builder })
- f.status(id, builder, 'review', 'Ready.')
- const step = f.run({ type: 'conversation.create', title: 'Review', step: 'Review', reviewOf: id, brief: 'Review it.', checks: [] }, f.as(builder))
- .result.conversationId as string
- const reviewer = f.add('Ivy', step)
- const assigned = f.run({ type: 'work.assign', conversationId: step, agentId: reviewer }, f.as(builder))
- const finished = f.status(step, reviewer, 'done', 'Ready to merge: Yes.')
- for (const effects of [assigned, finished]) {
- expect(f.lines(effects)).toEqual([])
- expect(effects.edits ?? []).toEqual([])
- }
- expect(f.task(step).cards?.line).toBeUndefined()
- expect(f.task(id).cards?.line?.state).toBe('review')
+ const asked = f.status(id, builder, 'needs_human', 'Keep drafts for a week?', { ask: { personId: 'owner', options: ['A week', 'A month'], recommended: 1,
+ unblocks: 'how long drafts are kept' } })
+ expect(thread(asked, root)).toEqual(['@dee Your call: Keep drafts for a week? Default: A month.'])
+ })
+
+ it('says it is not building a cancelled task, with the reason', () => {
+ const f = fixture(), id = f.group(), root = f.task(id).cards!.line!.messageId
+ const builder = f.add('Kai', id)
+ f.run({ type: 'work.assign', conversationId: id, agentId: builder })
+ const cancelled = f.run({ type: 'work.cancel', conversationId: id, assignmentId: f.task(id).assignment!.id, reason: 'Dee chose the web version.' }, f.as(f.pm))
+ expect(thread(cancelled, root)).toEqual(['Not building this: Dee chose the web version.'])
})
- it('keeps one line through a task stopped and reassigned', () => {
+ it('links a proposal root instead of posting a second opening message, and adds no brief under the proposal', () => {
const f = fixture()
- const id = f.group()
- const first = f.add('Kai', id), second = f.add('Max', id)
- const lineId = f.lines(f.run({ type: 'work.assign', conversationId: id, agentId: first }))[0]!.id
- f.status(id, first, 'working', 'Started.')
- const stopped = f.run({ type: 'work.cancel', conversationId: id, assignmentId: f.task(id).assignment!.id, reason: 'Moving it on.' }, f.as(f.pm))
- expect(stopped.edits).toEqual([expect.objectContaining({ id: lineId, text: 'Offline drafts · stopped', source: expect.objectContaining({ state: 'stopped' }) })])
- const again = f.run({ type: 'work.assign', conversationId: id, agentId: second }, f.as(f.pm))
- expect(f.lines(again)).toEqual([])
- expect(again.edits).toEqual([expect.objectContaining({ id: lineId, source: expect.objectContaining({ state: 'planned', builderId: second }) })])
+ const created = f.run({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [], proposalMessageId: 'proposal' }, f.as(f.pm),
+ { proposal: { id: 'proposal', conversationId: 'lead', author: { kind: 'person', id: 'owner', name: owner.email, membershipGeneration: f.state.people[0]!.generation },
+ source: { kind: 'buddy-proposal', personId: 'owner', buddyId: 'former-buddy' } } })
+ expect(f.lines(created)).toEqual([])
+ expect(f.task(created.result.conversationId as string).cards?.line).toMatchObject({ messageId: 'proposal', conversationId: 'lead' })
+ expect(created.messages.filter(m => m.conversationId === 'lead')).toEqual([])
})
- it('follows a rename of the task', () => {
+ it('keeps the message a person asked in as the root, with them as requester', () => {
const f = fixture()
- const id = f.group()
+ const generation = f.state.people[0]!.generation
+ const request = { id: 'ask', conversationId: 'lead', author: { kind: 'person' as const, id: 'owner', name: owner.email, membershipGeneration: generation },
+ source: null, replyTo: null }
+ const created = f.run({ type: 'conversation.create', title: 'Who answered', brief: 'Show who answered.', checks: [], requestMessageId: 'ask' } as Command,
+ f.as(f.pm), { request } as Partial<CommandContext>)
+ const id = created.result.conversationId as string
+ expect(created.messages.filter(m => m.conversationId === 'lead')).toEqual([])
+ expect(f.task(id)).toMatchObject({ requesterId: 'owner', cards: { line: { messageId: 'ask', conversationId: 'lead' } } })
const builder = f.add('Kai', id)
- const lineId = f.lines(f.run({ type: 'work.assign', conversationId: id, agentId: builder }))[0]!.id
- const renamed = f.run({ type: 'conversation.rename', conversationId: id, title: 'Drafts survive a restart' })
- expect(renamed.edits).toEqual([expect.objectContaining({ id: lineId, text: 'Drafts survive a restart · planned',
- source: expect.objectContaining({ title: 'Drafts survive a restart' }) })])
+ expect(thread(f.run({ type: 'work.assign', conversationId: id, agentId: builder }), 'ask')).toEqual(['On it: Kai is building it.'])
})
- it('posts a private project\'s task line in that project\'s own chat', () => {
+ it('refuses a request message that is not a person\'s own top-level message in the project chat', () => {
+ const generation = (f: ReturnType<typeof fixture>) => f.state.people[0]!.generation
+ const cases = (f: ReturnType<typeof fixture>) => [
+ { id: 'ask', conversationId: 'elsewhere', author: { kind: 'person', id: 'owner', name: owner.email, membershipGeneration: generation(f) }, source: null, replyTo: null },
+ { id: 'ask', conversationId: 'lead', author: { kind: 'person', id: 'owner', name: owner.email, membershipGeneration: generation(f) }, source: null, replyTo: 'root' },
+ { id: 'ask', conversationId: 'lead', author: { kind: 'person', id: 'owner', name: owner.email, membershipGeneration: generation(f) }, source: { kind: 'system' }, replyTo: null },
+ { id: 'ask', conversationId: 'lead', author: { kind: 'agent', id: f.pm, name: 'River', membershipGeneration: 'g' }, source: null, replyTo: null },
+ undefined,
+ ]
+ for (const index of [0, 1, 2, 3, 4]) {
+ const f = fixture()
+ expect(() => f.run({ type: 'conversation.create', title: 'Who answered', brief: '', checks: [], requestMessageId: 'ask' } as Command, f.as(f.pm),
+ { request: cases(f)[index] } as Partial<CommandContext>)).toThrow(expect.objectContaining({ code: 'REQUEST_UNKNOWN' }))
+ }
+ })
+
+ it('keeps legacy roots readable and appends updates without rewriting their stored words', () => {
+ const f = fixture(), id = f.group(), builder = f.add('Kai', id)
+ f.run({ type: 'work.assign', conversationId: id, agentId: builder })
+ f.task(id).cards!.line!.messageId = 'old-root'
+ const effects = f.status(id, builder, 'review', 'Review this.')
+ expect(effects.messages.filter(m => m.thread === 'old-root')).toHaveLength(1)
+ })
+
+ it('puts private project messages only in their own project chat and excludes steps', () => {
const f = fixture()
const project = f.run({ type: 'project.create', name: 'Secret', visibility: 'private', brief: '' }).result.projectId as string
const chat = f.state.projects!.find(p => p.id === project)!.leadConversationId
- const id = f.group('Hidden work', { projectId: project })
- const builder = f.add('Kai', id)
- const [line] = f.lines(f.run({ type: 'work.assign', conversationId: id, agentId: builder }))
- expect(line!.conversationId).toBe(chat)
- expect(line!.conversationId).not.toBe('lead')
+ const created = f.run({ type: 'conversation.create', projectId: project, title: 'Hidden work', brief: 'Hidden.', checks: [] })
+ expect(f.lines(created)[0]!.conversationId).toBe(chat)
+ const parent = created.result.conversationId as string
+ const step = f.run({ type: 'conversation.create', projectId: project, title: 'Review', step: 'Review', reviewOf: parent, brief: 'Review.', checks: [] })
+ expect(f.lines(step)).toEqual([])
})
- it('posts nothing for a task that existed before lines until it changes, and nothing for a finished one', () => {
- const f = fixture()
- const id = f.group()
- const builder = f.add('Kai', id)
+ it('does not create a root for an unchanged legacy task on unrelated chat activity', () => {
+ const f = fixture(), id = f.group(), builder = f.add('Kai', id)
f.run({ type: 'work.assign', conversationId: id, agentId: builder })
- // As stored before this release: assigned, with no line.
delete f.task(id).cards
expect(f.lines(f.run({ type: 'message.send', conversationId: 'lead', text: 'Hello.', replyTo: null, recipientIds: [] }))).toEqual([])
- const [line] = f.lines(f.status(id, builder, 'review', 'Ready.'))
- expect(line).toMatchObject({ text: 'Offline drafts · in review', source: { state: 'review' } })
+ expect(f.lines(f.status(id, builder, 'review', 'Ready.'))[0]!.text).toBe("Let's build: Offline drafts")
})
})
diff --git a/backend/src/superTabs/taskLine.ts b/backend/src/superTabs/taskLine.ts
index d1d0529f1..707971408 100644
--- a/backend/src/superTabs/taskLine.ts
+++ b/backend/src/superTabs/taskLine.ts
@@ -1,31 +1,17 @@
import { agentDisplayName } from './agentNames.js'
import { isBuddyChat } from './buddies.js'
import { shippedNotice } from './buddyNews.js'
-import { isLeads, stableId, type Author, type CommandEffects, type Conversation, type MessageDraft, type SuperTabState, type WorkStatus } from './model.js'
+import { isLeads, stableId, type Author, type CommandEffects, type Conversation, type SuperTabState } from './model.js'
import { groupProject, projectsOf } from './projects.js'
import { isStep } from './steps.js'
import { usernameOf } from './usernames.js'
-/**
- * A task's one message in its project chat (Quiet Swarm, Dee, 11-02; docs/plans/2026-11-02-quiet-swarm-task-line-plan.md):
- * like a Slack bot's long job, one message that keeps itself current until it ships, its thread the task's own
- * conversation. It replaces the Shipped line. The server posts it when a task first has an Engineer and edits it in place
- * as the task moves, only when its words change; Desktop and the phone draw it from its source, an older client from its
- * text. It wakes nobody.
- */
+/** A task's ordinary opening message in the project chat. Its details and progress are replies; the root is never edited. */
export const TASK_LINE_KIND = 'task-line'
-/** `ready`: Done with its pull request, not merged yet; `shipped`: a merge of it recorded; `done`: Done with no pull request,
- * such as a review (PM, review of #2633). */
-export type TaskLineState = 'planned' | 'working' | 'waiting' | 'review' | 'ready' | 'shipped' | 'done' | 'stopped'
-/** What the line last showed, kept on its task (cards.ts GroupCards.line). `reported`: the assignment whose agent has sent a
- * status, so the line reads planned until then. */
-export interface TaskLine { messageId: string; conversationId: string; state: TaskLineState; title: string; builderId: string; answerFor?: string; reported?: string }
-/** A stored message's new words, written by the store over the row with that id (store.ts). */
-export interface MessageEdit { id: string; conversationId: string; text: string; source: Record<string, unknown> }
-
-const WORDS: Record<Exclude<TaskLineState, 'waiting'>, string> = { planned: 'planned', working: 'working', review: 'in review', ready: 'ready',
- shipped: 'shipped', done: 'done', stopped: 'stopped' }
-const MOVING: ReadonlySet<WorkStatus> = new Set(['working', 'blocked', 'reconciling', 'lost'])
+/** Where a task's root is, kept on its task (cards.ts GroupCards.line). A line stored before plain chat (2026-11-03) also
+ * holds state, title, builderId, answerFor and reported, which nothing reads; they go with their task when it archives, and
+ * this note can go once no open task predates 2026-11-03. */
+export interface TaskLine { messageId: string; conversationId: string }
/** A task of a project with work of its own: never a step, the project chat, a Buddy chat, the Leads chat, or a private
* conversation (chat only: it holds no work, and its words are its own). */
@@ -33,31 +19,10 @@ function lined(chats: ReadonlySet<string>, group: Conversation): boolean {
return !group.kind && !isLeads(group) && !isBuddyChat(group) && !isStep(group) && !group.audience && !chats.has(group.id)
}
-/** What [group]'s line shows now. [reported]: its agent sent a status in this command. */
-function drawn(group: Conversation, line: TaskLine | undefined, reported: boolean): Omit<TaskLine, 'messageId' | 'conversationId'> {
- const assignment = group.assignment!
- const status = assignment.status
- const heard = reported || line?.reported === assignment.id
- // Shipped only once a merge is recorded (conversation.merged), never on Done alone: the batch merges after the review passed.
- const state: TaskLineState = status === 'working' && !heard ? 'planned' : MOVING.has(status) ? 'working'
- : status === 'needs_human' ? 'waiting' : group.ledger?.mergedAt != null ? 'shipped' : status === 'review' ? 'review'
- : status === 'done' ? group.pullRequestUrls?.length ? 'ready' : 'done' : 'stopped'
- return { state, title: group.title, builderId: assignment.agentId, ...(state === 'waiting' && assignment.askedOf ? { answerFor: assignment.askedOf } : {}),
- ...(heard ? { reported: assignment.id } : {}) }
-}
-
-const same = (a: Omit<TaskLine, 'messageId' | 'conversationId'>, b: TaskLine) => a.state === b.state && a.title === b.title
- && a.builderId === b.builderId && a.answerFor === b.answerFor
-
-function words(state: SuperTabState, line: Omit<TaskLine, 'messageId' | 'conversationId'>): string {
- const asked = line.answerFor && usernameOf(state, line.answerFor)
- return `${line.title} · ${line.state === 'waiting' ? asked ? `waiting on ${asked}` : 'waiting' : WORDS[line.state]}`
-}
-
-/** The line's source, but for its kind (written beside each `source` as TASK_LINE_KIND, notices.test.ts reads it there). */
-function fields(group: Conversation, line: Omit<TaskLine, 'messageId' | 'conversationId'>): Record<string, unknown> {
- return { taskId: group.id, ...(group.number != null ? { number: group.number } : {}), title: line.title, state: line.state,
- ...(line.answerFor ? { answerFor: line.answerFor } : {}), builderId: line.builderId, ...(group.requesterId ? { requesterId: group.requesterId } : {}) }
+/** Only stable linkage is on the root. State belongs to replies, never its text or visible source. */
+function fields(group: Conversation): Record<string, unknown> {
+ return { taskId: group.id, ...(group.number != null ? { number: group.number } : {}), title: group.title,
+ ...(group.requesterId ? { requesterId: group.requesterId } : {}) }
}
/** The line's author: its project's coordinator, as the server's other notices in that chat are (tidy.ts), else whoever moved
@@ -68,43 +33,113 @@ function lineAuthor(state: SuperTabState, chat: Conversation, sender: Author | u
membershipGeneration: coordinator.membershipGeneration } : sender
}
-/** After a command: each task whose line's words changed has it posted (the first time its assignment changes) or edited,
- * and the chat's reaction counter moves for each edit, so a reader polling it reads the page shown again (reactions.ts).
- * A task that had work before lines gets its line at its next change; one that never changes again, none. */
-export function syncTaskLines(before: SuperTabState, effects: CommandEffects, reported: string | undefined, sender: Author | undefined, operationId: string): void {
+/** One line of an agent's result, ending as a sentence ends: what a thread reply quotes of it. */
+function sentence(text: string | null | undefined): string {
+ const first = (text ?? '').split(/\r?\n/).map(l => l.trim()).find(Boolean) ?? ''
+ return !first || /[.!?。!?]$/.test(first) ? first : `${first}.`
+}
+
+/** `PR #12` for a GitHub pull request, else its link; several joined as a person would write them. */
+function pullRequests(urls: readonly string[]): string {
+ const names = urls.map(url => { const n = url.match(/\/pull\/(\d+)(?:[/?#]|$)/)?.[1]; return n ? `PR #${n}` : url })
+ return names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` : names[0] ?? ''
+}
+
+const PULL_REQUEST = /https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/\d+/g
+
+/** The thread's reply for what changed in [group] in this command, in the words Dee approved (2026-11-03), or none. */
+function progress(state: SuperTabState, effects: CommandEffects, group: Conversation, previous: Conversation | undefined, pm: string): string | null {
+ const cards = group.cards?.pullRequests
+ const merged = cards?.length ? cards.filter(card => card.mergedAt !== undefined
+ && previous?.cards?.pullRequests?.find(was => was.url === card.url)?.mergedAt === undefined).map(card => card.url) : []
+ if (merged.length) return `Merged: ${pullRequests(merged)}. Ships in the next release.`
+ const assignment = group.assignment
+ const was = previous?.assignment
+ // Most tasks did not move in this command: they say nothing, and nothing more is read for them.
+ if (!assignment || (was?.id === assignment.id && was.status === assignment.status)) return null
+ const builder = agentDisplayName(state.agents, assignment.agentId)
+ if (was?.id !== assignment.id) return assignment.status === 'lost' ? null : `On it: ${builder} is building it.`
+ switch (assignment.status) {
+ case 'needs_human': {
+ const asked = assignment.askedOf && usernameOf(state, assignment.askedOf)
+ const decision = effects.decisions?.find(d => d.conversationId === group.id && d.assignmentId === assignment.id)
+ const fallback = decision && decision.options[decision.recommended]
+ return `${asked ? `@${asked} ` : ''}Your call: ${sentence(assignment.result) || 'a decision is needed.'}${fallback ? ` Default: ${sentence(fallback)}` : ''}`
+ }
+ case 'review': {
+ const linked = [...new Set([...assignment.result?.match(PULL_REQUEST) ?? [], ...group.pullRequestUrls ?? []])]
+ .filter(url => !group.cards?.pullRequests?.some(card => card.url === url && card.mergedAt !== undefined))
+ return linked.length ? `Ready for review: ${pullRequests(linked)}` : 'Ready for review.'
+ }
+ case 'working': return was.status === 'review' ? `Changes needed: ${sentence(assignment.result) || 'see the review.'} ${builder} is fixing it.` : null
+ case 'blocked': return `Stuck: ${sentence(assignment.result) || `${builder} cannot go on.`} Next: ${pm} is looking at it.`
+ case 'lost': return `Stuck: ${builder} stopped. Next: another engineer takes it over.`
+ case 'cancelled': case 'stopped': return `Not building this: ${sentence(assignment.result) || 'it was stopped.'}`
+ case 'done': return (group.pullRequestUrls ?? []).length || (group.cards?.pullRequests ?? []).length ? null : 'Done.'
+ default: return null
+ }
+}
+
+/** Whether [group] neither moved nor merged in this command: true for nearly every task on every command. */
+function still(group: Conversation, previous: Conversation): boolean {
+ const now = group.assignment, was = previous.assignment
+ if (now?.id !== was?.id || now?.status !== was?.status || group.brief !== previous.brief) return false
+ if (group.ledger?.mergedAt != null && previous.ledger?.mergedAt == null) return false
+ const cards = group.cards?.pullRequests
+ return !cards?.some(card => card.mergedAt !== undefined && previous.cards?.pullRequests?.find(old => old.url === card.url)?.mergedAt === undefined)
+}
+
+/** Keep task commands in their own conversation while presenting their work in one ordinary project-chat thread: its root,
+ * the brief as its first reply, then the PM's one reply per change (Dee, 2026-11-03). Agents' own posts stay in the task.
+ * Replies wake nobody. It runs on every command, so a task that did not move costs a few field reads; its chat, its author
+ * and a map of the conversations before are looked up only for one that did. */
+export function syncTaskLines(before: SuperTabState, effects: CommandEffects, sender: Author | undefined, operationId: string): void {
const state = effects.state
+ // The clone keeps the order, and a command appends new conversations: a task is at its own index before, unless one was
+ // removed; only then is the map built.
let earlier: Map<string, Conversation> | undefined
- const was = (id: string) => (earlier ??= new Map(before.conversations.map(c => [c.id, c]))).get(id)
- const chats = new Set(projectsOf(state).map(p => p.leadConversationId))
- for (const group of state.conversations) {
- if (!group.assignment || !lined(chats, group)) continue
- const line = group.cards?.line
- const now = drawn(group, line, reported === group.id)
- if (line) {
- if (same(now, line)) {
- if (now.reported !== line.reported) group.cards = { ...group.cards, line: { ...line, ...now } }
- continue
- }
- const chat = state.conversations.find(c => c.id === line.conversationId)
- if (!chat) continue
- effects.edits = [...effects.edits ?? [], { id: line.messageId, conversationId: chat.id, text: words(state, now), source: { kind: TASK_LINE_KIND, ...fields(group, now) } }]
- chat.reactionSeq = (chat.reactionSeq ?? 0) + 1
- group.cards = { ...group.cards, line: { messageId: line.messageId, conversationId: chat.id, ...now } }
- } else {
- const previous = was(group.id)?.assignment
- if (previous && previous.id === group.assignment.id && previous.status === group.assignment.status && previous.askedOf === group.assignment.askedOf) continue
- const chat = state.conversations.find(c => c.id === groupProject(state, group).leadConversationId)
- const author = chat && lineAuthor(state, chat, sender)
- if (!chat || !author) continue
- const message: MessageDraft = { id: stableId(operationId, TASK_LINE_KIND, group.id), conversationId: chat.id, author, text: words(state, now),
- replyTo: null, recipients: [], source: { kind: TASK_LINE_KIND, ...fields(group, now) } }
- effects.messages.push(message)
- group.cards = { ...group.cards, line: { messageId: message.id, conversationId: chat.id, ...now } }
- }
- // Only its first recorded merge is news, as the Shipped line was: a merge recorded again tells nobody again.
- if (now.state === 'shipped' && was(group.id)?.ledger?.mergedAt == null) {
- const news = sender && shippedNotice(state, group, sender, operationId)
- if (news) effects.messages.push(news)
+ let chats: ReadonlySet<string> | undefined
+ for (let index = 0; index < state.conversations.length; index++) {
+ const group = state.conversations[index]!
+ const same = before.conversations[index]
+ const previous = same?.id === group.id ? same : (earlier ??= new Map(before.conversations.map(c => [c.id, c]))).get(group.id)
+ if (previous && still(group, previous)) continue
+ if (!lined(chats ??= new Set(projectsOf(state).map(p => p.leadConversationId)), group)) continue
+ moved(state, effects, group, previous, sender, operationId)
+ }
+}
+
+/** [group] is new, or moved in this command: its root when it has none, then its details and progress replies. */
+function moved(state: SuperTabState, effects: CommandEffects, group: Conversation, previous: Conversation | undefined, sender: Author | undefined,
+ operationId: string): void {
+ const line = group.cards?.line
+ const chat = state.conversations.find(c => c.id === (line?.conversationId ?? groupProject(state, group).leadConversationId))
+ const coordinator = chat && lineAuthor(state, chat, sender)
+ if (!chat || !coordinator) return
+ // Stuck names the coordinator, never the agent that is stuck when there is no coordinator to sign.
+ const pm = chat.leadId && coordinator.kind === 'agent' && coordinator.id === chat.leadId ? coordinator.displayName ?? coordinator.name : 'the PM'
+ const reply = (id: string, words: string) => {
+ const root = group.cards!.line!.messageId
+ effects.messages.push({ id, conversationId: chat.id, author: coordinator, text: words, replyTo: root, thread: root, recipients: [], source: { kind: 'system' } })
+ }
+ if (!line) {
+ const proposal = group.ledger?.proposal
+ const root = proposal?.messageId ?? stableId(operationId, TASK_LINE_KIND, group.id)
+ group.cards = { ...group.cards, line: { messageId: root, conversationId: chat.id } }
+ // A proposal's root already has the proposal as its first reply; only a root the server posts gets the brief.
+ if (!proposal) {
+ const requester = state.people.find(p => p.id === group.requesterId)
+ effects.messages.push({ id: root, conversationId: chat.id,
+ author: requester ? { kind: 'person', id: requester.id, name: requester.email, membershipGeneration: requester.generation } : coordinator,
+ text: `Let's build: ${group.title}`, replyTo: null, recipients: [], source: { kind: TASK_LINE_KIND, ...fields(group) } })
+ if (group.brief) reply(stableId(operationId, 'task-details', group.id), group.brief)
}
+ } else if (previous && previous.brief !== group.brief && group.brief) reply(stableId(operationId, 'task-details', group.id), group.brief)
+ const text = progress(state, effects, group, previous, pm)
+ if (text) reply(stableId(operationId, 'task-progress', group.id), text)
+ // Only its first recorded merge is news to the Buddy, as the Shipped line was: a merge recorded again tells nobody again.
+ if (group.ledger?.mergedAt != null && previous?.ledger?.mergedAt == null) {
+ const news = sender && shippedNotice(state, group, sender, operationId)
+ if (news) effects.messages.push(news)
}
}
diff --git a/backend/src/worker.ts b/backend/src/worker.ts
index a0b51e3c6..1136d273f 100644
--- a/backend/src/worker.ts
+++ b/backend/src/worker.ts
@@ -18,6 +18,7 @@ import { startQueryStats } from './lib/queryStats.js'
import { startRetryStats } from './superTabs/retryStats.js'
import { releaseSchema } from './lib/db/schemaRelease.js'
import { startSwarmSweeps } from './superTabs/sweeps.js'
+import { requeueCompactedAgents } from './superTabs/agentTombstones.js'
import { startLegacyDrop } from './superTabs/migration/dropLegacyJob.js'
import { startDeliverySettle } from './superTabs/deliverySettle.js'
import { startDeliveryCompaction } from './superTabs/deliveryCompaction.js'
@@ -124,6 +125,11 @@ async function start(): Promise<void> {
// Decisions still waiting in work that was over before #2454 closed them where work ends: they counted toward the open
// limit and came back on a reopen (store.ts withdrawEndedDecisions). Remove in the release after the one that runs it.
logger.info('[swarm-decisions] closed waiting decisions of finished work', { closed: await swarms.withdrawEndedDecisions() })
+ // Agent tombstones compacted for good before #2150 get a purge time, so the sweeps purge them (superTabs/agentTombstones.ts).
+ // Remove in the release after the one that runs it.
+ // A failure leaves them compacted, as before, and never stops the worker starting.
+ await requeueCompactedAgents(prisma, Date.now()).then(queued => logger.info('[swarm-sweeps] queued compacted agent tombstones for purge', { queued }),
+ error => logger.warn('[swarm-sweeps] queuing compacted agent tombstones failed', { error: error instanceof Error ? error.message : String(error) }))
stopSweeps = startSwarmSweeps(prisma, undefined, () => swarms.workspaces.finishRemovals())
// The dead old state of migrated Swarms goes by itself, a few at a time (superTabs/migration/dropLegacyJob.ts).
stopLegacyDrop = startLegacyDrop(prisma)
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 6bd0340d2..8b263fc84 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -8,5 +8,5 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts',
'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',
'integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts',
'integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',
- 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
+ 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/swarmAgentTombstones.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.ts
index c54d06a61..66ba0399e 100644
--- a/cli/src/cable/cableHost.spec.ts
+++ b/cli/src/cable/cableHost.spec.ts
@@ -1029,7 +1029,7 @@ describe('Swarm cards', () => {
it('hands the wiring what a device asks, and answers nothing when the wiring has none', async () => {
const w = wiring({
- swarmCardsWanted: vi.fn(), swarmCardOpen: vi.fn(), swarmCardSide: vi.fn(), superTabSelected: vi.fn(), swarmSay: vi.fn(async () => ({ said: true as const })),
+ swarmCardsWanted: vi.fn(), swarmCardOpen: vi.fn(), swarmCardSide: vi.fn(), superTabSelected: vi.fn(), superTabThread: vi.fn(), swarmSay: vi.fn(async () => ({ said: true as const })),
swarmCardRecap: vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'hi', at: 1, none: false })),
})
const host = new DaemonCableHost(w)
@@ -1056,8 +1056,21 @@ describe('Swarm cards', () => {
expect(w.swarmCardSide).toHaveBeenLastCalledWith('st1', 'buddy')
await host.swarmSay('h1', 'ship it', 'buddy', 'pm1')
expect(w.swarmSay).toHaveBeenLastCalledWith('h1', 'ship it', 'buddy', 'pm1')
+ // A swarmThread dial leaves the thread on its face (with its chat flag), and the window closes (null) or opens (a root) a
+ // thread beside a conversation, with no project pick.
+ const left = vi.fn(async () => ({ tabId: 'st1', conversationId: 'c1' }))
+ const threaded = new DaemonCableHost(wiring({ swarmThreadLeave: left, superTabThread: w.superTabThread }))
+ expect(await threaded.swarmThreadLeave('st1', 'l1', 'buddy')).toEqual({ tabId: 'st1', conversationId: 'c1' })
+ expect(left).toHaveBeenLastCalledWith('st1', 'l1', 'buddy')
+ threaded.superTabThread('st1', 'c1', null)
+ expect(w.superTabThread).toHaveBeenLastCalledWith('st1', 'c1', null)
+ threaded.superTabThread('st1', 'c1', 'm9')
+ expect(w.superTabThread).toHaveBeenLastCalledWith('st1', 'c1', 'm9')
+ await host.swarmSay('h1', 'ship it', 'buddy', 'pm1', false, { thread: null, threaded: true })
+ expect(w.swarmSay).toHaveBeenLastCalledWith('h1', 'ship it', 'buddy', 'pm1', false, { thread: null, threaded: true })
const bare = new DaemonCableHost(wiring())
- bare.swarmCardsWanted(false); bare.swarmCardOpen('c1', 'st1', null); bare.swarmCardSide('st1', 'pm'); bare.superTabSelected('st1', 'p1')
+ expect(await bare.swarmThreadLeave('st1', 'l1')).toBeNull()
+ bare.swarmCardsWanted(false); bare.swarmCardOpen('c1', 'st1', null); bare.swarmCardSide('st1', 'pm'); bare.superTabSelected('st1', 'p1'); bare.superTabThread('st1', 'c1', null)
expect(await bare.swarmCardRecap('st1', 'l1')).toBeNull()
expect(await bare.swarmSay('h1', 'ship it')).toEqual({ said: false })
})
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index af8e0c4c7..f50015fa9 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -28,7 +28,7 @@ import type { FleetRouting } from '../services/fleet.js'
import { ServiceUnavailableError } from '../core/serviceHost.js'
import { PLAYER_STATES, type PlayerSession } from './playerLibrary.js'
-import type { CardChat, CardSide, LeadRecap, SaidOnCard, SwarmCard } from '../superTabs/cards.js'
+import type { CardChat, CardSide, LeadRecap, SaidOnCard, SayOptions, SwarmCard } from '../superTabs/cards.js'
import type { ActivitySnapshot, AppSwarms, SuperTabAsk, CableAgent, CableHost, CableMachine, CableMachineSource, CableSwarm, CableTile, DialStatus, OpenReason, RouteDecision } from './cableSession.js'
import type { WindowRoute } from './windowRoute.js'
import type { SelectionCommand, SelectionResult } from './windowSelection.js'
@@ -113,11 +113,15 @@ export interface CableHostWiring {
swarmCardOpen?: (session: string, tabId: string, leadId: string | null, chat?: CardChat) => void
/** A round dial that speaks swarmBuddy swiped to a side of a Swarm (spec 2026-10-29-round-dial-pm-buddy). */
swarmCardSide?: (tabId: string, side: CardSide) => void
+ /** A swarmThread dial left the thread on its face: the conversation whose thread the window should close, or null when it had none. */
+ swarmThreadLeave?: (tabId: string, leadId: string, chat?: CardChat) => Promise<{ tabId: string; conversationId: string } | null>
/** Words for a Lead that runs here, posted as the person in its Swarm chat; not `said` when the harness leads no project,
* `refused` with the backend's reason when it refused the post. */
- swarmSay?: (harnessId: string, text: string, chat?: CardChat, chatId?: string, reviewed?: boolean) => Promise<SaidOnCard>
+ swarmSay?: (harnessId: string, text: string, chat?: CardChat, chatId?: string, reviewed?: boolean, options?: SayOptions) => Promise<SaidOnCard>
/** A device picked a Lead: the window opens that Swarm tab and project. */
superTabSelected?: (superTabId: string, projectId: string, chat?: CardSide) => void
+ /** The dial's thread opened (a root) or closed (null) beside a conversation of a Swarm tab, with no project pick. */
+ superTabThread?: (superTabId: string, conversationId: string, threadRoot: string | null) => void
/** A finger on the dial's glass, in pieces, while it is down; `superTabId` when it scrolls that Swarm's chat (a Pro's Lead view). */
scrolled?: (phase: 'down' | 'move' | 'up', dy: number, velocity: number, superTabId?: string) => void
/** The dial came, went, or started taking an update — see CableSession's onDialStatus. */
@@ -561,16 +565,25 @@ export class DaemonCableHost implements CableHost {
this.wiring.swarmCardSide?.(tabId, side)
}
- swarmSay(harnessId: string, text: string, chat: CardChat = false, chatId?: string, reviewed = false): Promise<SaidOnCard> {
+ swarmSay(harnessId: string, text: string, chat: CardChat = false, chatId?: string, reviewed = false, options?: SayOptions): Promise<SaidOnCard> {
+ if (options) return this.wiring.swarmSay?.(harnessId, text, chat, chatId, reviewed, options) ?? Promise.resolve({ said: false })
const pinned: [chatId?: string, reviewed?: boolean] = chatId ? (reviewed ? [chatId, true] : [chatId]) : []
return this.wiring.swarmSay?.(harnessId, text, chat, ...pinned) ?? Promise.resolve({ said: false })
}
+ swarmThreadLeave(tabId: string, leadId: string, chat: CardChat = true): Promise<{ tabId: string; conversationId: string } | null> {
+ return this.wiring.swarmThreadLeave?.(tabId, leadId, chat) ?? Promise.resolve(null)
+ }
+
superTabSelected(superTabId: string, projectId: string, chat?: CardSide): void {
if (chat) this.wiring.superTabSelected?.(superTabId, projectId, chat)
else this.wiring.superTabSelected?.(superTabId, projectId)
}
+ superTabThread(superTabId: string, conversationId: string, threadRoot: string | null): void {
+ this.wiring.superTabThread?.(superTabId, conversationId, threadRoot)
+ }
+
/**
* The active tab when it is a Swarm, with its open project or '' when none is (its Chat with PM, a DM, or a Swarm
* not loaded yet); `fromDevice` when the announce was a device's own pick. A Swarm tab with no project used to read
diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.ts
index a51149d1a..b131549b2 100644
--- a/cli/src/cable/cableSession.spec.ts
+++ b/cli/src/cable/cableSession.spec.ts
@@ -3949,7 +3949,7 @@ describe('swarm cards', () => {
swarmCards: () => state.cards,
listSwarms: () => state.desk ?? desk(),
activeSwarmProject: () => state.open ?? null,
- swarmCardsWanted: vi.fn(), swarmCardOpen: vi.fn(), superTabSelected: vi.fn(),
+ swarmCardsWanted: vi.fn(), swarmCardOpen: vi.fn(), superTabSelected: vi.fn(), superTabThread: vi.fn(),
swarmCardRecap: vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'Shipped it.', at: 1792560000, none: false })),
...over,
})
@@ -5336,6 +5336,172 @@ describe('swarm cards', () => {
} finally { await session.stop() }
})
+ // ── swarmThread: 'v1' (the dial's thread face, spec 2026-11-03-dial-thread-face) ─────────────────────────────
+ describe('swarmThread', () => {
+ const THREAD = { ...BUDDY, swarmThread: 'v1' }
+ const ROUND_THREAD = { ...ROUND, swarmThread: 'v1' }
+ const inThread = { kind: 'lead' as const, id: 'lead-c1', name: 'Lead', working: false, thread: { root: 'm9', title: 'build it', replies: 2 } }
+ const threaded = () => withBuddy({ local: 'h1', sideChat: inThread, chat: { ...pmChat, thread: { root: 'm9', title: 'build it' } } })
+ const threadKeys = (l: Record<string, unknown>) => Object.fromEntries(Object.entries(l).filter(([k]) => k.startsWith('thread')))
+
+ it('a swarmThread dial is sent the face\'s thread and its recap\'s thread', async () => {
+ for (const [hello, expected] of [[THREAD, { thread: 'm9', threadTitle: 'build it', threadReplies: 2 }], [ROUND_THREAD, { thread: 'm9', threadTitle: 'build it' }]] as const) {
+ const host = cardHost({ cards: [card('st1', [threaded()])] }, {
+ swarmCardRecap: vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'on it', at: 7, none: false, chatId: 'lead-c1', thread: 'm9' })) })
+ const { session, port } = await connect(host)
+ try {
+ port.say(hello)
+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))
+ expect(threadKeys((ofType(port, 'supertab')[0].leads as Array<Record<string, unknown>>)[0])).toEqual(expected)
+ port.say({ t: 'supertab.recap.get', tab: 'st1', lead: 'lead1' })
+ await vi.waitFor(() => expect(ofType(port, 'supertab.recap')).toEqual([
+ { t: 'supertab.recap', tab: 'st1', lead: 'lead1', text: 'on it', at: 7, none: false, chatId: 'lead-c1', thread: 'm9' }]))
+ } finally { await session.stop() }
+ }
+ })
+
+ it('an older dial is sent no thread and its leave is ignored', async () => {
+ for (const hello of [BUDDY, ROUND]) {
+ const swarmThreadLeave = vi.fn(async () => ({ tabId: 'st1', conversationId: 'lead-c1' }))
+ const host = cardHost({ cards: [card('st1', [threaded()])] }, { swarmThreadLeave,
+ swarmCardRecap: vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'on it', at: 7, none: false, chatId: 'lead-c1', thread: 'm9' })) })
+ const { session, port } = await connect(host)
+ try {
+ port.say(hello)
+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))
+ expect(threadKeys((ofType(port, 'supertab')[0].leads as Array<Record<string, unknown>>)[0])).toEqual({})
+ port.say({ t: 'supertab.recap.get', tab: 'st1', lead: 'lead1' })
+ await vi.waitFor(() => expect(ofType(port, 'supertab.recap')).toHaveLength(1))
+ expect(ofType(port, 'supertab.recap')[0]).not.toHaveProperty('thread')
+ port.say({ t: 'supertab.thread.leave', tab: 'st1', lead: 'lead1' }); await settle(); await settle()
+ expect(swarmThreadLeave).not.toHaveBeenCalled()
+ expect(host.superTabSelected).not.toHaveBeenCalled()
+ expect(host.superTabThread).not.toHaveBeenCalled()
+ } finally { await session.stop() }
+ }
+ })
+
+ it('supertab.thread.leave asks the service and closes the window\'s thread', async () => {
+ const swarmThreadLeave = vi.fn(async (): Promise<{ tabId: string; conversationId: string } | null> => ({ tabId: 'st1', conversationId: 'lead-c1' }))
+ const host = cardHost({ cards: [card('st1', [threaded()])] }, { swarmThreadLeave })
+ const { session, port } = await connect(host)
+ try {
+ port.say(THREAD)
+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))
+ for (const bad of [{ tab: 'bad id', lead: 'lead1' }, { tab: 'st1', lead: 'x'.repeat(48) }, { tab: 'st1' }, { lead: 'lead1' }]) port.say({ t: 'supertab.thread.leave', ...bad })
+ await settle(); await settle()
+ expect(swarmThreadLeave).not.toHaveBeenCalled()
+ port.say({ t: 'supertab.thread.leave', tab: 'st1', lead: 'lead1' }); await settle(); await settle()
+ // The dial's own chat flag rides along (a swarmBuddy dial: 'buddy').
+ expect(swarmThreadLeave.mock.calls).toEqual([['st1', 'lead1', 'buddy']])
+ // A leave closes the thread in the window without a project pick.
+ expect(vi.mocked(host.superTabThread!).mock.calls).toEqual([['st1', 'lead-c1', null]])
+ expect(host.superTabSelected).not.toHaveBeenCalled()
+ // A Lead that was in no thread closes nothing.
+ swarmThreadLeave.mockResolvedValueOnce(null)
+ port.say({ t: 'supertab.thread.leave', tab: 'st1', lead: 'lead1' }); await settle(); await settle()
+ expect(host.superTabThread).toHaveBeenCalledTimes(1)
+ } finally { await session.stop() }
+ })
+
+ it('a voice post that starts a thread opens it in the window, for a swarmThread dial only', async () => {
+ const started = { said: true as const, thread: { tabId: 'st1', conversationId: 'lead-c1', root: 'm9' } }
+ for (const [hello, calls] of [[THREAD, [['st1', 'lead-c1', 'm9']]], [BUDDY, []]] as const) {
+ const swarmSay = vi.fn(async () => started)
+ const host = cardHost({ cards: [card('st1', [withBuddy({ local: 'h1', sideChat: { kind: 'lead', id: 'lead-c1', name: 'Lead', working: false } })])] },
+ { transcribe: vi.fn(async () => 'build it'), route: vi.fn(), swarmSay })
+ const { session, port } = await connect(host)
+ try {
+ port.say(hello); await settle()
+ voice(port, 'h1')
+ await vi.waitFor(() => expect(swarmSay).toHaveBeenCalled())
+ await settle(); await settle()
+ // A thread start is no project pick: nothing but the thread frame reaches the window.
+ expect(vi.mocked(host.superTabThread!).mock.calls).toEqual(calls)
+ expect(host.superTabSelected).not.toHaveBeenCalled()
+ } finally { await session.stop() }
+ }
+ })
+
+ it('a group face\'s thread is opened in the window the same way', async () => {
+ const swarmSay = vi.fn(async () => ({ said: true as const, thread: { tabId: 'st1', conversationId: 'g1', root: 'm9' } }))
+ const host = cardHost({ cards: [card('st1', [withBuddy({ local: 'h1', sideChat: { kind: 'group', id: 'g1', name: 'Fix login', working: false } })])] },
+ { transcribe: vi.fn(async () => 'status'), route: vi.fn(), swarmSay })
+ const { session, port } = await connect(host)
+ try {
+ port.say(THREAD); await settle()
+ voice(port, 'h1')
+ await vi.waitFor(() => expect(host.superTabThread).toHaveBeenCalled())
+ expect(vi.mocked(host.superTabThread!).mock.calls).toEqual([['st1', 'g1', 'm9']])
+ } finally { await session.stop() }
+ })
+
+ it('words to a Lead\'s terminal tile start no thread, but are held to the face\'s thread', async () => {
+ const swarmSay = vi.fn(async (..._args: unknown[]) => ({ said: true as const }))
+ const host = cardHost({ cards: [card('st1', [threaded()])] }, { transcribe: vi.fn(async () => 'build it'), route: vi.fn(), swarmSay,
+ appFocus: () => ({ machineId: 'm1', agentId: 'h1' }) })
+ const { session, port } = await connect(host)
+ try {
+ port.say(THREAD); await settle()
+ // The dial names a terminal that is no Lead; the window's focused pane is the Lead's.
+ voice(port, 't9')
+ await vi.waitFor(() => expect(swarmSay).toHaveBeenCalled())
+ expect(swarmSay.mock.calls[0][5]).toEqual({ thread: 'm9' })
+ voice(port, 'h1')
+ await vi.waitFor(() => expect(swarmSay).toHaveBeenCalledTimes(2))
+ expect(swarmSay.mock.calls[1][5]).toEqual({ thread: 'm9', threaded: true })
+ } finally { await session.stop() }
+ })
+
+ it('a recap.get right after the face\'s thread changes reads again', async () => {
+ const state = { cards: [card('st1', [withBuddy({ local: 'h1', sideChat: { kind: 'lead', id: 'lead-c1', name: 'Lead', working: false } })])] }
+ const swarmCardRecap = vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'A', at: 1, none: false, chatId: 'lead-c1' }))
+ const swarmThreadLeave = vi.fn(async () => ({ tabId: 'st1', conversationId: 'lead-c1' }))
+ const swarmSay = vi.fn(async () => ({ said: true as const, thread: { tabId: 'st1', conversationId: 'lead-c1', root: 'm9' } }))
+ const host = cardHost(state, { swarmCardRecap, swarmThreadLeave, swarmSay, transcribe: vi.fn(async () => 'build it'), route: vi.fn() })
+ const { session, port } = await connect(host)
+ const now = vi.spyOn(Date, 'now')
+ try {
+ now.mockReturnValue(5_000_000)
+ port.say(THREAD)
+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))
+ const get = async () => { port.say({ t: 'supertab.recap.get', tab: 'st1', lead: 'lead1' }); await settle(); await settle() }
+ await get(); await get()
+ expect(swarmCardRecap).toHaveBeenCalledTimes(1)
+ // A cards frame that puts the face in a thread.
+ state.cards = [card('st1', [withBuddy({ local: 'h1', sideChat: inThread })])]
+ await session.syncSwarmCards(true); await get()
+ expect(swarmCardRecap).toHaveBeenCalledTimes(2)
+ await get()
+ expect(swarmCardRecap).toHaveBeenCalledTimes(2)
+ // The dial leaving it.
+ port.say({ t: 'supertab.thread.leave', tab: 'st1', lead: 'lead1' }); await settle(); await settle()
+ await get()
+ expect(swarmCardRecap).toHaveBeenCalledTimes(3)
+ // Its words starting one.
+ voice(port, 'h1')
+ await vi.waitFor(() => expect(host.superTabThread).toHaveBeenCalledTimes(2))
+ await get()
+ expect(swarmCardRecap).toHaveBeenCalledTimes(4)
+ } finally { now.mockRestore(); await session.stop() }
+ })
+ })
+
+ it('an older dial\'s voice post starts no thread and opens nothing in the window', async () => {
+ for (const [hello, threaded] of [[BUDDY, false], [{ ...BUDDY, swarmThread: 'v1' }, true]] as const) {
+ const swarmSay = vi.fn(async (..._args: unknown[]) => ({ said: true as const }))
+ const host = cardHost({ cards: [card('st1', [withBuddy({ local: 'h1', sideChat: { kind: 'lead', id: 'lead-c1', name: 'Lead', working: false } })])] },
+ { transcribe: vi.fn(async () => 'build it'), route: vi.fn(), swarmSay })
+ const { session, port } = await connect(host)
+ try {
+ port.say(hello); await settle()
+ voice(port, 'h1')
+ await vi.waitFor(() => expect(swarmSay).toHaveBeenCalled())
+ expect(swarmSay.mock.calls[0].slice(5)).toEqual(threaded ? [{ thread: null, threaded: true }] : [])
+ } finally { await session.stop() }
+ }
+ })
+
// Review Focus 5: a post the backend refuses (a read-only Chat with PM, Buddies off, a Buddy chat not the reader's) was
// typed into the Lead's terminal instead.
const spoken = async (hello: Record<string, unknown>, leads: SwarmLead[], swarmSay: CableHost['swarmSay']) => {
diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.ts
index 2a85ef9bc..a5c161d15 100644
--- a/cli/src/cable/cableSession.ts
+++ b/cli/src/cable/cableSession.ts
@@ -171,16 +171,19 @@ const PICK_ECHO_MS = 2000
const CARDS_UNREAD_MS = 10_000
/** The recap frame, its text shortened (on a character) until the whole JSON fits what the Pro reads. A chat's recap names
* its chat (`chatId`), for a round dial that speaks swarmChat; any other is today's frame. */
-export function recapFrame(r: LeadRecap): Message {
- return fitText(r.text, (text) => ({ t: 'supertab.recap', tab: r.tabId, lead: r.leadId, text, at: r.at, none: r.none, ...(r.chatId ? { chatId: r.chatId } : {}) }))
+export function recapFrame(r: LeadRecap, threaded = false): Message {
+ return fitText(r.text, (text) => ({ t: 'supertab.recap', tab: r.tabId, lead: r.leadId, text, at: r.at, none: r.none, ...(r.chatId ? { chatId: r.chatId } : {}),
+ ...(threaded && r.thread ? { thread: r.thread } : {}) }))
}
/** A Lead's entry for a swarmChat dial: its face chat, `work` only for a working group (with that group's clock), and never
* `ask` or `stuck`, which a group's state used to raise. A Lead whose chat did not come through reads as its Lead chat. */
-function chatLead(l: SwarmLead, chat = l.chat): Record<string, unknown> {
+function chatLead(l: SwarmLead, chat = l.chat, threaded = false): Record<string, unknown> {
const working = chat?.kind === 'group' && chat.working
return { id: l.id, projectId: l.projectId, project: l.project, engine: l.engine, owner: l.owner, local: l.local,
state: working ? 'work' : 'done', order: l.order, ...(working && chat.since !== undefined ? { since: chat.since } : {}),
- ...(chat ? { chat: chat.kind, chatId: chat.id, chatName: chat.name } : {}) }
+ ...(chat ? { chat: chat.kind, chatId: chat.id, chatName: chat.name } : {}),
+ // A swarmThread dial: the thread the face is in (spec 2026-11-03-dial-thread-face).
+ ...(threaded && chat?.thread ? { thread: chat.thread.root, threadTitle: chat.thread.title, ...(chat.thread.replies !== undefined ? { threadReplies: chat.thread.replies } : {}) } : {}) }
}
/** A Lead's entry for a swarmBuddy dial (spec 2026-10-29-round-dial-pm-buddy): the face on the side it keeps, and while the
* Swarm has Buddies on, `buddies` and the reader's Buddy. With Buddies off it is a swarmChat dial's entry. */
@@ -188,8 +191,8 @@ function chatLead(l: SwarmLead, chat = l.chat): Record<string, unknown> {
function dialBuddy({ local: _local, ...drawn }: SwarmBuddy): Record<string, unknown> {
return { ...drawn }
}
-function buddyLead(l: SwarmLead): Record<string, unknown> {
- return { ...chatLead(l, l.sideChat ?? l.chat), ...(l.buddies ? { buddies: true } : {}), ...(l.buddies && l.buddy ? { buddy: dialBuddy(l.buddy) } : {}) }
+function buddyLead(l: SwarmLead, threaded = false): Record<string, unknown> {
+ return { ...chatLead(l, l.sideChat ?? l.chat, threaded), ...(l.buddies ? { buddies: true } : {}), ...(l.buddies && l.buddy ? { buddy: dialBuddy(l.buddy) } : {}) }
}
/** A Swarm agent's id as the backend makes it; a harness's id is a UUID, so the two never meet. */
const SWARM_AGENT_ID = /^[0-9a-f]{24}$/
@@ -212,7 +215,7 @@ function fitFrame(frame: { name: string; leads: Array<Record<string, unknown>> }
const fits = () => small() && (tokens === undefined || jsonTokens(frame) <= tokens)
type Named = { [key: string]: unknown }
const buddies: Array<[Named, string]> = frame.leads.map((l) => l.buddy as Named | undefined).filter((b) => b !== undefined).map((b) => [b, 'name'])
- const names: Array<[Named, string]> = [[frame, 'name'], ...frame.leads.flatMap((l) => ['project', 'owner', 'chatName'].filter((key) => key in l).map((key): [Named, string] => [l, key]))]
+ const names: Array<[Named, string]> = [[frame, 'name'], ...frame.leads.flatMap((l) => ['project', 'owner', 'chatName', 'threadTitle'].filter((key) => key in l).map((key): [Named, string] => [l, key]))]
for (const fields of [buddies, [...buddies, ...names]]) {
for (const bytes of NAME_CUTS) {
if (small()) break
@@ -377,7 +380,7 @@ import type { FormCommand, FormResult } from './windowForm.js'
import { deriveLongRecap, extendShortRecap } from '../lib/deviceRecap.js'
import type { TurnStatsFields } from './turnStats.js'
import type { Tier } from '../lib/notifyTier.js'
-import type { CardChat, CardSide, LeadNotice, LeadRecap, SaidOnCard, SwarmBuddy, SwarmCard, SwarmChat, SwarmLead } from '../superTabs/cards.js'
+import type { CardChat, CardSide, LeadNotice, LeadRecap, SaidOnCard, SayOptions, SwarmBuddy, SwarmCard, SwarmChat, SwarmLead } from '../superTabs/cards.js'
import { truncateUtf8 } from '../lib/deviceRecentTrim.js'
export interface RouteDecision {
@@ -420,13 +423,19 @@ export interface CableHost {
swarmCardOpen?(session: string, tabId: string, leadId: string | null, chat?: CardChat): void
/** A round dial that speaks swarmBuddy swiped to a side of a Swarm: the cards show that side's face. */
swarmCardSide?(tabId: string, side: CardSide): void
+ /** A swarmThread dial left the thread on its face: the cards forget it. The conversation whose thread the window should close, or
+ * null when the Lead's face was in none. */
+ swarmThreadLeave?(tabId: string, leadId: string, chat?: CardChat): Promise<{ tabId: string; conversationId: string } | null>
/** Words for a Lead that runs here: posted as the person in its Swarm chat. Not `said`: not a Lead, send the turn as before;
* `refused`: the backend refused the post, whose words are never typed anywhere instead. `chatId`: the chat they were
* spoken to, the only one they may be posted in. */
- swarmSay?(harnessId: string, text: string, chat?: CardChat, chatId?: string, reviewed?: boolean): Promise<SaidOnCard>
+ swarmSay?(harnessId: string, text: string, chat?: CardChat, chatId?: string, reviewed?: boolean, options?: SayOptions): Promise<SaidOnCard>
/** A device picked a Lead: the window opens that Swarm tab and project. `chat` (a round dial that speaks swarmBuddy): the
* reader's Buddy chat there ('buddy') or the project's Lead chat ('pm'), so the desktop follows the dial's side. */
superTabSelected?(superTabId: string, projectId: string, chat?: CardSide): void
+ /** The dial's thread opened (a root) or closed (null) beside a conversation of a Swarm tab: the window shows it without a project
+ * pick, raising or refocusing nothing. */
+ superTabThread?(superTabId: string, conversationId: string, threadRoot: string | null): void
/** The Swarm tab the window has on screen and the project open in it ('' when none is); null when the active tab is not a Swarm or there is no window. */
activeSwarmProject?(): { superTabId: string; projectId: string; conversationId?: string; threadRoot?: string; fromDevice: boolean } | null
appName(): string
@@ -754,6 +763,9 @@ export class CableSession {
* (`supertab.side`), each Lead carries `buddies` and the reader's Buddy, and the Buddy's word is a quiet notice. A
* swarmChat dial without it gets today's frames byte for byte. */
private swarmBuddy = false
+ /** `swarmThread: 'v1'` beside swarmChat (spec 2026-11-03-dial-thread-face): the dial draws the thread its face is in
+ * (`thread`, `threadTitle`, `threadReplies` on a Lead, `thread` on a recap) and leaves it with `supertab.thread.leave`. */
+ private swarmThread = false
/** `swarmReview: 'v1'` beside swarmChat (docs/device-voice-swarm-chat.md): the dial reviews every word for a Swarm chat
* before it is posted, so one that comes unreviewed is refused before it is transcribed. */
private swarmReview = false
@@ -770,14 +782,14 @@ export class CableSession {
/** For the greeting's log line: which capabilities this hello named, or nothing. */
private capabilitiesNamed(): string {
- const named = [this.swarmMembers && 'swarms', this.longRecap && 'recap', this.stepsActivity && 'activity', this.statsTurn && 'stats', this.playerCapable && 'player', this.superTabWaits && 'superTab', this.swarmCard && 'swarmCard', this.swarmChat && 'swarmChat', this.swarmBuddy && 'swarmBuddy', this.swarmReview && 'swarmReview']
+ const named = [this.swarmMembers && 'swarms', this.longRecap && 'recap', this.stepsActivity && 'activity', this.statsTurn && 'stats', this.playerCapable && 'player', this.superTabWaits && 'superTab', this.swarmCard && 'swarmCard', this.swarmChat && 'swarmChat', this.swarmBuddy && 'swarmBuddy', this.swarmThread && 'swarmThread', this.swarmReview && 'swarmReview']
.filter(Boolean)
return named.length ? ` caps ${named.join(',')}` : ''
}
private resetCapabilities(): void {
this.swarmMembers = this.longRecap = this.stepsActivity = this.statsTurn = this.playerCapable = this.superTabWaits = false
- this.swarmCard = this.swarmChat = this.swarmBuddy = this.swarmReview = false
+ this.swarmCard = this.swarmChat = this.swarmBuddy = this.swarmThread = this.swarmReview = false
this.dropCards()
this.seqOn = false
this.seq = 0
@@ -901,6 +913,8 @@ export class CableSession {
/** The chat on this dial's face for that agent's Swarm project as the person began to speak: the words go there or
* nowhere, and a Buddy chat's never reach a terminal (review of #2146). */
swarmFace?: SwarmFace;
+ /** The words are said from the dial's own Swarm face, not for a Lead's terminal tile: only these may start its thread. */
+ onFace?: true;
/** That Lead runs on another machine: named by its Swarm id, it has no terminal here. */
swarmRemote?: true } | null = null
private voiceSearch?: SelectionCommand
@@ -1346,6 +1360,7 @@ export class CableSession {
this.swarmCard = str('swarmCard') === 'v1'
this.swarmChat = this.swarmCard && str('swarmChat') === 'v1'
this.swarmBuddy = this.swarmChat && str('swarmBuddy') === 'v1'
+ this.swarmThread = this.swarmChat && str('swarmThread') === 'v1'
this.swarmReview = this.swarmChat && str('swarmReview') === 'v1'
this.wantCards(this.swarmCard)
this.seqOn = str('board') === 'pro'
@@ -1473,6 +1488,11 @@ export class CableSession {
}
return
}
+ case 'supertab.thread.leave': {
+ const tab = str('tab') ?? '', lead = str('lead') ?? ''
+ if (this.swarmThread && CARD_ID.test(tab) && CARD_ID.test(lead)) await this.threadLeave(tab, lead)
+ return
+ }
case 'swarm.select':
// Not answered here: the window switches, its desk changes, and the new `swarms` and ring
// pushes are the answer — the same shape as `machine.select`, minus the refusal, because the
@@ -1790,6 +1810,7 @@ export class CableSession {
this.voice = {
agentId,
...(swarmFace ? { swarmFace } : {}),
+ ...(dialFace ? { onFace: true as const } : {}),
...((swarmFace && agentId && !this.swarmLeadHere(agentId)) || swarmId ? { swarmRemote: true } : {}),
cmd: str('cmd'),
lang: str('lang') ?? this.host.voiceLang(),
@@ -2405,10 +2426,10 @@ export class CableSession {
const state = this.voiceDraft.create({ agentId: recipient, name: `${face.project} · ${face.name}`, text: transcript,
context: 'Swarm chat',
submit: async words => {
- const [chat] = this.sayArgs(face)
- const said = await say(recipient, turn.cmd ? `/${turn.cmd} ${words}` : words, chat, face.id, true)
+ const [chat] = this.sayArgs(face, turn.onFace)
+ const said = await say(recipient, turn.cmd ? `/${turn.cmd} ${words}` : words, chat, face.id, true, ...(this.swarmThread ? [this.sayOptions(face, turn.onFace)!] as const : []))
.catch((): SaidOnCard => ({ said: false }))
- if (said.said) return { ok: true }
+ if (said.said) { this.threadStarted(said); return { ok: true } }
return { ok: false, error: said.refused?.message ?? (face.kind === 'buddy' ? 'Could not reach your Buddy. Try again.' : 'Could not reach the Swarm. Try again.') }
} })
if (!state.ok) { await reply({ t: 'voice.error', message: state.error }); return }
@@ -2442,10 +2463,11 @@ export class CableSession {
// refused post for a read-only Chat with PM was typed into the PM's terminal.
if (turn.agentId && !carried && !selection?.ok && this.host.swarmSay) {
const face = turn.swarmFace
- const said = await this.host.swarmSay(agentId, instruction, ...this.sayArgs(face)).catch((): SaidOnCard => ({ said: false }))
+ const said = await this.host.swarmSay(agentId, instruction, ...this.sayArgs(face, turn.onFace)).catch((): SaidOnCard => ({ said: false }))
if (!current()) return
if (said.said) {
this.log(`cable: voice → Swarm chat of ${agentId.slice(0, 8)}`)
+ this.threadStarted(said)
await reply({ t: 'voice.transcript', routeId: '', text: transcript, agentId, agentName, needsConfirm: false })
return
}
@@ -2804,6 +2826,8 @@ export class CableSession {
/** The project this Pro itself picked last and when: the desktop's announce of it is no news, and a stale one of another is held off. */
private picked: { key: string; at: number } | null = null
private lastRecapGet: { key: string; at: number; read: Promise<LeadRecap | null> } | null = null
+ /** The root of the thread each Lead's face was last told to be in (`${tab}/${lead}`), so a change drops a recap read held for the other. */
+ private readonly leadThreads = new Map<string, string | undefined>()
/** `${lead} ${why}` of each recap that came back with nothing and was logged (recapMissed). */
private readonly recapsMissed = new Set<string>()
/** A swarmChat dial's alerts (`${tab}:${lead}`): the notice it was last given or shown as already there, and whether it
@@ -2845,15 +2869,24 @@ export class CableSession {
}
/** The extra arguments of words spoken to a Swarm Lead: the dial's chat flag, and the chat they were spoken to. */
- private sayArgs(face: SwarmFace | undefined): [chat?: CardChat, chatId?: string] {
+ private sayArgs(face: SwarmFace | undefined, onFace?: true): [chat?: CardChat, chatId?: string, reviewed?: boolean, options?: SayOptions] {
// A chat flag with no id means "the chat open on the desktop" to the Swarm service: a Pro sends neither unless its words
// were for the face chat it showed (voiceFaceOf), and then names that chat.
if (this.seqOn && !face) return []
const [chat] = this.chatFlag()
if (chat === undefined) return []
+ const options = this.sayOptions(face, onFace)
+ if (options) return [chat, face?.id, false, options]
return face ? [chat, face.id] : [chat]
}
+ /** A swarmThread dial's words are held to the thread on the face as the person began to speak (none included), and may start
+ * its thread only when spoken from the face (spec 2026-11-03-dial-thread-face). */
+ private sayOptions(face: SwarmFace | undefined, onFace?: true): SayOptions | undefined {
+ if (!this.swarmThread) return undefined
+ return { ...(face ? { thread: face.thread?.root ?? null } : {}), ...(onFace ? { threaded: true } : {}) }
+ }
+
/** The extra argument a swarmChat dial's requests carry ('buddy' for a swarmBuddy dial's); none for any other device, whose
* calls stay as they were. */
private chatFlag(): [] | [CardChat] { return this.swarmBuddy ? ['buddy'] : this.swarmChat ? [true] : [] }
@@ -2877,6 +2910,7 @@ export class CableSession {
this.focusLogged = ''
this.picked = null
this.lastRecapGet = null
+ this.leadThreads.clear()
this.notices.clear()
this.noticesReplay = true
if (this.openLead) this.host.swarmCardOpen?.(this.cardSession, this.openLead.tabId, null, ...this.chatFlag())
@@ -2939,8 +2973,14 @@ export class CableSession {
// The desk tab of the same Swarm, when the window has one: empty when it is closed or never opened it.
const tab = desk.find((s) => s.superTabId === card.id)?.id ?? ''
// A swarmBuddy dial follows the Swarm's side as the daemon's (review of #2218); no other device hears one.
+ // A face that went into or out of a thread: a recap read held for the other is not handed out again.
+ for (const l of card.leads.slice(0, SWARM_LEADS_MAX)) {
+ const key = `${card.id}/${l.id}`, root = (this.swarmBuddy ? l.sideChat ?? l.chat : l.chat)?.thread?.root
+ if (this.leadThreads.has(key) && this.leadThreads.get(key) !== root && this.lastRecapGet?.key === key) this.lastRecapGet = null
+ this.leadThreads.set(key, root)
+ }
const frame = { t: 'supertab', id: card.id, tab, name: card.name, count: card.count, ...(this.swarmBuddy ? { side: card.side ?? 'pm' } : {}),
- leads: card.leads.slice(0, SWARM_LEADS_MAX).map((l) => this.swarmBuddy ? buddyLead(l) : this.swarmChat ? chatLead(l) : { id: l.id, projectId: l.projectId, project: l.project,
+ leads: card.leads.slice(0, SWARM_LEADS_MAX).map((l) => this.swarmBuddy ? buddyLead(l, this.swarmThread) : this.swarmChat ? chatLead(l, l.chat, this.swarmThread) : { id: l.id, projectId: l.projectId, project: l.project,
engine: l.engine, owner: l.owner, local: l.local, state: l.state, order: l.order, ...(l.since === undefined ? {} : { since: l.since }) }) }
const buddiesDropped = fitFrame(frame, this.seqOn ? SWARM_TOKENS_MAX : undefined)
const key = JSON.stringify(frame)
@@ -3060,7 +3100,7 @@ export class CableSession {
if (!this.swarmCard || this.openLead?.tabId !== recap.tabId || this.openLead.leadId !== recap.leadId) return
// The service pushes a Lead's recap and each dial's face chat's apart: each device takes only the kind it asked for.
if (this.swarmChat !== (recap.chatId !== undefined) || this.swarmBuddy !== (recap.buddy === true)) return
- return this.queued(async () => { await this.send(recapFrame(recap)) })
+ return this.queued(async () => { await this.send(recapFrame(recap, this.swarmThread)) })
}
/** The Pro's three requests about Swarm cards. Ids that are not ids are ignored, like any frame this daemon cannot use. */
@@ -3101,7 +3141,7 @@ export class CableSession {
}
const recap = await this.lastRecapGet.read
// Nothing on a failure: the Pro keeps its "…" and asks again on the next open.
- if (recap) await this.queued(async () => { await this.send(recapFrame(recap)) })
+ if (recap) await this.queued(async () => { await this.send(recapFrame(recap, this.swarmThread)) })
}
/** A recap the dial asked for that came back with nothing leaves its face on the resting pet: said once per Lead and why,
@@ -3122,6 +3162,20 @@ export class CableSession {
else this.host.superTabSelected?.(tab, projectId)
}
+ /** Words said on a swarmThread dial that started its thread: the window opens it beside the chat, with no project pick. */
+ private threadStarted(said: SaidOnCard): void {
+ if (!said.said || !said.thread || !this.swarmThread) return
+ this.lastRecapGet = null
+ this.host.superTabThread?.(said.thread.tabId, said.thread.conversationId, said.thread.root)
+ }
+
+ /** The dial left the thread on its face: the cards forget it, and the window closes its thread pane (the project stays). */
+ private async threadLeave(tab: string, lead: string): Promise<void> {
+ const left = await this.host.swarmThreadLeave?.(tab, lead, this.chatFlag()[0]).catch((err: Error) => { this.log(`cable: thread leave failed (${err.message})`); return null })
+ this.lastRecapGet = null
+ if (left) this.host.superTabThread?.(left.tabId, left.conversationId, null)
+ }
+
/** The reader's Buddy in a project of a card, when Buddies are on and they have one there. */
private buddyIn(card: SwarmCard, projectId: string): boolean {
const lead = card.leads.find((l) => l.projectId === projectId)
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index ef4fb8bf8..a6d923318 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -1256,7 +1256,9 @@ export interface SwarmLead {
export interface SwarmCard { id: string; name: string; count: number; leads: SwarmLead[]; side?: 'buddy' }
/** A Lead's last message, for its card; `chatId` when it is the last message of the chat on the round dial's face, and
* `buddy` when that face is a swarmBuddy dial's (`CardChat` 'buddy'), so each dial takes only the recaps it asked for. */
-export interface LeadRecap { tabId: string; leadId: string; text: string; at: number; none: boolean; chatId?: string; buddy?: true }
+export interface LeadRecap { tabId: string; leadId: string; text: string; at: number; none: boolean; chatId?: string; buddy?: true
+ /** The root of the thread this recap is of, when the face was in one: a dial never takes it for the main chat's. */
+ thread?: string }
/** A project's places to chat (designs 2026-10-28-round-dial-swarm-chat and 2026-10-29-round-dial-pm-buddy): its Lead
* conversation, the reader's Buddy chat, and a group. A dial without swarmBuddy calls the Buddy chat `pm`, where the PM's
* private lines land since Buddies replaced Chat with PM; a swarmBuddy dial calls it `buddy` and hears the Buddy there. */
@@ -1264,7 +1266,10 @@ export type ChatKind = 'lead' | 'pm' | 'group' | 'buddy'
/** The chat on a project's face on the round dial: the Lead's, unless the window has the project's Buddy chat or a group
* open (or a swarmBuddy dial's side says the Buddy's). `working` only for a working group, `since` from one of its agents'
* turn here. */
-export interface SwarmChat { kind: ChatKind; id: string; name: string; working: boolean; since?: number }
+export interface SwarmChat { kind: ChatKind; id: string; name: string; working: boolean; since?: number
+ /** While the face is in a thread (the app's, or the one the dial's words started): its root, its title (first line, 80 bytes)
+ * and, when the read gives it, its reply count. Sent only to a dial that speaks swarmThread. */
+ thread?: { root: string; title: string; replies?: number } }
/** The newest message the project's Lead wrote in its Lead conversation or the reader's Buddy chat since the baseline (the
* dial's alert), or the reader's Buddy wrote in its chat (`buddy`, the quiet one). */
export interface LeadNotice { chat: 'lead' | 'pm' | 'buddy'; chatId: string; id: string; text: string; at: number }
@@ -1281,7 +1286,11 @@ export type CardSide = 'pm' | 'buddy'
export type CardChat = boolean | 'buddy'
/** What became of words spoken on a device for a Lead: posted, not a Lead here (`said` false, so the turn goes as before), or
* refused by the backend with its code and message, which must never become a terminal turn instead. */
-export type SaidOnCard = { said: true } | { said: false; refused?: { code: string; message: string } }
+/** `thread`: set when the post started the dial's thread (spec 2026-11-03-dial-thread-face), so the window opens it. */
+export type SaidOnCard = { said: true; thread?: { tabId: string; conversationId: string; root: string } } | { said: false; refused?: { code: string; message: string } }
+/** How words for a Lead relate to the dial's thread (a swarmThread dial only): `thread` is the root of the thread on its face when
+ * they were spoken, null for none, and the post is held to it; `threaded`: they were spoken from the face, so they may start one. */
+export interface SayOptions { thread?: string | null; threaded?: boolean }
/** The conversation the window has open in a Swarm tab. */
/** `fromDevice`: the window moved there because a device picked it (a dial's swipe to the next project), so the move is
* that device's own and keeps the side it keeps (spec 2026-10-29-round-dial-pm-buddy, newest wins). */
diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.ts
index 8ee1ff1bc..7cc5b3c35 100644
--- a/cli/src/lib/swarmSkills.spec.ts
+++ b/cli/src/lib/swarmSkills.spec.ts
@@ -115,7 +115,7 @@ describe('built-in Swarm skills', () => {
// The requests section (Lead's ruling for v2 G, the human leaderboard, 2026-10-27): the Lead's alone, in both modes, in a
// section of its own so other groups' edits to the Lead text merge cleanly.
const update = '- Codex\'s "Update available" screen on a worker is dismissed with Esc alone, never a number and Enter (on a misread row that runs the update) and never as a question for the owner. The host does it for Swarm agents when the screen is exactly that prompt; if one still waits on it, press Esc yourself.\n'
- const requests = '## Requests and Done\n- 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.\n- Right after you merge a group\'s pull request, record it: conversation.merged with the group and the PR link, and mergedAt for a merge you record later. The leaderboard counts the request as shipped at the merge, even if its work is lost or cancelled afterwards. Mark a group Done only after its pull request has merged.\n\n'
+ const requests = '## Requests and Done\n- 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. Name the message it came from as well: proposalMessageId for their Buddy\'s proposal, requestMessageId for their own message in the project chat. That message stays the task\'s one message in the chat; without one, the Swarm posts "Let\'s build: <title>" as them. The Swarm replies in its thread at each change, so you post no progress there.\n- Right after you merge a group\'s pull request, record it: conversation.merged with the group and the PR link, and mergedAt for a merge you record later. The leaderboard counts the request as shipped at the merge, even if its work is lost or cancelled afterwards. Mark a group Done only after its pull request has merged.\n\n'
// Last in the Default Lead text, which has no red flags: after a blank line, ending the text.
const requestsLast = `\n${requests.trimEnd()}\n`
// The shared-machine rules (Ken, 2026-10-28): the Builder's and the Reviewer's alone, in both modes, in a section of their
diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.ts
index dc71c0972..9b001b243 100644
--- a/cli/src/lib/swarmSkills.ts
+++ b/cli/src/lib/swarmSkills.ts
@@ -174,7 +174,7 @@ For large work, post the group plan and get the owner's ok before assigning; onc
- When a group's pull request merges, react 🚀 to the message that assigned its work.
## 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.
+- 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. Name the message it came from as well: proposalMessageId for their Buddy's proposal, requestMessageId for their own message in the project chat. That message stays the task's one message in the chat; without one, the Swarm posts "Let's build: <title>" as them. The Swarm replies in its thread at each change, so you post no progress there.
- Right after you merge a group's pull request, record it: conversation.merged with the group and the PR link, and mergedAt for a merge you record later. The leaderboard counts the request as shipped at the merge, even if its work is lost or cancelled afterwards. Mark a group Done only after its pull request has merged.
## Red flags
@@ -495,7 +495,7 @@ When the project owner asks in chat to switch this project's skills (Default or
- When a group's pull request merges, react 🚀 to the message that assigned its work.
## 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.
+- 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. Name the message it came from as well: proposalMessageId for their Buddy's proposal, requestMessageId for their own message in the project chat. That message stays the task's one message in the chat; without one, the Swarm posts "Let's build: <title>" as them. The Swarm replies in its thread at each change, so you post no progress there.
- Right after you merge a group's pull request, record it: conversation.merged with the group and the PR link, and mergedAt for a merge you record later. The leaderboard counts the request as shipped at the merge, even if its work is lost or cancelled afterwards. Mark a group Done only after its pull request has merged.
`,
dev: `---
@@ -658,9 +658,9 @@ You are one person's Buddy. Your start note says which: their one Buddy for ever
- As your owner's one Buddy, you send to the PM of a project they read yourself, and name it: never tell them to open a session just to send. If they read several and it is unclear which one this is for, ask them first. A session in one project sends only to that project's PM.
- Only when your owner asks (for example "send to the PM"), never on your own, and once for each time they ask.
- Write the goal, the scope and a priority (low, normal or high) from what you agreed. Put in only what your owner wants sent; anything private stays in your chat.
-- Send it with harness super-tab --tab TAB propose OPERATION_ID '{"conversationId":"CHAT","ownerMessageId":"MESSAGE","projectId":"PROJECT","goal":"...","scope":"...","priority":"normal"}', where MESSAGE is the id of your owner's message asking you to send it and PROJECT is the project's id from status (a session in one project leaves projectId out). One message sends one proposal, to one project.
+- Send it with harness super-tab --tab TAB propose OPERATION_ID '{"conversationId":"CHAT","ownerMessageId":"MESSAGE","projectId":"PROJECT","title":"Short name (at most 80 characters)","goal":"...","scope":"...","priority":"normal"}', where MESSAGE is the id of your owner's message asking you to send it and PROJECT is the project's id from status (a session in one project leaves projectId out). One message sends one proposal, to one project.
- To hand the PM a plan, spec, log or screenshot, attach it, up to 5 files of 10 MB each: add --attach PATH for a file inside your folder (as your owner's one Buddy, inside that project's folder under projects/), and "attachmentIds":["ID"] in the JSON for a file your owner sent in your chat (its id is on their message). Attach only what your owner wants sent; nothing from anywhere else.
-- The Swarm posts it in the project chat as one message to the PM, marked as on your owner's behalf. Tell your owner it went; the PM answers in the project chat.
+- The Swarm posts it in the project chat as one plain message from your owner, "Let's build: <title>", with your full proposal as the first reply in its thread, for the PM. Tell your owner it went; the PM answers in the project chat.
## Tell your owner how it goes
- The Swarm hands you, unasked, the project-chat lines that answer your owner's proposals, tag your owner, or say work they requested shipped, and a notice when work they requested is assigned. Nothing else of the project, and nothing once your owner stops reading it.
diff --git a/cli/src/services/devices.spec.ts b/cli/src/services/devices.spec.ts
index a3261a5e5..abe21cb19 100644
--- a/cli/src/services/devices.spec.ts
+++ b/cli/src/services/devices.spec.ts
@@ -726,6 +726,40 @@ describe('what the windows say, reaching the dial', () => {
expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardSide', tabId: 'st1', side: 'buddy' })
})
+ it('carries a thread on the recap, on a post that started one, and leaves a thread through the service', async () => {
+ const answers: Array<Record<string, unknown>> = [
+ { ok: true, text: 'on it', at: 3, none: false, chatId: 'lead-c1', thread: 'm9' },
+ { ok: true, text: 'on it', at: 3, none: false, chatId: 'lead-c1', thread: 'bad id' },
+ { ok: true, said: true, thread: { tabId: 'st1', conversationId: 'lead-c1', root: 'm9' } },
+ { ok: true, said: true, thread: { tabId: 'st1', conversationId: 7, root: 'm9' } },
+ { ok: true, conversationId: 'lead-c1' }, { ok: true }, { error: 'OWNER_REQUIRED' },
+ ]
+ const superTabRequest = vi.fn(async (_payload: Record<string, unknown>) => answers.shift()!)
+ const { core } = withRequest(superTabRequest)
+ expect(await seen.host.swarmCardRecap!('st1', 'lead1', true)).toEqual({ tabId: 'st1', leadId: 'lead1', text: 'on it', at: 3, none: false, chatId: 'lead-c1', thread: 'm9' })
+ expect(await seen.host.swarmCardRecap!('st1', 'lead1', true)).not.toHaveProperty('thread')
+ expect(await seen.host.swarmSay!('h1', 'build it', true)).toEqual({ said: true, thread: { tabId: 'st1', conversationId: 'lead-c1', root: 'm9' } })
+ expect(await seen.host.swarmSay!('h1', 'build it', true)).toEqual({ said: true })
+ answers.unshift({ ok: true, said: true })
+ await seen.host.swarmSay!('h1', 'build it', true, undefined, false, { threaded: true, thread: null })
+ expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardSay', harnessId: 'h1', text: 'build it', chat: true, threaded: true, thread: null })
+ answers.unshift({ ok: true, said: true })
+ await seen.host.swarmSay!('h1', 'build it', true, 'lead-c1', true, { thread: 'm9' })
+ expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardSay', harnessId: 'h1', text: 'build it', chat: true, chatId: 'lead-c1', reviewed: true, thread: 'm9' })
+ expect(await seen.host.swarmThreadLeave!('st1', 'lead1', 'buddy')).toEqual({ tabId: 'st1', conversationId: 'lead-c1' })
+ expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardThreadLeave', tabId: 'st1', leadId: 'lead1', chat: 'buddy' })
+ expect(await seen.host.swarmThreadLeave!('st1', 'lead1')).toBeNull()
+ expect(await seen.host.swarmThreadLeave!('st1', 'lead1')).toBeNull()
+ // The window is told to open a thread beside a conversation, or to close the open one: no project, so an older window ignores it.
+ seen.host.superTabThread!('st1', 'lead-c1', 'm9')
+ expect(vi.mocked(core.clients.sendLocal)).toHaveBeenLastCalledWith({ type: 'dial_super_tab', payload: { superTabId: 'st1', conversationId: 'lead-c1', threadRoot: 'm9', threadOnly: true } })
+ seen.host.superTabThread!('st1', 'lead-c1', null)
+ expect(vi.mocked(core.clients.sendLocal)).toHaveBeenLastCalledWith({ type: 'dial_super_tab', payload: { superTabId: 'st1', conversationId: 'lead-c1', threadRoot: null, threadOnly: true } })
+ // An ordinary pick is untouched.
+ seen.host.superTabSelected!('st1', 'proj1', 'buddy')
+ expect(vi.mocked(core.clients.sendLocal)).toHaveBeenLastCalledWith({ type: 'dial_super_tab', payload: { superTabId: 'st1', projectId: 'proj1', chat: 'buddy' } })
+ })
+
it('reads a recap through the service, cut to 1,500 bytes on a character; anything unusable is null', async () => {
const answers: Array<Record<string, unknown> | 'throw'> = [
{ ok: true, tabId: 'st1', leadId: 'lead1', text: 'é'.repeat(1000), at: 1792560000, none: false },
diff --git a/cli/src/services/devices.ts b/cli/src/services/devices.ts
index b9123a277..faaad09aa 100644
--- a/cli/src/services/devices.ts
+++ b/cli/src/services/devices.ts
@@ -174,7 +174,11 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
/** What became of words for a Lead, as the service answered: a refusal keeps its code and its message, cut to what a dial
* shows in a voice error. */
const saidOf = (answer: Record<string, unknown>): SaidOnCard => {
- if (answer.said === true) return { said: true }
+ if (answer.said === true) {
+ const t = answer.thread && typeof answer.thread === 'object' ? answer.thread as Record<string, unknown> : {}
+ const ids = [t.tabId, t.conversationId, t.root]
+ return ids.every((v): v is string => typeof v === 'string' && CHAT_ID.test(v)) ? { said: true, thread: { tabId: ids[0], conversationId: ids[1], root: ids[2] } } : { said: true }
+ }
const refused = answer.refused && typeof answer.refused === 'object' ? answer.refused as Record<string, unknown> : {}
if (typeof refused.code !== 'string' || typeof refused.message !== 'string') return { said: false }
return { said: false, refused: { code: refused.code, message: truncateUtf8(refused.message, VOICE_ERROR_BYTES) } }
@@ -259,17 +263,27 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
if (r.ok !== true || typeof r.text !== 'string' || typeof r.at !== 'number' || !Number.isInteger(r.at) || r.at < 0 || typeof r.none !== 'boolean') return null
if (chat && !(typeof r.chatId === 'string' && CHAT_ID.test(r.chatId))) return null
return { tabId, leadId, text: truncateUtf8(r.text, 1500), at: r.at, none: r.none, ...(chat ? { chatId: r.chatId as string } : {}),
- ...(chat === 'buddy' ? { buddy: true as const } : {}) }
+ ...(chat === 'buddy' ? { buddy: true as const } : {}), ...(chat && typeof r.thread === 'string' && CHAT_ID.test(r.thread) ? { thread: r.thread } : {}) }
},
swarmCardOpen: (session, tabId, leadId, chat) => { void askCards({ action: 'cardOpen', session, tabId, leadId, ...chatFlag(chat) }) },
swarmCardSide: (tabId, side) => { void askCards({ action: 'cardSide', tabId, side }) },
+ // The conversation whose thread the window should close, or null when the Lead's face was in none (or the service is away).
+ swarmThreadLeave: async (tabId, leadId, chat) => {
+ const r = await askCards({ action: 'cardThreadLeave', tabId, leadId, ...chatFlag(chat) })
+ return r.ok === true && typeof r.conversationId === 'string' && CHAT_ID.test(r.conversationId) ? { tabId, conversationId: r.conversationId } : null
+ },
// An error (no service, a refused post) is not `said`: the words go to the harness instead, never lost.
- swarmSay: async (harnessId, text, chat, chatId, reviewed) => saidOf(await askCards({ action: 'cardSay', harnessId, text, ...chatFlag(chat),
- ...(chatId ? { chatId, ...(reviewed ? { reviewed: true } : {}) } : {}) })),
+ swarmSay: async (harnessId, text, chat, chatId, reviewed, options) => saidOf(await askCards({ action: 'cardSay', harnessId, text, ...chatFlag(chat),
+ ...(chatId ? { chatId, ...(reviewed ? { reviewed: true } : {}) } : {}), ...(options?.threaded ? { threaded: true } : {}),
+ ...(options?.thread !== undefined ? { thread: options.thread } : {}) })),
// The Pro picked a Lead: the window opens that Swarm tab and project. Harmless with no window. `chat`, from a round dial
// that keeps sides: the Buddy chat or the Lead chat there; a window from before it opens the project's Lead chat.
superTabSelected: (superTabId, projectId, chat) =>
core.clients.sendLocal({ type: 'dial_super_tab', payload: { superTabId, projectId, ...(chat ? { chat } : {}) } }),
+ // The dial's thread opened (a root) or closed (null) beside a conversation, with no project pick: no `projectId`, so an older
+ // window ignores it, and the new one neither raises nor refocuses (spec 2026-11-03-dial-thread-face).
+ superTabThread: (superTabId, conversationId, threadRoot) =>
+ core.clients.sendLocal({ type: 'dial_super_tab', payload: { superTabId, conversationId, threadRoot, threadOnly: true } }),
scrolled: (phase, dy, velocity, superTabId) => core.clients.sendLocal({ type: 'dial_scroll', payload: { phase, dy, velocity, ...(superTabId ? { superTabId } : {}) } }),
// Gestures stay at this desk. The device inventory and its settings also reach the owner's other
// machines, through the encrypted device-management event.
diff --git a/cli/src/superTabs/cards.spec.ts b/cli/src/superTabs/cards.spec.ts
index eb4247e4a..e17ce5dc9 100644
--- a/cli/src/superTabs/cards.spec.ts
+++ b/cli/src/superTabs/cards.spec.ts
@@ -770,17 +770,18 @@ describe('SwarmCards open recaps and recap reads', () => {
/** `web` with its three chats at the given sequences, each conversation's page served from `pages` (newest first or not: the code orders);
* a thread's page from `${conversation}#${root}`. */
/** With `withBuddy`, the Swarm has Buddies on and the reader's Buddy (`y1`, "diego's Buddy" on Codex) is in their `web` chat. */
-function chatSwarm(pages: Record<string, unknown[] | (() => unknown[])>, withBuddy = false, delayMs = 0) {
+function chatSwarm(pages: Record<string, unknown[] | (() => unknown[])>, withBuddy = false, delayMs = 0, post?: () => { status: number; body: Record<string, unknown> }) {
const state = (lead = 1, pmSeq = 1, groupSeq = 1) => chats({
...(withBuddy ? { buddies: true, agents: [...chats().agents as object[], buddy()] } : {}),
conversations: [
conv('lead-web', 'a1', { projectId: 'web', lastMessageSequence: lead }), conv('lead-mobile', 'a2', { projectId: 'mobile' }),
pm({ lastMessageSequence: pmSeq, ...(withBuddy ? { agentIds: ['y1'] } : {}) }), group({ lastMessageSequence: groupSeq })] })
const t = setup({ t1: { lastChangedAt: 1, state: state() } }, { messages: path => {
- const id = /conversations\/([^/]+)\/messages/.exec(path)?.[1] ?? '', thread = /[?&]thread=([^&]+)/.exec(path)?.[1]
- const page = pages[thread ? `${id}#${thread}` : id] ?? []
- return { messages: typeof page === 'function' ? page() : page, next: null }
- }, delayMs })
+ const id = /conversations\/([^/]+)\/messages/.exec(path)?.[1] ?? '', thread = /[?&]thread=([^&]+)/.exec(path)?.[1], one = /[?&]messageId=([^&]+)/.exec(path)?.[1]
+ const page = pages[one ? `${id}@${one}` : thread ? `${id}#${thread}` : id] ?? []
+ const rows = typeof page === 'function' ? page() : page
+ return { messages: rows, next: null, ...((rows as { threads?: unknown }).threads ? { threads: (rows as { threads?: unknown }).threads } : {}) }
+ }, delayMs, post })
const move = async (lead: number, pmSeq = 1, groupSeq = 1) => { t.tabs.t1.lastChangedAt++; t.tabs.t1.state = state(lead, pmSeq, groupSeq); await t.cards.tick() }
const webLead = (cards = t.seen.at(-1)) => cards?.[0].leads.find(l => l.id === 'a1')
const reads = (conversation: string) => t.calls.filter(c => c.includes(`/conversations/${conversation}/messages`)).length
@@ -1267,6 +1268,348 @@ describe('SwarmCards chat recap and threads', () => {
})
})
+describe('the face thread', () => {
+ const posted = () => ({ status: 200, body: { success: true, data: { result: { messageId: 'm9' } } } })
+ const root = (id: string, text: string) => said(3, 'me', { id, text, author: { kind: 'person', id: 'me' }, thread: id })
+ const pages = {
+ 'lead-web#m9': [root('m9', 'build it\nplease'), said(5, 'a1', { text: 'on it', thread: 'm9' })],
+ 'lead-web#x1': Object.assign([root('x1', 'fix login\nmore'), said(5, 'a1', { text: 'done', thread: 'x1' })], { threads: [{ id: 'x1', replies: 2 }] }),
+ }
+ const onThread = { tabId: 't1', conversationId: 'lead-web', threadRoot: 'x1' }
+ const started = async (withBuddy = false) => {
+ const t = chatSwarm(pages, withBuddy, 0, posted)
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ return t
+ }
+ const posts = (t: { call: { mock: { calls: unknown[][] } } }) =>
+ t.call.mock.calls.filter(c => c[0] === 'POST').map(c => (c[2] as { command: { conversationId: string; replyTo: string | null } }).command)
+
+ it('words said at top level start the dial\'s thread', async () => {
+ const t = await started()
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ expect(await t.cards.say('h-a1', 'build it\nplease', true, undefined, false, { threaded: true })).toEqual({ said: true, thread: { tabId: 't1', conversationId: 'lead-web', root: 'm9' } })
+ expect(t.webLead()?.chat?.thread).toEqual({ root: 'm9', title: 'build it' })
+ expect(await t.cards.recap('t1', 'a1', true)).toMatchObject({ text: 'on it', chatId: 'lead-web', thread: 'm9' })
+ t.cards.want(false)
+ })
+
+ it('cuts the dial\'s thread title to 80 bytes on a character', async () => {
+ const t = await started()
+ await t.cards.say('h-a1', 'é'.repeat(60), true, undefined, false, { threaded: true })
+ expect(t.webLead()?.chat?.thread?.title).toBe('é'.repeat(40))
+ t.cards.want(false)
+ })
+
+ it('words said by a dial without swarmThread start no thread', async () => {
+ const t = await started()
+ expect(await t.cards.say('h-a1', 'build it', true)).toEqual({ said: true })
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ expect(await t.cards.recap('t1', 'a1', true)).not.toHaveProperty('thread')
+ t.cards.want(false)
+ })
+
+ it('swiping to the Buddy side forgets the PM\'s thread', async () => {
+ const t = await started(true)
+ await t.cards.say('h-a1', 'build it', 'buddy', undefined, false, { threaded: true })
+ expect(t.webLead()?.sideChat?.thread?.root).toBe('m9')
+ t.cards.side('t1', 'buddy')
+ t.cards.side('t1', 'pm')
+ expect(t.webLead()?.sideChat).not.toHaveProperty('thread')
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ t.cards.want(false)
+ })
+
+ it('starts no thread when the answer has no message id', async () => {
+ const t = chatSwarm(pages, false, 0, () => ({ status: 200, body: { success: true, data: {} } }))
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ expect(await t.cards.say('h-a1', 'hello', true, undefined, false, { threaded: true })).toEqual({ said: true })
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ t.cards.want(false)
+ })
+
+ it('words said in a thread reply in it and start nothing', async () => {
+ const t = await started()
+ t.cards.want(true, [], onThread)
+ expect(await t.cards.say('h-a1', 'more', true, undefined, false, { threaded: true })).toEqual({ said: true })
+ expect(posts(t).map(p => [p.conversationId, p.replyTo])).toEqual([['lead-web', 'x1']])
+ t.cards.want(false)
+ })
+
+ it('the app\'s thread is the face\'s, titled from its root and counted from the read', async () => {
+ const t = await started()
+ t.cards.want(true, [], onThread)
+ expect(t.webLead()?.chat?.thread).toMatchObject({ root: 'x1' })
+ expect(await t.cards.recap('t1', 'a1', true)).toMatchObject({ text: 'done', thread: 'x1' })
+ await vi.waitFor(() => expect(t.webLead()?.chat?.thread).toEqual({ root: 'x1', title: 'fix login', replies: 2 }))
+ t.cards.want(false)
+ })
+
+ it('a focus move clears the dial\'s thread', async () => {
+ const t = await started()
+ await t.cards.say('h-a1', 'build it', true, undefined, false, { threaded: true })
+ // The move the dial's own thread caused keeps it.
+ t.cards.want(true, [], { tabId: 't1', conversationId: 'lead-web', threadRoot: 'm9', fromDevice: true })
+ expect(t.webLead()?.chat?.thread?.root).toBe('m9')
+ t.cards.want(true, [], { tabId: 't1', conversationId: 'lead-web' })
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ expect(await t.cards.recap('t1', 'a1', true)).not.toHaveProperty('thread')
+ t.cards.want(false)
+ })
+
+ it('threadLeave clears the dial\'s thread and names the conversation', async () => {
+ const t = await started()
+ await t.cards.say('h-a1', 'build it', true, undefined, false, { threaded: true })
+ expect(t.cards.threadLeave('t1', 'a1')).toEqual({ tabId: 't1', conversationId: 'lead-web' })
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ expect(t.cards.threadLeave('t1', 'a1')).toBeNull()
+ // The app's thread too: the dial is off it until the app moves again.
+ t.cards.want(true, [], onThread)
+ expect(t.cards.threadLeave('t1', 'a1')).toEqual({ tabId: 't1', conversationId: 'lead-web' })
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ expect(t.cards.threadLeave('t1', 'zz')).toBeNull()
+ t.cards.want(false)
+ })
+
+ it('a thread lives only while its conversation is on the face', async () => {
+ const t = await started(true)
+ expect(await t.cards.say('h-a1', 'build it', 'buddy', undefined, false, { threaded: true })).toMatchObject({ said: true, thread: { root: 'm9' } })
+ expect(t.webLead()?.sideChat?.thread?.root).toBe('m9')
+ t.cards.side('t1', 'buddy')
+ expect(t.webLead()?.sideChat).toMatchObject({ kind: 'buddy' })
+ expect(t.webLead()?.sideChat).not.toHaveProperty('thread')
+ expect(await t.cards.recap('t1', 'a1', 'buddy')).not.toHaveProperty('thread')
+ t.cards.want(false)
+ })
+ const asMe = { threaded: true, thread: null as string | null }
+ const hidden = (t: Awaited<ReturnType<typeof started>>, over: Record<string, unknown> = {}) => t.cards.want(true, [], { tabId: 't1', conversationId: 'lead-web', ...over })
+
+ it('a hidden pane keeps the dial\'s thread: the same root announced again clears nothing, the app closing it does', async () => {
+ const t = await started()
+ await t.cards.say('h-a1', 'build it', true, undefined, false, asMe)
+ // The window announces the very thread it was asked to open, and keeps announcing it while the pane is hidden.
+ for (let i = 0; i < 3; i++) {
+ hidden(t, { threadRoot: 'm9' })
+ expect(t.webLead()?.chat?.thread).toEqual({ root: 'm9', title: 'build it' })
+ }
+ hidden(t, { threadRoot: 'x1' })
+ expect(t.webLead()?.chat?.thread?.root).toBe('x1')
+ t.cards.want(false)
+ const u = await started()
+ await u.cards.say('h-a1', 'build it', true, undefined, false, asMe)
+ hidden(u, { threadRoot: 'm9' })
+ hidden(u)
+ expect(u.webLead()?.chat).not.toHaveProperty('thread')
+ u.cards.want(false)
+ })
+
+ it('the window\'s selecting the thread\'s chat keeps the dial\'s thread until it opens it', async () => {
+ const t = await started()
+ await t.cards.say('h-a1', 'build it', true, undefined, false, asMe)
+ hidden(t)
+ expect(t.webLead()?.chat?.thread?.root).toBe('m9')
+ hidden(t, { threadRoot: 'm9' })
+ expect(t.webLead()?.chat?.thread?.root).toBe('m9')
+ hidden(t)
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ t.cards.want(false)
+ })
+
+ it('an unconfirmed dial thread ends 15 s later without the window naming it', async () => {
+ const t = await started()
+ await t.cards.say('h-a1', 'build it', true, undefined, false, asMe)
+ t.advance(14_999)
+ hidden(t)
+ expect(t.webLead()?.chat?.thread?.root).toBe('m9')
+ t.cards.want(true, [], null)
+ t.advance(1)
+ hidden(t)
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ t.cards.want(false)
+ })
+
+ it('another root named before confirmation ends the dial\'s thread', async () => {
+ const t = await started()
+ await t.cards.say('h-a1', 'build it', true, undefined, false, asMe)
+ hidden(t, { threadRoot: 'x1' })
+ expect(t.webLead()?.chat?.thread?.root).toBe('x1')
+ hidden(t)
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ t.cards.want(false)
+ })
+
+ it('a group face\'s thread is kept like a chat\'s', async () => {
+ const t = await started()
+ t.cards.want(true, [], { tabId: 't1', conversationId: 'g-web' })
+ expect(await t.cards.say('h-a1', 'status?', true, undefined, false, asMe)).toEqual({ said: true, thread: { tabId: 't1', conversationId: 'g-web', root: 'm9' } })
+ expect(t.webLead()?.chat).toMatchObject({ kind: 'group', thread: { root: 'm9' } })
+ t.cards.want(false)
+ })
+
+ it('words spoken on a thread face post there even if the face left it (reviewed), and are refused CHAT_MOVED when not reviewed', async () => {
+ const t = await started()
+ hidden(t, { threadRoot: 'x1' })
+ expect(t.webLead()?.chat?.thread?.root).toBe('x1')
+ t.cards.threadLeave('t1', 'a1')
+ const refused = await t.cards.say('h-a1', 'more', true, 'lead-web', false, { thread: 'x1' })
+ expect(refused).toEqual({ said: false, refused: { code: 'CHAT_MOVED', message: 'That chat is no longer on the dial. Say it again.' } })
+ expect(posts(t)).toEqual([])
+ expect(await t.cards.say('h-a1', 'more', true, 'lead-web', true, { thread: 'x1', threaded: true })).toEqual({ said: true })
+ expect(posts(t).map(p => [p.conversationId, p.replyTo])).toEqual([['lead-web', 'x1']])
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ t.cards.want(false)
+ })
+
+ it('words spoken on the main chat never land in a thread the app opened meanwhile', async () => {
+ const t = await started()
+ hidden(t, { threadRoot: 'x1' })
+ expect(await t.cards.say('h-a1', 'main', true, 'lead-web', false, asMe)).toMatchObject({ said: false, refused: { code: 'CHAT_MOVED' } })
+ expect(posts(t)).toEqual([])
+ expect(await t.cards.say('h-a1', 'main', true, 'lead-web', true, asMe)).toEqual({ said: true })
+ expect(posts(t).map(p => p.replyTo)).toEqual([null])
+ // Posted at top level, but the face is in the app's thread now: no thread of the dial's.
+ expect(t.webLead()?.chat?.thread?.root).toBe('x1')
+ t.cards.want(false)
+ })
+
+ it('a post whose face or focus moved meanwhile starts no thread', async () => {
+ let during: (() => void) | undefined
+ const t = chatSwarm(pages, true, 0, () => { during?.(); return posted() })
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ during = () => { during = undefined; t.cards.want(true, [], { tabId: 't1', conversationId: 'lead-web', fromDevice: true }) }
+ expect(await t.cards.say('h-a1', 'one', true, undefined, false, asMe)).toEqual({ said: true })
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ during = () => { during = undefined; t.cards.side('t1', 'buddy') }
+ expect(await t.cards.say('h-a1', 'two', 'buddy', undefined, false, asMe)).toEqual({ said: true })
+ t.cards.side('t1', 'pm')
+ expect(t.webLead()?.sideChat).not.toHaveProperty('thread')
+ during = () => { during = undefined; t.core.account.identity = vi.fn(async () => ({ accountId: 'sam', email: '[email protected]' })) as never; t.tabs.t1.lastChangedAt++; void t.cards.tick() }
+ await t.cards.say('h-a1', 'three', true, undefined, false, asMe)
+ await vi.waitFor(() => expect(t.cards.threadLeave('t1', 'a1')).toBeNull())
+ t.cards.want(false)
+ })
+
+ it('an old Desktop\'s re-announce after a leave does not pull the dial back, until the app names another thread', async () => {
+ const t = await started()
+ hidden(t, { threadRoot: 'x1' })
+ expect(t.cards.threadLeave('t1', 'a1')).toEqual({ tabId: 't1', conversationId: 'lead-web' })
+ hidden(t, { threadRoot: 'x1' })
+ hidden(t, { threadRoot: 'x1' })
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ hidden(t, { threadRoot: 'x2' })
+ expect(t.webLead()?.chat?.thread?.root).toBe('x2')
+ hidden(t, { threadRoot: 'x1' })
+ expect(t.webLead()?.chat?.thread?.root).toBe('x1')
+ // Closed in the app, then opened again: it is the app's.
+ t.cards.threadLeave('t1', 'a1')
+ hidden(t)
+ hidden(t, { threadRoot: 'x1' })
+ expect(t.webLead()?.chat?.thread?.root).toBe('x1')
+ t.cards.want(false)
+ })
+
+ it('a leave resolves the face by the dial\'s own chat flag and strips the focus thread only of that conversation', async () => {
+ const t = await started(true)
+ t.cards.side('t1', 'buddy')
+ await t.cards.say('h-a1', 'hello buddy', 'buddy', undefined, false, asMe)
+ const buddyId = t.webLead()?.sideChat?.id
+ expect(t.webLead()?.sideChat?.thread?.root).toBe('m9')
+ // The window is in another conversation's thread, set by the dial's own pick so the dial's thread stays.
+ t.cards.want(true, [], { tabId: 't1', conversationId: 'lead-web', threadRoot: 'x1', fromDevice: true })
+ expect(t.cards.threadLeave('t1', 'a1', 'buddy')).toEqual({ tabId: 't1', conversationId: buddyId })
+ expect(t.webLead()?.chat?.thread?.root).toBe('x1')
+ expect(t.webLead()?.sideChat).not.toHaveProperty('thread')
+ expect(t.cards.threadLeave('t1', 'a1', false)).toBeNull()
+ t.cards.want(false)
+ })
+
+ it('an app thread whose root is not on the page is titled by reading its root once, and keeps the last title', async () => {
+ const t = chatSwarm({ ...pages, 'lead-web#x2': Object.assign([said(5, 'a1', { text: 'reply', thread: 'x2' })], { threads: [{ id: 'x2', replies: 1 }] }),
+ 'lead-web@x2': [root('x2', 'old root\nmore')] }, false, 0, posted)
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ hidden(t, { threadRoot: 'x2' })
+ await t.cards.recap('t1', 'a1', true)
+ await vi.waitFor(() => expect(t.webLead()?.chat?.thread).toEqual({ root: 'x2', title: 'old root', replies: 1 }))
+ await t.move(2)
+ await t.cards.recap('t1', 'a1', true)
+ expect(t.webLead()?.chat?.thread?.title).toBe('old root')
+ expect(t.calls.filter(c => c.includes('messageId=x2'))).toHaveLength(1)
+ t.cards.want(false)
+ })
+
+ // Review of #2756 (ENGINEERING.md §6): a failed read of the root was dropped silently and never tried again, so the face kept a
+ // blank title. It is logged, by its code and nothing of the thread, and read again after a wait.
+ it('a failed read of an app thread\'s root is logged and read again after a wait', async () => {
+ let fails = true
+ const t = chatSwarm({ ...pages, 'lead-web#x2': Object.assign([said(5, 'a1', { text: 'reply', thread: 'x2' })], { threads: [{ id: 'x2', replies: 1 }] }),
+ 'lead-web@x2': () => { if (fails) throw Object.assign(new Error('busy'), { code: 'SERVICE_UNAVAILABLE' }); return [root('x2', 'old root')] } }, false, 0, posted)
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ hidden(t, { threadRoot: 'x2' })
+ await t.cards.recap('t1', 'a1', true)
+ await vi.waitFor(() => expect(t.calls.filter(c => c.includes('messageId=x2'))).toHaveLength(1))
+ const lines = t.log.mock.calls.map(c => String(c[0])).filter(l => l.includes('thread'))
+ expect(lines).toHaveLength(1)
+ expect(lines[0]).not.toContain('x2')
+ // Within the wait it is not read again; after it, it is, and the face takes the title.
+ await t.move(2)
+ await t.cards.recap('t1', 'a1', true)
+ expect(t.calls.filter(c => c.includes('messageId=x2'))).toHaveLength(1)
+ fails = false
+ t.advance(60_000)
+ await t.move(3)
+ await t.cards.recap('t1', 'a1', true)
+ await vi.waitFor(() => expect(t.webLead()?.chat?.thread?.title).toBe('old root'))
+ expect(t.calls.filter(c => c.includes('messageId=x2'))).toHaveLength(2)
+ t.cards.want(false)
+ })
+
+ it('a thread of a reader that was not signed in when the read ended is not learned', async () => {
+ const t = await started()
+ hidden(t, { threadRoot: 'x1' })
+ const pending = t.cards.recap('t1', 'a1', true)
+ vi.mocked(t.core.account.identity).mockResolvedValue({ accountId: 'sam', email: '[email protected]' } as never)
+ t.tabs.t1.lastChangedAt++
+ await t.cards.tick()
+ await pending
+ expect(t.webLead()?.chat?.thread).not.toHaveProperty('title', 'fix login')
+ t.cards.want(false)
+ })
+
+ it('forgets the dial\'s thread when the device is gone, another person signs in, or the Swarm is lost', async () => {
+ const t = await started()
+ await t.cards.say('h-a1', 'build it', true, undefined, false, asMe)
+ t.cards.want(false)
+ const shown = t.seen.length
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen.length).toBeGreaterThan(shown))
+ expect(t.webLead()?.chat).not.toHaveProperty('thread')
+ t.cards.want(false)
+
+ const u = await started()
+ await u.cards.say('h-a1', 'build it', true, undefined, false, asMe)
+ vi.mocked(u.core.account.identity).mockResolvedValue({ accountId: 'sam', email: '[email protected]' } as never)
+ u.tabs.t1.lastChangedAt++
+ await u.cards.tick()
+ expect(u.webLead()?.chat).not.toHaveProperty('thread')
+ u.cards.want(false)
+
+ const v = await started()
+ await v.cards.say('h-a1', 'build it', true, undefined, false, asMe)
+ const kept = v.tabs.t1
+ delete v.tabs.t1
+ await v.cards.tick()
+ v.tabs.t1 = kept
+ v.tabs.t1.lastChangedAt++
+ await v.cards.tick()
+ expect(v.webLead()?.chat).not.toHaveProperty('thread')
+ v.cards.want(false)
+ })
+})
+
describe('SwarmCards Buddy side', () => {
const buddySays = [said(1, 'a1', { text: 'from the PM' }), said(2, 'y1', { text: 'from the Buddy' }), said(3, 'me', { author: { kind: 'person', id: 'me' }, text: 'mine' })]
diff --git a/cli/src/superTabs/cards.ts b/cli/src/superTabs/cards.ts
index b2386accb..c1caa28f9 100644
--- a/cli/src/superTabs/cards.ts
+++ b/cli/src/superTabs/cards.ts
@@ -26,12 +26,14 @@ import { buddyAvatar } from './buddyAvatar.js'
type Json = Record<string, unknown>
/** The cards' shapes are the core's contract with the Swarm (core/api.ts), which the core declares and the Swarm imports. */
-import type { CardChat, CardFocus, CardSide, ChatKind, LeadNotice, LeadRecap, LeadState, SaidOnCard, SwarmBuddy, SwarmCard, SwarmChat, SwarmLead } from '../core/api.js'
-export type { CardChat, CardFocus, CardSide, LeadNotice, LeadRecap, LeadState, SaidOnCard, SwarmBuddy, SwarmCard, SwarmChat, SwarmLead } from '../core/api.js'
+import type { CardChat, CardFocus, CardSide, ChatKind, LeadNotice, LeadRecap, LeadState, SaidOnCard, SayOptions, SwarmBuddy, SwarmCard, SwarmChat, SwarmLead } from '../core/api.js'
+export type { CardChat, CardFocus, CardSide, LeadNotice, LeadRecap, LeadState, SaidOnCard, SayOptions, SwarmBuddy, SwarmCard, SwarmChat, SwarmLead } from '../core/api.js'
const MAX_CARDS = 16, MAX_LEADS = 12, NAME_BYTES = 48, RECAP_BYTES = 1500, MAX_LIST_PAGES = 10, MAX_RECAPS_IN_FLIGHT = 2
/** The longest a dial's recap read waits on the one before it. */
const ASK_WAIT_MS = 10_000
+/** A failed read of a dial thread's first message is tried again after this, doubling, at most ROOT_READ_TRIES times in all. */
+const ROOT_READ_WAIT_MS = 10_000, ROOT_READ_TRIES = 5
/** The Pro keeps an id in 48 bytes with its NUL: 47 characters at most reach it. */
const ID_BYTES = 47
export const cardId = (v: unknown): v is string => identifier(v) && v.length <= ID_BYTES
@@ -131,7 +133,7 @@ function buddyOf(agents: Json[], chat: Json, me: string | undefined, local: (a:
* harness and whether it is in a turn (null: not here); `me` is the signed-in person's id, so a Lead on someone else's
* machine names that owner (people[] has an email, which is the name a Swarm shows a person by).
*/
-export function leadsOf(state: Json, machineId: string, live: (harnessId: string) => { inTurn: boolean; since?: number } | null, me?: string, focus?: string, side?: CardSide): { count: number; leads: SwarmLead[] } {
+export function leadsOf(state: Json, machineId: string, live: (harnessId: string) => { inTurn: boolean; since?: number } | null, me?: string, focus?: string, side?: CardSide, thread?: (conversationId: string) => SwarmChat['thread']): { count: number; leads: SwarmLead[] } {
const agents = list(state.agents), conversations = list(state.conversations), people = list(state.people)
const buddies = state.buddies === true
// An old tab has no `projects`: its one project is the tab itself, `lead`, led by the conversation `lead`.
@@ -173,7 +175,11 @@ export function leadsOf(state: Json, machineId: string, live: (harnessId: string
const ownerId = agent.machineOwnerId
const owner = me && typeof ownerId === 'string' && ownerId !== me ? people.find(p => p.id === ownerId) : undefined
const projectId = projectKey(project)
- const chatOf = (face: Face | null): SwarmChat | undefined => face ? faceChat(face, String(agent.id), agents, me, turnHere) : undefined
+ const chatOf = (face: Face | null): SwarmChat | undefined => {
+ if (!face) return undefined
+ const inThread = thread?.(face.conversation.id as string)
+ return { ...faceChat(face, String(agent.id), agents, me, turnHere), ...(inThread ? { thread: inThread } : {}) }
+ }
const chat = chatOf(faceOf(conversations, projectId, lead, focus, me, buddies))
const buddyChat = buddies ? buddyChatOf(conversations, projectId, me) : undefined
const sideChat = buddies ? chatOf(sideFaceOf(conversations, projectId, lead, focus, me, side)) : undefined
@@ -244,6 +250,8 @@ const recapKey = (tabId: string, leadId: string, chatId?: string) => chatId ===
* the face is apart from its chat. */
const cachedKey = (tabId: string, leadId: string, target: Pick<Target, 'chatId' | 'thread'>, chat: CardChat) =>
`${recapKey(tabId, leadId, target.chatId)}${target.thread === undefined ? '' : `#${target.thread}`}${chat === 'buddy' ? ':buddy' : ''}`
+/** A thread's title on the dial: the first line, at most 80 bytes. */
+const titleOf = (text: string): string => cut(text.split('\n')[0].trim(), 80)
const isSide = (v: unknown): v is CardSide => v === 'pm' || v === 'buddy'
/** Spec 2026-11-02-poll-cost Part 4.3: the list was read every 5 s whatever changed (prod 2026-11-02: about 200 list reads a
* minute). While the server says it pushes this account's Swarm changes (`swarm_changed` naming none, repeated every 4
@@ -300,6 +308,14 @@ export class SwarmCards {
private inChat = new WeakSet<LeadNotice>()
/** The side a swarmBuddy dial swiped to, per Swarm; cleared by the window's next focus change (the newest wins). */
private sides = new Map<string, CardSide>()
+ /** The thread the dial's own words started, per Swarm (spec 2026-11-03-dial-thread-face); cleared like `sides`. */
+ private threads = new Map<string, { conversationId: string; root: string; title: string; at: number; opened?: true }>()
+ /** Title and reply count of the app's threads, as the recap reads gave them (`${tab}/${root}`). */
+ private titles = new Map<string, { title: string; replies?: number; looked?: true; failures?: number; retryAt?: number }>()
+ /** The thread the dial last left, per Swarm: an older Desktop that announces it again does not pull the dial back into it. */
+ private left = new Map<string, { conversationId: string; root: string }>()
+ /** Bumped at each refocus of the window, so a post that was out while it moved knows it did (spec 2026-11-03-dial-thread-face). */
+ private focusGen = 0
/** Watched conversations whose last read failed, so a run of failures is logged once. */
private failed = new Set<string>()
private readonly reads: SwarmReads
@@ -327,7 +343,7 @@ export class SwarmCards {
this.stopNotices?.()
this.stopNotices = null
this.pushUntil = 0
- this.opened.clear(); this.openBy.clear(); this.include = []; this.focus = null; this.sides.clear()
+ this.opened.clear(); this.openBy.clear(); this.include = []; this.focus = null; this.sides.clear(); this.threads.clear(); this.titles.clear(); this.left.clear()
// A device that attaches again starts a fresh baseline: what was said while none was here never alerts.
this.seen.clear(); this.forgetNotices()
return
@@ -335,14 +351,35 @@ export class SwarmCards {
const wanted = include.filter(cardId).slice(0, MAX_CARDS)
const moved = wanted.join(',') !== this.include.join(',')
this.include = wanted
- const next = focus && cardId(focus.tabId) && cardId(focus.conversationId)
+ let next: Focus | null = focus && cardId(focus.tabId) && cardId(focus.conversationId)
? { tabId: focus.tabId, conversationId: focus.conversationId, ...(cardId(focus.threadRoot) ? { threadRoot: focus.threadRoot } : {}),
...(focus.fromDevice === true ? { fromDevice: true as const } : {}) } : null
+ // A thread the dial left stays left until the window names another conversation or another root (an older Desktop announces
+ // it again): its root is not the focus's.
+ for (const [tabId, gone] of [...this.left]) {
+ if (!(next?.tabId === tabId && next.conversationId === gone.conversationId && next.threadRoot === gone.root)) this.left.delete(tabId)
+ else { const { threadRoot: _, ...rest } = next; next = rest }
+ }
// A thread opened or closed beside the conversation moves the face too.
const refocused = `${next?.tabId}/${next?.conversationId}/${next?.threadRoot}` !== `${this.focus?.tabId}/${this.focus?.conversationId}/${this.focus?.threadRoot}`
+ const before = this.focus
this.focus = next
// The desktop's own move clears the dial's side; the move a dial's pick caused is the dial's, and keeps it.
- if (refocused && !next?.fromDevice) this.sides.clear()
+ // The dial's thread outlives the window's announce of that very thread (same conversation, same root), which a hidden pane keeps
+ // making; another conversation, another root, or no root (the app closed it) ends it.
+ if (refocused) this.focusGen++
+ // The window opens the dial's thread only after selecting its chat (up to 10 s): a no-root announce of that chat is not the
+ // person closing it until the window has named the root once, or 15 s have passed.
+ const mine = next && this.threads.get(next.tabId)
+ if (mine && next!.conversationId === mine.conversationId && next!.threadRoot === mine.root) mine.opened = true
+ if (refocused && !next?.fromDevice) {
+ const own = mine
+ const confirmed = !!next && !!own && own.conversationId === next.conversationId &&
+ (own.root === next.threadRoot || (next.threadRoot === undefined && !own.opened && this.now() - own.at < 15_000))
+ // Only the root appearing beside the same conversation is no move of the person's: the dial's side stays.
+ if (!(confirmed && before?.tabId === next!.tabId && before.conversationId === next!.conversationId)) this.sides.clear()
+ for (const tabId of [...this.threads.keys()]) if (!(confirmed && tabId === next!.tabId)) this.threads.delete(tabId)
+ }
// Other Swarms to show first: the list is read for them now, whatever the server pushes.
if (moved) this.listTold = true
if (this.timer) {
@@ -374,7 +411,37 @@ export class SwarmCards {
side(tabId: string, side: CardSide): void {
if (!cardId(tabId) || !isSide(side) || this.sides.get(tabId) === side) return
this.sides.set(tabId, side)
+ // Up to the Buddy side leaves the PM's thread for good (spec 2026-11-03-dial-thread-face).
+ this.threads.delete(tabId)
+ if (this.timer && this.live) { this.emit(); void this.pushOpen() }
+ }
+
+ /** The root of the thread on the face whose conversation is `conversationId`: the one open in the window beside it, else the
+ * one the dial's words started there. */
+ private threadOn(tabId: string, conversationId: string): string | undefined {
+ const open = this.focus?.tabId === tabId && this.focus.conversationId === conversationId ? this.focus.threadRoot : undefined
+ const own = this.threads.get(tabId)
+ return open ?? (own?.conversationId === conversationId ? own.root : undefined)
+ }
+
+ private threadInfo(tabId: string, conversationId: string): SwarmChat['thread'] {
+ const root = this.threadOn(tabId, conversationId)
+ if (root === undefined) return undefined
+ const own = this.threads.get(tabId), read = this.titles.get(`${tabId}/${root}`)
+ return { root, title: own?.root === root ? own.title : read?.title ?? '', ...(read?.replies !== undefined ? { replies: read.replies } : {}) }
+ }
+
+ /** The dial leaves the thread on its face (`chat`: the dial's own chat flag): the dial's own is forgotten and the app's is no
+ * longer the face's (the window is asked to close it), and an older Desktop's announce of it is ignored from now on. The
+ * conversation whose thread that was, or null when the Lead's face was in none. */
+ threadLeave(tabId: string, leadId: string, chat: CardChat = true): { tabId: string; conversationId: string } | null {
+ const face = chat ? this.target(tabId, leadId, chat) : null
+ if (!face || face.thread === undefined) return null
+ if (this.threads.get(tabId)?.conversationId === face.id) this.threads.delete(tabId)
+ if (this.focus?.tabId === tabId && this.focus.conversationId === face.id && this.focus.threadRoot !== undefined) { const { threadRoot: _, ...rest } = this.focus; this.focus = rest }
+ this.left.set(tabId, { conversationId: face.id, root: face.thread })
if (this.timer && this.live) { this.emit(); void this.pushOpen() }
+ return { tabId, conversationId: face.id }
}
/** The recap on a Pro's screen (leadId null: closed), per Pro `session`: a change in that Lead's conversation is pushed once.
@@ -480,11 +547,13 @@ export class SwarmCards {
this.holding = this.unreadSince !== null && this.now() - this.unreadSince < UNREAD_HOLD_MS
// A Swarm that left the cards (access lost) takes the dial's side with it.
for (const tabId of [...this.sides.keys()]) if (!known.has(tabId)) this.sides.delete(tabId)
+ for (const tabId of [...this.threads.keys()]) if (!known.has(tabId)) this.threads.delete(tabId)
+ for (const tabId of [...this.left.keys()]) if (!known.has(tabId)) this.left.delete(tabId)
this.rows = rows.map(row => ({ id: row.id as string, name: row.name }))
}
const me = (await this.core.account.identity().catch(() => null))?.accountId
// Another person signed in: nothing of the last account's is kept, and the list is said again whatever it is.
- if (this.me !== undefined && me !== this.me) { this.last = null; this.recaps.clear(); this.seen.clear(); this.forgetNotices(); this.sides.clear() }
+ if (this.me !== undefined && me !== this.me) { this.last = null; this.recaps.clear(); this.seen.clear(); this.forgetNotices(); this.sides.clear(); this.threads.clear(); this.titles.clear(); this.left.clear() }
this.me = me ?? this.me
const turns = await this.turnsHere()
this.live = (harnessId: string) => this.core.agents.byAgent(harnessId) ? turns.get(harnessId) ?? { inTurn: false } : null
@@ -504,7 +573,7 @@ export class SwarmCards {
if (!tab) continue
const focus = this.focus?.tabId === row.id ? this.focus.conversationId : undefined
const side = this.sideOf(row.id, tab.state)
- const { count, leads } = leadsOf(tab.state, this.machineId, live, this.me, focus, side)
+ const { count, leads } = leadsOf(tab.state, this.machineId, live, this.me, focus, side, id => this.threadInfo(row.id, id))
const noticed = leads.map(lead => {
const notice = this.notices.get(recapKey(row.id, lead.id)), buddyNotice = this.buddyNotices.get(recapKey(row.id, lead.id))
return { ...lead, ...(notice ? { notice } : {}), ...(buddyNotice ? { buddyNotice } : {}) }
@@ -644,7 +713,7 @@ export class SwarmCards {
const found = leadProjects(state).find(p => p.leadId === leadId)
if (!found || !identifier(found.lead.id)) return null
if (!chat) return { id: found.lead.id, sequence: sequenceOf(found.lead), voices: new Set([leadId]) }
- const open = this.focus?.tabId === tabId ? this.focus : null, focus = open?.conversationId
+ const focus = this.focus?.tabId === tabId ? this.focus.conversationId : undefined
const conversations = list(state.conversations), projectId = projectKey(found.project), buddies = state.buddies === true
const face = chat === 'buddy' && buddies ? sideFaceOf(conversations, projectId, found.lead, focus, this.me, this.sideOf(tabId, state))
: faceOf(conversations, projectId, found.lead, focus, this.me, buddies)
@@ -652,7 +721,7 @@ export class SwarmCards {
const id = face.conversation.id as string
// The thread open beside the window's conversation, while that conversation is the one on the face: any agent's reply
// there is its recap (a worker answering in the Lead's thread, the Buddy's thread session).
- const thread = open?.threadRoot !== undefined && open.conversationId === id ? open.threadRoot : undefined
+ const thread = this.threadOn(tabId, id)
const voices = thread === undefined ? voicesOf(face, leadId, list(state.agents), this.me)
: new Set(list(state.agents).map(a => a.id).filter((a): a is string => typeof a === 'string'))
return { id, sequence: sequenceOf(face.conversation), voices, chatId: id,
@@ -744,12 +813,48 @@ export class SwarmCards {
// this reader's to have now (a Buddy chat is its owner's alone), so it is neither given nor kept.
const now = this.target(tabId, leadId, chat)
if (this.me !== reader || now?.id !== target.id || now.thread !== target.thread) return { tabId, leadId, text: '', at: 0, none: true }
+ if (target.thread !== undefined) await this.learnThread(tabId, target.id, target.thread, newest)
const recap: LeadRecap = said ? { tabId, leadId, text: cut(said.text, RECAP_BYTES), at: said.at, none: false, ...named } : { tabId, leadId, text: '', at: 0, none: true, ...named }
this.recaps.set(key, { sequence: target.sequence, recap, ...(target.thread === undefined ? {} : { thread: target.thread }) })
return recap
})
}
+ /** The title (the root's first line) and reply count of a thread read for the face, said again to the dial when they changed.
+ * A page that lacks the root (an app thread's root is further back) has it read once by its id; the last title is kept. A
+ * failed read is logged and tried again after a wait that doubles, at most ROOT_READ_TRIES times (review of #2756). */
+ private async learnThread(tabId: string, conversationId: string, root: string, page: Json): Promise<void> {
+ const key = `${tabId}/${root}`, was = this.titles.get(key)
+ let text = list(page.messages).find(m => m.id === root)?.text
+ let looked = was?.looked, failures = was?.failures, retryAt = was?.retryAt
+ if (typeof text !== 'string' && !was?.title && !looked && (retryAt === undefined || this.now() >= retryAt)) {
+ try {
+ const one = await backend(this.core, 'GET', `/api/super-tabs/${tabId}/conversations/${conversationId}/messages?messageId=${encodeURIComponent(root)}`)
+ text = list(object(one).messages).find(m => m.id === root)?.text
+ looked = true
+ } catch (error) {
+ failures = (failures ?? 0) + 1
+ // Nothing of the thread in the line: its id and title are the reader's.
+ const code = String(object(error).code ?? (error instanceof Error ? error.name : 'error'))
+ if (failures >= ROOT_READ_TRIES) {
+ looked = true
+ this.log(`[super-tabs] a dial thread's first message was not read (${code}); its title stays as it is`)
+ } else {
+ const wait = Math.min(ROOT_READ_WAIT_MS * 2 ** (failures - 1), 5 * 60_000)
+ retryAt = this.now() + wait
+ this.log(`[super-tabs] a dial thread's first message was not read (${code}); read again in ${Math.round(wait / 1000)} s`)
+ }
+ }
+ }
+ const replies = list(page.threads).find(t => t.id === root)?.replies
+ const next = { title: (typeof text === 'string' ? titleOf(text) : '') || was?.title || '', ...(typeof replies === 'number' ? { replies } : {}),
+ ...(looked ? { looked: true as const } : {}), ...(failures && !looked ? { failures, retryAt } : {}) }
+ if (was?.title === next.title && was.replies === next.replies && was.looked === next.looked && was.failures === next.failures && was.retryAt === next.retryAt) return
+ this.titles.set(key, next)
+ if (this.titles.size > 32) this.titles.delete(this.titles.keys().next().value!)
+ if (was?.title !== next.title || was.replies !== next.replies) { if (this.timer && this.live) this.emit() }
+ }
+
/** Words spoken on a Pro to a Lead that runs here (its harness): posted as the person in that Lead's conversation, as typed in
* the Swarm chat; with `chat`, in the chat on its face. Not `said` when that harness leads no project in the Swarms as last
* read, so the caller sends the turn as before; `refused` when the backend refused the post (a 4xx: a read-only Chat with
@@ -758,8 +863,12 @@ export class SwarmCards {
* were spoken; they go there or nowhere, so words for the reader's Buddy never land in the project's chat because the
* window moved on while they were said (review of #2146). `reviewed`: the person saw that chat named and pressed Send,
* so the words go there even if the face moved since, while it is still a chat of the Lead's project this reader may
- * see (docs/device-voice-swarm-chat.md); the backend checks the post as for typing. */
- async say(harnessId: string, text: string, chat: CardChat = false, chatId?: string, reviewed = false): Promise<SaidOnCard> {
+ * see (docs/device-voice-swarm-chat.md); the backend checks the post as for typing. `options.thread`: the thread on the
+ * face when the words were spoken (null: none), pinned like `chatId`: another one now refuses the words (CHAT_MOVED), unless
+ * `reviewed`, which posts them where they were spoken. `options.threaded`: the words came from the face, so a top-level post
+ * may start the dial's thread, if nothing moved meanwhile (spec 2026-11-03-dial-thread-face). */
+ async say(harnessId: string, text: string, chat: CardChat = false, chatId?: string, reviewed = false, options: SayOptions = {}): Promise<SaidOnCard> {
+ const reader = this.me, gen = this.focusGen
for (const [tabId, { state }] of this.tabs) {
// A Lead on another machine has no harness here, so the dial names it by its Swarm id (Diego's dial, 2026-10-29).
const agent = list(state.agents).find(a => (a.machineId === this.machineId && a.harnessId === harnessId) || a.id === harnessId)
@@ -768,16 +877,27 @@ export class SwarmCards {
const to = chatId === undefined || found.id === chatId ? found.id
: reviewed && this.chatOfLead(state, agent!.id as string, chatId) ? chatId : null
if (!to) return { said: false, refused: { code: 'CHAT_MOVED', message: 'That chat is no longer on the dial. Say it again.' } }
- // A thread on the face as the words are sent, in that chat, is where they go: a reply to its root.
- const replyTo = to === found.id ? found.thread ?? null : null
+ // A thread pinned with the words is where they go, or none; with none pinned, the thread on the face as they are sent.
+ const pinned = options.thread
+ if (pinned !== undefined && !reviewed && (found.thread ?? null) !== pinned) return { said: false, refused: { code: 'CHAT_MOVED', message: 'That chat is no longer on the dial. Say it again.' } }
+ const replyTo = pinned !== undefined ? pinned : to === found.id ? found.thread ?? null : null
+ let sent: unknown
try {
- await backend(this.core, 'POST', `/api/super-tabs/${tabId}/commands`, { operationId: `pro-voice-${randomUUID()}`,
+ sent = await backend(this.core, 'POST', `/api/super-tabs/${tabId}/commands`, { operationId: `pro-voice-${randomUUID()}`,
command: { type: 'message.send', conversationId: to, text, replyTo, recipientIds: [] } })
} catch (error) {
if (error instanceof SuperTabHostError && error.status >= 400 && error.status < 500) return { said: false, refused: { code: error.code, message: error.message } }
throw error
}
- return { said: true }
+ // Words said on the dial at top level, on the face, start the dial's thread, rooted at the message just posted.
+ const root = object(object(sent).result).messageId
+ if (chat === false || !options.threaded || replyTo !== null || !cardId(root)) return { said: true }
+ // Only if the person, the face and the window are where the call began: a post out while any moved starts no thread.
+ const now = this.target(tabId, agent!.id as string, chat)
+ if (this.me !== reader || gen !== this.focusGen || now?.id !== to || now.thread !== undefined) return { said: true }
+ this.threads.set(tabId, { conversationId: to, root, title: titleOf(text), at: this.now() })
+ if (this.timer && this.live) { this.emit(); void this.pushOpen() }
+ return { said: true, thread: { tabId, conversationId: to, root } }
}
return { said: false }
}
@@ -834,8 +954,8 @@ export class SwarmCards {
}
/** How a chat's recap names it: by its id, and as a swarmBuddy dial's when asked for one. */
-function namedFor(target: Target, chat: CardChat): { chatId?: string; buddy?: true } {
- return target.chatId === undefined ? {} : { chatId: target.chatId, ...(chat === 'buddy' ? { buddy: true as const } : {}) }
+function namedFor(target: Target, chat: CardChat): { chatId?: string; buddy?: true; thread?: string } {
+ return target.chatId === undefined ? {} : { chatId: target.chatId, ...(chat === 'buddy' ? { buddy: true as const } : {}), ...(target.thread === undefined ? {} : { thread: target.thread }) }
}
diff --git a/cli/src/superTabs/inCore/cards.spec.ts b/cli/src/superTabs/inCore/cards.spec.ts
index 05bdac7e3..570f8b8d5 100644
--- a/cli/src/superTabs/inCore/cards.spec.ts
+++ b/cli/src/superTabs/inCore/cards.spec.ts
@@ -166,6 +166,10 @@ describe('the Swarm cards on the devices', () => {
})
describe('whether the Swarm cards are wanted, which the core owns', () => {
+ function wantingRecaps() {
+ const request = vi.fn(async (_payload: Record<string, unknown>) => ({ ok: true })), swarmCards = vi.fn(), swarmCardRecap = vi.fn()
+ return { cards: createSuperTabCards({ swarmCards, swarmCardRecap, request, log: vi.fn() }), request, swarmCards, swarmCardRecap }
+ }
function wanting() {
const request = vi.fn(async (_payload: Record<string, unknown>) => ({ ok: true }))
const swarmCards = vi.fn()
@@ -303,6 +307,28 @@ describe('whether the Swarm cards are wanted, which the core owns', () => {
for (const side of ['up', null, undefined, true]) expect(await cards.ask({ action: 'cardSide', tabId: 't1', side })).toEqual({ error: 'INVALID_REQUEST' })
expect(request).not.toHaveBeenCalled()
})
+ it('keeps a sound face thread and a recap\'s thread, drops a malformed one, and passes cardThreadLeave on', async () => {
+ const { cards, request, swarmCards, swarmCardRecap } = wantingRecaps()
+ const face = { kind: 'lead', id: 'lead-c1', name: 'Lead', working: false }
+ cards.cards([card('t1', [lead('l1', { chat: { ...face, thread: { root: 'm9', title: 'é'.repeat(60), replies: 2 } } }),
+ lead('l2', { chat: { ...face, thread: { root: 'bad id', title: 'x' } } }), lead('l3', { chat: { ...face, thread: { root: 'm9', title: 'x', replies: -1 } } })])])
+ const leads = (swarmCards.mock.calls.at(-1)?.[0] as Array<{ leads: Array<{ chat: Record<string, unknown> }> }>)[0].leads
+ expect(leads[0].chat.thread).toEqual({ root: 'm9', title: 'é'.repeat(40), replies: 2 })
+ expect(leads[1].chat).not.toHaveProperty('thread')
+ expect(leads[2].chat.thread).toEqual({ root: 'm9', title: 'x' })
+ cards.recap(recap({ chatId: 'lead-c1', thread: 'm9' })); cards.recap(recap({ chatId: 'lead-c1', thread: 'bad id' }))
+ expect(swarmCardRecap.mock.calls.map((c: Array<{ thread?: string }>) => c[0].thread)).toEqual(['m9', undefined])
+ request.mockClear()
+ await cards.ask({ action: 'cardSay', harnessId: 'h1', text: 'x', chat: true, threaded: true, thread: null })
+ expect(request).toHaveBeenLastCalledWith({ action: 'cardSay', harnessId: 'h1', text: 'x', chat: true, threaded: true, thread: null })
+ await cards.ask({ action: 'cardSay', harnessId: 'h1', text: 'x', chat: true, thread: 'm9' })
+ expect(request).toHaveBeenLastCalledWith({ action: 'cardSay', harnessId: 'h1', text: 'x', chat: true, thread: 'm9' })
+ await cards.ask({ action: 'cardSay', harnessId: 'h1', text: 'x', chat: true, thread: 'bad id' })
+ expect(request).toHaveBeenLastCalledWith({ action: 'cardSay', harnessId: 'h1', text: 'x', chat: true })
+ request.mockClear()
+ await cards.ask({ action: 'cardThreadLeave', tabId: 't1', leadId: 'l1', extra: 1 })
+ expect(request.mock.calls).toEqual([[{ action: 'cardThreadLeave', tabId: 't1', leadId: 'l1' }]])
+ })
it('on an account change with no device wanting cards only clears the list', () => {
const { cards, request, swarmCards } = wanting()
cards.cards([card('t1')])
diff --git a/cli/src/superTabs/inCore/cards.ts b/cli/src/superTabs/inCore/cards.ts
index 46d210b18..47242eed0 100644
--- a/cli/src/superTabs/inCore/cards.ts
+++ b/cli/src/superTabs/inCore/cards.ts
@@ -35,6 +35,8 @@ const BUDDY_NOTICE_CHATS: ReadonlySet<string> = new Set(['buddy'])
/** Desktop's pattern is the 15 half bits of a 5×5 grid (superTabs/buddyAvatar.ts). */
const MAX_CELLS = 0x7fff
const COLOR = /^#[0-9a-f]{6}$/
+/** The dial's thread title: the first line, at most 80 bytes (the cards service cuts it; checked again here). */
+const THREAD_TITLE_BYTES = 80
/** The Pro keeps an id in 48 bytes with its NUL. */
const ID = /^[A-Za-z0-9_-]{1,47}$/
const id = (value: unknown): value is string => typeof value === 'string' && ID.test(value)
@@ -57,7 +59,11 @@ function chatIn(value: unknown): SwarmChat | null {
const chat = object(value)
if (typeof chat.kind !== 'string' || !CHATS.has(chat.kind) || !id(chat.id) || typeof chat.name !== 'string' || typeof chat.working !== 'boolean') return null
if (chat.since !== undefined && !whole(chat.since)) return null
- return { kind: chat.kind as SwarmChat['kind'], id: chat.id, name: cut(chat.name, NAME_BYTES), working: chat.working, ...(chat.since === undefined ? {} : { since: chat.since }) }
+ // The thread the face is in (spec 2026-11-03-dial-thread-face); one that is not sound is left out and the chat is kept.
+ const thread = object(chat.thread)
+ const inThread = id(thread.root) && typeof thread.title === 'string'
+ return { kind: chat.kind as SwarmChat['kind'], id: chat.id, name: cut(chat.name, NAME_BYTES), working: chat.working, ...(chat.since === undefined ? {} : { since: chat.since }),
+ ...(inThread ? { thread: { root: thread.root as string, title: cut(thread.title as string, THREAD_TITLE_BYTES), ...(whole(thread.replies) ? { replies: thread.replies } : {}) } } : {}) }
}
/** A Lead's notice from one of `chats`, checked and cut; null when it is not one, and the Lead goes on without it. */
@@ -124,7 +130,7 @@ function recapIn(value: unknown): LeadRecap | null {
// A chat's recap names its chat or is not one: a dial must never show it for another chat.
if (recap.chatId !== undefined && !id(recap.chatId)) return null
return { tabId: recap.tabId, leadId: recap.leadId, text: cut(recap.text, RECAP_BYTES), at: recap.at, none: recap.none, ...(recap.chatId === undefined ? {} : { chatId: recap.chatId }),
- ...(recap.buddy === true ? { buddy: true as const } : {}) }
+ ...(recap.buddy === true ? { buddy: true as const } : {}), ...(id(recap.thread) ? { thread: recap.thread } : {}) }
}
export function createSuperTabCards({ swarmCards, swarmCardRecap, request, log = (line) => console.log(line) }: SuperTabCardsDeps) {
@@ -206,9 +212,12 @@ export function createSuperTabCards({ swarmCards, swarmCardRecap, request, log =
// The chat on the dial's face when the words were spoken, which they may be posted in and no other.
// `reviewed`: the person saw that chat named on the dial and pressed Send.
if (payload.action === 'cardSay') return route({ action: 'cardSay', harnessId: payload.harnessId, text: payload.text, ...chat,
- ...(id(payload.chatId) ? { chatId: payload.chatId, ...(payload.reviewed === true ? { reviewed: true } : {}) } : {}) })
+ ...(id(payload.chatId) ? { chatId: payload.chatId, ...(payload.reviewed === true ? { reviewed: true } : {}) } : {}),
+ ...(payload.threaded === true ? { threaded: true } : {}), ...(payload.thread === null || id(payload.thread) ? { thread: payload.thread } : {}) })
if (payload.action === 'cardOpen') return route({ action: 'cardOpen', session: payload.session, tabId: payload.tabId, leadId: payload.leadId, ...chat })
// A card's failure from another computer: whether its agent is a Swarm's worker (services/devices.ts asks; it decides).
+ // The dial left the thread on its face: the service forgets it and names the conversation whose thread the window should close.
+ if (payload.action === 'cardThreadLeave') return route({ action: 'cardThreadLeave', tabId: payload.tabId, leadId: payload.leadId, ...chat })
if (payload.action === 'cardWorker') return route({ action: 'cardWorker', machineId: payload.machineId, harnessId: payload.harnessId })
return Promise.resolve({ error: 'INVALID_REQUEST' })
},
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index f822fc9f0..8830fcbbd 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -864,7 +864,7 @@ it('documents finished worker decisions and explains an older backend without re
describe('the Swarm cards the devices ask for', () => {
function withCards() {
- const cards = { want: vi.fn(), open: vi.fn(), side: vi.fn(), say: vi.fn(async (): Promise<SaidOnCard> => ({ said: true })), worker: vi.fn((machineId: string, harnessId: string) => machineId === 'm2' && harnessId === 'h-r1'), recap: vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'Shipped', at: 5, none: false })), onCards: undefined as unknown, onRecap: undefined as unknown }
+ const cards = { want: vi.fn(), open: vi.fn(), side: vi.fn(), threadLeave: vi.fn((..._a: unknown[]): { tabId: string; conversationId: string } | null => null), say: vi.fn(async (): Promise<SaidOnCard> => ({ said: true })), worker: vi.fn((machineId: string, harnessId: string) => machineId === 'm2' && harnessId === 'h-r1'), recap: vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'Shipped', at: 5, none: false })), onCards: undefined as unknown, onRecap: undefined as unknown }
const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn(), inputIfScreen: vi.fn() }
const core = fakeCore({ superTabs })
const make = vi.fn(() => cards as never)
@@ -966,6 +966,28 @@ describe('the Swarm cards the devices ask for', () => {
await t.ask({ action: 'cardSay', harnessId: 'h1', text: 'ship it', chat: 'buddy', reviewed: true }, owner)
expect(t.cards.say).toHaveBeenLastCalledWith('h1', 'ship it', 'buddy')
})
+ it('cardThreadLeave tells the cards and answers the project; cardSay answers the thread its words started', async () => {
+ const t = withCards()
+ t.cards.threadLeave.mockReturnValueOnce({ tabId: 't1', conversationId: 'lead-web' })
+ expect(await t.ask({ action: 'cardThreadLeave', tabId: 't1', leadId: 'l1', chat: 'buddy' }, owner)).toEqual({ ok: true, conversationId: 'lead-web' })
+ expect(t.cards.threadLeave).toHaveBeenLastCalledWith('t1', 'l1', 'buddy')
+ expect(await t.ask({ action: 'cardThreadLeave', tabId: 't1', leadId: 'l1' }, owner)).toEqual({ ok: true })
+ for (const bad of [{ tabId: 'bad id', leadId: 'l1' }, { tabId: 't1', leadId: 'x'.repeat(48) }, { tabId: 't1' }]) {
+ expect(await t.ask({ action: 'cardThreadLeave', ...bad }, owner)).toEqual({ error: 'INVALID_REQUEST' })
+ }
+ expect(await t.ask({ action: 'cardThreadLeave', tabId: 't1', leadId: 'l1' }, visitor)).toEqual({ error: 'OWNER_REQUIRED' })
+ expect(t.cards.threadLeave).toHaveBeenCalledTimes(2)
+ expect(t.cards.threadLeave).toHaveBeenLastCalledWith('t1', 'l1', false)
+ await t.ask({ action: 'cardSay', harnessId: 'h1', text: 'ship it', chat: true, threaded: true, thread: null }, owner)
+ expect(t.cards.say).toHaveBeenLastCalledWith('h1', 'ship it', true, undefined, false, { threaded: true, thread: null })
+ await t.ask({ action: 'cardSay', harnessId: 'h1', text: 'ship it', chat: true, chatId: 'lead-web', reviewed: true, thread: 'm9' }, owner)
+ expect(t.cards.say).toHaveBeenLastCalledWith('h1', 'ship it', true, 'lead-web', true, { thread: 'm9' })
+ await t.ask({ action: 'cardSay', harnessId: 'h1', text: 'ship it', chat: true, thread: 'bad id' }, owner)
+ expect(t.cards.say).toHaveBeenLastCalledWith('h1', 'ship it', true)
+ t.cards.say.mockResolvedValueOnce({ said: true, thread: { tabId: 't1', conversationId: 'lead-web', root: 'm9' } })
+ expect(await t.ask({ action: 'cardSay', harnessId: 'h1', text: 'ship it', chat: true }, owner))
+ .toEqual({ ok: true, said: true, thread: { tabId: 't1', conversationId: 'lead-web', root: 'm9' } })
+ })
it('cardSay passes a refused post\'s code and message on, and says nothing of a refusal otherwise', async () => {
const t = withCards()
t.cards.say.mockResolvedValueOnce({ said: false, refused: { code: 'PM_CHAT_READ_ONLY', message: 'Chat with PM is read-only.' } })
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 8ade6c2d3..66900f6de 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -82,7 +82,7 @@ const HELP = {
release: 'agent.release records keep, or requests stop, for an agent whose work ended; assigning it new work reuses it. Wait for the execution host to confirm a stop. A person can withdraw a stuck stop; the session cannot receive new work in that Swarm. Its native capacity stays reserved until its host confirms stopping. Other Swarms wait up to two minutes for an in-flight close, then may reuse it.',
resume: 'resume START_ID: finish a pending start without creating another agent.',
// Buddies (backend superTabs/buddies.ts): a person adds and removes their own; the Buddy proposes only when they ask.
- buddies: 'Buddies, in every Swarm: each person has one Buddy chat for the whole Swarm that only they and their Buddy read (buddy.chat opens it before any Buddy; with projectId, their older chat in that project), may add their one Buddy (buddy.create with machineId of their own machine, engine claude), remove it (buddy.remove), and name it (buddy.rename with conversationId of their Buddy chat and name, or null for the default name). It reads every project they read and brainstorms with them in that chat, and the PM\'s private lines to them land there too, marked with their project. A proposal is the only thing it sends into a project. propose OPERATION_ID JSON [--attach PATH]...: when its owner asks (a New session in one project, in its thread, for that project): {"conversationId":"its chat","ownerMessageId":"their message asking","projectId":"the project they read to send it to; a session of one project leaves it out","goal":"...","scope":"...","priority":"low|normal|high","attachmentIds":["a file its owner sent in its chat"]}. --attach adds a file inside its own folder (in that project\'s folder, for their one Buddy); up to 5 files in all, 10 MB each. The Swarm posts it in the project chat to the PM, marked as on the owner\'s behalf. A Buddy is never assigned work.',
+ buddies: 'Buddies, in every Swarm: each person has one Buddy chat for the whole Swarm that only they and their Buddy read (buddy.chat opens it before any Buddy; with projectId, their older chat in that project), may add their one Buddy (buddy.create with machineId of their own machine, engine claude), remove it (buddy.remove), and name it (buddy.rename with conversationId of their Buddy chat and name, or null for the default name). It reads every project they read and brainstorms with them in that chat, and the PM\'s private lines to them land there too, marked with their project. A proposal is the only thing it sends into a project. propose OPERATION_ID JSON [--attach PATH]...: when its owner asks (a New session in one project, in its thread, for that project): {"conversationId":"its chat","ownerMessageId":"their message asking","projectId":"the project they read to send it to; a session of one project leaves it out","title":"Short name (at most 80 characters)","goal":"...","scope":"...","priority":"low|normal|high","attachmentIds":["a file its owner sent in its chat"]}. --attach adds a file inside its own folder (in that project\'s folder, for their one Buddy); up to 5 files in all, 10 MB each. The Swarm posts it in the project chat as "Let\'s build: <title>" from its owner, with the full proposal as the first reply in its thread, for the PM. A Buddy is never assigned work.',
// A person's own command, for the machines they added; an agent's terminal is refused (command.ts), so no agent raises its
// own machine's room (Lead, 2026-10-28).
setAgents: 'set-agents MACHINE_ID COUNT: for a machine\'s owner, from their own terminal, not an agent\'s: how many Swarm agents may run on that machine at once. Each agent still needs free memory when it starts. A machine may offer one agent for every 2 GB of its memory, and at least 4; a larger number is refused.',
@@ -493,7 +493,7 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
// The devices' (core/devicesLink.ts): a Harness Pro that shows the Swarm cards is attached or gone, wants a Lead's recap, or
// has one open. They read the account's Swarms as the person, and need no agent.
// Only this computer's own devices ask: an account owner on another machine does not make this one read the Swarms.
- if (payload.action === 'cardsWanted' || payload.action === 'cardRecap' || payload.action === 'cardOpen' || payload.action === 'cardSay' || payload.action === 'cardWorker' || payload.action === 'cardSide') {
+ if (payload.action === 'cardsWanted' || payload.action === 'cardRecap' || payload.action === 'cardOpen' || payload.action === 'cardSay' || payload.action === 'cardWorker' || payload.action === 'cardSide' || payload.action === 'cardThreadLeave') {
if (!asker.local) return { error: 'OWNER_REQUIRED' }
// A round dial that speaks swarmChat asks for the chat on its face (design 2026-10-28-round-dial-swarm-chat), and one
// that speaks swarmBuddy for the face on the side it keeps ('buddy', spec 2026-10-29-round-dial-pm-buddy).
@@ -509,16 +509,26 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
}
if (payload.action === 'cardRecap' && cardId(payload.tabId) && cardId(payload.leadId)) return { ok: true, ...await cards().recap(payload.tabId, payload.leadId, chat) }
if (payload.action === 'cardSay' && cardId(payload.harnessId) && typeof payload.text === 'string' && payload.text.trim() && payload.text.length <= 32_000) {
+ // `threaded`: the dial speaks swarmThread and the words came from its face; `thread`: the root of the thread on the face
+ // then (null: none), which the words are held to.
+ const options = { ...(payload.threaded === true ? { threaded: true } : {}),
+ ...(payload.thread === null || cardId(payload.thread) ? { thread: payload.thread } : {}) }
const pinned: [chatId?: string, reviewed?: boolean] = !cardId(payload.chatId) ? []
: payload.reviewed === true ? [payload.chatId, true] : [payload.chatId]
- const result = await cards().say(payload.harnessId, payload.text.trim(), chat, ...pinned)
+ const result = Object.keys(options).length
+ ? await cards().say(payload.harnessId, payload.text.trim(), chat, cardId(payload.chatId) ? payload.chatId : undefined, cardId(payload.chatId) && payload.reviewed === true, options)
+ : await cards().say(payload.harnessId, payload.text.trim(), chat, ...pinned)
// A refusal travels with its code and message, which the dial shows instead of typing the words anywhere.
- return { ok: true, said: result.said, ...(!result.said && result.refused ? { refused: result.refused } : {}) }
+ return { ok: true, said: result.said, ...(!result.said && result.refused ? { refused: result.refused } : {}), ...(result.said && result.thread ? { thread: result.thread } : {}) }
}
// A card's failure from another computer: whether its agent is a Swarm's Builder or Reviewer, from the Swarms read last.
if (payload.action === 'cardWorker' && identifier(payload.machineId) && identifier(payload.harnessId)) {
return { ok: true, worker: cards().worker(payload.machineId, payload.harnessId) }
}
+ if (payload.action === 'cardThreadLeave' && cardId(payload.tabId) && cardId(payload.leadId)) {
+ const left = cards().threadLeave(payload.tabId, payload.leadId, chat)
+ return { ok: true, ...(left ? { conversationId: left.conversationId } : {}) }
+ }
if (payload.action === 'cardSide' && cardId(payload.tabId) && (payload.side === 'pm' || payload.side === 'buddy')) {
cards().side(payload.tabId, payload.side)
return { ok: true }
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index e62515988..4bf317fdc 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -4743,7 +4743,8 @@ class AppNotifier extends ChangeNotifier {
);
if (_disposed || _devicePick != pick) return;
} else {
- controller.select(project.leadConversationId);
+ await controller.select(project.leadConversationId);
+ if (_disposed || _devicePick != pick) return;
}
// Selecting what is already selected announces nothing by itself.
_announceOpenPanesToDial();
@@ -4755,6 +4756,94 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// A thread the dial opened ([root] a string) or closed (null) in
+ /// [conversationId] of the Swarm tab [tabId], without any navigation.
+ Future<void> _dialThreadOnly(
+ String tabId,
+ String conversationId,
+ Object? root,
+ ) async {
+ if (!_superTabNames.containsKey(tabId) &&
+ !swarms.any((s) => s.superTabId == tabId)) {
+ return;
+ }
+ // Every thread frame, a leave included, supersedes a pending open.
+ final token = ++_dialThreadToken;
+ try {
+ final controller = await superTabs.open(tabId);
+ if (_disposed) return;
+ if (root is String) {
+ if (controller.snapshot == null) await controller.refresh();
+ if (_disposed ||
+ controller.snapshot?.conversation(conversationId) == null) {
+ return;
+ }
+ if (controller.selectedId != conversationId) {
+ await controller.select(conversationId);
+ }
+ if (_disposed || controller.selectedId != conversationId) return;
+ if (_dialThreadToken != token) return;
+ // Not a new pick: a later pick bumps [_devicePick] and drops this.
+ await _openDialThread(controller, root, _devicePick, token);
+ } else if (controller.openedThread?.conversationId == conversationId) {
+ controller.closeThread();
+ }
+ } catch (error) {
+ appLog.warn('super-tab', 'Could not open the dial\'s thread: $error');
+ }
+ }
+
+ /// Opens [root] beside the selected chat once the chat holds it. The dial
+ /// names a thread right after its post made the root, so the app often has
+ /// not read it: read once, then wait for a later read, until another pick,
+ /// another chat or 10 seconds. A root the chat never holds opens nothing.
+ Future<void> _openDialThread(
+ SuperTabController controller,
+ String root,
+ int pick, [
+ int? token,
+ ]) async {
+ final id = controller.selectedId;
+ // The person's own open or close while this waits makes it stale.
+ final before = controller.openedThread;
+ void open() {
+ // The pane may not be on screen (another Swarm tab, background window):
+ // the view's _syncThreadPane calls threadPaneShown when it is.
+ controller.openThread(root, shown: false);
+ }
+ bool holds() => controller
+ .messages(id)
+ .any((m) => m.id == root || m.thread == root);
+ if (!holds()) await controller.refresh();
+ bool superseded() =>
+ _disposed ||
+ _devicePick != pick ||
+ controller.selectedId != id ||
+ (token != null && _dialThreadToken != token) ||
+ controller.openedThread != before;
+ if (superseded()) return;
+ if (holds()) return open();
+ Timer? giveUp;
+ void listener() {
+ final stale = superseded();
+ if (!stale && !holds()) return;
+ giveUp?.cancel();
+ controller.removeListener(listener);
+ if (!stale) open();
+ }
+
+ controller.addListener(listener);
+ giveUp = Timer(dialThreadWaitForTest, () {
+ controller.removeListener(listener);
+ // A later dial frame asks again; nothing of the thread is logged.
+ appLog.warn(
+ 'super-tab',
+ 'The dial\'s thread never reached its chat in '
+ '${dialThreadWaitForTest.inSeconds} s; it stays closed',
+ );
+ });
+ }
+
void _noteNavigation() {
_paneFocusByUser = !_navigatingFromDevice;
// A device's move is not a person opening anything — but it does leave a
@@ -6057,6 +6146,11 @@ class AppNotifier extends ChangeNotifier {
bool _announceFromDevice = false;
int _devicePick = 0;
+ int _dialThreadToken = 0;
+
+ /// How long the dial's thread waits for its root to reach the chat.
+ @visibleForTesting
+ Duration dialThreadWaitForTest = const Duration(seconds: 10);
/// The project each Swarm tab's row last told the dial, by backend tab id;
/// null while its Swarm had not loaded. See `onSnapshot`.
@@ -6084,8 +6178,8 @@ class AppNotifier extends ChangeNotifier {
return controller.snapshot?.conversation(id) == null ? null : id;
}
- /// The thread whose pane is on screen beside that conversation, by its
- /// root: the round dial shows and answers it while it stays open.
+ /// The thread open beside that conversation, by its root, shown or hidden:
+ /// the round dial shows and answers it while it stays open.
String? _dialThread(String tabId) => _dialConversation(tabId) == null
? null
: superTabs.peek(tabId)?.threadOnScreen;
@@ -22472,7 +22566,18 @@ class AppNotifier extends ChangeNotifier {
// Buddy chat there; anything else is the Lead chat.
final tabId = payload['superTabId'];
final projectId = payload['projectId'];
- if (tabId is String && projectId is String) {
+ if (payload['threadOnly'] == true) {
+ // The dial opened or closed a thread of a chat the app already
+ // shows: no window raised, no Swarm switched, no chat re-selected.
+ final conversationId = payload['conversationId'];
+ if (tabId is String && conversationId is String) {
+ await _dialThreadOnly(
+ tabId,
+ conversationId,
+ payload['threadRoot'] as Object?,
+ );
+ }
+ } else if (tabId is String && projectId is String) {
await _openSuperTabProject(
machine,
tabId,
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index b884e0c18..f5b750296 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -23,6 +23,7 @@ import 'read_marks.dart';
import 'reading.dart';
import 'linked_tasks.dart';
import 'task_steps.dart';
+import 'task_groups.dart';
/// A messages read started beside a state read, and what it asked for.
typedef _EarlyRead = ({String query, Future<Map<String, dynamic>> page});
@@ -876,25 +877,25 @@ class SuperTabController extends ChangeNotifier {
if (!_threadUnshown) return;
_threadUnshown = false;
if (openedThread case final open?) _seeThread(open.root);
- // The round dial follows a thread whose pane is on screen.
_changed();
}
/// The pane of the open thread left the screen: the app went to the
/// background, another Swarm came to the front, or something covers it.
- /// Called from a build or a dispose, so the round dial, which follows a
- /// thread only while its pane is on screen, is told after it.
+ /// Called from a build or a dispose, so listeners are told after it.
void threadPaneHidden() {
if (_threadUnshown) return;
_threadUnshown = true;
if (openedThread != null) scheduleMicrotask(_changed);
}
- /// The root of the thread open beside the selected conversation while its
- /// pane is on screen, which the round dial's face follows; null otherwise.
+ /// The root of the thread open beside the selected conversation, which the
+ /// round dial's face follows; null when none is. Open, not on screen: a
+ /// hidden pane (app in the background, another Swarm in front) is still the
+ /// person's open thread, and the daemon drops the dial out of a thread that
+ /// is not named. Read marks stay gated by [_threadUnshown], not this.
String? get threadOnScreen => switch (openedThread) {
- final open? when open.conversationId == selectedId && !_threadUnshown =>
- open.root,
+ final open? when open.conversationId == selectedId => open.root,
_ => null,
};
@@ -1057,6 +1058,22 @@ class SuperTabController extends ChangeNotifier {
_changed();
}
+ /// Each project's task groups folded or unfolded against their default
+ /// (`<project>/<group>`), remembered as Closed is: not saved.
+ final _taskGroupsToggled = <String>{};
+
+ /// Whether [group] of [projectId]'s tasks is folded in the sidebar; only
+ /// The rest starts folded.
+ bool taskGroupFolded(String projectId, SuperTabTaskGroup group) =>
+ group.foldedByDefault !=
+ _taskGroupsToggled.contains('$projectId/${group.name}');
+
+ void toggleTaskGroup(String projectId, SuperTabTaskGroup group) {
+ final key = '$projectId/${group.name}';
+ if (!_taskGroupsToggled.remove(key)) _taskGroupsToggled.add(key);
+ _changed();
+ }
+
/// Open decisions the reader set aside in their Buddy chat (Not now, Hide):
/// saved on this computer for this reader, so they stay folded after a
/// restart. A decision asked later is not among them, so it shows.
@@ -1617,10 +1634,12 @@ class SuperTabController extends ChangeNotifier {
}
/// Opens [root]'s thread of the selected conversation beside the chat.
- void openThread(String root) {
+ /// [shown] false opens it with its pane not on screen (the dial opened it
+ /// in a background tab): nothing reads until [threadPaneShown].
+ void openThread(String root, {bool shown = true}) {
if (accessRevoked) return;
openedThread = (conversationId: selectedId, root: root);
- _threadUnshown = false;
+ _threadUnshown = !shown;
_pruneThreadFiles();
_seeThread(root);
_saveSoon();
@@ -3114,10 +3133,13 @@ class SuperTabController extends ChangeNotifier {
return _heldSinceRead(group) ? count : max(count, 1);
}
- /// Whether [m] is the reader's own: written by them, not by an agent or a
- /// terminal.
+ /// Whether [m] is the reader's own: written by them, not by an agent, a
+ /// terminal or the server in their name.
bool isOwn(SuperTabMessage m) =>
- !m.fromAgent && !m.fromTerminal && m.authorId == accountId;
+ !m.fromAgent &&
+ !m.fromTerminal &&
+ !m.postedForAuthor &&
+ m.authorId == accountId;
/// Whether what [id]'s main stream gained since sequence [after] is all the reader's own, sent from
/// any device. Unsure is no: a message that can't be read is told about, never lost.
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
index 33e8213dd..03bde6fd0 100644
--- a/desktop/lib/super_tabs/message_row.dart
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -47,7 +47,6 @@ class SuperTabMessageRow extends StatefulWidget {
this.readerId = '',
this.reactorName,
this.onReact,
- this.proposalOwner,
this.headerStatus,
this.dimmed = false,
this.thread,
@@ -85,10 +84,6 @@ class SuperTabMessageRow extends StatefulWidget {
/// reply line; without it each shows the face its recorded name gives.
final SuperTabMemberOf? member;
- /// 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;
-
/// The names of the people [message] tags.
final List<String> mentions;
@@ -469,30 +464,6 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
: () => widget.onOpenReply!(context),
),
),
- if (widget.proposalOwner case final owner?)
- Padding(
- padding: const EdgeInsets.only(
- bottom: grid.AppDesktop.menuInset,
- ),
- child: Container(
- key: const ValueKey('super-proposal-label'),
- padding: const EdgeInsets.symmetric(
- horizontal: grid.AppDesktop.controlGap,
- ),
- decoration: BoxDecoration(
- border: Border.all(
- color: DesktopChrome.rim,
- ),
- borderRadius: BorderRadius.circular(
- DesktopChrome.rowRadius,
- ),
- ),
- child: Text(
- "Proposal · on $owner's behalf",
- style: DesktopChrome.metadata(),
- ),
- ),
- ),
if (message.terminalNote case final note?)
Padding(
padding: const EdgeInsets.only(bottom: 6),
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index ca801e593..522e58988 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -1322,10 +1322,11 @@ class SuperTabMessage {
SuperTabRoute? get route => SuperTabRoute.fromSource(source);
bool get routeOverride => source['kind'] == 'route-override';
- /// The person a Buddy's proposal speaks for, from the tag the server writes
- /// on it; null for every other message, whatever its text says.
- String? get proposalOwnerId =>
- source['kind'] == 'buddy-proposal' ? source['personId'] as String? : null;
+ /// A "Let's build" root the server posted in its person's name (plain chat,
+ /// #2294): theirs to read, not their own writing, so it reads nothing
+ /// before it and is unread for them as anyone else's message is.
+ bool get postedForAuthor =>
+ source['kind'] == 'task-line' || source['kind'] == 'buddy-proposal';
/// The agent a "waiting at a prompt" note is about; null for any other row.
String? get promptAlertAgentId =>
diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dart
index 73153f42a..100aa80cc 100644
--- a/desktop/lib/super_tabs/project_sidebar.dart
+++ b/desktop/lib/super_tabs/project_sidebar.dart
@@ -29,6 +29,7 @@ import 'model.dart';
import 'buddy_rows.dart';
import 'section_heading.dart';
import 'swarm_switcher.dart';
+import 'task_groups.dart';
import 'task_status.dart';
import 'workgroup_name.dart';
import 'project_github.dart';
@@ -790,55 +791,85 @@ class ProjectSidebar extends StatelessWidget {
reading.conversations,
);
- /// The "… N more" row under a project's newest conversations.
- Widget _moreRow(SuperTabProject project, int hidden, VoidCallback onTap) =>
- Padding(
- padding: const EdgeInsets.only(bottom: 2),
- child: Material(
- color: Colors.transparent,
- borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
- clipBehavior: Clip.antiAlias,
- child: Semantics(
- button: true,
- child: InkWell(
- key: ValueKey('super-project-more-${project.id}'),
- onTap: onTap,
- hoverColor: grid.AppSurface.hoverFill,
- focusColor: grid.AppSurface.hoverFill,
- borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
- child: Row(
- children: [
- SizedBox(width: SuperTabSectionHeading.indentFor(0)),
- const SizedBox(width: _iconColumn),
- Expanded(
- child: ConstrainedBox(
- constraints: BoxConstraints(
- minHeight: SwarmType.sidebarRowHeight(compact: compact),
- ),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- '… $hidden more',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: SwarmType.sidebar(
- compact: compact,
- color: DesktopChrome.muted,
- ),
- ),
+ /// A task group's heading under a project, as the mockup Huy approved
+ /// draws it: "▾ Needs you 1". It folds and unfolds the group, by click,
+ /// Enter or Space.
+ Widget _taskGroupHeading(
+ SuperTabProject project,
+ SuperTabTaskGroup group,
+ int count,
+ ) {
+ final folded = controller.taskGroupFolded(project.id, group);
+ final style = SwarmType.sidebar(
+ compact: compact,
+ color: DesktopChrome.muted,
+ );
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 2),
+ child: Material(
+ color: Colors.transparent,
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ clipBehavior: Clip.antiAlias,
+ child: Semantics(
+ button: true,
+ expanded: !folded,
+ child: InkWell(
+ key: ValueKey('super-task-group-${project.id}-${group.name}'),
+ onTap: () => controller.toggleTaskGroup(project.id, group),
+ hoverColor: grid.AppSurface.hoverFill,
+ focusColor: grid.AppSurface.hoverFill,
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ child: Row(
+ children: [
+ SizedBox(width: SuperTabSectionHeading.indentFor(0)),
+ SizedBox(
+ width: _iconColumn,
+ child: Icon(
+ folded ? AppIcons.chevronRight : AppIcons.chevronDown,
+ size: AppIcons.inlineSize,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ Flexible(
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ minHeight: SwarmType.sidebarRowHeight(compact: compact),
+ ),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text(
+ group.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: style,
),
),
),
- ],
- ),
+ ),
+ const SizedBox(width: 8),
+ Text('$count', style: style),
+ const SizedBox(width: _rowEnd),
+ ],
),
),
),
- );
+ ),
+ );
+ }
+ /// A project's open tasks in their groups (Huy, #2309): each group with a
+ /// row the unread filter keeps gets its heading, then its rows newest
+ /// first; a folded one shows only the open chat's row.
List<Widget> _workgroups(_ProjectReading reading) {
final project = reading.project;
final groups = _newestFirst(reading).where(_keptByFilter).toList();
+ final grouped = superTabGroupTasks(
+ groups,
+ readerId: controller.accountId,
+ mentions: (g) => attention?.mentionsIn(g.id) ?? 0,
+ // Asked once per build already (_ProjectReading).
+ needsHuman: (g) => reading.waiting.contains(g.id) ? 1 : 0,
+ );
return groups.isEmpty
? [
Padding(
@@ -858,24 +889,16 @@ class ProjectSidebar extends StatelessWidget {
),
]
: [
- _NewestConversations(
- key: ValueKey('super-project-list-${project.id}'),
- rows: [
- for (final group in groups)
- (group.id, () => _workgroupRow(group, reading)),
+ for (final MapEntry(key: taskGroup, value: rows) in grouped.entries)
+ if (rows.isNotEmpty) ...[
+ _taskGroupHeading(project, taskGroup, rows.length),
+ for (final group in rows)
+ // The open chat stays listed, Manage or Devices over it
+ // too: its row is the way back to it.
+ if (!controller.taskGroupFolded(project.id, taskGroup) ||
+ controller.selectedId == group.id)
+ _workgroupRow(group, reading),
],
- // Never behind "… N more": the open one, and those with
- // something to read or answer.
- kept: {
- if (!_paneCovered) controller.selectedId,
- for (final group in groups)
- if (reading.unread.contains(group.id) ||
- reading.waiting.contains(group.id) ||
- (attention?.mentionsIn(group.id) ?? 0) > 0)
- group.id,
- },
- more: (hidden, onTap) => _moreRow(project, hidden, onTap),
- ),
];
}
@@ -913,7 +936,15 @@ class ProjectSidebar extends StatelessWidget {
children: [
_row(read.lead!, reading: read),
if (controller.expandedProjects.contains(project.id)) ...[
- ..._workgroups(read),
+ // Built when the list lays the project out, not on every
+ // rebuild: an expanded project off screen costs nothing, as
+ // the 8 newest did behind "… N more" (#2309).
+ Builder(
+ builder: (_) => Column(
+ mainAxisSize: MainAxisSize.min,
+ children: _workgroups(read),
+ ),
+ ),
..._closed(read),
],
],
@@ -1084,60 +1115,6 @@ class _RowSurfaceState extends State<_RowSurface> {
);
}
-/// A project's open conversations, newest first: the first
-/// [_NewestConversations.shown] and the [_NewestConversations.kept] ones, then
-/// a "… N more" row that shows the rest. Showing the rest lasts until the
-/// project is collapsed.
-class _NewestConversations extends StatefulWidget {
- const _NewestConversations({
- super.key,
- required this.rows,
- required this.kept,
- required this.more,
- });
-
- static const shown = 8;
-
- /// Each conversation's id and how its row is built, newest first: only the
- /// rows shown are built.
- final List<(String, Widget Function())> rows;
-
- /// Listed even when older than the newest.
- final Set<String> kept;
- final Widget Function(int hidden, VoidCallback onTap) more;
-
- @override
- State<_NewestConversations> createState() => _NewestConversationsState();
-}
-
-class _NewestConversationsState extends State<_NewestConversations> {
- bool _all = false;
-
- @override
- Widget build(BuildContext context) {
- final rows = widget.rows;
- final visible = _all || rows.length <= _NewestConversations.shown
- ? rows
- : [
- for (final (index, row) in rows.indexed)
- if (index < _NewestConversations.shown ||
- widget.kept.contains(row.$1))
- row,
- ];
- return Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- for (final (_, row) in visible) row(),
- if (visible.length < rows.length)
- widget.more(
- rows.length - visible.length,
- () => setState(() => _all = true),
- ),
- ],
- );
- }
-}
-
/// What one build of the sidebar reads, each piece once: per row, a Swarm's
/// thousands of conversations were scanned again on every rebuild (Diego,
/// 10-29).
@@ -1234,14 +1211,19 @@ List<SuperTabConversation> superTabOpenWorkgroups(
/// The chats in the order the sidebar lists them, for Option+Shift+Down and
/// Up (Slack's next unread): the reader's one Buddy chat (`# buddy`, first
/// under Projects), each project from A to Z, its chat then its open
-/// workgroups newest first, then the reader's project Buddy chats. The round
-/// dial swipes projects in this A to Z order too (cli superTabs/cards.ts
-/// `leadsOf`): the two must match.
-List<String> superTabSidebarOrder(SuperTabController controller) {
+/// workgroups in their groups (#2309), each newest first, then the reader's
+/// project Buddy chats. [needsHuman] is the sidebar's. The round dial swipes
+/// projects in this A to Z order too (cli superTabs/cards.ts `leadsOf`): the
+/// two must match.
+List<String> superTabSidebarOrder(
+ SuperTabController controller, {
+ int Function(SuperTabConversation group)? needsHuman,
+}) {
final snapshot = controller.snapshot;
if (snapshot == null) return const [];
final projects = [...snapshot.projects]
..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
+ final attention = SuperTabAttention.of(controller);
return [
if (controller.oneBuddy)
if (controller.buddyChat(SuperTabController.kSwarmBuddyKey)
@@ -1250,7 +1232,13 @@ List<String> superTabSidebarOrder(SuperTabController controller) {
for (final project in projects) ...[
if (snapshot.conversation(project.leadConversationId) != null)
project.leadConversationId,
- for (final group in superTabOpenWorkgroups(controller, project)) group.id,
+ for (final tasks in superTabGroupTasks(
+ superTabOpenWorkgroups(controller, project),
+ readerId: controller.accountId,
+ mentions: (g) => attention.mentionsIn(g.id),
+ needsHuman: needsHuman,
+ ).values)
+ for (final group in tasks) group.id,
],
for (final project in projects)
if (controller.buddyChat(project.id) case final chat?) chat.id,
diff --git a/desktop/lib/super_tabs/task_groups.dart b/desktop/lib/super_tabs/task_groups.dart
new file mode 100644
index 000000000..a221c1a38
--- /dev/null
+++ b/desktop/lib/super_tabs/task_groups.dart
@@ -0,0 +1,77 @@
+import 'model.dart';
+
+/// The groups a project's open tasks are listed in under it in the sidebar, in
+/// this order (Huy, #2309): a busy project's list read as one long run of
+/// unread rows.
+enum SuperTabTaskGroup {
+ needsYou('Needs you'),
+ working('Working'),
+ waitingOnOthers('Waiting on others'),
+ rest('The rest');
+
+ const SuperTabTaskGroup(this.label);
+ final String label;
+
+ /// Only The rest starts folded: the first screen is what needs the reader
+ /// and what is moving.
+ bool get foldedByDefault => this == rest;
+}
+
+/// Which group [group] is listed in, for the reader [readerId]: tagged, or
+/// waited on (by name, or by no one named), or asked in its agent's terminal
+/// ([needsHuman]) is theirs; a wait on someone or something else, or a stuck
+/// task the PM hands on, is others'; an agent moving or starting is working.
+/// The task line says the same states (task_status.dart).
+SuperTabTaskGroup superTabTaskGroupOf(
+ SuperTabConversation group, {
+ required String readerId,
+ int mentions = 0,
+ int needsHuman = 0,
+}) {
+ if (mentions > 0) return SuperTabTaskGroup.needsYou;
+ final liveness = group.liveness;
+ if (liveness == null) {
+ if (needsHuman > 0) return SuperTabTaskGroup.needsYou;
+ return const {'working', 'planned'}.contains(group.assignment?['status'])
+ ? SuperTabTaskGroup.working
+ : SuperTabTaskGroup.rest;
+ }
+ return switch ((liveness['state'], liveness['why'])) {
+ ('waiting', 'person') => switch (liveness['personId']) {
+ final String person when person != readerId =>
+ SuperTabTaskGroup.waitingOnOthers,
+ _ => SuperTabTaskGroup.needsYou,
+ },
+ // An agent at a question makes no progress, so its task goes quiet
+ // after 30 minutes: the question still waits on the reader.
+ ('quiet', _) when needsHuman > 0 => SuperTabTaskGroup.needsYou,
+ ('waiting', 'review' || 'revision' || 'blocked' || 'queued') ||
+ ('quiet' || 'orphaned', _) => SuperTabTaskGroup.waitingOnOthers,
+ ('waiting', 'starting') => SuperTabTaskGroup.working,
+ _ => SuperTabTaskGroup.rest,
+ };
+}
+
+/// [tasks] in their groups, in the groups' order and each in the order given:
+/// how the sidebar lists them and how next unread walks them.
+Map<SuperTabTaskGroup, List<SuperTabConversation>> superTabGroupTasks(
+ Iterable<SuperTabConversation> tasks, {
+ required String readerId,
+ int Function(SuperTabConversation task)? mentions,
+ int Function(SuperTabConversation task)? needsHuman,
+}) {
+ final grouped = {
+ for (final group in SuperTabTaskGroup.values)
+ group: <SuperTabConversation>[],
+ };
+ for (final task in tasks) {
+ grouped[superTabTaskGroupOf(
+ task,
+ readerId: readerId,
+ mentions: mentions?.call(task) ?? 0,
+ needsHuman: needsHuman?.call(task) ?? 0,
+ )]!
+ .add(task);
+ }
+ return grouped;
+}
diff --git a/desktop/lib/super_tabs/task_line.dart b/desktop/lib/super_tabs/task_line.dart
deleted file mode 100644
index f69fb0c00..000000000
--- a/desktop/lib/super_tabs/task_line.dart
+++ /dev/null
@@ -1,474 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter/material.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 '../widgets/laid_out_list.dart';
-import 'controller.dart';
-import 'message_row.dart' show SuperTabMessageRow;
-import 'model.dart';
-import 'reply_box.dart';
-
-/// A row too narrow for a task's name and word on one line keeps the name whole
-/// and puts the word under it (Quiet Swarm, screen 12).
-const _narrow = 360.0;
-
-/// What a task's message says of its state (Quiet Swarm, screen 2): one word,
-/// or Answer for the person asked. [readerId] is who is reading. A state this
-/// build does not know says nothing rather than a word it cannot stand behind.
-String superTabTaskWord(SuperTabMessage message, String readerId) =>
- switch (message.source['state']) {
- 'planned' => 'planned',
- 'working' => 'working',
- 'waiting' =>
- message.source['answerFor'] == readerId ? 'Answer' : 'working',
- 'review' => 'in review',
- 'ready' => 'ready',
- 'shipped' => 'shipped',
- 'done' => 'done',
- 'stopped' => 'stopped',
- _ => '',
- };
-
-/// A task's name, from the line's title. Its text is for older apps, which
-/// read it whole ("name · word"), and is the name only on a line with no title.
-String superTabTaskName(SuperTabMessage message) =>
- switch (message.source['title']) {
- final String title when title.isNotEmpty => title,
- _ => message.text,
- };
-
-IconData superTabTaskMark(SuperTabMessage message) =>
- switch (message.source['state']) {
- 'planned' => AppIcons.circleDashed,
- 'ready' => AppIcons.circleDot,
- 'shipped' || 'done' => AppIcons.check,
- 'stopped' => AppIcons.circleSlash,
- _ => AppIcons.circleDot,
- };
-
-/// What a proposal is for: its goal, as the server writes it (backend
-/// buddies.ts, under its own opening line), else its first line.
-String _proposalName(String text) {
- final lines = text.split('\n').map((line) => line.trim());
- for (final line in lines) {
- if (line.startsWith('Goal: ')) return line.substring(6).trim();
- }
- return lines.first;
-}
-
-/// A line's mark, in the column a message's avatar stands in, so its name starts
-/// where a message's text does.
-class _Gutter extends StatelessWidget {
- const _Gutter(this.mark);
- final Widget mark;
-
- @override
- Widget build(BuildContext context) => SizedBox(
- width: SuperTabMessageRow.avatarSize + SuperTabMessageRow.avatarGap,
- child: Align(
- alignment: Alignment.centerLeft,
- child: SizedBox(
- width: SuperTabMessageRow.avatarSize,
- child: Center(child: mark),
- ),
- ),
- );
-}
-
-/// One line that opens: the row both a task's and a proposal's message are.
-class _OpeningRow extends StatelessWidget {
- const _OpeningRow({required this.child, required this.label, this.onOpen});
-
- final Widget child;
- final String label;
- final VoidCallback? onOpen;
-
- @override
- Widget build(BuildContext context) => Semantics(
- button: onOpen != null,
- label: label,
- excludeSemantics: true,
- child: InkWell(
- onTap: onOpen,
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: SuperTabMessageRow.horizontalInset,
- vertical: grid.AppDesktop.menuInset,
- ),
- child: child,
- ),
- ),
- );
-}
-
-/// A task's message in a project's chat (Quiet Swarm, screen 2; the server's
-/// `task-line`, edited in place as the task moves): its mark, name and one word.
-class SuperTabTaskLine extends StatelessWidget {
- const SuperTabTaskLine({
- super.key,
- required this.message,
- required this.readerId,
- this.onOpen,
- });
-
- final SuperTabMessage message;
- final String readerId;
-
- /// Null when the reader's read does not hold the task: the line stays, and
- /// opens nothing.
- final VoidCallback? onOpen;
-
- @override
- Widget build(BuildContext context) {
- final word = superTabTaskWord(message, readerId);
- final answer = word == 'Answer';
- final title = superTabTaskName(message);
- final name = Text(
- title,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.text(medium: answer),
- );
- final said = Text(
- word,
- maxLines: 1,
- style: answer
- ? DesktopChrome.text(medium: true)
- : DesktopChrome.metadata(),
- );
- return _OpeningRow(
- label: word.isEmpty ? title : '$title, $word',
- onOpen: onOpen,
- child: LayoutBuilder(
- builder: (context, constraints) {
- final mark = _Gutter(
- Icon(
- superTabTaskMark(message),
- size: AppIcons.inlineSize,
- color: DesktopChrome.muted,
- ),
- );
- const gap = SizedBox(width: grid.AppDesktop.controlGap);
- if (constraints.maxWidth < _narrow && word.isNotEmpty) {
- return Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- mark,
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [name, said],
- ),
- ),
- ],
- );
- }
- return Row(
- children: [
- mark,
- Expanded(child: name),
- if (word.isNotEmpty) ...[gap, said],
- ],
- );
- },
- ),
- );
- }
-}
-
-/// A Buddy's proposal in a project's chat (Quiet Swarm, screen 1): whose it is
-/// and its first line; opening it shows the whole message.
-class SuperTabProposalLine extends StatelessWidget {
- const SuperTabProposalLine({
- super.key,
- required this.message,
- required this.owner,
- this.onOpen,
- });
-
- final SuperTabMessage message;
- final String owner;
- final VoidCallback? onOpen;
-
- @override
- Widget build(BuildContext context) {
- final text = 'Proposal from $owner: ${_proposalName(message.text)}';
- return _OpeningRow(
- label: text,
- onOpen: onOpen,
- child: Row(
- children: [
- _Gutter(
- Icon(
- AppIcons.chevronRight,
- size: AppIcons.inlineSize,
- color: DesktopChrome.muted,
- ),
- ),
- Expanded(
- child: Text(
- text,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.text(),
- ),
- ),
- ],
- ),
- );
- }
-}
-
-/// A task's own conversation beside the project's chat (Quiet Swarm, screen 3):
-/// its name, who has it and its word, its messages as the chat draws them, and
-/// a reply. Open in full gives it the main column.
-class SuperTabTaskPanel extends StatefulWidget {
- const SuperTabTaskPanel({
- super.key,
- required this.controller,
- required this.taskId,
- required this.word,
- this.mark,
- required this.rows,
- required this.row,
- required this.outgoing,
- required this.onClose,
- required this.onOpenInFull,
- });
-
- final SuperTabController controller;
- final String taskId;
-
- /// The word its line says.
- final String word;
-
- /// The mark its line shows; null once the line is out of the chat's rows.
- final IconData? mark;
-
- /// The task's whole conversation in time order: its steps' rows and every
- /// thread's replies, without hidden notices.
- final List<SuperTabMessage> Function() rows;
-
- final Widget Function(SuperTabMessage message) row;
-
- /// A reply on its way, or refused with its Retry, as the chat draws one.
- final Widget Function(SuperTabOutgoing sent) outgoing;
-
- final VoidCallback onClose;
- final VoidCallback onOpenInFull;
-
- @override
- State<SuperTabTaskPanel> createState() => _SuperTabTaskPanelState();
-}
-
-class _SuperTabTaskPanelState extends State<SuperTabTaskPanel> {
- int _read = -1;
- final _reply = TextEditingController();
- final _focus = FocusNode();
-
- SuperTabController get c => widget.controller;
-
- @override
- void initState() {
- super.initState();
- c.addListener(_follow);
- _reply.text = c.threadDraft(widget.taskId);
- _follow();
- }
-
- @override
- void didUpdateWidget(SuperTabTaskPanel old) {
- super.didUpdateWidget(old);
- if (old.controller != c) {
- old.controller.removeListener(_follow);
- c.addListener(_follow);
- }
- if (old.taskId != widget.taskId) {
- _read = -1;
- _reply.text = c.threadDraft(widget.taskId);
- _follow();
- }
- }
-
- @override
- void dispose() {
- c.removeListener(_follow);
- _reply.dispose();
- _focus.dispose();
- super.dispose();
- }
-
- /// Reads the task once, then only when it or a step has something new.
- void _follow() {
- final newest = c.taskProgress(widget.taskId);
- if (newest == null || newest == _read) return;
- _read = newest;
- unawaited(c.loadTaskMessages(widget.taskId));
- }
-
- bool get _busy => c.uploading || c.saving || c.hasPendingAction;
-
- /// A plain message in the task's own conversation, to the agent with the
- /// task. Refused while something else saves: the words stay in the box.
- Future<void> _send() async {
- final id = widget.taskId;
- final files = c.threadAttachments(id, id);
- if (_busy || (_reply.text.trim().isEmpty && files.isEmpty)) return;
- final task = c.snapshot?.conversation(id);
- final assignee = task?.assignment?['agentId'];
- c.setThreadDraft(id, _reply.text, conversationId: id);
- await c.sendThreadReply(
- to: (conversationId: id, root: id),
- plain: true,
- recipients: [
- if (assignee is String && task!.agentIds.contains(assignee)) assignee,
- ],
- onSending: () {
- if (mounted && widget.taskId == id) _reply.clear();
- },
- );
- }
-
- @override
- Widget build(BuildContext context) => ListenableBuilder(
- listenable: c,
- builder: (context, _) {
- grid.AppTheme.watch(context);
- final task = c.snapshot?.conversation(widget.taskId);
- final assignee = task?.assignment?['agentId'];
- final who = assignee is String ? c.snapshot?.agent(assignee)?.name : null;
- final rows = widget.rows();
- final pending = [
- for (final sent in c.outgoing(widget.taskId))
- if (sent.thread == null) sent,
- ];
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Container(
- // As high as the chat's header, so their rules meet.
- constraints: const BoxConstraints(minHeight: 51),
- alignment: Alignment.center,
- padding: const EdgeInsets.fromLTRB(
- SuperTabMessageRow.horizontalInset,
- 0,
- grid.AppDesktop.controlGap,
- 0,
- ),
- child: Row(
- children: [
- Expanded(
- child: Semantics(
- header: true,
- child: Text(
- 'Thread',
- style: DesktopChrome.text(medium: true),
- ),
- ),
- ),
- TextButton(
- key: const ValueKey('super-task-panel-full'),
- onPressed: widget.onOpenInFull,
- child: const Text('Open in full'),
- ),
- AppIconButton(
- key: const ValueKey('super-task-panel-close'),
- icon: AppIcons.close,
- tooltip: 'Close thread',
- onPressed: widget.onClose,
- ),
- ],
- ),
- ),
- Divider(height: 1, thickness: 1, color: DesktopChrome.rim),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- SuperTabMessageRow.horizontalInset,
- grid.AppDesktop.groupGap,
- SuperTabMessageRow.horizontalInset,
- grid.AppDesktop.groupGap,
- ),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- if (widget.mark case final mark?) ...[
- Icon(
- mark,
- size: AppIcons.inlineSize,
- color: DesktopChrome.muted,
- ),
- const SizedBox(width: grid.AppDesktop.controlGap),
- ],
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- task?.title ?? '',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.text(medium: true),
- ),
- Text(
- [
- ?who,
- if (widget.word.isNotEmpty) widget.word,
- ].join(' · '),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.metadata(),
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- Expanded(
- child: LaidOutListView.builder(
- itemCount: rows.length + pending.length,
- itemBuilder: (context, index) => index < rows.length
- ? widget.row(rows[index])
- : widget.outgoing(pending[index - rows.length]),
- ),
- ),
- if (c.canWrite && task?.archived == false)
- Padding(
- padding: const EdgeInsets.fromLTRB(
- grid.AppDesktop.groupGap,
- 0,
- grid.AppDesktop.groupGap,
- grid.AppDesktop.groupGap,
- ),
- child: SuperTabReplyBox(
- controller: c,
- text: _reply,
- focus: _focus,
- files: c.threadAttachments(widget.taskId, widget.taskId),
- enabled: true,
- writable: true,
- busy: _busy,
- error:
- c.composerError(widget.taskId) ??
- c.threadComposerError(widget.taskId, widget.taskId),
- onEdited: (text) => c.setThreadDraft(
- widget.taskId,
- text,
- conversationId: widget.taskId,
- ),
- onSend: () => unawaited(_send()),
- surfaceKey: const ValueKey('super-task-reply-surface'),
- fieldKey: const ValueKey('super-task-reply'),
- sendKey: const ValueKey('super-task-send'),
- ),
- ),
- ],
- );
- },
- );
-}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index f6de5e855..f2293b147 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -1,4 +1,5 @@
import 'dart:async';
+import 'dart:math' as math;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
@@ -68,7 +69,6 @@ import 'project_options.dart';
import 'project_status.dart';
import 'ship_row.dart';
import 'switch_pm.dart';
-import 'task_line.dart';
import 'pane_layout.dart';
import 'view_room.dart';
import 'swarm_type.dart';
@@ -720,7 +720,10 @@ class _SuperTabViewState extends State<SuperTabView>
bool _jumpUnread(int step) {
final snapshot = c.snapshot;
if (snapshot == null || c.accessRevoked) return false;
- final order = superTabSidebarOrder(c);
+ final order = superTabSidebarOrder(
+ c,
+ needsHuman: (group) => _needsHuman(group).length,
+ );
var at = order.indexOf(c.selectedId);
if (at < 0) at = step > 0 ? -1 : order.length;
for (var i = at + step; i >= 0 && i < order.length; i += step) {
@@ -2002,20 +2005,12 @@ class _SuperTabViewState extends State<SuperTabView>
messages,
(agentId) => c.snapshot?.agent(agentId),
);
- // A task's line says it shipped: its Shipped card, from before it had the
- // line, leaves. One with no line stays (Quiet Swarm, part 2).
- final lined = {
- for (final m in messages)
- if (m.isTaskLine) m.source['taskId'],
- };
return messages
.where(
(m) =>
_shown(m) &&
(replies || m.inMainStream) &&
- !answered.contains(m.id) &&
- !(SuperTabShipRow.shows(m) &&
- lined.contains(m.source['conversationId'])),
+ !answered.contains(m.id),
)
.toList();
}
@@ -2210,12 +2205,6 @@ class _SuperTabViewState extends State<SuperTabView>
bool get _terminalsVisible =>
!_devicesVisible && (widget.terminalsVisible || widget.terminal != null);
- /// Whom a Buddy's proposal speaks for, by name; null for other messages.
- String? _proposalOwner(SuperTabMessage message) =>
- message.proposalOwnerId == null
- ? null
- : buddyPersonName(c, message.proposalOwnerId!);
-
/// The reader's own chat with their Buddy.
bool _isBuddyChat(SuperTabConversation group) =>
c.buddyChat(group.projectId)?.id == group.id;
@@ -2350,15 +2339,56 @@ class _SuperTabViewState extends State<SuperTabView>
],
);
}
+ // A phone with too little height keeps its squeezed row as it was.
+ if (_phone) {
+ return ConstrainedBox(
+ constraints: BoxConstraints(
+ minHeight: grid.AppControl.heightFieldScaled,
+ ),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Expanded(child: field),
+ ...options,
+ attach,
+ send,
+ ],
+ ),
+ );
+ }
+ // The controls stay at the bottom-right as the message grows, level with
+ // its last line (Scholes, 11-03: centred, they drifted up the box). The
+ // field is padded to the row's height, so one line sits where it did,
+ // centred on the controls, and a longer message's last line keeps that
+ // place.
+ final row = grid.AppControl.heightFieldScaled;
+ // The line of the style the field draws with: a padding measured on
+ // another one left the chips a pixel off the line once the composer took
+ // Slack's 15 px on 22 px lines (#2732).
+ final style = SwarmType.composer(context);
+ final line =
+ MediaQuery.textScalerOf(context).scale(style.fontSize!) * style.height!;
+ final inset = math.max(0.0, (row - line) / 2);
return ConstrainedBox(
- constraints: BoxConstraints(minHeight: grid.AppControl.heightFieldScaled),
+ constraints: BoxConstraints(minHeight: row),
child: Row(
- crossAxisAlignment: CrossAxisAlignment.center,
+ crossAxisAlignment: CrossAxisAlignment.end,
children: [
- Expanded(child: field),
- ...options,
- attach,
- send,
+ Expanded(
+ child: Padding(
+ padding: EdgeInsets.symmetric(vertical: inset),
+ child: field,
+ ),
+ ),
+ // As tall as the row at least, the controls centred in it as before;
+ // taller with larger text.
+ ConstrainedBox(
+ constraints: BoxConstraints(minHeight: row),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [...options, attach, send],
+ ),
+ ),
],
),
);
@@ -2423,11 +2453,10 @@ class _SuperTabViewState extends State<SuperTabView>
setState(() => _showPullRequests = true);
}
- /// Members takes the right side from an open thread or task, as in Slack.
+ /// Members takes the right side from an open thread, as in Slack.
void _toggleRoster() {
if (!_rosterOpen) c.closeThread();
setState(() {
- if (!_rosterOpen) _openedTask = null;
_rosterOpen = !_rosterOpen;
});
}
@@ -2935,7 +2964,6 @@ class _SuperTabViewState extends State<SuperTabView>
message: message,
dimmed: sent.state == SuperTabOutgoingState.sending,
author: _shownAuthor(c, message),
- proposalOwner: _proposalOwner(message),
person: person,
member: _member,
grouped: grouped,
@@ -3012,31 +3040,6 @@ class _SuperTabViewState extends State<SuperTabView>
bool inThread = false,
}) {
_index();
- // A task's message and a Buddy's proposal are one line that opens (Quiet
- // Swarm, screens 1 and 2); inside its own thread, a proposal reads whole.
- if (message.isTaskLine) {
- final taskId = message.source['taskId'];
- return SuperTabTaskLine(
- key: ValueKey('super-message-${message.id}'),
- message: message,
- readerId: c.accountId,
- onOpen: taskId is String && c.snapshot?.conversation(taskId) != null
- ? () => _openTask(taskId, message.id)
- : null,
- );
- }
- final proposer = inThread ? null : _proposalOwner(message);
- if (proposer != null) {
- return SuperTabProposalLine(
- key: ValueKey('super-message-${message.id}'),
- message: message,
- owner: proposer,
- onOpen: () {
- setState(() => _openedTask = null);
- c.openThread(message.id);
- },
- );
- }
if (SuperTabShipRow.shows(message)) {
return SuperTabShipRow(
key: ValueKey(
@@ -3108,7 +3111,6 @@ class _SuperTabViewState extends State<SuperTabView>
facts: _facts,
),
author: _shownAuthor(c, message),
- proposalOwner: _proposalOwner(message),
// A person is named by their username, as they are tagged.
mentions: [
for (final id in message.mentions)
@@ -3227,9 +3229,6 @@ class _SuperTabViewState extends State<SuperTabView>
/// The open thread of the selected conversation, beside the chat.
Widget? _threadPanel() {
final open = c.openedThread;
- // A thread opened from anywhere takes the panel's place, for good.
- if (open != null) _openedTask = null;
- if (_taskPanel() case final panel?) return panel;
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};
@@ -3246,42 +3245,6 @@ class _SuperTabViewState extends State<SuperTabView>
);
}
- /// The task a line opened beside its project's chat (Quiet Swarm, screen 3):
- /// which, and the line, whose word the panel says.
- ({String id, String line, String chat})? _openedTask;
-
- void _openTask(String taskId, String line) {
- c.closeThread();
- setState(() => _openedTask = (id: taskId, line: line, chat: c.selectedId));
- }
-
- Widget? _taskPanel() {
- final open = _openedTask;
- final task = open == null ? null : c.snapshot?.conversation(open.id);
- if (open == null || task == null || open.chat != c.selectedId) return null;
- final line = c
- .messages(open.chat)
- .where((m) => m.id == open.line)
- .firstOrNull;
- final byId = {for (final m in c.taskMessages(open.id)) m.id: m};
- return SuperTabTaskPanel(
- key: ValueKey('super-task-panel-${open.id}'),
- controller: c,
- taskId: open.id,
- word: line == null ? '' : superTabTaskWord(line, c.accountId),
- mark: line == null ? null : superTabTaskMark(line),
- // The whole conversation (screen 3): agents answer with replies.
- rows: () => _shownMessages(open.id, replies: true),
- row: (message) => _message(message, false, byId, inThread: true),
- outgoing: (sent) => _outgoingRow(sent, byId, grouped: false),
- onClose: () => setState(() => _openedTask = null),
- onOpenInFull: () {
- setState(() => _openedTask = null);
- unawaited(c.select(open.id));
- },
- );
- }
-
/// 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;
@@ -4509,7 +4472,6 @@ class _SuperTabViewState extends State<SuperTabView>
child: BlockSemantics(
child: GestureDetector(
onTap: () {
- setState(() => _openedTask = null);
c.closeThread();
},
child: ColoredBox(
diff --git a/desktop/test/benchmarks/super_tab_sidebar_benchmark.dart b/desktop/test/benchmarks/super_tab_sidebar_benchmark.dart
index 03681aa3b..55eb49b3c 100644
--- a/desktop/test/benchmarks/super_tab_sidebar_benchmark.dart
+++ b/desktop/test/benchmarks/super_tab_sidebar_benchmark.dart
@@ -11,9 +11,17 @@ import '../support/super_tab_fixture.dart';
import 'swarm_benchmark.dart' show distribution;
void main() {
- for (final (projects, perProject) in [(5, 50), (20, 200)]) {
+ // `mixed`: open tasks in every state the sidebar groups by (#2309): a
+ // quarter working, a quarter waiting on a person, a quarter in review, a
+ // quarter with no work, four in five unread.
+ for (final (projects, perProject, mixed) in [
+ (5, 50, false),
+ (20, 200, false),
+ (5, 50, true),
+ (20, 200, true),
+ ]) {
testWidgets(
- 'Swarm sidebar rebuild with $projects projects x $perProject conversations',
+ 'Swarm sidebar rebuild with $projects projects x $perProject conversations${mixed ? ', mixed states' : ''}',
(tester) async {
final server = ConversationServer();
final ids = ['lead', for (var p = 1; p < projects; p++) 'p$p'];
@@ -48,6 +56,25 @@ void main() {
'projectId': id,
'number': n,
'archived': n % 4 == 0,
+ if (mixed) ...{
+ 'archived': false,
+ 'lastMessageSequence': n % 5 == 0 ? 0 : n,
+ if (n % 4 != 3)
+ 'assignment': {
+ 'agentId': 'a1',
+ 'status': n % 4 == 2 ? 'review' : 'working',
+ 'progressAt': 1,
+ },
+ if (n % 4 == 1)
+ 'liveness': {
+ 'state': 'waiting',
+ 'why': 'person',
+ 'personId': 'other',
+ 'since': 1,
+ },
+ if (n % 4 == 2)
+ 'liveness': {'state': 'waiting', 'why': 'review', 'since': 1},
+ },
});
}
}
@@ -73,7 +100,6 @@ void main() {
return ProjectSidebar(
controller: controller,
onSelect: controller.select,
- onAddAgent: (_) {},
needsHuman: (_) => 0,
);
},
@@ -100,6 +126,7 @@ void main() {
'benchmark': 'super_tab_sidebar_rebuild',
'projects': projects,
'conversationsPerProject': perProject,
+ 'mixed': mixed,
...distribution(times),
}),
);
diff --git a/desktop/test/super_tab_activity_test.dart b/desktop/test/super_tab_activity_test.dart
index 38fa7d62d..cb315bfb5 100644
--- a/desktop/test/super_tab_activity_test.dart
+++ b/desktop/test/super_tab_activity_test.dart
@@ -11,6 +11,7 @@ import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/model.dart';
import 'package:harness/super_tabs/parts.dart';
import 'package:harness/super_tabs/project_sidebar.dart';
+import 'package:harness/super_tabs/task_groups.dart';
import 'package:harness/super_tabs/view.dart';
import 'package:harness/super_tabs/workgroup_name.dart';
import 'package:harness/widgets/desktop_chrome.dart';
@@ -556,6 +557,8 @@ void main() {
final c = await openHere(server);
await SuperTabAttention.of(c).mentions.load();
c.toggleProject('lead');
+ // A muted chat's tag needs no one: it is in The rest, unfolded here.
+ c.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
await c.setNotify('offline', SuperTabNotify.muted);
await pumpSidebar(tester, c, brightness: brightness);
expect(find.text('Notifications'), findsNothing);
@@ -602,6 +605,8 @@ void main() {
fromLead(server, 'Hushed news', conversationId: 'hushed');
final c = await openHere(server);
c.toggleProject('lead');
+ // Workgroups with no work are in The rest, unfolded here (#2309).
+ c.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
await c.setNotify('hushed', SuperTabNotify.muted);
await pumpSidebar(tester, c);
expect(find.byKey(const ValueKey('super-group-quiet')), findsOneWidget);
diff --git a/desktop/test/super_tab_attention_test.dart b/desktop/test/super_tab_attention_test.dart
index 9b8ff89b1..54b01e0f8 100644
--- a/desktop/test/super_tab_attention_test.dart
+++ b/desktop/test/super_tab_attention_test.dart
@@ -12,6 +12,7 @@ import 'package:harness/super_tabs/buddy_rows.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/model.dart';
import 'package:harness/super_tabs/project_sidebar.dart';
+import 'package:harness/super_tabs/task_groups.dart';
import 'package:harness/widgets/desktop_chrome.dart';
import 'support/super_tab_fixture.dart';
@@ -382,6 +383,8 @@ void main() {
await attention.load();
c.select('open');
if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');
+ // Workgroups with no work are in The rest, unfolded here (#2309).
+ c.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
await pumpSidebar(tester, c, attention, brightness: brightness);
final read = rowText(tester, 'super-group-lead', 'web-project');
expect(read.style?.color, DesktopChrome.muted);
@@ -890,8 +893,8 @@ void main() {
});
});
- testWidgets('a read workgroup with a tag of the reader is never behind '
- '"… N more"', (tester) async {
+ testWidgets('a read workgroup with a tag of the reader is listed under '
+ 'Needs you while The rest is folded', (tester) async {
final server = projectServer();
server.followedThreads = {'unread': [], 'read': [], 'more': false};
final groups = server.state['conversations'] as List;
@@ -915,9 +918,10 @@ void main() {
c.toggleProject('lead');
await pumpSidebar(tester, c, attention);
expect(
- find.byKey(const ValueKey('super-project-more-lead')),
+ find.byKey(const ValueKey('super-task-group-lead-needsYou')),
findsOneWidget,
);
+ expect(find.byKey(const ValueKey('super-group-g28')), findsNothing);
expect(find.byKey(const ValueKey('super-group-offline')), findsOneWidget);
expect(inRow('super-group-offline', find.text('1')), findsOneWidget);
await close(tester, c);
diff --git a/desktop/test/super_tab_buddies_test.dart b/desktop/test/super_tab_buddies_test.dart
index 1bc2137b6..efc33991f 100644
--- a/desktop/test/super_tab_buddies_test.dart
+++ b/desktop/test/super_tab_buddies_test.dart
@@ -11,6 +11,7 @@ import 'package:harness/super_tabs/buddies.dart' show kBuddyEngineRefusals;
import 'package:harness/super_tabs/buddy_machines.dart' show kBuddyNoMachine;
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/view.dart';
+import 'package:harness/super_tabs/task_groups.dart';
import 'support/buddy_fixture.dart';
import 'support/pm_chat_fixture.dart';
@@ -1477,6 +1478,8 @@ void main() {
});
final c = await show(tester, server);
if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');
+ // Workgroups with no work are in The rest, unfolded here (#2309).
+ c.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
await tester.pumpAndSettle();
expect(
@@ -1540,7 +1543,7 @@ void main() {
group('a proposal in the project chat', () {
testWidgets(
- "opens labelled from the server's tag, with whose behalf it is on",
+ "legacy content stays complete and opens with ordinary Reply",
(tester) async {
final server = buddySwarm();
giveBuddy(server);
@@ -1563,20 +1566,18 @@ void main() {
await c.select('lead');
await tester.pumpAndSettle();
- // In the chat it is one line; opened, it reads whole, labelled.
- expect(
- find.byKey(const ValueKey('super-proposal-label')),
- findsNothing,
+ expect(find.textContaining('Scope: Desktop only'), findsOneWidget);
+ final row = find.byKey(ValueKey('super-message-${proposal['id']}'));
+ await tester.tap(
+ find.descendant(of: row, matching: find.byTooltip('Reply')),
);
- await tester.tap(find.textContaining('Proposal from'));
await tester.pumpAndSettle();
+ expect(c.openedThread?.root, proposal['id']);
expect(
- find.descendant(
- of: find.byKey(const ValueKey('super-proposal-label')),
- matching: find.text("Proposal · on ken.tran's behalf"),
- ),
- findsOneWidget,
+ find.byKey(const ValueKey('super-proposal-label')),
+ findsNothing,
);
+ expect(find.textContaining('Scope: Desktop only'), findsNWidgets(2));
await close(tester, c);
},
);
diff --git a/desktop/test/super_tab_buddy_chat_counts_test.dart b/desktop/test/super_tab_buddy_chat_counts_test.dart
index a4605c1ea..1d3dc22b0 100644
--- a/desktop/test/super_tab_buddy_chat_counts_test.dart
+++ b/desktop/test/super_tab_buddy_chat_counts_test.dart
@@ -25,6 +25,7 @@ import 'package:harness/super_tabs/buddy_chat_shortcut.dart';
import 'package:harness/super_tabs/buddy_rows.dart';
import 'package:harness/super_tabs/project_sidebar.dart';
import 'package:harness/super_tabs/view.dart';
+import 'package:harness/super_tabs/task_groups.dart';
import 'package:harness/widgets/desktop_chrome.dart';
import 'box_render_preview_test.dart' show loadPreviewFonts;
@@ -524,6 +525,8 @@ void main() {
(server.state['conversations'] as List).last['number'] = 196;
final c = await show(tester, server);
c.toggleProject('lead');
+ // Workgroups with no work are in The rest, unfolded here (#2309).
+ c.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
await tester.pumpAndSettle();
final row = find.byKey(const ValueKey('super-group-offline'));
final name = find.descendant(
diff --git a/desktop/test/super_tab_chat_test.dart b/desktop/test/super_tab_chat_test.dart
index 67cda700e..0476a300b 100644
--- a/desktop/test/super_tab_chat_test.dart
+++ b/desktop/test/super_tab_chat_test.dart
@@ -395,6 +395,9 @@ void main() {
expect(projectWeight(), grid.AppFont.semibold);
await tester.tap(find.byKey(const ValueKey('super-group-lead')));
await tester.pumpAndSettle();
+ // A workgroup with no work is in The rest, which starts folded (#2309).
+ await tester.tap(find.byKey(const ValueKey('super-task-group-lead-rest')));
+ await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('super-group-offline')));
await tester.pumpAndSettle();
expect(find.text('An unread workgroup update'), findsOneWidget);
diff --git a/desktop/test/super_tab_composer_chips_bottom_test.dart b/desktop/test/super_tab_composer_chips_bottom_test.dart
new file mode 100644
index 000000000..f03deba8f
--- /dev/null
+++ b/desktop/test/super_tab_composer_chips_bottom_test.dart
@@ -0,0 +1,229 @@
+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/controller.dart';
+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_COMPOSER_CHIPS_SHOTS'];
+
+/// Scholes, 11-03: the chips beside the message (New session, attach, send)
+/// stay at the bottom-right of the box as the message grows, level with its
+/// last line, rather than drifting to the middle of a tall box; one line
+/// reads as before. The thread reply box keeps its chips on their own row
+/// under the text.
+void main() {
+ setUpAll(() async {
+ if (shots != null) await loadPreviewFonts();
+ });
+
+ const fiveLines =
+ 'Five things for today:\nmeasure prod CPU\ncheck the '
+ 'release notes\nanswer Diego\nand plan the next batch';
+
+ /// The reader's own Buddy chat with its Buddy running: the main chat offers
+ /// New session beside attach and send.
+ ConversationServer buddyChat() {
+ final server = ConversationServer()..threads = true;
+ server.state['threadSessions'] = true;
+ server.state['sessionsFromChat'] = true;
+ final chat = (server.state['conversations'] as List)[1] as Map;
+ chat
+ ..['kind'] = 'buddy'
+ ..['buddyOwnerId'] = 'owner'
+ ..['title'] = 'Wren'
+ ..['agentIds'] = ['buddy-main'];
+ (server.state['agents'] as List).add({
+ 'id': 'buddy-main',
+ 'name': 'Wren',
+ 'displayName': 'Wren',
+ 'machineId': 'mac',
+ 'harnessId': 'h-main',
+ 'contributorId': 'owner',
+ 'buddyOf': {'personId': 'owner', 'generation': 'g1'},
+ 'configuration': {'engine': 'claude'},
+ });
+ server.append(
+ 'Measure prod CPU for the last day',
+ conversationId: 'offline',
+ );
+ server.append('On it', conversationId: 'offline');
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1';
+ return server;
+ }
+
+ final picture = GlobalKey();
+
+ Future<SuperTabController> show(
+ WidgetTester tester, {
+ Brightness brightness = Brightness.light,
+ bool thread = false,
+ }) async {
+ final c = buddyChat().controller();
+ 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 c.select('offline');
+ await tester.pumpAndSettle();
+ if (thread) {
+ c.openThread('message-1');
+ await tester.pumpAndSettle();
+ }
+ return c;
+ }
+
+ Finder field({required bool thread}) => find.byKey(
+ ValueKey(thread ? 'super-thread-composer' : 'super-message-composer'),
+ );
+
+ /// The global rect of the last line of [text] in the field: where the caret
+ /// sits at its end.
+ Rect lastLine(WidgetTester tester, Finder box) {
+ final state = tester.state<EditableTextState>(
+ find.descendant(of: box, matching: find.byType(EditableText)),
+ );
+ final editable = state.renderEditable;
+ final caret = editable.getLocalRectForCaret(
+ TextPosition(offset: state.textEditingValue.text.length),
+ );
+ return MatrixUtils.transformRect(editable.getTransformTo(null), caret);
+ }
+
+ Future<void> type(WidgetTester tester, Finder box, String text) async {
+ await tester.enterText(box, text);
+ await tester.pumpAndSettle();
+ }
+
+ group('the main chat', () {
+ final chips = [
+ find.byKey(const ValueKey('super-chat-new-session')),
+ find.byKey(const ValueKey('new-harness-attach')),
+ find.byTooltip('Send message'),
+ ];
+ final surface = find.byKey(
+ const ValueKey('super-message-composer-surface'),
+ );
+
+ testWidgets('one line: the chips are centered on the line, as before', (
+ tester,
+ ) async {
+ await show(tester);
+ final box = field(thread: false);
+ await type(tester, box, 'Check the release notes.');
+ final line = lastLine(tester, box);
+ for (final chip in chips) {
+ expect(
+ (tester.getCenter(chip).dy - line.center.dy).abs(),
+ lessThan(1),
+ reason: '$chip',
+ );
+ }
+ // The box is as tall as before: one control row inside its padding.
+ expect(
+ tester.getRect(surface).height,
+ closeTo(grid.AppControl.heightFieldScaled + 16, 1),
+ );
+ });
+
+ testWidgets('five lines: the chips stay at the bottom-right, level with '
+ 'the last line', (tester) async {
+ await show(tester);
+ final box = field(thread: false);
+ await type(tester, box, fiveLines);
+ final line = lastLine(tester, box);
+ final first = tester.getRect(box).top;
+ expect(line.top - first, greaterThan(line.height * 3.5));
+ for (final chip in chips) {
+ final rect = tester.getRect(chip);
+ expect(
+ (rect.center.dy - line.center.dy).abs(),
+ lessThan(1),
+ reason: '$chip',
+ );
+ expect(rect.bottom, lessThanOrEqualTo(tester.getRect(surface).bottom));
+ }
+ // Send at the right end, and the text keeps its width.
+ expect(
+ tester.getRect(chips.last).right,
+ greaterThan(tester.getRect(surface).right - 16),
+ );
+ expect(
+ tester.getRect(box).right,
+ lessThanOrEqualTo(tester.getRect(chips.first).left),
+ );
+ });
+ });
+
+ testWidgets('the thread reply box: its chips stay on their own row under the '
+ 'last line, at the right', (tester) async {
+ await show(tester, thread: true);
+ final box = field(thread: true);
+ await type(tester, box, fiveLines);
+ final line = lastLine(tester, box);
+ final surface = tester.getRect(
+ find.byKey(const ValueKey('super-thread-composer-surface')),
+ );
+ final send = tester.getRect(
+ find.byKey(const ValueKey('super-thread-send')),
+ );
+ expect(send.top, greaterThanOrEqualTo(line.bottom));
+ expect(send.right, greaterThan(surface.right - 16));
+ expect(send.bottom, lessThanOrEqualTo(surface.bottom));
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final scene in ['chat-1', 'chat-5', 'thread-1', 'thread-5']) {
+ testWidgets('screenshots for review ($scene, ${brightness.name})', (
+ tester,
+ ) async {
+ final thread = scene.startsWith('thread');
+ await show(tester, brightness: brightness, thread: thread);
+ await type(
+ tester,
+ field(thread: thread),
+ scene.endsWith('5') ? fiveLines : 'Check the release notes.',
+ );
+ await tester.runAsync(() async {
+ final boundary =
+ picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 2);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/composer-chips-$scene-${brightness.name}.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ await tester.pumpWidget(const SizedBox());
+ }, skip: shots == null);
+ }
+ }
+}
diff --git a/desktop/test/super_tab_dial_test.dart b/desktop/test/super_tab_dial_test.dart
index 3fa216ebc..fcc930d63 100644
--- a/desktop/test/super_tab_dial_test.dart
+++ b/desktop/test/super_tab_dial_test.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/logging/app_log.dart';
import 'package:harness/super_tabs/controller.dart';
import 'support/super_tab_fixture.dart';
@@ -484,6 +485,208 @@ void main() {
expect(row(announces(f).last).containsKey('threadRoot'), isFalse);
});
+ test('a hidden thread pane still names its root to the dial', () async {
+ final (f, c) = await openChats();
+ c.select('design-fix');
+ c.openThread('m-root');
+ await settle();
+ final before = announces(f).length;
+ c.threadPaneHidden();
+ await settle();
+ // Hiding the pane re-announces nothing and keeps the root in the row.
+ expect(announces(f).length, before);
+ expect(row(announces(f).last)['threadRoot'], 'm-root');
+ f.app.announceWindowForeground();
+ await settle();
+ expect(row(announces(f).last)['threadRoot'], 'm-root');
+ });
+
+ test('closing the pane drops the root from the announce', () async {
+ final (f, c) = await openChats();
+ c.select('design-fix');
+ c.openThread('m-root');
+ c.threadPaneHidden();
+ await settle();
+ c.closeThread();
+ await settle();
+ expect(row(announces(f).last).containsKey('threadRoot'), isFalse);
+ });
+
+ Future<void> threadOnly(
+ SuperTabLaunchFixture f,
+ String conversation,
+ Object? root,
+ ) => f.app.handleEventForTest('m', {
+ 'type': 'dial_super_tab',
+ 'payload': {
+ 'superTabId': tabId,
+ 'conversationId': conversation,
+ 'threadRoot': root,
+ 'threadOnly': true,
+ },
+ });
+
+ test('a threadOnly open does not raise the window or change the active Swarm', () async {
+ final (f, c) = await openChats();
+ final tab = f.app.activeSwarmId;
+ f.app.newSwarm(newTabPage: true);
+ final other = f.app.activeSwarmId;
+ var raised = 0;
+ final sub = f.app.deviceWindowRequests.listen((_) => raised++);
+ f.connection.server.append('Fix it', conversationId: 'design-lead');
+ final root = 'message-${f.connection.server.revision}';
+ await threadOnly(f, 'design-lead', root);
+ await settle();
+ await sub.cancel();
+ expect(raised, 0);
+ expect(f.app.activeSwarmId, other);
+ expect(f.app.activeSwarmId, isNot(tab));
+ expect(c.openedThread?.conversationId, 'design-lead');
+ expect(c.openedThread?.root, root);
+ });
+
+ test('a threadOnly open in a group chat opens the group\'s thread', () async {
+ final (f, c) = await openChats();
+ f.connection.server.append('Fix it', conversationId: 'design-fix');
+ final root = 'message-${f.connection.server.revision}';
+ await threadOnly(f, 'design-fix', root);
+ await settle();
+ expect(c.selectedId, 'design-fix');
+ expect(c.openedThread?.conversationId, 'design-fix');
+ expect(c.openedThread?.root, root);
+ });
+
+ test('a threadOnly close closes only that conversation\'s thread', () async {
+ final (f, c) = await openChats();
+ c.select('design-fix');
+ c.openThread('m-root');
+ await threadOnly(f, 'design-fix', null);
+ await settle();
+ expect(c.openedThread, isNull);
+ expect(c.selectedId, 'design-fix');
+ });
+
+ test('a threadOnly close for another conversation changes nothing', () async {
+ final (f, c) = await openChats();
+ c.select('design-fix');
+ c.openThread('m-root');
+ await threadOnly(f, 'design-lead', null);
+ await settle();
+ expect(c.openedThread?.root, 'm-root');
+ expect(c.selectedId, 'design-fix');
+ });
+
+ // A dial open that waits for its root (the post is still on its way).
+ String nextRoot(SuperTabLaunchFixture f) =>
+ 'message-${f.connection.server.revision + 1}';
+
+ Future<void> arrive(SuperTabLaunchFixture f, SuperTabController c) async {
+ f.connection.server.append('Fix it', conversationId: 'design-lead');
+ await c.refresh();
+ await settle();
+ }
+
+ test('a thread the person opens while a dial open waits is kept', () async {
+ final (f, c) = await openChats();
+ final root = nextRoot(f);
+ await threadOnly(f, 'design-lead', root);
+ await settle();
+ expect(c.openedThread, isNull);
+ c.openThread('m-root');
+ await arrive(f, c);
+ expect(c.openedThread?.root, 'm-root');
+ });
+
+ test('a leave while the dial\'s thread still waits opens nothing later', () async {
+ final (f, c) = await openChats();
+ final root = nextRoot(f);
+ await threadOnly(f, 'design-lead', root);
+ await settle();
+ await threadOnly(f, 'design-lead', null);
+ await settle();
+ await arrive(f, c);
+ expect(c.openedThread, isNull);
+ });
+
+ test('a newer dial thread replaces a pending one', () async {
+ final (f, c) = await openChats();
+ final first = 'message-2';
+ await threadOnly(f, 'design-lead', first);
+ await settle();
+ f.connection.server.append('Other', conversationId: 'design-lead');
+ final second = 'message-${f.connection.server.revision}';
+ await threadOnly(f, 'design-lead', second);
+ await settle();
+ await arrive(f, c);
+ expect(c.openedThread?.root, second);
+ });
+
+ test('a thread the dial opens in a background tab marks nothing read until shown', () async {
+ final (f, c) = await openChats();
+ final server = f.connection.server..threads = true;
+ server.append('Fix it', conversationId: 'design-lead');
+ final root = 'message-${server.revision}';
+ server.append('Reply', conversationId: 'design-lead');
+ server.messages.last
+ ..['thread'] = root
+ ..['replyTo'] = root;
+ await threadOnly(f, 'design-lead', root);
+ await settle();
+ await c.loadThread();
+ await settle();
+ expect(c.openedThread?.root, root);
+ expect(server.threadMarkPosts, isEmpty);
+ c.threadPaneShown();
+ await settle();
+ expect(server.threadMarkPosts, hasLength(1));
+ });
+
+ // Review of #2756 (ENGINEERING.md §1, §2): only the thread-only message
+ // opens or closes the dial's thread. An ordinary pick, which nothing sends
+ // with a root, keeps whatever thread the person has open.
+ test('an ordinary dial pick leaves the open thread as it is, whatever root it names', () async {
+ final (f, c) = await openChats();
+ f.connection.server.append('Fix it', conversationId: 'design-lead');
+ final posted = 'message-${f.connection.server.revision}';
+ c.select('design-lead');
+ await settle();
+ c.openThread('m-root');
+ for (final root in [posted, null]) {
+ await f.app.handleEventForTest('m', {
+ 'type': 'dial_super_tab',
+ 'payload': {
+ 'superTabId': tabId,
+ 'projectId': 'design',
+ 'threadRoot': root,
+ },
+ });
+ await settle();
+ expect(c.selectedId, 'design-lead');
+ expect(c.openedThread?.root, 'm-root', reason: '$root');
+ }
+ });
+
+ // Review of #2756 (ENGINEERING.md §6): a dial thread whose root never
+ // reaches the chat is given up, and the log says so, without its root.
+ test('a dial thread whose root never arrives is given up, and logged', () async {
+ final lines = <String>[];
+ final previous = appLog;
+ appLog = _RecordingLog(lines);
+ addTearDown(() => appLog = previous);
+ final (f, c) = await openChats();
+ f.app.dialThreadWaitForTest = const Duration(milliseconds: 20);
+ await threadOnly(f, 'design-lead', 'message-never');
+ // Waits for the give-up's log line itself, never a fixed time (ENGINEERING.md §3).
+ final given = DateTime.now().add(const Duration(seconds: 5));
+ while (!lines.any((l) => l.contains('thread')) &&
+ DateTime.now().isBefore(given)) {
+ await settle();
+ }
+ expect(c.openedThread, isNull);
+ expect(lines.where((l) => l.contains('thread')), hasLength(1));
+ expect(lines.join('\n'), isNot(contains('message-never')));
+ });
+
test('a decisions view or an unloaded Swarm leaves conversationId out', () async {
final (f, c) = await openChats();
c.select('design-pm');
@@ -509,3 +712,16 @@ void main() {
await settle();
});
}
+
+class _RecordingLog implements AppLog {
+ _RecordingLog(this.lines);
+ final List<String> lines;
+ @override
+ void record(
+ AppLogLevel level,
+ String category,
+ String message, {
+ Object? error,
+ StackTrace? stackTrace,
+ }) => lines.add('$category $message');
+}
diff --git a/desktop/test/super_tab_new_messages_test.dart b/desktop/test/super_tab_new_messages_test.dart
index 4016ceac2..59cc0a71c 100644
--- a/desktop/test/super_tab_new_messages_test.dart
+++ b/desktop/test/super_tab_new_messages_test.dart
@@ -732,6 +732,9 @@ void main() {
?.fontWeight;
await tester.tap(find.byKey(const ValueKey('super-group-lead')));
await tester.pumpAndSettle();
+ // A workgroup with no work is in The rest, which starts folded (#2309).
+ await tester.tap(find.byKey(const ValueKey('super-task-group-lead-rest')));
+ await tester.pumpAndSettle();
expect(weight(), grid.AppFont.semibold);
// Read on another device.
server.markReadElsewhere('offline', 3);
diff --git a/desktop/test/super_tab_plain_work_shots_test.dart b/desktop/test/super_tab_plain_work_shots_test.dart
new file mode 100644
index 000000000..7503da5d4
--- /dev/null
+++ b/desktop/test/super_tab_plain_work_shots_test.dart
@@ -0,0 +1,211 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.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';
+import 'swarm_state_test.dart' show createApp;
+
+/// Set to a folder to write the PR's screenshots there.
+final shots = Platform.environment['SUPER_TAB_PLAIN_WORK_SHOTS'];
+
+/// Plain chat proposals and tasks (task #2294) as the PR shows them, in both
+/// appearances: the project chat with a Buddy's proposal and a task the PM
+/// opened, each one ordinary "Let's build" message, and the proposal's thread
+/// with its details and the PM's replies, in the server's own words.
+void main() {
+ setUpAll(() async {
+ if (shots == null) return;
+ await loadPreviewFonts();
+ if (!Platform.isMacOS) return;
+ for (final font in [
+ ('.AppleSystemUIFontMonospaced', '/System/Library/Fonts/SFNSMono.ttf'),
+ ('Menlo', '/System/Library/Fonts/Menlo.ttc'),
+ ('Apple Symbols', '/System/Library/Fonts/Apple Symbols.ttf'),
+ ]) {
+ final bytes = ByteData.sublistView(await File(font.$2).readAsBytes());
+ await (FontLoader(font.$1)..addFont(Future.value(bytes))).load();
+ }
+ });
+
+ const diego = {'kind': 'person', 'id': 'owner', 'name': '[email protected]'};
+ const buddy = {
+ 'kind': 'agent',
+ 'id': 'buddy-main',
+ 'name': 'Buddy',
+ 'displayName': "diego's Buddy",
+ };
+ const river = {
+ 'kind': 'agent',
+ 'id': 'agent-lead',
+ 'name': 'River',
+ 'displayName': 'River',
+ };
+
+ for (final brightness in Brightness.values) {
+ for (final view in ['chat', 'thread']) {
+ testWidgets('screenshot $view (${brightness.name})', (tester) async {
+ final picture = GlobalKey();
+ final app = createApp(connected: true);
+ addTearDown(app.dispose);
+ final server = ConversationServer()..threads = true;
+ (server.state['people'] as List).first['email'] = '[email protected]';
+ // The chat has its PM, as a project chat does.
+ (server.state['conversations'] as List)[1] as Map
+ ..['leadId'] = 'agent-lead'
+ ..['agentIds'] = ['agent-lead'];
+ (server.state['agents'] as List).add({
+ 'id': 'agent-lead',
+ 'name': 'River',
+ 'displayName': 'River',
+ 'machineId': 'm',
+ 'harnessId': 'h-lead',
+ 'contributorId': 'owner',
+ 'machineOwnerId': 'owner',
+ 'configuration': {'engine': 'claude', 'model': 'opus'},
+ });
+ final now = DateTime.now().toUtc();
+ void say(
+ String text,
+ Map<String, Object> author, {
+ String? thread,
+ int minutesAgo = 0,
+ Map<String, Object>? source,
+ }) {
+ server.append(text, conversationId: 'offline');
+ server.messages.last
+ ..['author'] = author
+ ..['createdAt'] = now
+ .subtract(Duration(minutes: minutesAgo))
+ .toIso8601String();
+ if (thread != null) {
+ server.messages.last
+ ..['thread'] = thread
+ ..['replyTo'] = thread;
+ }
+ if (source != null) server.messages.last['source'] = source;
+ }
+
+ say(
+ "Let's build: Hub reports hide an item from everyone",
+ diego,
+ minutesAgo: 210,
+ source: {
+ 'kind': 'buddy-proposal',
+ 'personId': 'owner',
+ 'buddyId': 'buddy-main',
+ },
+ );
+ say(
+ "Goal: three readers' reports hide a post from everyone.\n"
+ 'Scope: backend fix, tested on a real database.\n'
+ 'Priority: normal',
+ buddy,
+ thread: 'message-1',
+ minutesAgo: 210,
+ );
+ say(
+ 'On it: Dune is building it.',
+ river,
+ thread: 'message-1',
+ minutesAgo: 150,
+ source: {'kind': 'system'},
+ );
+ say(
+ 'Ready for review: PR #2710',
+ river,
+ thread: 'message-1',
+ minutesAgo: 50,
+ source: {'kind': 'system'},
+ );
+ say(
+ 'Merged: PR #2710. Ships in the next release.',
+ river,
+ thread: 'message-1',
+ minutesAgo: 5,
+ source: {'kind': 'system'},
+ );
+ say(
+ "Let's build: Desktop tests pass on any date",
+ river,
+ minutesAgo: 40,
+ source: {'kind': 'task-line', 'taskId': 'task-2', 'title': 'x'},
+ );
+ say(
+ 'Desktop tests pass whatever the date.',
+ river,
+ thread: 'message-6',
+ minutesAgo: 40,
+ source: {'kind': 'system'},
+ );
+ say(
+ 'On it: Wren is building it.',
+ river,
+ thread: 'message-6',
+ minutesAgo: 39,
+ source: {'kind': 'system'},
+ );
+ final c = server.controller();
+ 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(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) =>
+ RepaintBoundary(key: picture, child: child),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ app: app,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Mac Studio',
+ ),
+ ),
+ ),
+ );
+ c.select('offline');
+ await tester.pumpAndSettle();
+ expect(
+ find.text("Let's build: Hub reports hide an item from everyone"),
+ findsOneWidget,
+ );
+ // Replies stay in their threads, out of the chat.
+ expect(find.text('On it: Dune is building it.'), findsNothing);
+ if (view == 'thread') {
+ c.openThread('message-1');
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Merged: PR #2710. Ships in the next release.'),
+ findsOneWidget,
+ );
+ }
+ await 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/plain-work-$view-${brightness.name}.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ }, skip: shots == null);
+ }
+ }
+}
diff --git a/desktop/test/super_tab_quiet_chat_test.dart b/desktop/test/super_tab_quiet_chat_test.dart
index 677ada496..94ec576eb 100644
--- a/desktop/test/super_tab_quiet_chat_test.dart
+++ b/desktop/test/super_tab_quiet_chat_test.dart
@@ -75,27 +75,34 @@ void main() {
expect(find.byType(SuperTabShipRow), findsOneWidget);
});
- testWidgets('a Shipped card leaves the chat once the task has its line', (
- tester,
- ) async {
- final c = await showView(
- tester,
- project([
- shipped(),
- row(
- 'l1',
- 2,
- 'Avatars · shipped',
- kind: 'task-line',
- source: {'taskId': 'task-1', 'title': 'Avatars', 'state': 'shipped'},
- ),
- ]),
- );
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- expect(find.byType(SuperTabShipRow), findsNothing);
- expect(find.text('Avatars'), findsOneWidget);
- });
+ // Plain chat (#2294): a stored Shipped card and a task's old line both stay,
+ // each read as it was written (super_tab_task_line_test.dart).
+ testWidgets(
+ 'a Shipped card stays beside a task\'s old line, read as written',
+ (tester) async {
+ final c = await showView(
+ tester,
+ project([
+ shipped(),
+ row(
+ 'l1',
+ 2,
+ 'Avatars · shipped',
+ kind: 'task-line',
+ source: {
+ 'taskId': 'task-1',
+ 'title': 'Avatars',
+ 'state': 'shipped',
+ },
+ ),
+ ]),
+ );
+ await c.loadMessages('lead');
+ await tester.pumpAndSettle();
+ expect(find.byType(SuperTabShipRow), findsOneWidget);
+ expect(find.text('Avatars · shipped'), findsOneWidget);
+ },
+ );
for (final kind in [
'work-stalled',
diff --git a/desktop/test/super_tab_quiet_polish_test.dart b/desktop/test/super_tab_quiet_polish_test.dart
index 6ce88bbb1..d5fe9cf8d 100644
--- a/desktop/test/super_tab_quiet_polish_test.dart
+++ b/desktop/test/super_tab_quiet_polish_test.dart
@@ -18,6 +18,7 @@ Map<String, dynamic> _taskLine(int sequence, String state, String title) => {
'conversationId': 'lead',
'sequence': sequence,
'text': '$title · $state',
+ 'thread': 'line-$sequence',
'createdAt': '2026-11-02T09:00:00Z',
'author': {'kind': 'agent', 'id': 'kai', 'name': 'Kai'},
'source': {
@@ -151,8 +152,11 @@ void main() {
});
await showView(tester, server);
final text = tester.getTopLeft(find.text('A plain message.')).dx;
- expect(tester.getTopLeft(find.text('Windows credential fix')).dx, text);
- expect(tester.getTopLeft(find.textContaining('Proposal from')).dx, text);
+ expect(
+ tester.getTopLeft(find.text('Windows credential fix · working')).dx,
+ text,
+ );
+ expect(tester.getTopLeft(find.text('Goal: Activity read fix')).dx, text);
});
});
@@ -207,18 +211,18 @@ void main() {
});
});
- group("a task's pane", () {
+ group("a task message's thread pane", () {
Future<void> open(WidgetTester tester) async {
final server = swarm();
server.messages.add(_taskLine(1, 'working', 'Windows credential fix'));
- await showView(tester, server);
- await tester.tap(find.text('Windows credential fix').first);
+ final c = await showView(tester, server);
+ c.openThread('line-1');
await tester.pumpAndSettle();
}
testWidgets("its header's rule meets the chat's", (tester) async {
await open(tester);
- final panel = find.byKey(const ValueKey('super-task-panel-close'));
+ final panel = find.byKey(const ValueKey('super-thread-close'));
final rule = find.descendant(
of: find.ancestor(of: panel, matching: find.byType(Column)).first,
matching: find.byType(Divider),
@@ -230,8 +234,8 @@ void main() {
tester,
) async {
await open(tester);
- final box = _key('super-task-reply-surface');
- final close = tester.getTopRight(_key('super-task-panel-close')).dx;
+ final box = _key('super-thread-composer-surface');
+ final close = tester.getTopRight(_key('super-thread-close')).dx;
expect(tester.getTopRight(box).dx, lessThan(close));
expect(900 - tester.getBottomLeft(box).dy, greaterThanOrEqualTo(16));
});
diff --git a/desktop/test/super_tab_sidebar_rows_test.dart b/desktop/test/super_tab_sidebar_rows_test.dart
index c57892948..4ef2abb66 100644
--- a/desktop/test/super_tab_sidebar_rows_test.dart
+++ b/desktop/test/super_tab_sidebar_rows_test.dart
@@ -6,6 +6,7 @@ import 'package:harness/shared/theme/app_icons.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/buddy_rows.dart';
+import 'package:harness/super_tabs/task_groups.dart';
import 'package:harness/super_tabs/view.dart';
import 'support/humans_fixture.dart';
@@ -20,12 +21,12 @@ void main() {
final project = find.byKey(const ValueKey('super-group-lead'));
final workgroup = find.byKey(const ValueKey('super-group-offline'));
final machine = find.byKey(const ValueKey('super-machine-studio'));
- final more = find.byKey(const ValueKey('super-project-more-lead'));
Future<SuperTabController> show(
WidgetTester tester,
- ConversationServer server,
- ) async {
+ ConversationServer server, {
+ bool restFolded = false,
+ }) async {
await tester.binding.setSurfaceSize(const Size(1300, 900));
addTearDown(() => tester.binding.setSurfaceSize(null));
final controller = server.controller(
@@ -33,6 +34,9 @@ void main() {
initial: {'tabId': 'tab', 'accountId': 'peer', 'selectedId': 'lead'},
);
await controller.refresh();
+ // These workgroups have no work, so they are in The rest, which starts
+ // folded (#2309): unfolded here, where the rows are what is tested.
+ if (!restFolded) controller.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
await tester.pumpWidget(
MaterialApp(
theme: grid.buildAppTheme(brightness: Brightness.light),
@@ -335,6 +339,7 @@ void main() {
Future<SuperTabController> reopen(String account) async {
final next = server.controller(account: account, initial: server.saved);
await next.refresh();
+ next.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
@@ -363,7 +368,7 @@ void main() {
);
testWidgets(
- 'an open project lists its 8 newest conversations, and "… N more" shows the rest',
+ 'an open project lists every open conversation newest first, with no "… N more"',
(tester) async {
final server = humansSwarm();
addNumberedWorkgroups(server, 11);
@@ -372,7 +377,8 @@ void main() {
await tester.pumpAndSettle();
Finder row(String id) => find.byKey(ValueKey('super-group-$id'));
- final shown = [for (var n = 11; n >= 4; n--) row('g$n')];
+ // The unnumbered "Offline editing" predates numbering: last.
+ final shown = [for (var n = 11; n >= 1; n--) row('g$n'), workgroup];
for (final finder in shown) {
expect(finder, findsOneWidget);
}
@@ -382,46 +388,27 @@ void main() {
greaterThan(tester.getTopLeft(shown[i - 1]).dy),
);
}
- // #3, #2, #1 and the unnumbered "Offline editing" wait behind the row.
- expect(row('g3'), findsNothing);
- expect(workgroup, findsNothing);
- expect(more, findsOneWidget);
- expect(find.text('… 4 more'), findsOneWidget);
- expect(
- tester.getTopLeft(more).dy,
- greaterThan(tester.getTopLeft(row('g4')).dy),
- );
+ expect(find.textContaining('more'), findsNothing);
+ await close(tester, controller);
+ },
+ );
- await tester.tap(more);
+ testWidgets(
+ 'an older conversation that is open stays listed in a folded group',
+ (tester) async {
+ final server = humansSwarm();
+ addNumberedWorkgroups(server, 11);
+ final controller = await show(tester, server, restFolded: true);
+ await controller.select('g1');
await tester.pumpAndSettle();
- expect(more, findsNothing);
- for (final id in ['g3', 'g2', 'g1', 'offline']) {
- expect(row(id), findsOneWidget);
- }
- expect(
- tester.getTopLeft(workgroup).dy,
- greaterThan(tester.getTopLeft(row('g1')).dy),
- );
+ expect(find.byKey(const ValueKey('super-group-g1')), findsOneWidget);
+ expect(find.byKey(const ValueKey('super-group-g2')), findsNothing);
await close(tester, controller);
},
);
- testWidgets('an older conversation that is open stays listed', (
- tester,
- ) async {
- final server = humansSwarm();
- addNumberedWorkgroups(server, 11);
- final controller = await show(tester, server);
- await controller.select('g1');
- await tester.pumpAndSettle();
- expect(find.byKey(const ValueKey('super-group-g1')), findsOneWidget);
- expect(find.byKey(const ValueKey('super-group-g2')), findsNothing);
- expect(find.text('… 3 more'), findsOneWidget);
- await close(tester, controller);
- });
-
testWidgets(
- 'unread and waiting conversations older than the 8 newest stay listed',
+ 'a conversation waiting on a person is listed under Needs you while The rest is folded',
(tester) async {
final server = humansSwarm();
addNumberedWorkgroups(server, 11);
@@ -431,15 +418,15 @@ void main() {
.firstWhere((g) => g['id'] == 'g2')
..['agentIds'] = ['lead-agent']
..['assignment'] = {'agentId': 'lead-agent', 'status': 'needs_human'};
- final controller = await show(tester, server);
- server.append('New work', conversationId: 'g1');
- await controller.refresh();
+ final controller = await show(tester, server, restFolded: true);
controller.toggleProject('lead');
await tester.pumpAndSettle();
- expect(find.byKey(const ValueKey('super-group-g1')), findsOneWidget);
expect(find.byKey(const ValueKey('super-group-g2')), findsOneWidget);
expect(find.byKey(const ValueKey('super-group-g3')), findsNothing);
- expect(find.text('… 2 more'), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('super-task-group-lead-needsYou')),
+ findsOneWidget,
+ );
await close(tester, controller);
},
);
diff --git a/desktop/test/super_tab_sidebar_test.dart b/desktop/test/super_tab_sidebar_test.dart
index 78f9f2204..ecf88feaf 100644
--- a/desktop/test/super_tab_sidebar_test.dart
+++ b/desktop/test/super_tab_sidebar_test.dart
@@ -206,6 +206,11 @@ void main() {
// A second click shows its workgroups (no chevrons: Quiet Swarm).
await tester.tap(project);
await tester.pumpAndSettle();
+ // A workgroup with no work is in The rest, which starts folded (#2309).
+ await tester.tap(
+ find.byKey(const ValueKey('super-task-group-lead-rest')),
+ );
+ await tester.pumpAndSettle();
final work = find.byKey(const ValueKey('super-group-offline'));
expect(work, findsOneWidget);
final textX = tester
@@ -217,6 +222,8 @@ void main() {
sample,
// A workgroup's number is grey, with no #: it is no channel.
inRow('super-group-offline', find.text('12 Offline editing')),
+ // Its group's heading lines up with it.
+ inRow('super-task-group-lead-rest', find.text('The rest')),
]) {
expect(tester.getTopLeft(label).dx, textX, reason: '$label');
}
@@ -316,7 +323,8 @@ void main() {
find.byKey(const ValueKey('super-group-empty-lead')),
find.text('No workgroups yet'),
find.byKey(const ValueKey('super-group-lead')),
- find.byKey(const ValueKey('super-group-offline')),
+ // Its one workgroup has no work: The rest, folded (#2309).
+ find.byKey(const ValueKey('super-task-group-lead-rest')),
find.text('Buddies'),
find.byKey(const ValueKey('super-buddy-lead')),
find.byKey(const ValueKey('super-buddy-empty')),
diff --git a/desktop/test/super_tab_task_groups_shots_test.dart b/desktop/test/super_tab_task_groups_shots_test.dart
new file mode 100644
index 000000000..c1c330544
--- /dev/null
+++ b/desktop/test/super_tab_task_groups_shots_test.dart
@@ -0,0 +1,178 @@
+import 'dart:io';
+
+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/activity.dart';
+import 'package:harness/super_tabs/attention.dart';
+import 'package:harness/super_tabs/project_sidebar.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/capture.dart';
+import 'support/super_tab_fixture.dart';
+
+/// Set to a folder to write the PR's pictures of the task groups (#2309) there.
+final shots = Platform.environment['SUPER_TAB_SIDEBAR_SHOTS'];
+
+/// A busy project, as Huy's: something waits on the reader, several agents
+/// work, some wait on review or another person, and older tasks rest.
+ConversationServer busyProject() {
+ final now = DateTime.now().millisecondsSinceEpoch;
+ int ago(int minutes) => now - minutes * 60000;
+ final server = ConversationServer();
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ {'id': 'ken', 'email': '[email protected]', 'role': 'collaborator'},
+ ];
+ server.state['projects'] = [
+ projectFixture('lead', 'openharness', 'lead'),
+ projectFixture('site', 'website', 'site-chat'),
+ ];
+ var sequence = 0;
+ Map<String, dynamic> task(
+ String id,
+ int number,
+ String title, {
+ String? status,
+ Map<String, dynamic>? liveness,
+ bool unread = false,
+ }) => {
+ ...conversationFixture(id, title),
+ 'projectId': 'lead',
+ 'number': number,
+ 'lastMessageSequence': unread ? ++sequence : 0,
+ if (status != null)
+ 'assignment': {'agentId': 'a1', 'status': status, 'progressAt': ago(3)},
+ 'liveness': ?liveness,
+ };
+ Map<String, dynamic> waiting(String why, int minutes, {String? personId}) => {
+ 'state': 'waiting',
+ 'why': why,
+ 'since': ago(minutes),
+ 'personId': ?personId,
+ };
+ (server.state['conversations'] as List)
+ ..removeWhere((g) => (g as Map)['id'] == 'offline')
+ ..addAll(<Map<String, dynamic>>[
+ task(
+ 't1',
+ 2309,
+ 'Sidebar: tasks in foldable groups',
+ status: 'needs_human',
+ liveness: waiting('person', 4, personId: 'owner'),
+ unread: true,
+ ),
+ task(
+ 't2',
+ 2311,
+ 'Web: thread bar on a phone',
+ status: 'working',
+ unread: true,
+ ),
+ task('t3', 2307, 'Dial: recap answers at once', status: 'working'),
+ task(
+ 't4',
+ 2305,
+ 'Hub reports hide for everyone',
+ status: 'working',
+ liveness: waiting('starting', 1),
+ ),
+ task(
+ 't5',
+ 2304,
+ 'Typography pass on Activity',
+ status: 'review',
+ liveness: waiting('review', 12),
+ unread: true,
+ ),
+ task(
+ 't6',
+ 2302,
+ 'Machine names in review',
+ status: 'needs_human',
+ liveness: waiting('person', 40, personId: 'ken'),
+ ),
+ task(
+ 't7',
+ 2298,
+ 'Remove machine privacy',
+ status: 'working',
+ liveness: {'state': 'quiet', 'since': ago(34)},
+ ),
+ task('t8', 2290, 'Sidebar groups for Buddy chats', unread: true),
+ task('t9', 2287, 'Older: thread pane width'),
+ task('t10', 2281, 'Older: release notes copy', status: 'done'),
+ {...conversationFixture('site-chat', 'website'), 'projectId': 'site'},
+ ]);
+ return server;
+}
+
+void main() {
+ setUpAll(() => loadCaptureFonts(shots));
+
+ for (final brightness in Brightness.values) {
+ for (final (name, size) in [
+ ('desktop', const Size(1100, 760)),
+ ('phone', const Size(390, 844)),
+ ]) {
+ testWidgets('the task groups at $name width in ${brightness.name}', (
+ tester,
+ ) async {
+ if (shots == null) return;
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ tester.view.devicePixelRatio = 2;
+ tester.view.physicalSize = size * 2;
+ addTearDown(tester.view.reset);
+ final c = busyProject().controller();
+ await c.refresh();
+ if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');
+ await c.select('lead');
+ final picture = GlobalKey();
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: RepaintBoundary(
+ key: picture,
+ child: Scaffold(
+ // On a phone the web app shows the sidebar on its own.
+ body: name == 'phone'
+ ? ListenableBuilder(
+ listenable: c,
+ builder: (context, _) => ProjectSidebar(
+ controller: c,
+ needsHuman: (_) => 0,
+ onSelect: c.select,
+ attention: SuperTabAttention.of(c),
+ activity: SuperTabActivity.of(c),
+ onNotifications: () {},
+ ),
+ )
+ : SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await captureBoundary(
+ tester,
+ picture.currentContext!.findRenderObject()! as RenderRepaintBoundary,
+ shots,
+ 'task-groups-$name-${brightness.name}',
+ );
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
+ }
+ }
+}
diff --git a/desktop/test/super_tab_task_groups_test.dart b/desktop/test/super_tab_task_groups_test.dart
new file mode 100644
index 000000000..91cafd0d8
--- /dev/null
+++ b/desktop/test/super_tab_task_groups_test.dart
@@ -0,0 +1,471 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/activity.dart';
+import 'package:harness/super_tabs/attention.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/project_sidebar.dart';
+import 'package:harness/super_tabs/task_groups.dart';
+
+import 'support/super_tab_fixture.dart';
+
+/// Two projects: web-project (chat `lead`) with one task in each group and two
+/// working, and alpha (chat `alpha-chat`) with one working task. Every chat is
+/// read unless a test says otherwise.
+ConversationServer groupedServer() {
+ final server = ConversationServer();
+ server.state['projects'] = [
+ projectFixture('lead', 'web-project', 'lead'),
+ projectFixture('alpha', 'alpha', 'alpha-chat'),
+ ];
+ Map<String, dynamic> task(
+ String id,
+ String projectId,
+ int number, {
+ String? status,
+ Map<String, dynamic>? liveness,
+ }) => {
+ ...conversationFixture(id, id),
+ 'projectId': projectId,
+ 'number': number,
+ if (status != null)
+ 'assignment': {'agentId': 'a1', 'status': status, 'progressAt': 1},
+ 'liveness': ?liveness,
+ };
+ (server.state['conversations'] as List)
+ ..removeWhere((g) => (g as Map)['id'] == 'offline')
+ ..addAll(<Map<String, dynamic>>[
+ task(
+ 'mine',
+ 'lead',
+ 15,
+ status: 'needs_human',
+ liveness: {
+ 'state': 'waiting',
+ 'why': 'person',
+ 'personId': 'owner',
+ 'since': 1,
+ },
+ ),
+ task('busy-old', 'lead', 13, status: 'working'),
+ task('busy-new', 'lead', 16, status: 'working'),
+ task(
+ 'review',
+ 'lead',
+ 14,
+ status: 'review',
+ liveness: {'state': 'waiting', 'why': 'review', 'since': 1},
+ ),
+ task('quiet-chat', 'lead', 12),
+ {...conversationFixture('alpha-chat', 'alpha'), 'projectId': 'alpha'},
+ task('alpha-busy', 'alpha', 3, status: 'working'),
+ ]);
+ return server;
+}
+
+Future<SuperTabController> pumpGrouped(
+ WidgetTester tester,
+ ConversationServer server, {
+ Size size = const Size(1300, 1600),
+}) async {
+ await tester.binding.setSurfaceSize(size);
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller();
+ await c.refresh();
+ for (final project in ['lead', 'alpha']) {
+ if (!c.expandedProjects.contains(project)) c.toggleProject(project);
+ }
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.light),
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: c,
+ builder: (context, _) => ProjectSidebar(
+ controller: c,
+ needsHuman: (_) => 0,
+ onSelect: c.select,
+ attention: SuperTabAttention.of(c),
+ activity: SuperTabActivity.of(c),
+ onNotifications: () {},
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return c;
+}
+
+Future<void> closeGrouped(WidgetTester tester, SuperTabController c) async {
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+}
+
+Finder heading(String project, SuperTabTaskGroup group) =>
+ find.byKey(ValueKey('super-task-group-$project-${group.name}'));
+Finder row(String id) => find.byKey(ValueKey('super-group-$id'));
+
+/// A project's open tasks in the sidebar, in four foldable groups (Huy, #2309): Needs you, Working, Waiting on
+/// others, The rest.
+void main() {
+ SuperTabConversation task({String? status, Map<String, dynamic>? liveness}) =>
+ SuperTabConversation.fromJson({
+ ...conversationFixture('t', 'Task'),
+ if (status != null)
+ 'assignment': {'agentId': 'a1', 'status': status, 'progressAt': 1},
+ 'liveness': ?liveness,
+ });
+ Map<String, dynamic> waiting(String why, {String? personId}) => {
+ 'state': 'waiting',
+ 'why': why,
+ 'since': 1,
+ 'personId': ?personId,
+ };
+
+ group('which group a task is in', () {
+ SuperTabTaskGroup of(
+ SuperTabConversation g, {
+ int mentions = 0,
+ int needsHuman = 0,
+ }) => superTabTaskGroupOf(
+ g,
+ readerId: 'me',
+ mentions: mentions,
+ needsHuman: needsHuman,
+ );
+
+ test('the groups read in the sidebar\'s order, The rest folded', () {
+ expect(SuperTabTaskGroup.values.map((g) => g.label), [
+ 'Needs you',
+ 'Working',
+ 'Waiting on others',
+ 'The rest',
+ ]);
+ expect(SuperTabTaskGroup.values.where((g) => g.foldedByDefault), [
+ SuperTabTaskGroup.rest,
+ ]);
+ });
+
+ test(
+ 'a task that tags the reader needs them, whatever else it waits on',
+ () {
+ expect(of(task(), mentions: 1), SuperTabTaskGroup.needsYou);
+ expect(
+ of(
+ task(
+ status: 'needs_human',
+ liveness: waiting('person', personId: 'other'),
+ ),
+ mentions: 2,
+ ),
+ SuperTabTaskGroup.needsYou,
+ );
+ },
+ );
+
+ test('a wait on the reader, or on no one named, needs them', () {
+ expect(
+ of(
+ task(
+ status: 'needs_human',
+ liveness: waiting('person', personId: 'me'),
+ ),
+ ),
+ SuperTabTaskGroup.needsYou,
+ );
+ expect(
+ of(task(status: 'needs_human', liveness: waiting('person'))),
+ SuperTabTaskGroup.needsYou,
+ );
+ });
+
+ test('a question left unanswered past quiet still needs the reader', () {
+ // An agent at a question makes no progress: after 30 minutes the
+ // backend marks its task quiet (liveness.ts TASK_QUIET_MS).
+ expect(
+ of(
+ task(status: 'working', liveness: {'state': 'quiet', 'since': 1}),
+ needsHuman: 1,
+ ),
+ SuperTabTaskGroup.needsYou,
+ );
+ });
+
+ test('a question in a working task\'s terminal needs the reader', () {
+ expect(
+ of(task(status: 'working'), needsHuman: 1),
+ SuperTabTaskGroup.needsYou,
+ );
+ });
+
+ test('a wait on another person, a review, a revision, a block or a machine waits on others', () {
+ for (final g in [
+ task(
+ status: 'needs_human',
+ liveness: waiting('person', personId: 'other'),
+ ),
+ task(status: 'review', liveness: waiting('review')),
+ task(status: 'working', liveness: waiting('revision')),
+ task(status: 'blocked', liveness: waiting('blocked')),
+ task(status: 'working', liveness: waiting('queued')),
+ ]) {
+ expect(
+ of(g, needsHuman: 1),
+ SuperTabTaskGroup.waitingOnOthers,
+ reason: '${g.liveness}',
+ );
+ }
+ });
+
+ test('a stuck task waits on others: the PM hands it on', () {
+ expect(
+ of(task(status: 'working', liveness: {'state': 'quiet', 'since': 1})),
+ SuperTabTaskGroup.waitingOnOthers,
+ );
+ expect(
+ of(
+ task(
+ status: 'working',
+ liveness: {'state': 'orphaned', 'why': 'lost', 'since': 1},
+ ),
+ ),
+ SuperTabTaskGroup.waitingOnOthers,
+ );
+ });
+
+ test('a task moving or starting its agent is working', () {
+ expect(of(task(status: 'working')), SuperTabTaskGroup.working);
+ expect(of(task(status: 'planned')), SuperTabTaskGroup.working);
+ expect(
+ of(task(status: 'working', liveness: waiting('starting'))),
+ SuperTabTaskGroup.working,
+ );
+ });
+
+ test('anything else is the rest', () {
+ expect(of(task()), SuperTabTaskGroup.rest);
+ expect(of(task(status: 'done')), SuperTabTaskGroup.rest);
+ expect(of(task(status: 'stopped')), SuperTabTaskGroup.rest);
+ expect(
+ of(
+ task(
+ status: 'working',
+ liveness: {'state': 'unheard-of', 'since': 1},
+ ),
+ ),
+ SuperTabTaskGroup.rest,
+ );
+ });
+ });
+
+ group('the sidebar lists a project\'s tasks in its groups', () {
+ testWidgets(
+ 'headings in order with their counts, each task under its own, newest first',
+ (tester) async {
+ final c = await pumpGrouped(tester, groupedServer());
+ final top = {
+ for (final g in SuperTabTaskGroup.values)
+ g: tester.getTopLeft(heading('lead', g)).dy,
+ };
+ expect(
+ SuperTabTaskGroup.values.map((g) => top[g]).toList(),
+ orderedEquals([...top.values]..sort()),
+ );
+ for (final (g, count) in [
+ (SuperTabTaskGroup.needsYou, '1'),
+ (SuperTabTaskGroup.working, '2'),
+ (SuperTabTaskGroup.waitingOnOthers, '1'),
+ (SuperTabTaskGroup.rest, '1'),
+ ]) {
+ expect(
+ find.descendant(
+ of: heading('lead', g),
+ matching: find.text(g.label),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: heading('lead', g), matching: find.text(count)),
+ findsOneWidget,
+ reason: g.label,
+ );
+ }
+ double y(String id) => tester.getTopLeft(row(id)).dy;
+ expect(y('mine'), greaterThan(top[SuperTabTaskGroup.needsYou]!));
+ expect(y('mine'), lessThan(top[SuperTabTaskGroup.working]!));
+ expect(y('busy-new'), greaterThan(top[SuperTabTaskGroup.working]!));
+ expect(y('busy-new'), lessThan(y('busy-old')));
+ expect(
+ y('busy-old'),
+ lessThan(top[SuperTabTaskGroup.waitingOnOthers]!),
+ );
+ expect(
+ y('review'),
+ greaterThan(top[SuperTabTaskGroup.waitingOnOthers]!),
+ );
+ expect(y('review'), lessThan(top[SuperTabTaskGroup.rest]!));
+ await closeGrouped(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'The rest starts folded; its heading shows and hides its tasks',
+ (tester) async {
+ final c = await pumpGrouped(tester, groupedServer());
+ expect(heading('lead', SuperTabTaskGroup.rest), findsOneWidget);
+ expect(row('quiet-chat'), findsNothing);
+ await tester.tap(heading('lead', SuperTabTaskGroup.rest));
+ await tester.pumpAndSettle();
+ expect(row('quiet-chat'), findsOneWidget);
+ await tester.tap(heading('lead', SuperTabTaskGroup.rest));
+ await tester.pumpAndSettle();
+ expect(row('quiet-chat'), findsNothing);
+ await closeGrouped(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'a fold is the project\'s own, and outlasts hiding the project',
+ (tester) async {
+ final c = await pumpGrouped(tester, groupedServer());
+ await tester.tap(heading('lead', SuperTabTaskGroup.working));
+ await tester.pumpAndSettle();
+ expect(row('busy-new'), findsNothing);
+ expect(row('alpha-busy'), findsOneWidget);
+ c.toggleProject('lead');
+ await tester.pumpAndSettle();
+ expect(heading('lead', SuperTabTaskGroup.working), findsNothing);
+ c.toggleProject('lead');
+ await tester.pumpAndSettle();
+ expect(heading('lead', SuperTabTaskGroup.working), findsOneWidget);
+ expect(row('busy-new'), findsNothing);
+ await closeGrouped(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'the open chat in a folded group still shows under its heading',
+ (tester) async {
+ final c = await pumpGrouped(tester, groupedServer());
+ await c.select('quiet-chat');
+ await tester.pumpAndSettle();
+ expect(row('quiet-chat'), findsOneWidget);
+ expect(
+ tester.getTopLeft(row('quiet-chat')).dy,
+ greaterThan(
+ tester.getTopLeft(heading('lead', SuperTabTaskGroup.rest)).dy,
+ ),
+ );
+ await closeGrouped(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'under the unread filter, groups list only unread tasks and count those',
+ (tester) async {
+ final server = groupedServer();
+ for (final g
+ in (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>()) {
+ if (g['id'] == 'busy-old' || g['id'] == 'quiet-chat')
+ g['lastMessageSequence'] = 5;
+ }
+ final c = await pumpGrouped(tester, server);
+ c.toggleUnreadOnly();
+ await tester.pumpAndSettle();
+ expect(heading('lead', SuperTabTaskGroup.needsYou), findsNothing);
+ expect(
+ heading('lead', SuperTabTaskGroup.waitingOnOthers),
+ findsNothing,
+ );
+ expect(row('busy-old'), findsOneWidget);
+ expect(row('busy-new'), findsNothing);
+ expect(
+ find.descendant(
+ of: heading('lead', SuperTabTaskGroup.working),
+ matching: find.text('1'),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: heading('lead', SuperTabTaskGroup.rest),
+ matching: find.text('1'),
+ ),
+ findsOneWidget,
+ );
+ expect(row('quiet-chat'), findsNothing);
+ await closeGrouped(tester, c);
+ },
+ );
+
+ testWidgets('Tab reaches a heading, and Enter folds it', (tester) async {
+ final c = await pumpGrouped(tester, groupedServer());
+ const key = ValueKey('super-task-group-lead-needsYou');
+ bool onHeading() {
+ final focused = tester.binding.focusManager.primaryFocus?.context;
+ if (focused == null) return false;
+ var found = focused.widget.key == key;
+ focused.visitAncestorElements((e) {
+ if (e.widget.key == key) found = true;
+ return !found;
+ });
+ return found;
+ }
+
+ for (var i = 0; i < 60 && !onHeading(); i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ }
+ expect(onHeading(), isTrue);
+ expect(row('mine'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(row('mine'), findsNothing);
+ await closeGrouped(tester, c);
+ });
+
+ testWidgets(
+ 'a phone-wide sidebar, as the web app draws it on a phone, shows the same groups',
+ (tester) async {
+ final c = await pumpGrouped(
+ tester,
+ groupedServer(),
+ size: const Size(390, 844),
+ );
+ for (final g in SuperTabTaskGroup.values) {
+ expect(heading('lead', g), findsOneWidget, reason: g.label);
+ }
+ expect(tester.takeException(), isNull);
+ await closeGrouped(tester, c);
+ },
+ );
+ });
+
+ group('next unread follows the groups', () {
+ testWidgets(
+ 'each project\'s chat, then its tasks in group order, each group newest first',
+ (tester) async {
+ final server = groupedServer();
+ final c = server.controller();
+ await c.refresh();
+ expect(superTabSidebarOrder(c), [
+ 'alpha-chat',
+ 'alpha-busy',
+ 'lead',
+ 'mine',
+ 'busy-new',
+ 'busy-old',
+ 'review',
+ 'quiet-chat',
+ ]);
+ await c.flush();
+ c.dispose();
+ },
+ );
+ });
+}
diff --git a/desktop/test/super_tab_task_line_test.dart b/desktop/test/super_tab_task_line_test.dart
index 5e959a681..916db921e 100644
--- a/desktop/test/super_tab_task_line_test.dart
+++ b/desktop/test/super_tab_task_line_test.dart
@@ -1,535 +1,319 @@
-import 'dart:typed_data';
-import 'dart:async';
-
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/shared/theme/app_icons.dart';
-import 'package:harness/state/harness_attachments.dart';
-import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/identity.dart';
import 'package:harness/super_tabs/message_row.dart';
-import 'package:harness/super_tabs/roster.dart';
-import 'package:harness/super_tabs/task_line.dart';
+import 'package:harness/super_tabs/message_text.dart';
+import 'package:harness/super_tabs/ship_row.dart';
+import 'package:harness/super_tabs/model.dart';
import 'package:harness/super_tabs/thread_panel.dart';
+import 'package:harness/super_tabs/unread_line.dart';
-import 'super_tab_mentions_test.dart' show showView;
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'super_tab_mentions_test.dart' show showView, shot;
import 'support/super_tab_fixture.dart';
-final at = DateTime.utc(2026, 11, 2, 9);
+const _legacyProposal =
+ "Proposal from Dee's Buddy, on Dee's behalf.\n\n"
+ 'Goal: Save offline drafts.\nScope: Desktop and phone\nPriority: high';
-Map<String, dynamic> taskRow(
- String state, {
- String id = 'line-1',
- String? answerFor,
- String taskId = 'group-1',
- int sequence = 5,
- String? title = 'Phone Activity opens the right message',
- String? text,
-}) => {
- 'id': id,
+Map<String, dynamic> _root(String kind, {bool legacy = false}) => {
+ 'id': 'root',
'conversationId': 'lead',
- 'sequence': sequence,
- 'text': text ?? 'Phone Activity opens the right message · $state',
- 'createdAt': at.toIso8601String(),
- 'author': {'kind': 'agent', 'id': 'kai', 'name': 'Kai'},
+ 'thread': 'root',
+ 'sequence': 1,
+ 'text': legacy
+ ? kind == 'task-line'
+ ? 'Save offline drafts · in review'
+ : _legacyProposal
+ : "Let's build: Offline drafts",
+ 'createdAt': '2026-11-03T09:00:00Z',
+ 'author': legacy
+ ? {'kind': 'agent', 'id': 'buddy', 'name': 'Draft Buddy'}
+ : {'kind': 'person', 'id': 'requester', 'name': '[email protected]'},
'source': {
- 'kind': 'task-line',
- 'taskId': taskId,
- 'title': ?title,
- 'state': state,
- 'answerFor': ?answerFor,
+ 'kind': kind,
+ if (kind == 'task-line') ...{
+ 'taskId': 'offline',
+ 'title': 'Save offline drafts',
+ 'state': 'review',
+ } else
+ 'personId': 'requester',
},
+ 'reactions': [
+ {
+ 'emoji': 'heart',
+ 'count': 1,
+ 'by': [
+ {'kind': 'agent', 'id': 'buddy'},
+ ],
+ },
+ ],
};
-Map<String, dynamic> proposalRow() => {
- 'id': 'proposal-1',
- 'conversationId': 'lead',
- 'thread': 'proposal-1',
- 'sequence': 6,
- 'text': 'Activity read fix\n\nA second line of detail the row leaves out.',
- 'createdAt': at.toIso8601String(),
- 'author': {'kind': 'agent', 'id': 'kai', 'name': 'Kai'},
- 'source': {'kind': 'buddy-proposal', 'personId': 'owner'},
-};
-
-ConversationServer serverWith(List<Map<String, dynamic>> rows) {
- final server = ConversationServer();
+ConversationServer _server(String kind, {bool legacy = false}) {
+ final server = ConversationServer()..threads = true;
+ (server.state['people'] as List).add({
+ 'id': 'requester',
+ 'email': '[email protected]',
+ 'username': 'dee',
+ 'role': 'member',
+ });
server.state['agents'] = [
{
- 'id': 'kai',
- 'name': 'Kai',
- 'machineId': 'm',
- 'harnessId': 'h',
+ 'id': 'buddy',
+ 'name': 'Draft Buddy',
+ 'machineId': 'mac',
+ 'harnessId': 'buddy',
'contributorId': 'owner',
'configuration': {'engine': 'codex'},
},
];
- server.messages.addAll(rows);
- final conversations = (server.state['conversations'] as List)
- .cast<Map<String, dynamic>>();
- final lead = conversations.firstWhere((g) => g['id'] == 'lead');
- lead['lastMessageSequence'] = rows.length + 5;
- // The task a line opens.
- conversations.add({
- ...lead,
- 'id': 'group-1',
- 'title': 'Phone Activity opens the right message',
- 'lastMessageSequence': 1,
- 'leadId': null,
- });
+ server.messages.addAll([
+ _root(kind, legacy: legacy),
+ {
+ 'id': 'details',
+ 'conversationId': 'lead',
+ 'thread': 'root',
+ 'replyTo': 'root',
+ 'sequence': 2,
+ 'text': 'Goal: Save offline drafts.\nScope: Desktop and phone\nPriority: high',
+ 'createdAt': '2026-11-03T09:01:00Z',
+ 'author': {'kind': 'agent', 'id': 'buddy', 'name': 'Draft Buddy'},
+ },
+ ]);
+ (server.state['conversations'] as List).first['lastMessageSequence'] = 2;
return server;
}
-Finder get line => find.byType(SuperTabTaskLine);
+Finder _row(String id, {bool thread = false}) => find.byKey(
+ ValueKey('${thread ? 'super-thread-message' : 'super-message'}-$id'),
+);
void main() {
- for (final (state, word, icon) in [
- ('planned', 'planned', AppIcons.circleDashed),
- ('working', 'working', AppIcons.circleDot),
- ('review', 'in review', AppIcons.circleDot),
- ('ready', 'ready', AppIcons.circleDot),
- ('shipped', 'shipped', AppIcons.check),
- ('done', 'done', AppIcons.check),
- ('stopped', 'stopped', AppIcons.circleSlash),
- ]) {
- testWidgets('a $state task is one line: its mark, name and "$word"', (
+ // A source-based compact row, title substitution, or task-conversation
+ // navigation loses message content/actions; these exercise the real view.
+ for (final kind in ['task-line', 'buddy-proposal']) {
+ testWidgets('$kind root keeps the requester identity and message actions', (
tester,
) async {
- final c = await showView(tester, serverWith([taskRow(state)]));
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- expect(line, findsOneWidget);
+ final server = _server(kind);
+ await showView(tester, server);
+ final row = _row('root');
+ expect(tester.widget(row), isA<SuperTabMessageRow>());
expect(
- find.descendant(of: line, matching: find.text(word)),
+ find.descendant(of: row, matching: find.text('dee')),
findsOneWidget,
);
+ final avatar = tester.widget<SuperTabAvatar>(
+ find.descendant(of: row, matching: find.byType(SuperTabAvatar)).first,
+ );
+ expect(avatar.identity, 'person:requester');
expect(
- find.descendant(of: line, matching: find.byIcon(icon)),
+ find.descendant(
+ of: row,
+ matching: find.text("Let's build: Offline drafts"),
+ ),
findsOneWidget,
);
+ expect(find.byKey(const ValueKey('super-proposal-label')), findsNothing);
+ expect(find.textContaining('Scope:'), findsNothing);
expect(
- tester.getSize(line).height,
- lessThan(48),
- reason: 'one line, not a card',
- );
- // Not also drawn as a message, with its author.
- expect(find.byType(SuperTabMessageRow), findsNothing);
- });
- }
-
- testWidgets('the name comes from the title, not the text older apps read', (
- tester,
- ) async {
- final c = await showView(
- tester,
- serverWith([
- taskRow(
- 'review',
- title: 'Offline drafts',
- text: 'Offline drafts · in review',
- ),
- ]),
- );
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- expect(find.text('Offline drafts'), findsOneWidget);
- expect(find.text('Offline drafts · in review'), findsNothing);
- });
-
- testWidgets('a line with no title still reads, as its text says it', (
- tester,
- ) async {
- final c = await showView(
- tester,
- serverWith([taskRow('review', title: null, text: 'Offline drafts')]),
- );
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- expect(find.text('Offline drafts'), findsOneWidget);
- });
-
- testWidgets('an edited line redraws in place at the next read', (
- tester,
- ) async {
- final server = serverWith([
- taskRow(
- 'working',
- text: 'Offline drafts · working',
- title: 'Offline drafts',
- ),
- ]);
- final c = await showView(tester, server);
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- expect(
- find.descendant(of: line, matching: find.text('working')),
- findsOneWidget,
- );
-
- // The server edits the one message, and moves the chat's reaction counter.
- server.messages.first
- ..['text'] = 'Offline drafts · in review'
- ..['source'] = {
- ...server.messages.first['source'] as Map,
- 'state': 'review',
- };
- final group = (server.state['conversations'] as List)
- .cast<Map<String, dynamic>>()
- .firstWhere((g) => g['id'] == 'lead');
- group['reactionSeq'] = ((group['reactionSeq'] as int?) ?? 0) + 1;
- await c.loadMessages('lead');
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- expect(
- find.descendant(of: line, matching: find.text('in review')),
- findsOneWidget,
- );
- expect(line, findsOneWidget);
- });
-
- testWidgets('a task waiting on the reader says Answer', (tester) async {
- final c = await showView(
- tester,
- serverWith([taskRow('waiting', answerFor: 'owner')]),
- );
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- expect(
- find.descendant(of: line, matching: find.text('Answer')),
- findsOneWidget,
- );
- });
-
- testWidgets(
- 'a task waiting on someone else never says Answer to the reader',
- (tester) async {
- final c = await showView(
- tester,
- serverWith([taskRow('waiting', answerFor: 'someone-else')]),
+ find.byKey(const ValueKey('super-thread-count-root')),
+ findsOneWidget,
);
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
expect(
- find.descendant(of: line, matching: find.text('Answer')),
- findsNothing,
+ find.descendant(of: row, matching: find.byTooltip('Reply')),
+ findsOneWidget,
);
expect(
- find.descendant(of: line, matching: find.text('working')),
+ find.descendant(of: row, matching: find.byTooltip('Add reaction')),
findsOneWidget,
);
- },
- );
-
- testWidgets('an unknown state keeps the line and says nothing it cannot', (
- tester,
- ) async {
- final c = await showView(tester, serverWith([taskRow('later')]));
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- expect(line, findsOneWidget);
- expect(find.text('later'), findsNothing);
- });
-
- testWidgets('clicking a task opens its conversation on the right', (
- tester,
- ) async {
- final server = serverWith([taskRow('working')]);
- server.messages.add({
- 'id': 'in-task',
- 'conversationId': 'group-1',
- 'sequence': 1,
- 'text': 'Ready: PR #2605.',
- 'createdAt': at.toIso8601String(),
- 'author': {'kind': 'agent', 'id': 'kai', 'name': 'Kai'},
- });
- final c = await showView(tester, server);
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- await tester.tap(line);
- await tester.pumpAndSettle();
- expect(find.byType(SuperTabTaskPanel), findsOneWidget);
- expect(find.text('Ready: PR #2605.'), findsOneWidget);
- // Headed as the line reads, with its mark (screen 3).
- expect(
- find.descendant(
- of: find.byType(SuperTabTaskPanel),
- matching: find.byIcon(AppIcons.circleDot),
- ),
- findsOneWidget,
- );
- // The project stays open beside it.
- expect(c.selectedId, 'lead');
- await tester.tap(find.byKey(const ValueKey('super-task-panel-close')));
- await tester.pumpAndSettle();
- expect(find.byType(SuperTabTaskPanel), findsNothing);
- });
-
- testWidgets('the panel shows the whole conversation, without hidden rows', (
- tester,
- ) async {
- final server = serverWith([taskRow('review')]);
- (server.state['conversations'] as List).add({
- ...conversationFixture('step-1', 'Review'),
- 'projectId': 'lead',
- 'reviewOf': 'group-1',
- 'step': 'Review',
- 'number': 7,
- 'lastMessageSequence': 2,
- });
- Map<String, dynamic> inTask(
- String id,
- String conversation,
- int sequence,
- String text, {
- Map<String, Object?> source = const {},
- String? thread,
- }) => {
- 'id': id,
- 'conversationId': conversation,
- 'sequence': sequence,
- 'thread': thread ?? id,
- 'text': text,
- 'createdAt': at.toIso8601String(),
- 'author': {'kind': 'agent', 'id': 'kai', 'name': 'Kai'},
- 'source': source,
- };
- server.messages.addAll([
- inTask('t1', 'group-1', 1, 'Ready: PR #2605.'),
- inTask(
- 't2',
- 'group-1',
- 2,
- 'Kai has gone quiet.',
- source: {'kind': 'work-stalled'},
- ),
- inTask('t3', 'group-1', 3, 'A reply in a thread.', thread: 't1'),
- inTask('v1', 'step-1', 1, 'Please review.'),
- inTask('v2', 'step-1', 2, 'With fixes: one Important.', thread: 'v1'),
- ]);
- final c = await showView(tester, server);
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- await tester.tap(line);
- await tester.pumpAndSettle();
- expect(find.text('Ready: PR #2605.'), findsOneWidget);
- expect(find.text('With fixes: one Important.'), findsOneWidget);
- expect(find.text('Kai has gone quiet.'), findsNothing);
- // Agents answer with replies: a verdict is one (screen 3 lists them all).
- expect(find.text('A reply in a thread.'), findsOneWidget);
- });
-
- testWidgets('a thread opened takes the task panel\'s place for good', (
- tester,
- ) async {
- final server = serverWith([taskRow('working'), proposalRow()]);
- final c = await showView(tester, server);
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- await tester.tap(line);
- await tester.pumpAndSettle();
- expect(find.byType(SuperTabTaskPanel), findsOneWidget);
- c.openThread('proposal-1');
- await tester.pumpAndSettle();
- expect(find.byType(SuperTabThreadPanel), findsOneWidget);
- expect(find.byType(SuperTabTaskPanel), findsNothing);
- c.closeThread();
- await tester.pumpAndSettle();
- expect(find.byType(SuperTabTaskPanel), findsNothing);
- });
-
- testWidgets('Members takes the task panel\'s place, as it takes a thread\'s', (
- tester,
- ) async {
- final c = await showView(tester, serverWith([taskRow('working')]));
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- await tester.tap(line);
- await tester.pumpAndSettle();
- expect(find.byType(SuperTabTaskPanel), findsOneWidget);
- await tester.tap(find.byKey(const ValueKey('super-members-button')));
- await tester.pumpAndSettle();
- expect(find.byType(SuperTabRoster), findsOneWidget);
- expect(find.byType(SuperTabTaskPanel), findsNothing);
- });
-
- testWidgets('on a narrow window, a click outside closes the task panel', (
- tester,
- ) async {
- final c = await showView(tester, serverWith([taskRow('working')]));
- await c.loadMessages('lead');
- await tester.binding.setSurfaceSize(const Size(900, 800));
- await tester.pumpAndSettle();
- await tester.tap(line);
- await tester.pumpAndSettle();
- expect(find.byType(SuperTabTaskPanel), findsOneWidget);
- await tester.tapAt(const Offset(20, 400));
- await tester.pumpAndSettle();
- expect(find.byType(SuperTabTaskPanel), findsNothing);
- });
-
- group('the panel\'s reply', () {
- final field = find.byKey(const ValueKey('super-task-reply'));
- final send = find.byKey(const ValueKey('super-task-send'));
-
- ConversationServer assigned() {
- final server = serverWith([taskRow('working')]);
- final task = (server.state['conversations'] as List)
- .cast<Map<String, dynamic>>()
- .firstWhere((g) => g['id'] == 'group-1');
- task['agentIds'] = ['kai'];
- task['assignment'] = {'agentId': 'kai', 'status': 'working'};
- return server;
- }
-
- Future<SuperTabController> open(
- WidgetTester tester,
- ConversationServer server,
- ) async {
- final c = await showView(tester, server);
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- await tester.tap(line);
- await tester.pumpAndSettle();
- return c;
- }
-
- testWidgets('goes to the agent with the task, as a plain message', (
- tester,
- ) async {
- final server = assigned();
- await open(tester, server);
- await tester.enterText(field, 'Yes, ship it.');
- await tester.pump();
- await tester.tap(send);
- await tester.pumpAndSettle();
- final sent =
- server.posts.lastWhere(
- (p) => (p['command'] as Map?)?['type'] == 'message.send',
- )['command']
- as Map;
- expect(sent['conversationId'], 'group-1');
- expect(sent['text'], 'Yes, ship it.');
- expect(sent['replyTo'], isNull);
- expect(sent['recipientIds'], ['kai']);
- expect(tester.widget<TextField>(field).controller!.text, isEmpty);
- });
-
- testWidgets('a file with no words goes too', (tester) async {
- final server = assigned();
- final c = await open(tester, server);
- c.threadAttachments('group-1', 'group-1').add([
- HarnessAttachment('a.txt', Uint8List.fromList([104, 105])),
- ]);
- await tester.pump();
- await tester.tap(send);
+ await tester.tap(find.byKey(const ValueKey('super-reaction-root-heart')));
await tester.pumpAndSettle();
final sent =
server.posts.lastWhere(
- (p) => (p['command'] as Map?)?['type'] == 'message.send',
+ (p) => (p['command'] as Map?)?['type'] == 'message.react',
)['command']
as Map;
- expect(sent['conversationId'], 'group-1');
- expect(sent['attachmentIds'], hasLength(1));
- });
-
- testWidgets('while something else is saving, the words stay in the box', (
- tester,
- ) async {
- final server = assigned();
- final c = await open(tester, server);
- final hold = server.holdCommands = Completer<void>();
- final other = c.command({
- 'type': 'conversation.rename',
- 'conversationId': 'lead',
- 'title': 'x',
- });
- await tester.pump();
- await tester.enterText(field, 'Do not lose me.');
- await tester.pump();
- await tester.tap(send, warnIfMissed: false);
- await tester.pump();
- expect(
- tester.widget<TextField>(field).controller!.text,
- 'Do not lose me.',
- );
- server.holdCommands = null;
- hold.complete();
- await other;
- await tester.pumpAndSettle();
- await tester.tap(send);
- await tester.pumpAndSettle();
+ expect(sent['messageId'], 'root');
+ expect(sent['emoji'], 'heart');
+ expect(sent['on'], isTrue);
expect(
- server.posts.map((p) => (p['command'] as Map?)?['text']),
- contains('Do not lose me.'),
+ find.descendant(of: row, matching: find.text('2')),
+ findsOneWidget,
);
});
- testWidgets('a reply on its way shows in the panel', (tester) async {
- final server = assigned();
- await open(tester, server);
- final hold = server.holdCommands = Completer<void>();
- await tester.enterText(field, 'On its way.');
- await tester.pump();
- await tester.tap(send);
- await tester.pump();
- expect(
- find.descendant(
- of: find.byType(SuperTabTaskPanel),
- matching: find.textContaining('On its way.'),
- ),
- findsWidgets,
- );
- server.holdCommands = null;
- hold.complete();
- await tester.pumpAndSettle();
- });
- });
+ testWidgets(
+ '$kind Reply opens the ordinary project thread and sends there',
+ (tester) async {
+ final server = _server(kind);
+ final c = await showView(tester, server);
+ await tester.tap(
+ find.descendant(of: _row('root'), matching: find.byTooltip('Reply')),
+ );
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'lead');
+ expect(c.openedThread?.root, 'root');
+ expect(find.byType(SuperTabThreadPanel), findsOneWidget);
+ expect(find.textContaining('Scope: Desktop and phone'), findsOneWidget);
+ await tester.enterText(
+ find.byKey(const ValueKey('super-thread-composer')),
+ 'Please include attachments.',
+ );
+ await tester.pump();
+ await tester.tap(find.byKey(const ValueKey('super-thread-send')));
+ await tester.pumpAndSettle();
+ final sent =
+ server.posts.lastWhere(
+ (p) => (p['command'] as Map?)?['type'] == 'message.send',
+ )['command']
+ as Map;
+ expect(sent['conversationId'], 'lead');
+ expect(sent['replyTo'], 'root');
+ expect(sent['text'], 'Please include attachments.');
+ expect(find.text('Please include attachments.'), findsOneWidget);
+ },
+ );
+
+ testWidgets(
+ 'legacy $kind keeps its complete text and ordinary thread at narrow width',
+ (tester) async {
+ final c = await showView(tester, _server(kind, legacy: true));
+ await tester.binding.setSurfaceSize(const Size(800, 800));
+ await tester.pumpAndSettle();
+ final row = _row('root');
+ expect(tester.widget(row), isA<SuperTabMessageRow>());
+ expect(
+ find.descendant(of: row, matching: find.text('Draft Buddy')),
+ findsOneWidget,
+ );
+ final text = tester.widget<SuperTabMessageText>(
+ find.descendant(of: row, matching: find.byType(SuperTabMessageText)),
+ );
+ expect(
+ text.text,
+ kind == 'task-line'
+ ? 'Save offline drafts · in review'
+ : _legacyProposal,
+ );
+ if (kind == 'buddy-proposal') {
+ expect(
+ find.descendant(
+ of: row,
+ matching: find.textContaining("on Dee's behalf."),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: row,
+ matching: find.textContaining('Priority: high'),
+ ),
+ findsOneWidget,
+ );
+ } else {
+ expect(
+ find.descendant(
+ of: row,
+ matching: find.text('Save offline drafts · in review'),
+ ),
+ findsOneWidget,
+ );
+ }
+ await tester.tap(find.byKey(const ValueKey('super-thread-line-root')));
+ await tester.pumpAndSettle();
+ expect(c.openedThread?.root, 'root');
+ expect(c.selectedId, 'lead');
+ expect(find.byType(SuperTabThreadPanel), findsOneWidget);
+ expect(find.textContaining('Scope: Desktop and phone'), findsWidgets);
+ expect(tester.takeException(), isNull);
+ await tester.tap(find.byKey(const ValueKey('super-thread-close')));
+ await tester.pumpAndSettle();
+ expect(c.openedThread, isNull);
+ },
+ );
+ }
- testWidgets('a task the reader\'s read does not hold opens nothing', (
+ testWidgets('a legacy task root keeps its recorded ship message visible', (
tester,
) async {
- final c = await showView(
- tester,
- serverWith([taskRow('working', taskId: 'not-readable')]),
- );
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- await tester.tap(line);
- await tester.pumpAndSettle();
- expect(find.byType(SuperTabTaskPanel), findsNothing);
+ final server = _server('task-line', legacy: true);
+ server.messages.add({
+ 'id': 'ship',
+ 'conversationId': 'lead',
+ 'thread': 'ship',
+ 'sequence': 3,
+ 'text': 'Shipped: Offline drafts',
+ 'createdAt': '2026-11-03T09:02:00Z',
+ 'author': {'kind': 'agent', 'id': 'buddy', 'name': 'Draft Buddy'},
+ 'source': {
+ 'kind': 'ship',
+ 'conversationId': 'offline',
+ 'title': 'Offline drafts',
+ 'requesterId': 'requester',
+ 'builderIds': ['buddy'],
+ },
+ });
+ (server.state['conversations'] as List).first['lastMessageSequence'] = 3;
+ await showView(tester, server);
+ expect(find.text('Save offline drafts · in review'), findsOneWidget);
+ expect(find.byType(SuperTabShipRow), findsOneWidget);
+ expect(find.text('Shipped: Offline drafts'), findsOneWidget);
+ expect(find.text('Built by'), findsOneWidget);
});
- testWidgets('a proposal says its goal, not the server\'s opening words', (
+ testWidgets('plain proposal and task thread screenshot fixture', (
tester,
) async {
- final c = await showView(
- tester,
- serverWith([
- {
- ...proposalRow(),
- 'text':
- "Proposal from diego's Buddy, on diego's behalf.\n\n"
- 'Goal: Activity read fix\nScope: The app\nPriority: high',
- },
- ]),
- );
- await c.loadMessages('lead');
+ await loadPreviewFonts();
+ final server = _server('buddy-proposal');
+ server.messages.first['reactions'] = <dynamic>[];
+ final c = await showView(tester, server, brightness: Brightness.light);
+ await shot(tester, 'desktop-plain-chat');
+ c.openThread('root');
await tester.pumpAndSettle();
- expect(find.textContaining(': Activity read fix'), findsOneWidget);
- expect(find.textContaining('behalf'), findsNothing);
- expect(find.textContaining('Scope'), findsNothing);
+ expect(find.textContaining('Scope: Desktop and phone'), findsOneWidget);
+ await shot(tester, 'desktop-plain-chat-thread');
});
- testWidgets('a proposal is one line that opens', (tester) async {
- final c = await showView(tester, serverWith([proposalRow()]));
- await c.loadMessages('lead');
- await tester.pumpAndSettle();
- final row = find.byType(SuperTabProposalLine);
- expect(row, findsOneWidget);
- expect(tester.getSize(row).height, lessThan(48));
- expect(find.textContaining('second line of detail'), findsNothing);
- await tester.tap(row);
- await tester.pumpAndSettle();
- expect(c.openedThread?.root, 'proposal-1');
- expect(find.textContaining('second line of detail'), findsOneWidget);
+ test("a root the server posted in the reader's name is not their own "
+ 'writing, so it reads nothing before it (plain chat, #2294)', () {
+ final c = ConversationServer().controller();
+ addTearDown(c.dispose);
+ SuperTabMessage row(
+ int sequence,
+ Map<String, Object> author, [
+ String? kind,
+ ]) => SuperTabMessage.fromJson({
+ 'id': 'm$sequence',
+ 'conversationId': 'lead',
+ 'sequence': sequence,
+ 'text': 'Message $sequence',
+ 'createdAt': '2026-11-03T09:00:00Z',
+ 'author': author,
+ 'source': ?(kind == null ? null : {'kind': kind}),
+ });
+ final reader = {
+ 'kind': 'person',
+ 'id': c.accountId,
+ 'name': '[email protected]',
+ };
+ final river = {'kind': 'agent', 'id': 'lead-agent', 'name': 'River'};
+ for (final kind in ['task-line', 'buddy-proposal']) {
+ final root = row(3, reader, kind);
+ expect(root.postedForAuthor, isTrue);
+ expect(c.isOwn(root), isFalse);
+ expect(
+ superTabFirstUnread(
+ [row(1, river), row(2, river), root],
+ 1,
+ own: c.isOwn,
+ ),
+ 'm2',
+ );
+ }
+ expect(c.isOwn(row(4, reader)), isTrue);
});
}
diff --git a/desktop/test/super_tab_view_test.dart b/desktop/test/super_tab_view_test.dart
index 1ad1d0cdb..6f28e45ca 100644
--- a/desktop/test/super_tab_view_test.dart
+++ b/desktop/test/super_tab_view_test.dart
@@ -284,6 +284,9 @@ void main() {
}
await tester.tap(find.byKey(const ValueKey('super-group-lead')));
await tester.pumpAndSettle();
+ // A workgroup with no work is in The rest, which starts folded (#2309).
+ await tester.tap(find.byKey(const ValueKey('super-task-group-lead-rest')));
+ await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('super-group-offline')));
await tester.pumpAndSettle();
expect(controller.selectedId, 'offline');
@@ -373,6 +376,11 @@ void main() {
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('super-group-lead')));
await tester.pumpAndSettle();
+ // A workgroup with no work is in The rest, which starts folded (#2309).
+ await tester.tap(
+ find.byKey(const ValueKey('super-task-group-lead-rest')),
+ );
+ await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('super-group-offline')));
await tester.pumpAndSettle();
expect(controller.selectedId, 'offline');
diff --git a/desktop/test/swarm_projects_test.dart b/desktop/test/swarm_projects_test.dart
index a7541cb97..f9093894f 100644
--- a/desktop/test/swarm_projects_test.dart
+++ b/desktop/test/swarm_projects_test.dart
@@ -7,6 +7,7 @@ import 'package:harness/super_tabs/view.dart';
import 'package:harness/super_tabs/section_heading.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/project_visibility.dart';
+import 'package:harness/super_tabs/task_groups.dart';
import 'support/super_tab_fixture.dart';
import 'support/super_tab_members.dart';
@@ -95,6 +96,9 @@ void main() {
// Already open: a click on it shows its workgroups.
await tester.tap(find.byKey(const ValueKey('super-group-lead')));
await tester.pumpAndSettle();
+ // A workgroup with no work is in The rest, which starts folded (#2309).
+ await tester.tap(find.byKey(const ValueKey('super-task-group-lead-rest')));
+ await tester.pumpAndSettle();
expect(find.text('12 Offline editing'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('super-group-offline')));
await tester.pumpAndSettle();
@@ -118,6 +122,8 @@ void main() {
(tester) async {
final server = projectsServer(), c = server.controller();
await mount(tester, c);
+ // Workgroups with no work are in The rest, unfolded here (#2309).
+ c.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
final project = find.byKey(const ValueKey('super-group-lead'));
final projectName = find.descendant(
of: project,
diff --git a/devices/harness-device/firmware/main/cable_client.c b/devices/harness-device/firmware/main/cable_client.c
index 8c8e65793..7ddb510b8 100644
--- a/devices/harness-device/firmware/main/cable_client.c
+++ b/devices/harness-device/firmware/main/cable_client.c
@@ -327,6 +327,9 @@ static void send_hello(void)
// A PM and a Buddy side per Swarm (spec 2026-10-29-round-dial-pm-buddy): each Lead's `buddies` and the reader's
// Buddy, a face that may be the Buddy chat, its quiet notice, and `supertab.side` back. Older daemons ignore it.
msg_string(&root, "swarmBuddy", "v1");
+ // A face in a thread (spec 2026-11-03-dial-thread-face): each Lead's `thread`, `threadTitle`, `threadReplies`, a recap
+ // that names its thread, and `supertab.thread.leave` back. Older daemons ignore it and send none.
+ msg_string(&root, "swarmThread", "v1");
// No swarmReview: words for a Swarm chat are sent as any harness's are and reviewed only when held (Diego's dial,
// 2026-10-29), and a daemon that heard it would refuse every word not reviewed (docs/device-voice-swarm-chat.md).
// Which of the two dials this is (board.h) — informational, so a log or a bug report can say. A
@@ -398,6 +401,16 @@ void cable_client_supertab_send(const char *t, const char *tab, const char *lead
send_json(root);
}
+// The dial's face leaves its thread (spec 2026-11-03-dial-thread-face); a daemon without swarmThread ignores it.
+void cable_client_supertab_thread_leave(const char *tab, const char *lead)
+{
+ if (!tab || !tab[0] || strlen(tab) >= ID_MAX || !lead || !lead[0] || strlen(lead) >= ID_MAX) return;
+ cJSON *root = msg("supertab.thread.leave");
+ msg_string(&root, "tab", tab);
+ msg_string(&root, "lead", lead);
+ send_json(root);
+}
+
void cable_client_supertab_side(const char *tab, bool buddy)
{
if (!tab || !tab[0] || strlen(tab) >= ID_MAX) return;
@@ -981,7 +994,7 @@ static void handle_supertab(const cJSON *p)
if (card.lead_n >= HT_SUPERTAB_LEADS_MAX) break;
if (!cJSON_IsObject(l)) continue;
const cJSON *order = cJSON_GetObjectItemCaseSensitive(l, "order"), *since = cJSON_GetObjectItemCaseSensitive(l, "since");
- const cJSON *buddy = cJSON_GetObjectItemCaseSensitive(l, "buddy");
+ const cJSON *buddy = cJSON_GetObjectItemCaseSensitive(l, "buddy"), *replies = cJSON_GetObjectItemCaseSensitive(l, "threadReplies");
const cJSON *cells = cJSON_IsObject(buddy) ? cJSON_GetObjectItemCaseSensitive(buddy, "cells") : NULL;
ht_lead_in_t in = {
.id = str_of(l, "id"), .project_id = str_of(l, "projectId"), .project = str_of(l, "project"),
@@ -991,6 +1004,9 @@ static void handle_supertab(const cJSON *p)
.since = cJSON_IsNumber(since) && since->valuedouble >= 0 ? (since->valuedouble > 2592000 ? 2592000 : (long)since->valuedouble) : -1,
// The chat on the face; absent from a daemon without swarmChat, which reads as the Lead chat.
.chat = str_of(l, "chat"), .chat_id = str_of(l, "chatId"), .chat_name = str_of(l, "chatName"),
+ // The thread on the face, from a swarmThread daemon; absent reads as the main chat, and replies as unknown.
+ .thread = str_of(l, "thread"), .thread_title = str_of(l, "threadTitle"),
+ .thread_replies = cJSON_IsNumber(replies) && replies->valuedouble >= 0 ? (replies->valuedouble > 2147483647.0 ? 2147483647L : (long)replies->valuedouble) : -1,
// The reader's Buddy, from a swarmBuddy daemon while Buddies are on; supertab.c drops a block it cannot draw.
.buddies = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(l, "buddies")),
.buddy = {.present = cJSON_IsObject(buddy), .chat_id = str_of(buddy, "chatId"), .name = str_of(buddy, "name"),
@@ -1013,10 +1029,13 @@ static void handle_supertab_recap(const cJSON *p)
if (!id_fits(tab) || !id_fits(lead)) return;
// A chat's recap names its chat; one whose chat cannot be held is not one (never shown for another).
if (chat_id && !id_fits(chat_id)) return;
+ // And a thread's names its root; one whose root cannot be held is not one (never taken for the main chat's).
+ const char *thread = str_of(p, "thread");
+ if (thread && !id_fits(thread)) return;
const cJSON *at = cJSON_GetObjectItemCaseSensitive(p, "at");
const double secs = cJSON_IsNumber(at) && at->valuedouble > 0 ? at->valuedouble : 0;
const bool none = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(p, "none"));
- ui_supertab_recap(tab, lead, chat_id ? chat_id : "", none || !text ? "" : text, secs > 4294967295.0 ? 0xFFFFFFFFu : (uint32_t)secs, none);
+ ui_supertab_recap(tab, lead, chat_id ? chat_id : "", thread ? thread : "", none || !text ? "" : text, secs > 4294967295.0 ? 0xFFFFFFFFu : (uint32_t)secs, none);
}
// `supertab.notice` {tab, lead, chat, chatId, id, text, at}: the Lead's new message in its Lead conversation or Chat with
// PM, the one thing that alerts with a swarmChat daemon, or the Buddy's in its chat (chat "buddy", a quiet one). The daemon
diff --git a/devices/harness-device/firmware/main/cable_client.h b/devices/harness-device/firmware/main/cable_client.h
index 0e73a0e81..c41be4db6 100644
--- a/devices/harness-device/firmware/main/cable_client.h
+++ b/devices/harness-device/firmware/main/cable_client.h
@@ -226,7 +226,7 @@ void cable_client_list_swarms(void);
// supertab {id, tab, name, count, leads:[{id, projectId, project, engine, owner, local, state, since?, order?}]}
// one Swarm, ≤12 Leads; `tab` is its desk tab or ""; `order` is the project's
// place in the app (absent from an older daemon: the frame's order)
-// supertab.recap {tab, lead, text, at, none} the open Lead's last message
+// supertab.recap {tab, lead, text, at, none, thread?} the open Lead's last message
// supertab.focus {tab, lead} the desktop moved to that Lead
// question {…, superTab, attention} a Super Tab wait (id "supertab:…"); never an answer screen here
// out supertab.recap.get / supertab.open / supertab.select {tab, lead}
@@ -235,6 +235,7 @@ void cable_client_list_swarms(void);
void cable_client_supertab_send(const char *t, const char *tab, const char *lead);
// `supertab.side` {tab, side}: the dial swiped that Swarm to its Buddy side (true) or its PM side (spec
// 2026-10-29-round-dial-pm-buddy). A tab id it cannot hold sends nothing.
+void cable_client_supertab_thread_leave(const char *tab, const char *lead); // {t: supertab.thread.leave, tab, lead}
void cable_client_supertab_side(const char *tab, bool buddy);
void cable_client_supertab_side_kept(const char *tab);
diff --git a/devices/harness-device/firmware/main/ui/habitat/supertab.c b/devices/harness-device/firmware/main/ui/habitat/supertab.c
index b3bb577e7..d4b29f560 100644
--- a/devices/harness-device/firmware/main/ui/habitat/supertab.c
+++ b/devices/harness-device/firmware/main/ui/habitat/supertab.c
@@ -79,6 +79,11 @@ bool ht_supertab_lead_add(ht_supertab_t *t, const ht_lead_in_t *in)
put_id(l->chat_id, in->chat_id, true);
if (named) put_text(l->chat_name, sizeof l->chat_name, in->chat_name);
else { l->chat = HT_CHAT_LEAD; l->chat_id[0] = 0; l->chat_name[0] = 0; }
+ // The thread on the face: a root this dial cannot hold is no thread (the main chat), and so is one without a title read.
+ if (put_id(l->thread_root, in->thread, true)) {
+ put_text(l->thread_title, sizeof l->thread_title, in->thread_title);
+ l->thread_replies = in->thread_replies < 0 ? -1 : in->thread_replies > INT32_MAX ? INT32_MAX : (int32_t)in->thread_replies;
+ } else { l->thread_root[0] = 0; l->thread_title[0] = 0; l->thread_replies = -1; }
// The reader's Buddy, only while Buddies are on. One the dial cannot draw is no Buddy; the Lead stays.
l->buddies = in->buddies;
const ht_buddy_in_t *b = &in->buddy;
@@ -193,40 +198,54 @@ int ht_supertabs_put(ht_supertabs_t *s, const ht_supertab_t *in, uint32_t now_ms
return events;
}
+static ht_lead_t *lead_of(ht_supertabs_t *s, const char *tab, const char *lead)
+{
+ ht_supertab_t *t = (ht_supertab_t *)ht_supertabs_find(s, tab);
+ for (int i = 0; t && lead && i < t->lead_n; i++) if (!strcmp(t->leads[i].id, lead)) return &t->leads[i];
+ return NULL;
+}
void ht_supertabs_recap_open(ht_supertabs_t *s, const char *tab, const char *lead, uint32_t now_ms)
{
bool open = lead && *lead && tab && *tab;
// The Lead already on the face keeps what it shows until a new recap replaces it: emptying it left the resting pet
- // for the 5 s retry on every reopen (Diego, 2026-10-29). Only while the face's chat is still the one it was for.
- // A kept recap is not LOADING, so its refresh has no 5 s retry: one lost on the way waits for the next push.
+ // for the 5 s retry on every reopen (Diego, 2026-10-29). Only while the face's chat and thread are still the ones it
+ // was for. A kept recap is not LOADING, so its refresh has no 5 s retry: one lost on the way waits for the next push.
if (open && (s->recap.state == HT_RECAP_LOADED || s->recap.state == HT_RECAP_EMPTY) && !strcmp(s->recap.tab, tab) && !strcmp(s->recap.lead, lead)) {
- const ht_supertab_t *t = ht_supertabs_find(s, tab);
- for (int i = 0; t && i < t->lead_n; i++)
- if (!strcmp(t->leads[i].id, lead) && !strcmp(t->leads[i].chat_id, s->recap.chat_id)) {
- s->recap.asked_ms = now_ms;
- return;
- }
+ const ht_lead_t *l = lead_of(s, tab, lead);
+ if (l && !strcmp(l->chat_id, s->recap.chat_id) && !strcmp(l->thread_root, s->recap.thread)) {
+ s->recap.asked_ms = now_ms;
+ return;
+ }
}
put_text(s->recap.tab, sizeof s->recap.tab, open ? tab : "");
put_text(s->recap.lead, sizeof s->recap.lead, open ? lead : "");
s->recap.chat_id[0] = 0;
+ s->recap.thread[0] = 0;
s->recap.text[0] = 0;
s->recap.at = 0;
s->recap.asked_ms = now_ms;
s->recap.state = open ? HT_RECAP_LOADING : HT_RECAP_NONE;
}
-bool ht_supertabs_recap_put(ht_supertabs_t *s, const char *tab, const char *lead, const char *chat_id, const char *text, uint32_t at, bool none)
+bool ht_supertabs_recap_put(ht_supertabs_t *s, const char *tab, const char *lead, const char *chat_id, const char *thread, const char *text, uint32_t at, bool none)
{
if (s->recap.state == HT_RECAP_NONE || !tab || !lead || strcmp(s->recap.tab, tab) || strcmp(s->recap.lead, lead))
return false;
- // A recap for another chat than the one on the face (the desktop moved on while it was read) is not this face's.
- const ht_supertab_t *t = ht_supertabs_find(s, tab);
- const char *face = "";
- for (int i = 0; t && i < t->lead_n; i++) if (!strcmp(t->leads[i].id, lead)) face = t->leads[i].chat_id;
- if (strcmp(chat_id ? chat_id : "", face)) return false;
+ // A recap for another chat or thread than the one on the face (the desktop moved on while it was read, or the dial
+ // left its thread) is not this face's.
+ const ht_lead_t *l = lead_of(s, tab, lead);
+ const char *face = l ? l->chat_id : "", *root = l ? l->thread_root : "";
+ if (strcmp(chat_id ? chat_id : "", face) || strcmp(thread ? thread : "", root)) return false;
put_text(s->recap.chat_id, sizeof s->recap.chat_id, face);
+ put_text(s->recap.thread, sizeof s->recap.thread, root);
put_text(s->recap.text, sizeof s->recap.text, none ? "" : text);
s->recap.at = at;
s->recap.state = s->recap.text[0] ? HT_RECAP_LOADED : HT_RECAP_EMPTY;
return true;
}
+bool ht_supertabs_thread_leave(ht_supertabs_t *s, const char *tab, const char *lead)
+{
+ ht_lead_t *l = lead_of(s, tab, lead);
+ if (!l || !l->thread_root[0]) return false;
+ l->thread_root[0] = 0; l->thread_title[0] = 0; l->thread_replies = -1;
+ return true;
+}
diff --git a/devices/harness-device/firmware/main/ui/habitat/supertab.h b/devices/harness-device/firmware/main/ui/habitat/supertab.h
index d5101333c..be5e5a558 100644
--- a/devices/harness-device/firmware/main/ui/habitat/supertab.h
+++ b/devices/harness-device/firmware/main/ui/habitat/supertab.h
@@ -23,6 +23,10 @@ typedef struct {
uint32_t since_at_ms; // the dial's clock when since_s arrived
ht_chat_kind_t chat;
char chat_id[ID_MAX], chat_name[HT_SUPERTAB_NAME]; // "" from a daemon without swarmChat
+ // The thread the face is in (spec 2026-11-03-dial-thread-face, a swarmThread daemon only): its root message id ("" = the
+ // main chat), its title (the first line, at most 80 bytes) and its reply count (-1 unknown).
+ char thread_root[ID_MAX], thread_title[HT_SUPERTAB_NAME * 2];
+ int32_t thread_replies;
// The Swarm has Buddies on, and the reader's own Buddy in this project: its chat, name, engine, the 15 half bits of
// Desktop's avatar pattern (bit i = half cell i) and its colour 0xRRGGBB. `live` false while the Buddy is down.
bool buddies;
@@ -45,7 +49,7 @@ typedef struct {
int id_n;
// One slot: the recap of the Lead on the face, and nothing else.
// `chat_id`: the chat the text is the last message of ("" from a daemon without swarmChat).
- struct { char tab[ID_MAX], lead[ID_MAX], chat_id[ID_MAX], text[HT_SUPERTAB_TEXT]; uint32_t at, asked_ms; ht_recap_state_t state; } recap;
+ struct { char tab[ID_MAX], lead[ID_MAX], chat_id[ID_MAX], thread[ID_MAX], text[HT_SUPERTAB_TEXT]; uint32_t at, asked_ms; ht_recap_state_t state; } recap;
} ht_supertabs_t;
typedef enum { HT_LEAD_RAISED_ASK, HT_LEAD_RAISED_STUCK, HT_LEAD_CLEARED } ht_lead_event_kind_t;
typedef struct { ht_lead_event_kind_t kind; char tab[ID_MAX], lead[ID_MAX]; } ht_lead_event_t;
@@ -54,6 +58,7 @@ typedef struct { ht_lead_event_kind_t kind; char tab[ID_MAX], lead[ID_MAX]; } ht
// `color` is "#rrggbb"; a block that does not read (no chat id, a bad colour, cells past 15 bits) is dropped, not the Lead.
typedef struct { bool present, live; const char *chat_id, *name, *engine, *color; long cells; } ht_buddy_in_t;
typedef struct { const char *id, *project_id, *project, *engine, *owner, *local, *state; int order; long since; const char *chat, *chat_id, *chat_name;
+ const char *thread, *thread_title; long thread_replies;
bool buddies; ht_buddy_in_t buddy; } ht_lead_in_t;
// false: an empty or overlong id or tab. Names are cut on a UTF-8 boundary.
bool ht_supertab_init(ht_supertab_t *, const char *id, const char *tab, const char *name, int count);
@@ -71,7 +76,10 @@ const ht_supertab_t *ht_supertabs_find(const ht_supertabs_t *, const char *id);
const ht_supertab_t *ht_supertabs_at(const ht_supertabs_t *, int i);
const ht_supertab_t *ht_supertabs_for_desk(const ht_supertabs_t *, const char *desk_tab_id);
const ht_lead_t *ht_supertabs_lead_by_local(const ht_supertabs_t *, const char *harness_id, const ht_supertab_t **tab);
-// LOADING with no text; an empty lead closes the slot (NONE).
+// LOADING with no text; an empty lead closes the slot (NONE). A held recap is kept only for the same chat and thread.
void ht_supertabs_recap_open(ht_supertabs_t *, const char *tab, const char *lead, uint32_t now_ms);
-// false: not the open Lead, or not the chat on its face (`chat_id` "" is the Lead's own, from a daemon without swarmChat).
-bool ht_supertabs_recap_put(ht_supertabs_t *, const char *tab, const char *lead, const char *chat_id, const char *text, uint32_t at, bool none);
+// false: not the open Lead, or not the chat on its face (`chat_id` "" is the Lead's own, from a daemon without swarmChat),
+// or not its thread (`thread` "" or NULL is the main chat).
+bool ht_supertabs_recap_put(ht_supertabs_t *, const char *tab, const char *lead, const char *chat_id, const char *thread, const char *text, uint32_t at, bool none);
+// The face's Lead leaves its thread at once (the dial's swipe): true when it was in one.
+bool ht_supertabs_thread_leave(ht_supertabs_t *, const char *tab, const char *lead);
diff --git a/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c b/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c
index 14854dde0..50b4f1f1f 100644
--- a/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c
+++ b/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c
@@ -589,7 +589,7 @@ static int workspace_index(const char *id)
* never in focus, agent.open or voice.begin. Voice goes to the Lead's `local` harness id.
*/
// SIDE: id "buddy" or "pm". SIDE_KEPT: the side a restart took off the face, told to the daemon without moving the window.
-enum { SUPERTAB_RECAP_GET, SUPERTAB_OPEN, SUPERTAB_SELECT, SUPERTAB_SIDE, SUPERTAB_SIDE_KEPT };
+enum { SUPERTAB_RECAP_GET, SUPERTAB_OPEN, SUPERTAB_SELECT, SUPERTAB_SIDE, SUPERTAB_SIDE_KEPT, SUPERTAB_THREAD_LEAVE };
#define SWARM_WAITS 16
#define SWARM_SAID 24 // one per inbox entry the Lead messages can fill (NOTICES)
static EXT_RAM_BSS_ATTR ht_supertabs_t swarm;
@@ -598,6 +598,7 @@ static EXT_RAM_BSS_ATTR struct {
char desk[ID_MAX]; // the desk tab that Swarm is listed at, "" when none (entered from the inbox)
int at; // that Lead's place, where the face lands when the Lead goes
bool retried; // its recap was asked for a second time
+ struct { char tab[ID_MAX], lead[ID_MAX], root[ID_MAX]; uint32_t until; } left; // the thread just swiped out of: a card still in flight naming it is refused
struct { char tab[ID_MAX], lead[ID_MAX]; } focus[HT_SUPERTABS_MAX]; // the Lead the desktop last showed, per Swarm
char pending[ID_MAX]; // a Swarm the desktop opened before its `swarms` frame said so (ui_supertab_focus)
// The Swarm, Lead and side a session down or an emptied list took off the face, not the person: stale until that
@@ -757,6 +758,21 @@ static void swarm_leave(void)
ht_supertabs_recap_open(&swarm, "", "", ms());
change();
}
+// A horizontal swipe on a thread face leaves the thread (spec 2026-11-03-dial-thread-face): the daemon is told, the face
+// shows the main chat at once and asks for its recap again. It changes no project and selects nothing; true when it was one.
+static bool swarm_thread_swipe(void)
+{
+ const ht_lead_t *l = swarm_lead();
+ if (!l || !l->thread_root[0] || !s.connected) return false;
+ COPY(sw.left.tab, sw.tab); COPY(sw.left.lead, sw.lead); COPY(sw.left.root, l->thread_root); sw.left.until = ms() + 3000;
+ swarm_send(SUPERTAB_THREAD_LEAVE, sw.tab, sw.lead);
+ ht_supertabs_thread_leave(&swarm, sw.tab, sw.lead);
+ sw.retried = false;
+ ht_supertabs_recap_open(&swarm, sw.tab, sw.lead, ms());
+ swarm_send(SUPERTAB_RECAP_GET, sw.tab, sw.lead);
+ change();
+ return true;
+}
static void swarm_desk_note(void)
{
const ht_supertab_t *t = swarm_here();
@@ -1437,6 +1453,86 @@ static void render_buddy_empty(ht_scene_t *f, const ht_lead_t *l)
face_buddy_dots(f, true, false);
s.hits[s.hit_count++] = (hit_t){{83, 0, 300, 66}, A_AGENTS, 0, true};
}
+/*
+ * THE THREAD FACE (spec 2026-11-03-dial-thread-face, mockup round-thread): a Lead whose face chat is a thread. The teal
+ * ring at the glass edge, "Thread" (Buddy: "Thread · Buddy"), the thread's title on two lines, no pet, and the card of the
+ * thread's last message with a teal spine, its meta line (who, how many replies) and up to three lines; "Waiting for ..."
+ * until one comes. "‹ chat" at the left edge says which way out. Inter has no hooked arrow, so the label leads with ›.
+ */
+// The next line of `*cursor` in `w` px, copied to `out`.
+static void thread_line(const char **cursor, const ht_font_t *font, int w, char out[HT_TEXT_BYTES])
+{
+ const char *start = *cursor, *end = focus_take(cursor, font, w);
+ size_t n = (size_t)(end - start);
+ if (n >= HT_TEXT_BYTES) {
+ n = HT_TEXT_BYTES - 1;
+ while (n && ((unsigned char)start[n] & 0xC0) == 0x80) n--; // on a character boundary
+ }
+ memcpy(out, start, n);
+ out[n] = 0;
+}
+// What is left of `*cursor` as one line (newlines as spaces); focus_put ends it "…" when it does not fit.
+static void thread_rest(const char *cursor, char out[HT_TEXT_BYTES])
+{
+ size_t n = strlen(cursor);
+ if (n >= HT_TEXT_BYTES) {
+ n = HT_TEXT_BYTES - 1;
+ while (n && ((unsigned char)cursor[n] & 0xC0) == 0x80) n--;
+ }
+ for (size_t i = 0; i < n; i++) out[i] = cursor[i] == '\n' ? ' ' : cursor[i];
+ out[n] = 0;
+}
+static void face_thread(ht_scene_t *f, const ht_lead_t *l, bool buddy, const char *recap, const char *wait)
+{
+ // A Lead waiting on the person stays visible: the wait's text in the card, in the accent the main face writes it in.
+ if (wait) recap = wait;
+ ht_arc_title_face(f, FG, l->project[0] ? l->project : "Untitled", &ht_arc_inter_prop);
+ const unsigned TEAL = 0x2dd4bfu;
+ ht_ring_arc(f, 233 * 16, 233 * 16, 229 * 16, 5 * 16, 90, 180, color(mix_black(TEAL, 55)));
+ const ht_font_t *small = &ht_lv_inter_20.base, *body = &ht_lv_inter_25.base;
+ uint16_t teal = color(TEAL), bg = BG, card = color(0x1c1e26u);
+ char line[HT_TEXT_BYTES];
+ // "↳" is not in Inter: a hook arrow of boxes (a stroke down, a stroke right, a small head), 21 px wide, left of the label.
+ const char *label = buddy ? "Thread \u00b7 Buddy" : "Thread";
+ int lw = ht_measure(small, label), ax = 233 - (21 + 6 + lw) / 2;
+ ht_box(f, ax + 2, 100, 2, 12, 0, teal, teal);
+ ht_box(f, ax + 2, 110, 12, 2, 0, teal, teal);
+ for (int k = 0; k < 4; k++) ht_box(f, ax + 13 + 2 * k, 107 + k, 2, 9 - 2 * k, 0, teal, teal);
+ ht_text(f, ax + 27, 93, lw, small, teal, bg, label);
+ // The title on words: a first line, then the rest on a second that ends "…" when it runs long.
+ const char *cursor = l->thread_title;
+ thread_line(&cursor, body, 330, line);
+ focus_put(f, 63, 119, 340, body, FG, bg, line, true);
+ bool two = *cursor != 0;
+ if (two) { thread_rest(cursor, line); focus_put(f, 63, 119 + 29, 340, body, FG, bg, line, true); }
+ // The card, lower by a title line: the meta line (who, how many replies) above up to three lines, else what it waits for.
+ int top = 172 + (two ? 29 : 0);
+ char meta[40] = "";
+ if (recap && !wait && l->thread_replies >= 0)
+ snprintf(meta, sizeof meta, "%s · %ld repl%s", buddy ? "Buddy" : "PM", (long)l->thread_replies, l->thread_replies == 1 ? "y" : "ies");
+ int rows = recap ? 0 : 1;
+ char text[3][HT_TEXT_BYTES] = {{0}};
+ for (const char *p = recap; p && *p && rows < 3; rows++) {
+ if (rows == 2) { thread_rest(p, text[rows++]); break; }
+ thread_line(&p, body, 304, text[rows]);
+ }
+ if (rows == 0) rows = 1;
+ int h = 26 + rows * 38 + (meta[0] ? 28 : 0);
+ // x 63..403, symmetric, so "‹ chat" has room at the edge. Three lines under a two-line title end at y 369: its corners
+ // are 180 px from the centre at most, inside the ring's 226 px inner edge, so all three lines stay.
+ ht_box(f, 63, top, 340, h, 28, card, color(mix_black(TEAL, 70)));
+ ht_box(f, 63, top + 18, 7, h - 36, 3, teal, teal);
+ if (meta[0]) focus_put(f, 75, top + 13, 316, small, teal, card, meta, true);
+ if (!recap) focus_put(f, 75, top + 17, 316, body, DIM, card, buddy ? "Waiting for your Buddy…" : "Waiting for the PM…", true);
+ else for (int i = 0; i < rows; i++) focus_put(f, 75, top + (meta[0] ? 45 : 17) + i * 38, 316, body, wait ? ACCENT : FG, card, text[i], true);
+ // The way out: a chevron at the left edge, small "chat" under it.
+ uint16_t out = color(mix_black(TEAL, 85));
+ // At the screen's vertical centre, where the glass is widest: "‹" just above y 233, "chat" just below, 15 px in from the
+ // edge, so every corner of both runs is 6 px or more inside the ring's inner edge (r 226.5), and 8 px clear of the card.
+ int cw = ht_measure(&ht_mono_16, "chat"), vw = ht_measure(body, "\u2039");
+ ht_text(f, 15 + (cw - vw) / 2, 233 - body->height, vw, body, out, bg, "\u2039");
+ ht_text(f, 15, 234, cw, &ht_mono_16, out, bg, "chat");
+}
/*
* A SWARM PANE'S FACE (spec §4): the agent face, built from the Lead. The project on the upper arc; working: the pet
* and the time since `since` (none for a remote Lead); asking or stuck: the asking pose and, in the recap's place, the
@@ -1452,11 +1548,13 @@ static void render_swarm_face(ht_scene_t *f)
if (buddy && !l->buddy.has) { render_buddy_empty(f, l); return; }
const char *wait = swarm_wait_text(l);
bool asking = l->state == HT_LEAD_ASK || l->state == HT_LEAD_STUCK || wait;
- bool working = l->state == HT_LEAD_WORK && !wait && !buddy;
+ bool thread = l->thread_root[0] != 0; // the face is a thread: no pet, no working time, its own recap card
+ bool working = l->state == HT_LEAD_WORK && !wait && !buddy && !thread;
// A swarmChat daemon's recap is that of the chat on the face: one read for a chat the desktop has since left is not
// shown (design 2026-10-28-round-dial-swarm-chat §3). An older daemon names no chat on either side.
- const char *recap = wait ? wait : !working && swarm.recap.state == HT_RECAP_LOADED &&
- !strcmp(swarm.recap.lead, l->id) && !strcmp(swarm.recap.chat_id, l->chat_id) && (l->chat == HT_CHAT_BUDDY) == buddy &&
+ const char *recap = wait && !thread ? wait : !working && swarm.recap.state == HT_RECAP_LOADED &&
+ !strcmp(swarm.recap.lead, l->id) && !strcmp(swarm.recap.chat_id, l->chat_id) && !strcmp(swarm.recap.thread, l->thread_root) &&
+ (l->chat == HT_CHAT_BUDDY) == buddy &&
!s.nap ? swarm.recap.text : NULL;
uint32_t since_ms = working && l->since_s >= 0 ? (uint32_t)l->since_s * 1000u + (ms() - l->since_at_ms) : 0;
uint32_t since = since_ms / 1000;
@@ -1482,21 +1580,22 @@ static void render_swarm_face(ht_scene_t *f)
.straight_title = s.straight_title, .ink = FG, .foreground = FG, .dim = DIM,
.primary_title = true, .roomy_reading = true};
bool focus_face = character.id == HT_CHARACTER_FOCUS;
- if (focus_face) ht_focus_pick_working(&s.working_pick, &f_, recap, l->id, esp_random);
- if (again && focus_face) {
+ if (focus_face && !thread) ht_focus_pick_working(&s.working_pick, &f_, recap, l->id, esp_random);
+ if (again && focus_face && !thread) {
s.notice_ms = (clock - ht_focus_alert_pop_ms(&f_)) | 1;
f_.notice_ms = bell ? s.notice_ms : 0;
}
- ht_character_face(f, &character, &f_, ACCENT, recap);
- s.pet_next_ms = focus_face ? ht_focus_pet_next_ms(&f_, recap) : 0;
+ if (thread) face_thread(f, l, buddy, recap, wait);
+ else ht_character_face(f, &character, &f_, ACCENT, recap);
+ s.pet_next_ms = focus_face && !thread ? ht_focus_pet_next_ms(&f_, recap) : 0;
ht_rect_t bubble = {0};
- bool told = bell && focus_face && ht_focus_alert_shown(&f_, recap, &bubble);
+ bool told = bell && focus_face && !thread && ht_focus_alert_shown(&f_, recap, &bubble);
int bell_y = 400;
if (bell && !told) {
if (focus_face) focus_bell(f, unread, bell_y);
else ht_notification_bell(f, unread, f_.ink);
}
- if (buddy) {
+ if (buddy && !thread) {
// The avatar stands where the pet does on Focus, at 233, 158 or higher: 8 px clear of the recap's card, which keeps
// today's place (it rises with its lines). A creature skin keeps its creature.
if (focus_face) {
@@ -1526,7 +1625,7 @@ static void render_swarm_face(ht_scene_t *f)
face_buddy_dots(f, buddy, heard);
for (int i = 0; i < f->count; i++) lower |= f->runs[i].arc == 2 && f->runs[i].text[0];
ht_box(f, 0, 0, 1, 1, 0, BG, BG); ht_box(f, 0, 0, 1, 1, 0, BG, BG);
- if (heard && !lower) ht_arc_status_face(f, color(BUDDY_LILAC), "Your Buddy replied", &ht_arc_inter_lower);
+ if (heard && !lower && !thread) ht_arc_status_face(f, color(BUDDY_LILAC), "Your Buddy replied", &ht_arc_inter_lower);
else ht_text(f, 0, 0, 1, &ht_lv_inter_20.base, BG, BG, "");
}
// The same targets as a pane's face: the name opens PANES, the bell the inbox, the rest talks (to a local Lead).
@@ -3378,6 +3477,7 @@ static void worker(void *unused)
if (a.value >= SUPERTAB_RECAP_GET && a.value <= SUPERTAB_SELECT) cable_client_supertab_send(ops[a.value], a.text, a.id);
else if (a.value == SUPERTAB_SIDE) cable_client_supertab_side(a.text, !strcmp(a.id, "buddy"));
else if (a.value == SUPERTAB_SIDE_KEPT) cable_client_supertab_side_kept(a.text);
+ else if (a.value == SUPERTAB_THREAD_LEAVE) cable_client_supertab_thread_leave(a.text, a.id);
break;
}
case A_NOTICE_READ:
@@ -3793,7 +3893,9 @@ void habitat_touch(bool down, int x, int y, uint32_t now)
if (dx>0 && !s.q.pending) view(s.view==ANSWER_REVIEW ? CHOICE : s.view==CHOICE ? QUESTION : HOME);
} else if (s.view == INBOX && s.notice_count)
s.offset = (s.offset + (dx < 0 ? 1 : s.notice_count - 1)) % s.notice_count;
- else if (surface && swarm_here() && swarm_here()->lead_n && s.connected) {
+ else if (surface && swarm_thread_swipe()) {
+ // A thread face: out of the thread, not to the next project.
+ } else if (surface && swarm_here() && swarm_here()->lead_n && s.connected) {
// A Swarm's next or previous project, by `order`, wrapping as the panes do (never `focus`).
// One project wraps onto itself: nothing to pick, ask or reopen on the desktop (Diego, 2026-10-29).
int n = swarm_here()->lead_n, i = (sw.at + (dx < 0 ? 1 : n - 1)) % n;
@@ -5270,6 +5372,15 @@ bool ui_supertab(const ht_supertab_t *in)
else if (before && !now && !turn) turn = -1;
}
int n = ht_supertabs_put(&swarm, in, ms(), ev, (int)(sizeof ev / sizeof ev[0]));
+ // A card made before the swipe out still names the thread left: it does not bring the face back, until a card without it
+ // comes or 3 s pass.
+ if (sw.left.root[0] && !strcmp(sw.left.tab, in->id)) {
+ const ht_supertab_t *now = ht_supertabs_find(&swarm, in->id);
+ int j = now ? swarm_lead_index(now, sw.left.lead) : -1;
+ if (j >= 0 && !strcmp(now->leads[j].thread_root, sw.left.root) && (int32_t)(ms() - sw.left.until) < 0)
+ ht_supertabs_thread_leave(&swarm, in->id, sw.left.lead);
+ else sw.left.root[0] = 0;
+ }
// A daemon that says the side is the truth: a face alone cannot tell it where no project has a Buddy chat (review of
// #2218). An older one says none, and the faces' turns tell it.
if (in->side != HT_SIDE_NONE) swarm_side_put(in->id, buddies && in->side == HT_SIDE_BUDDY);
@@ -5298,10 +5409,10 @@ bool ui_supertab(const ht_supertab_t *in)
sw.opened = true;
} else
// The face's chat moved (a side the daemon took, the desktop) and what is held is another chat's: asked for
- // again. That chat's recap can come before this frame, and is refused as another chat's (a card is held 300 ms,
+ // again, and so is a thread entered or left. That chat's recap can come before this frame, and is refused as another chat's (a card is held 300 ms,
// a recap is not): the Buddy side showed no last message (Diego's dial, 2026-10-29).
if ((swarm.recap.state == HT_RECAP_LOADED || swarm.recap.state == HT_RECAP_EMPTY) && !strcmp(swarm.recap.lead, sw.lead) &&
- strcmp(swarm.recap.chat_id, t->leads[i].chat_id)) {
+ (strcmp(swarm.recap.chat_id, t->leads[i].chat_id) || strcmp(swarm.recap.thread, t->leads[i].thread_root))) {
sw.retried = false;
ht_supertabs_recap_open(&swarm, t->id, sw.lead, ms());
swarm_send(SUPERTAB_RECAP_GET, t->id, sw.lead);
@@ -5316,10 +5427,10 @@ bool ui_supertab(const ht_supertab_t *in)
display_unlock();
return beep;
}
-void ui_supertab_recap(const char *tab, const char *lead, const char *chat_id, const char *text, uint32_t at, bool none)
+void ui_supertab_recap(const char *tab, const char *lead, const char *chat_id, const char *thread, const char *text, uint32_t at, bool none)
{
display_lock();
- if (ht_supertabs_recap_put(&swarm, tab, lead, chat_id, text, at, none)) change();
+ if (ht_supertabs_recap_put(&swarm, tab, lead, chat_id, thread, text, at, none)) change();
display_unlock();
}
// `lead` "" is the desktop on that Swarm's tab with no project open (its Chat with PM, a DM): the dial still goes in, on
diff --git a/devices/harness-device/firmware/main/ui/ui_screens.h b/devices/harness-device/firmware/main/ui/ui_screens.h
index df0e3080a..0dbae208b 100644
--- a/devices/harness-device/firmware/main/ui/ui_screens.h
+++ b/devices/harness-device/firmware/main/ui/ui_screens.h
@@ -259,7 +259,7 @@ void ui_supertabs_ids(const char ids[][ID_MAX], int n);
// One Swarm's card. True when the caller should beep: a Lead started needing a person, off the face.
bool ui_supertab(const ht_supertab_t *in);
// `chat_id`: the chat the text is the last message of, "" from a daemon without swarmChat. Dropped for another chat.
-void ui_supertab_recap(const char *tab, const char *lead, const char *chat_id, const char *text, uint32_t at, bool none);
+void ui_supertab_recap(const char *tab, const char *lead, const char *chat_id, const char *thread, const char *text, uint32_t at, bool none);
void ui_supertab_focus(const char *tab, const char *lead);
// The Lead's new message in its Lead conversation or Chat with PM (`supertab.notice`): that Lead's one inbox entry, read at
// once when its chat is on the face. True when the caller should beep.
diff --git a/devices/harness-device/firmware/test/test_cable_supertab.py b/devices/harness-device/firmware/test/test_cable_supertab.py
index e2d6e13e1..b2cbfad2e 100644
--- a/devices/harness-device/firmware/test/test_cable_supertab.py
+++ b/devices/harness-device/firmware/test/test_cable_supertab.py
@@ -57,15 +57,15 @@ static void audio_notify_done(void) { beeps++; }
static char got_ids[HT_SUPERTABS_MAX][ID_MAX]; static int got_id_n;
static ht_supertab_t got_card;
static char got_tab[ID_MAX], got_lead[ID_MAX], got_text[2048], got_agent[ID_MAX], got_request[80], got_swarm[80];
-static char got_chat_id[ID_MAX]; static ht_chat_kind_t got_chat;
+static char got_chat_id[ID_MAX], got_thread[ID_MAX]; static ht_chat_kind_t got_chat;
static uint32_t got_at; static bool got_none, got_stuck, got_text_null;
static void ui_supertabs_ids(const char ids[][ID_MAX],int n) {
ids_calls++;got_id_n=n;memcpy(got_ids,ids,(size_t)n*ID_MAX);
}
static bool ui_supertab(const ht_supertab_t *in) { card_calls++;got_card=*in;return beep_next; }
-static void ui_supertab_recap(const char *tab,const char *lead,const char *chat_id,const char *text,uint32_t at,bool none) {
+static void ui_supertab_recap(const char *tab,const char *lead,const char *chat_id,const char *thread,const char *text,uint32_t at,bool none) {
recap_calls++;snprintf(got_tab,sizeof got_tab,"%s",tab);snprintf(got_lead,sizeof got_lead,"%s",lead);
- snprintf(got_chat_id,sizeof got_chat_id,"%s",chat_id);
+ snprintf(got_chat_id,sizeof got_chat_id,"%s",chat_id);snprintf(got_thread,sizeof got_thread,"%s",thread);
snprintf(got_text,sizeof got_text,"%s",text?text:"");got_at=at;got_none=none;
}
static bool ui_supertab_notice(const char *tab,const char *lead,ht_chat_kind_t chat,const char *chat_id,const char *text,uint32_t at) {
@@ -95,7 +95,7 @@ static void ui_question_close(const char *a,const char *r) { (void)a;(void)r;qcl
for name in ['str_of', 'msg', 'msg_check', 'msg_string', 'msg_number', 'msg_array', 'send_hello', 'id_fits',
'handle_supertabs', 'handle_supertab', 'handle_supertab_recap', 'handle_supertab_focus',
'handle_supertab_notice', 'handle_supertab_notice_read',
- 'handle_question', 'handle_question_close', 'cable_client_supertab_send', 'cable_client_supertab_side']:
+ 'handle_question', 'handle_question_close', 'cable_client_supertab_send', 'cable_client_supertab_thread_leave', 'cable_client_supertab_side']:
code += function(name)
code += r'''
static cJSON *parse(const char *json) { cJSON *p=cJSON_Parse(json);assert(p);return p; }
@@ -117,6 +117,8 @@ int main(void) {
assert(!strcmp(field(wire[0],"swarmChat"),"v1"));
// and swarmBuddy v1: each Lead's Buddy block, a Buddy face and the Buddy's quiet notice.
assert(!strcmp(field(wire[0],"swarmBuddy"),"v1"));
+ // and swarmThread v1: each Lead's thread fields, a recap naming its thread, and supertab.thread.leave back.
+ assert(!strcmp(field(wire[0],"swarmThread"),"v1"));
// and no swarmReview: words for a Swarm chat are sent as any harness's are, reviewed only when held (Diego's dial,
// 2026-10-29), and a daemon that heard it would refuse every word not reviewed.
assert(!strcmp(field(wire[0],"swarmReview"),"<absent>"));
@@ -232,6 +234,16 @@ int main(void) {
assert(read_calls==1);
beeps=beeps_before; // the waits below count from here
+ // A Lead in a thread: its root, title and reply count; a Lead without them is the main chat (replies unknown).
+ feed(handle_supertab,"{\"id\":\"s1\",\"name\":\"openharness\",\"leads\":["
+ "{\"id\":\"L1\",\"state\":\"work\",\"chat\":\"pm\",\"chatId\":\"pm1\",\"thread\":\"m9\",\"threadTitle\":\"Fix the login bug\",\"threadReplies\":2},"
+ "{\"id\":\"L2\",\"state\":\"work\",\"thread\":\"m8\",\"threadReplies\":-1},"
+ "{\"id\":\"L3\",\"state\":\"work\",\"thread\":7,\"threadTitle\":\"x\",\"threadReplies\":\"3\"},"
+ "{\"id\":\"L4\",\"state\":\"done\"}]}");
+ assert(got_card.lead_n==4 && !strcmp(got_card.leads[0].thread_root,"m9") && !strcmp(got_card.leads[0].thread_title,"Fix the login bug") && got_card.leads[0].thread_replies==2);
+ assert(!strcmp(got_card.leads[1].thread_root,"m8") && !got_card.leads[1].thread_title[0] && got_card.leads[1].thread_replies==-1);
+ assert(!got_card.leads[2].thread_root[0] && got_card.leads[2].thread_replies==-1); // a non-string root is no thread
+ assert(!got_card.leads[3].thread_root[0] && got_card.leads[3].thread_replies==-1);
// supertab.recap and supertab.focus.
feed(handle_supertab_recap,"{\"tab\":\"s1\",\"lead\":\"L1\",\"text\":\"Shipped.\",\"at\":1792560000,\"none\":false}");
assert(recap_calls==1 && !strcmp(got_text,"Shipped.") && got_at==1792560000u && !got_none && !strcmp(got_lead,"L1"));
@@ -247,6 +259,14 @@ int main(void) {
snprintf(bad,sizeof bad,"{\"tab\":\"s1\",\"lead\":\"L1\",\"text\":\"x\",\"at\":3,\"chatId\":\"%s\"}",longer_id);
feed(handle_supertab_recap,bad);
assert(recap_calls==3);
+ // A thread's recap names its root; the main chat's names none; a root that cannot be held is dropped.
+ assert(!got_thread[0]);
+ feed(handle_supertab_recap,"{\"tab\":\"s1\",\"lead\":\"L1\",\"text\":\"Taken.\",\"at\":4,\"none\":false,\"chatId\":\"pm1\",\"thread\":\"m9\"}");
+ assert(recap_calls==4 && !strcmp(got_thread,"m9") && !strcmp(got_text,"Taken."));
+ feed(handle_supertab_recap,"{\"tab\":\"s1\",\"lead\":\"L1\",\"text\":\"Main.\",\"at\":5,\"none\":false,\"chatId\":\"pm1\"}");
+ assert(recap_calls==5 && !got_thread[0]);
+ { char wide[256]; snprintf(wide,sizeof wide,"{\"tab\":\"s1\",\"lead\":\"L1\",\"text\":\"x\",\"thread\":\"%0*d\"}",ID_MAX+1,7);
+ feed(handle_supertab_recap,wide); assert(recap_calls==5); }
feed(handle_supertab_focus,"{\"tab\":\"s1\",\"lead\":\"L2\"}");
assert(focus_calls==1 && !strcmp(got_tab,"s1") && !strcmp(got_lead,"L2"));
feed(handle_supertab_focus,"{\"tab\":\"s1\"}");
@@ -308,6 +328,17 @@ int main(void) {
cable_client_supertab_side("",true);
cable_client_supertab_side(NULL,false);
assert(sends==2);
+ // supertab.thread.leave: exactly {t, tab, lead}, for a Swarm and a Lead the dial can hold; no Lead is nothing to leave.
+ sends=0;
+ cable_client_supertab_thread_leave("t1","L1");
+ assert(sends==1 && !strcmp(wire[0],"{\"t\":\"supertab.thread.leave\",\"tab\":\"t1\",\"lead\":\"L1\"}"));
+ cable_client_supertab_thread_leave("","L1");
+ cable_client_supertab_thread_leave("t1","");
+ cable_client_supertab_thread_leave(NULL,"L1");
+ cable_client_supertab_thread_leave("t1",NULL);
+ cable_client_supertab_thread_leave(longer,"L1");
+ cable_client_supertab_thread_leave("t1",longer);
+ assert(sends==1);
puts("Swarm frames: hello capabilities, supertabs/supertab/recap/focus parsing, chats, Buddies and Lead/PM/Buddy notices, supertab.side, malformed Leads skipped, Super Tab waits kept off the question screen, exact requests PASS");
}
'''
diff --git a/devices/harness-device/firmware/test/test_supertab.c b/devices/harness-device/firmware/test/test_supertab.c
index a9c915296..fb60d510c 100644
--- a/devices/harness-device/firmware/test/test_supertab.c
+++ b/devices/harness-device/firmware/test/test_supertab.c
@@ -176,17 +176,17 @@ static void lookups_and_recap(void)
// Recap: only the open Lead's text lands.
ht_supertabs_recap_open(&model, "s1", "L0", 100);
assert(model.recap.state == HT_RECAP_LOADING && model.recap.asked_ms == 100 && !model.recap.text[0]);
- assert(!ht_supertabs_recap_put(&model, "s1", "L1", "", "other", 1, false));
+ assert(!ht_supertabs_recap_put(&model, "s1", "L1", "", "", "other", 1, false));
assert(model.recap.state == HT_RECAP_LOADING && !model.recap.text[0]);
char *big = malloc(1601); memset(big, 'r', 1599); strcpy(big + 1499, "\xe2\x80\xa6"); memset(big + 1502, 'r', 98); big[1600] = 0;
- assert(ht_supertabs_recap_put(&model, "s1", "L0", "", big, 1792560000u, false));
+ assert(ht_supertabs_recap_put(&model, "s1", "L0", "", "", big, 1792560000u, false));
assert(model.recap.state == HT_RECAP_LOADED && strlen(model.recap.text) == 1499 && model.recap.at == 1792560000u);
free(big);
ht_supertabs_recap_open(&model, "s1", "L1", 200);
assert(model.recap.state == HT_RECAP_LOADING && !model.recap.text[0]);
- assert(ht_supertabs_recap_put(&model, "s1", "L1", "", "", 0, true) && model.recap.state == HT_RECAP_EMPTY);
+ assert(ht_supertabs_recap_put(&model, "s1", "L1", "", "", "", 0, true) && model.recap.state == HT_RECAP_EMPTY);
ht_supertabs_recap_open(&model, "", "", 300);
- assert(model.recap.state == HT_RECAP_NONE && !ht_supertabs_recap_put(&model, "", "", "", "x", 0, false));
+ assert(model.recap.state == HT_RECAP_NONE && !ht_supertabs_recap_put(&model, "", "", "", "", "x", 0, false));
ht_supertabs_recap_open(&model, "s1", "L0", 400);
ht_supertabs_reset(&model);
assert(model.n == 0 && model.id_n == 0 && model.recap.state == HT_RECAP_NONE && !model.recap.lead[0]);
@@ -227,25 +227,25 @@ static void chats(void)
// drops a recap for another chat: the face is the group's, so the Lead chat's recap (or none named) is not its.
ht_supertabs_recap_open(&model, "s1", "L0", 100);
- assert(!ht_supertabs_recap_put(&model, "s1", "L0", "lead-web", "the Lead", 1, false));
- assert(!ht_supertabs_recap_put(&model, "s1", "L0", "", "no chat named", 1, false));
+ assert(!ht_supertabs_recap_put(&model, "s1", "L0", "lead-web", "", "the Lead", 1, false));
+ assert(!ht_supertabs_recap_put(&model, "s1", "L0", "", "", "no chat named", 1, false));
assert(model.recap.state == HT_RECAP_LOADING && !model.recap.text[0]);
- assert(ht_supertabs_recap_put(&model, "s1", "L0", "g1", "Tests green.", 2, false));
+ assert(ht_supertabs_recap_put(&model, "s1", "L0", "g1", "", "Tests green.", 2, false));
assert(model.recap.state == HT_RECAP_LOADED && !strcmp(model.recap.chat_id, "g1") && !strcmp(model.recap.text, "Tests green."));
// An old daemon's Lead (no chat) takes the recap that names none, as before.
ht_supertabs_recap_open(&model, "s1", "L2", 200);
- assert(ht_supertabs_recap_put(&model, "s1", "L2", "", "Shipped.", 3, false) && !model.recap.chat_id[0]);
+ assert(ht_supertabs_recap_put(&model, "s1", "L2", "", "", "Shipped.", 3, false) && !model.recap.chat_id[0]);
// Opening the Lead already on the face keeps its recap until a new one arrives; one still on its way is asked anew.
ht_supertabs_recap_open(&model, "s1", "L0", 250);
- assert(ht_supertabs_recap_put(&model, "s1", "L0", "g1", "Tests green.", 2, false));
+ assert(ht_supertabs_recap_put(&model, "s1", "L0", "g1", "", "Tests green.", 2, false));
ht_supertabs_recap_open(&model, "s1", "L0", 260);
assert(model.recap.state == HT_RECAP_LOADED && !strcmp(model.recap.text, "Tests green.") && model.recap.asked_ms == 260);
- assert(ht_supertabs_recap_put(&model, "s1", "L0", "g1", "Deployed.", 4, false) && !strcmp(model.recap.text, "Deployed."));
+ assert(ht_supertabs_recap_put(&model, "s1", "L0", "g1", "", "Deployed.", 4, false) && !strcmp(model.recap.text, "Deployed."));
ht_supertabs_recap_open(&model, "s1", "L2", 270); ht_supertabs_recap_open(&model, "s1", "L2", 280);
assert(model.recap.state == HT_RECAP_LOADING && model.recap.asked_ms == 280);
// The face's chat moved on: what it holds is another chat's, and is not kept.
ht_supertabs_recap_open(&model, "s1", "L0", 290);
- assert(ht_supertabs_recap_put(&model, "s1", "L0", "g1", "Tests green.", 2, false));
+ assert(ht_supertabs_recap_put(&model, "s1", "L0", "g1", "", "Tests green.", 2, false));
t.leads[0].chat_id[0] = 'h'; ht_supertabs_put(&model, &t, 0, NULL, 0);
ht_supertabs_recap_open(&model, "s1", "L0", 295);
assert(model.recap.state == HT_RECAP_LOADING && !model.recap.text[0] && !model.recap.chat_id[0]);
@@ -255,6 +255,53 @@ static void chats(void)
puts("supertab: chat kind/id/name, old Leads as the Lead chat, recap only for the face's chat, the face's own reopen keeps it PASS");
}
+// A Lead in a thread (spec 2026-11-03-dial-thread-face): its root, title and replies, and a recap that must be the thread's.
+static void threads(void)
+{
+ static ht_supertab_t t;
+ ht_supertabs_reset(&model);
+ const char ids[1][ID_MAX] = {"s1"};
+ ht_supertabs_ids(&model, ids, 1, NULL, 0);
+ assert(ht_supertab_init(&t, "s1", "", "openharness", 2));
+ char title[200]; memset(title, 't', 97); strcpy(title + 97, "\xc3\xa9x"); // the buffer holds 97 bytes: a letter straddling it is dropped
+ ht_lead_in_t a = lead("L0", "work", 0); a.chat = "pm"; a.chat_id = "pm1"; a.thread = "m9"; a.thread_title = "Fix the login bug"; a.thread_replies = 3;
+ ht_lead_in_t b = lead("L1", "work", 1); b.chat = "pm"; b.chat_id = "pm1"; b.thread = "m8"; b.thread_title = title; b.thread_replies = -1;
+ ht_lead_in_t old = lead("L2", "work", 2); old.thread_replies = -1; // no thread fields: the main chat
+ assert(ht_supertab_lead_add(&t, &a) && ht_supertab_lead_add(&t, &b) && ht_supertab_lead_add(&t, &old));
+ // "a lead keeps its thread root, title and replies"
+ assert(!strcmp(t.leads[0].thread_root, "m9") && !strcmp(t.leads[0].thread_title, "Fix the login bug") && t.leads[0].thread_replies == 3);
+ assert(!strcmp(t.leads[1].thread_root, "m8") && strlen(t.leads[1].thread_title) == 97 && t.leads[1].thread_replies == -1);
+ assert(!t.leads[2].thread_root[0] && !t.leads[2].thread_title[0] && t.leads[2].thread_replies == -1);
+ ht_supertabs_put(&model, &t, 0, NULL, 0);
+
+ // "a recap for another thread than the face's is refused"
+ ht_supertabs_recap_open(&model, "s1", "L0", 100);
+ assert(!ht_supertabs_recap_put(&model, "s1", "L0", "pm1", "", "main chat", 1, false));
+ assert(!ht_supertabs_recap_put(&model, "s1", "L0", "pm1", "m7", "another thread", 1, false));
+ assert(model.recap.state == HT_RECAP_LOADING && !model.recap.text[0]);
+ assert(ht_supertabs_recap_put(&model, "s1", "L0", "pm1", "m9", "Taken.", 2, false));
+ assert(model.recap.state == HT_RECAP_LOADED && !strcmp(model.recap.thread, "m9"));
+ // and the main chat's face refuses a thread's recap
+ ht_supertabs_recap_open(&model, "s1", "L2", 110);
+ assert(!ht_supertabs_recap_put(&model, "s1", "L2", "", "m9", "thread", 1, false));
+ assert(ht_supertabs_recap_put(&model, "s1", "L2", "", NULL, "main", 1, false));
+
+ // "leaving the thread re-opens the main chat's recap": the held thread recap is kept for the thread, not the main chat.
+ ht_supertabs_recap_open(&model, "s1", "L0", 200);
+ assert(ht_supertabs_recap_put(&model, "s1", "L0", "pm1", "m9", "Taken.", 2, false));
+ ht_supertabs_recap_open(&model, "s1", "L0", 210);
+ assert(model.recap.state == HT_RECAP_LOADED && !strcmp(model.recap.text, "Taken.") && model.recap.asked_ms == 210); // same thread: kept
+ assert(!ht_supertabs_thread_leave(&model, "s1", "L2") && !ht_supertabs_thread_leave(&model, "s1", "nope"));
+ assert(ht_supertabs_thread_leave(&model, "s1", "L0"));
+ const ht_lead_t *l0 = &ht_supertabs_find(&model, "s1")->leads[0];
+ assert(!l0->thread_root[0] && !l0->thread_title[0] && l0->thread_replies == -1);
+ ht_supertabs_recap_open(&model, "s1", "L0", 300);
+ assert(model.recap.state == HT_RECAP_LOADING && !model.recap.text[0] && !model.recap.thread[0] && model.recap.asked_ms == 300);
+ assert(!ht_supertabs_recap_put(&model, "s1", "L0", "pm1", "m9", "late thread recap", 3, false));
+ assert(ht_supertabs_recap_put(&model, "s1", "L0", "pm1", "", "Merged #2704.", 4, false) && !strcmp(model.recap.text, "Merged #2704."));
+ puts("supertab: thread root/title/replies, a recap only for the face's thread, leaving it asks the main chat again PASS");
+}
+
// The reader's own Buddy in each project (spec 2026-10-29-round-dial-pm-buddy): `buddies` while the Swarm has them on,
// the Buddy block with its avatar's 15 half bits and colour, and a face that may be its chat.
static void buddies(void)
@@ -317,6 +364,7 @@ int main(void)
transitions();
lookups_and_recap();
chats();
+ threads();
buddies();
return 0;
}
diff --git a/devices/harness-device/firmware/test/test_touch_ui.py b/devices/harness-device/firmware/test/test_touch_ui.py
index 6864ee51e..01b02670a 100644
--- a/devices/harness-device/firmware/test/test_touch_ui.py
+++ b/devices/harness-device/firmware/test/test_touch_ui.py
@@ -202,7 +202,7 @@ static bool queue(action_t a) {
if (a.kind==A_NOTICE_READ) { notice_reads_sent++; notice_read_queued=a; }
if (a.kind==A_DESKTOP) { desktop_opens++; COPY(opened_agent,a.id); }
if (a.kind==A_SUPERTAB && swarm_sent<64) {
- static const char *ops[]={"recap.get","open","select","side","side-kept"};
+ static const char *ops[]={"recap.get","open","select","side","side-kept","thread-leave"};
snprintf(swarm_wire[swarm_sent++],sizeof swarm_wire[0],"%s %s %s",ops[a.value],a.text,a.id);
}
if (a.kind==A_STOP_YES) COPY(stopped_agent,a.id);
@@ -228,7 +228,7 @@ swarm_parts = {
# with the last `swarms` list it keeps beside it
'swarms_apply': source[source.index('// The last `swarms` list as it came'):source.index('void ui_swarms_replace(')],
}
-for name in ['copy', 'recap_preview', 'notice_unread', 'notice_was_read', 'notice_forget_read', 'notice_flush_reads', 'notice_mark_read', 'habitat_scene_receipt', 'habitat_scene_presented', 'pane_memory', 'pane_memory_apply', 'dismiss_result', 'activity_text', 'ensure', 'input_cancel', 'view', 'notice_open', 'workspace_index', 'swarm_core', 'swarm_voice_id', 'voice_lead', 'tabs_open', 'workspace_failed', 'tab_request', 'tabs_sync', 'ui_scroll_reportable', 'focus_skin', 'focus_face_for', 'focus_chord', 'focus_put', 'focus_span', 'focus_take', 'focus_rows', 'ui_rows', 'ui_can_display', 'ui_wrap', 'text_in', 'control', 'home_footer', 'footer_control', 'text', 'center', 'render_brand', 'heading', 'question_view', 'question_rows', 'question_move', 'question_text', 'render_question', 'render_choices', 'render_answer_review', 'question_answer', 'send_answer', 'make_action', 'character_mood', 'voice_status', 'home_caption_rotates', 'home_caption_tick', 'status_animated', 'status_speed', 'status_wake_ms', 'surface_tick', 'command_face', 'render_workspace_preview', 'question_prompt', 'focus_bell', 'mix_black', 'face_buddy_disc', 'face_buddy_ring', 'face_buddy_dots', 'face_buddy_avatar', 'render_buddy_empty', 'render_swarm_face', 'render_home', 'render_voice', 'render_selection', 'render_form', 'draft_move', 'render_draft', 'render_draft_options', 'swarms_apply', 'ui_swarms_replace', 'ui_workspace_applied', 'ui_land_after_reload']:
+for name in ['copy', 'recap_preview', 'notice_unread', 'notice_was_read', 'notice_forget_read', 'notice_flush_reads', 'notice_mark_read', 'habitat_scene_receipt', 'habitat_scene_presented', 'pane_memory', 'pane_memory_apply', 'dismiss_result', 'activity_text', 'ensure', 'input_cancel', 'view', 'notice_open', 'workspace_index', 'swarm_core', 'swarm_voice_id', 'voice_lead', 'tabs_open', 'workspace_failed', 'tab_request', 'tabs_sync', 'ui_scroll_reportable', 'focus_skin', 'focus_face_for', 'focus_chord', 'focus_put', 'focus_span', 'focus_take', 'focus_rows', 'ui_rows', 'ui_can_display', 'ui_wrap', 'text_in', 'control', 'home_footer', 'footer_control', 'text', 'center', 'render_brand', 'heading', 'question_view', 'question_rows', 'question_move', 'question_text', 'render_question', 'render_choices', 'render_answer_review', 'question_answer', 'send_answer', 'make_action', 'character_mood', 'voice_status', 'home_caption_rotates', 'home_caption_tick', 'status_animated', 'status_speed', 'status_wake_ms', 'surface_tick', 'command_face', 'render_workspace_preview', 'question_prompt', 'focus_bell', 'mix_black', 'face_buddy_disc', 'face_buddy_ring', 'face_buddy_dots', 'face_buddy_avatar', 'render_buddy_empty', 'thread_line', 'thread_rest', 'face_thread', 'render_swarm_face', 'render_home', 'render_voice', 'render_selection', 'render_form', 'draft_move', 'render_draft', 'render_draft_options', 'swarms_apply', 'ui_swarms_replace', 'ui_workspace_applied', 'ui_land_after_reload']:
code += swarm_parts[name] if name in swarm_parts else function(name)
code += function('render_settings') + function('ui_visit_state')
code += function('ui_project_known') + function('ui_focus_project') + function('ui_apply_pending_focus')
@@ -1516,8 +1516,8 @@ static void swarm_pane_checks(const char *dir) {
fake_ms += 6000; scene_take(); assert(scene_says("2:20")); // the dial's own clock carries it on
// 2b a long name, done: the recap card. A recap for another Lead is dropped.
enter_at("s1", "L1");
- ui_supertab_recap("s1", "L2", "", "Not this one.", 1792560000u, false); scene_take(); assert(!scene_says("Not this one."));
- ui_supertab_recap("s1", "L1", "", "Release candidate built and checked on both dials.", 1792560000u, false); scene_take();
+ ui_supertab_recap("s1", "L2", "", "", "Not this one.", 1792560000u, false); scene_take(); assert(!scene_says("Not this one."));
+ ui_supertab_recap("s1", "L1", "", "", "Release candidate built and checked on both dials.", 1792560000u, false); scene_take();
assert(scene_says("Release candidate built"));
FOCUS_PAGE("swarm-2b");
// 2g a 1,500-byte recap: four lines, the last ending in "…".
@@ -1525,13 +1525,13 @@ static void swarm_pane_checks(const char *dir) {
char longer[HT_SUPERTAB_TEXT]; size_t n = 0;
while (n + 6 < sizeof longer - 1) { memcpy(longer + n, "words ", 6); n += 6; }
longer[n] = 0;
- ui_supertab_recap("s1", "L1", "", longer, 1792560000u, false); scene_take();
+ ui_supertab_recap("s1", "L1", "", "", longer, 1792560000u, false); scene_take();
const char *last = ""; int lines = card_lines(&last);
assert(lines >= 1 && lines <= 4 && strstr(last, "\xe2\x80\xa6"));
FOCUS_PAGE("swarm-2g");
}
// 2f no message yet: the resting face, no card.
- ui_supertab_recap("s1", "L1", "", "", 0, true); scene_take();
+ ui_supertab_recap("s1", "L1", "", "", "", 0, true); scene_take();
{ const char *last; assert(!card_lines(&last)); }
// With nothing unread the bell leaves the lower arc to the resting face's one line, as in the mockup.
for (int i = 0; i < s.notice_count; i++) notice_mark_read(&s.notice[i]);
@@ -1539,7 +1539,7 @@ static void swarm_pane_checks(const char *dir) {
FOCUS_PAGE("swarm-2f");
// 2c "docs" needs you, here: its wait's question takes the recap's place, in the asking pose.
enter_at("s1", "L2");
- ui_supertab_recap("s1", "L2", "", "Docs drafted.", 1792560000u, false);
+ ui_supertab_recap("s1", "L2", "", "", "Docs drafted.", 1792560000u, false);
assert(!ui_supertab_wait("h2", "supertab:w1", "openharness", false, "Publish the docs today?")); // on the face: no beep
scene_take(); assert(scene_says("Publish the docs") && !scene_says("Docs drafted."));
FOCUS_PAGE("swarm-2c");
@@ -1553,7 +1553,7 @@ static void swarm_pane_checks(const char *dir) {
static const void *asking[64], *done[64]; int asking_n = pet_frames(asking);
card_begin("s1", "t1", "openharness"); openharness_card(); card.leads[1].state = HT_LEAD_DONE; // L3, firmware
assert(!strcmp(card.leads[1].id, "L3")); card_send(); ui_supertab_wait_close("h3", "supertab:w2");
- ui_supertab_recap("s1", "L3", "", "Release key found; build signed.", 1792560000u, false);
+ ui_supertab_recap("s1", "L3", "", "", "Release key found; build signed.", 1792560000u, false);
int done_n = pet_frames(done); bool other = false;
for (int i = 0; i < asking_n; i++) { bool shared = false; for (int k = 0; k < done_n; k++) shared |= asking[i] == done[k]; other |= !shared; }
assert(asking_n && done_n && other);
@@ -1575,7 +1575,7 @@ static void swarm_pane_checks(const char *dir) {
card_lead("L0", "mobile", "claude", "h0", "work", 0, 134); card_lead("L1", "Round dial firmware release candidate", "claude", "h1", "done", 1, -1);
card_lead("L2", "docs", "claude", "h2", "ask", 2, -1); card_lead("L3", "firmware", "codex", "h3", "stuck", 3, -1);
card_lead("L4", "backend", "cursor", "", "ask", 4, -1); card_send();
- ui_supertab_recap("s1", "L4", "", "Need a decision on the cache size.", 1792560000u, false); scene_take();
+ ui_supertab_recap("s1", "L4", "", "", "Need a decision on the cache size.", 1792560000u, false); scene_take();
assert(scene_says("Need a decision") && !scene_says("Working"));
FOCUS_PAGE("swarm-2e-ask");
// 2h a Swarm with no projects: PANES' own empty page, and "Choose a tab" goes to TABS.
@@ -1601,7 +1601,7 @@ static void swarm_pane_checks(const char *dir) {
// A swipe on a Swarm of one project lands on the project already on the face: nothing happens. It used to empty
// the recap for 5 s and pick the project again, which reopened its Lead chat on the desktop (Diego, 2026-10-29).
swarm_setup(); enter_at("s2", "P0");
- ui_supertab_recap("s2", "P0", "", "Sandbox rebuilt.", 1792560000u, false); scene_take();
+ ui_supertab_recap("s2", "P0", "", "", "Sandbox rebuilt.", 1792560000u, false); scene_take();
assert(swarm.recap.state == HT_RECAP_LOADED); swarm_sent = 0;
habitat_touch(true, 320, 220, fake_ms); habitat_touch(false, 150, 220, fake_ms + 120); scene_take();
habitat_touch(true, 150, 220, fake_ms + 1000); habitat_touch(false, 320, 220, fake_ms + 1120); scene_take();
@@ -1933,7 +1933,7 @@ static void swarm_chat_checks(const char *dir) {
enter_at("s1", "C0");
assert(title_is("mobile") && scene_says("0:09") && inner_arc() && !strcmp(inner_arc()->text, "Fix login"));
FOCUS_PAGE("swarm-6c");
- ui_supertab_recap("s1", "C0", "g1", "Tests green on both dials.", 1792560000u, false); scene_take();
+ ui_supertab_recap("s1", "C0", "g1", "", "Tests green on both dials.", 1792560000u, false); scene_take();
assert(!scene_says("Tests green"));
// A done group shows its recap.
assert(!chat_card("done", "pm", "pm1")); scene_take();
@@ -1941,7 +1941,7 @@ static void swarm_chat_checks(const char *dir) {
// The PM chat: its recap, never working.
enter_at("s1", "C1");
- ui_supertab_recap("s1", "C1", "pm1", "The release notes are ready.", 1792560000u, false); scene_take();
+ ui_supertab_recap("s1", "C1", "pm1", "", "The release notes are ready.", 1792560000u, false); scene_take();
assert(scene_says("release notes") && !scene_says("Working"));
// The desktop moved that project to its Lead chat: the PM chat's recap is no longer this face's.
assert(!chat_card("done", "lead", "lead-docs")); scene_take();
@@ -2147,6 +2147,130 @@ static void swarm_restart_checks(void) {
assert(swarm_mode() && !strcmp(sw.lead, "B1") && swarm_side_buddy("s1") && wire_has(0, "side-kept s1 buddy") && !wire_has(0, "side s1 buddy"));
puts("Swarm restart: the face keeps its Swarm, Lead and side across a session down or an empty list with no time limit, follows the app, and only the person or a Swarm really gone ends it");
}
+// A face in a thread (spec 2026-11-03-dial-thread-face): the teal face, the card, and the swipe out that selects nothing.
+static void thread_lead(const char *id, const char *project, const char *thread, const char *title, long replies) {
+ ht_lead_in_t in = {.id = id, .project = project, .engine = "claude", .local = "", .state = "done", .order = card.lead_n, .since = -1,
+ .chat = "pm", .chat_id = "pm1", .chat_name = "PM", .thread = thread, .thread_title = title, .thread_replies = replies};
+ assert(ht_supertab_lead_add(&card, &in));
+}
+static bool teal_ring(void) {
+ for (int i = 0; i < scene.count; i++) {
+ const ht_run_t *r = &scene.runs[i];
+ if (r->ring.set && r->ring.w16 == 5 * 16 && r->ring.r16 == 229 * 16 && r->ring.colour == ht_rgb(0x197569)) return true; // #2dd4bf at 55 % over black
+ }
+ return false;
+}
+// The label is "Thread" with a teal hook arrow of boxes left of it (Inter has no U+21B3, and no "›" stands in); the card starts at
+// x 60 and "chat" ends 8 px or more left of it.
+static void thread_chrome_checks(void) {
+ const ht_run_t *label = NULL, *chat = NULL; int card_x = -1;
+ for (int i = 0; i < scene.count; i++) {
+ const ht_run_t *r = &scene.runs[i];
+ if (!strcmp(r->text, "Thread")) label = r;
+ if (!strcmp(r->text, "chat")) chat = r;
+ if (!r->text[0] && r->w == 340 && r->box.h >= 60) card_x = r->x;
+ }
+ assert(label && chat && card_x == 63 && !scene_says("\xe2\x80\xba"));
+ assert(chat->x + chat->w + 8 <= card_x);
+ // Both runs of the way out: every corner of the box is 6 px or more inside the ring's inner edge (r 226.5 from 233, 233).
+ const ht_run_t *out[2] = {chat, NULL};
+ for (int i = 0; i < scene.count; i++) if (!strcmp(scene.runs[i].text, "\xe2\x80\xb9")) out[1] = &scene.runs[i];
+ assert(out[1]);
+ for (int k = 0; k < 2; k++) {
+ ht_rect_t b = ht_run_bounds(out[k]);
+ for (int c = 0; c < 4; c++) {
+ int dx = (c & 1 ? b.x + b.w : b.x) - 233, dy = (c & 2 ? b.y + b.h : b.y) - 233;
+ assert(dx * dx + dy * dy <= 220 * 220 + 220 / 2); // 220.5 squared, to the pixel
+ }
+ }
+ int strokes = 0;
+ for (int i = 0; i < scene.count; i++) {
+ const ht_run_t *r = &scene.runs[i];
+ if (!r->text[0] && r->box.fill == ht_rgb(0x2dd4bf) && r->y >= 100 && r->y <= 116 && r->x + r->w <= label->x) strokes++;
+ }
+ assert(strokes >= 6); // the down stroke, the right stroke and the head's four columns, all left of the label
+}
+static void swarm_thread_checks(const char *dir) {
+ reset(); ht_character_select(&character, HT_CHARACTER_FOCUS); fake_ms = 100000;
+ desk_open();
+ const char ids[1][ID_MAX] = {"s1"};
+ ui_supertabs_ids(ids, 1);
+ card_begin("s1", "t1", "openharness");
+ thread_lead("T0", "web-api", "m9", "Fix the login bug on Safari when the session expires", 1);
+ thread_lead("T1", "firmware", "", "", -1);
+ assert(!card_send());
+ enter_at("s1", "T0"); swarm_sent = 0;
+ // Before a reply: the thread, its title on two lines, and what it waits for; no pet, no working time.
+ scene_take();
+ assert(title_is("web-api") && scene_says("Thread") && scene_says("Fix the login bug on Safari") && scene_says("session expires"));
+ thread_chrome_checks();
+ portrait(dir, "thread-a-waiting-1line");
+ assert(scene_says("Waiting for the PM") && scene_says("chat") && !scene_says("Working") && teal_ring() && !pet_frame());
+ // The main chat's recap is not the thread's; the thread's is, with who spoke and how many.
+ ui_supertab_recap("s1", "T0", "pm1", "", "Merged #2704.", 1792560000u, false); scene_take();
+ assert(!scene_says("Merged") && scene_says("Waiting for the PM"));
+ ui_supertab_recap("s1", "T0", "pm1", "m9", "Taken: Milo fixes it now.", 1792560000u, false); scene_take();
+ portrait(dir, "thread-1line-recap");
+ // 2-line title, 3-line recap, "PM · 2 replies": the largest card.
+ card_begin("s1", "t1", "openharness");
+ thread_lead("T0", "web-api", "m9", "Fix the login bug on Safari when the session expires", 2); thread_lead("T1", "firmware", "", "", -1); assert(!card_send());
+ ui_supertab_recap("s1", "T0", "pm1", "m9", "Taken: Milo fixes the login bug now and Quinn reviews it before the end of the day, then we ship the release to everyone on the beta channel.", 1792560000u, false); scene_take();
+ assert(scene_says("PM \xc2\xb7 2 replies")); thread_chrome_checks();
+ portrait(dir, "thread-b-2line-3line-recap");
+ // A Buddy thread: "Thread · Buddy" and the same chrome.
+ { ht_lead_in_t in = {.id = "T0", .project = "web-api", .engine = "claude", .local = "", .state = "done", .order = 0, .since = -1,
+ .chat = "buddy", .chat_id = "b0", .chat_name = "Buddy", .thread = "m5", .thread_title = "Plan the Pro voice", .thread_replies = 2,
+ .buddies = true, .buddy = {.present = true, .chat_id = "b0", .name = "Buddy", .engine = "claude", .color = "#d6a79a", .cells = 25513, .live = true}};
+ card_begin("s1", "t1", "openharness"); assert(ht_supertab_lead_add(&card, &in)); thread_lead("T1", "firmware", "", "", -1); card.leads[0].buddies = true;
+ card.side = HT_SIDE_BUDDY; assert(!card_send()); }
+ ui_supertab_recap("s1", "T0", "b0", "m5", "Two options: push-to-talk or wake word.", 1792560000u, false); scene_take();
+ assert(scene_says("Thread \xc2\xb7 Buddy") && scene_says("Buddy \xc2\xb7 2 replies")); portrait(dir, "thread-c-buddy");
+ // Back to the PM thread for the rest of the checks.
+ card_begin("s1", "t1", "openharness");
+ thread_lead("T0", "web-api", "m9", "Fix the login bug on Safari when the session expires", 1); thread_lead("T1", "firmware", "", "", -1); assert(!card_send());
+ ui_supertab_recap("s1", "T0", "pm1", "m9", "Taken: Milo fixes it now.", 1792560000u, false); scene_take();
+ assert(scene_says("Taken: Milo") && scene_says("PM \xc2\xb7 1 reply") && !scene_says("Waiting"));
+ // A Lead that starts waiting on the person stays visible on the thread face: the wait takes the card, the chrome stays.
+ card_begin("s1", "t1", "openharness");
+ thread_lead("T0", "web-api", "m9", "Fix the login bug on Safari when the session expires", 1); thread_lead("T1", "firmware", "", "", -1);
+ strcpy(card.leads[0].local, "h5"); assert(!card_send());
+ assert(!ui_supertab_wait("h5", "supertab:w1", "openharness", false, "Publish the docs today?")); scene_take();
+ assert(scene_says("Publish the docs today?") && !scene_says("Taken: Milo") && !scene_says("1 reply") && scene_says("Thread") && teal_ring());
+ thread_chrome_checks();
+ portrait(dir, "thread-e-waiting-lead");
+ ui_supertab_wait_close("h5", "supertab:w1"); scene_take();
+ assert(scene_says("Taken: Milo") && !scene_says("Publish the docs"));
+ // The swipe sideways leaves the thread: the daemon is told, the main chat's recap is asked for, nothing is selected, and the
+ // face stays on the same project.
+ swarm_sent = 0; swipe_next();
+ assert(swarm_sent == 2 && !strcmp(swarm_wire[0], "thread-leave s1 T0") && !strcmp(swarm_wire[1], "recap.get s1 T0"));
+ assert(!strcmp(sw.lead, "T0") && !scene_says("Thread") && !teal_ring() && !scene_says("Taken: Milo") && swarm.recap.state == HT_RECAP_LOADING);
+ ui_supertab_recap("s1", "T0", "pm1", "", "Merged #2704. Next: the Kilo picker fix.", 1792560000u, false); scene_take(); portrait(dir, "thread-d-main-pm-after-leave");
+ // The thread's recap arriving late is refused; the main chat's lands.
+ ui_supertab_recap("s1", "T0", "pm1", "m9", "Late.", 1792560000u, false); scene_take(); assert(!scene_says("Late."));
+ ui_supertab_recap("s1", "T0", "pm1", "", "Merged #2704.", 1792560000u, false); scene_take(); assert(scene_says("Merged #2704."));
+ // A card made before the swipe still names the thread left: it does not bring the face back. One without it, or 3 s, ends that.
+ swarm_sent = 0; card_begin("s1", "t1", "openharness");
+ thread_lead("T0", "web-api", "m9", "Fix the login bug on Safari when the session expires", 1); thread_lead("T1", "firmware", "", "", -1); assert(!card_send());
+ scene_take(); assert(!scene_says("Thread") && !teal_ring() && swarm_sent == 0 && swarm.recap.state == HT_RECAP_LOADED);
+ card_begin("s1", "t1", "openharness"); thread_lead("T0", "web-api", "", "", -1); thread_lead("T1", "firmware", "", "", -1); assert(!card_send());
+ card_begin("s1", "t1", "openharness");
+ thread_lead("T0", "web-api", "m9", "Fix the login bug on Safari when the session expires", 1); thread_lead("T1", "firmware", "", "", -1); assert(!card_send());
+ scene_take(); assert(scene_says("Thread") && teal_ring()); // a thread entered again after the mask ended
+ ui_supertab_recap("s1", "T0", "pm1", "m9", "Back.", 1792560000u, false);
+ // A frame that puts the face in a thread (the app opened one, or the dial's words started it) asks for that thread's recap.
+ swarm_sent = 0; card_begin("s1", "t1", "openharness");
+ thread_lead("T0", "web-api", "m10", "Plan the release", 0); thread_lead("T1", "firmware", "", "", -1); assert(!card_send());
+ assert(swarm_sent == 1 && !strcmp(swarm_wire[0], "recap.get s1 T0") && swarm.recap.state == HT_RECAP_LOADING);
+ scene_take(); assert(scene_says("Plan the release") && scene_says("Waiting for the PM"));
+ ui_supertab_recap("s1", "T0", "pm1", "m10", "Two options.", 1792560000u, false); scene_take(); assert(scene_says("PM \xc2\xb7 0 replies"));
+ swarm_sent = 0; card_begin("s1", "t1", "openharness"); thread_lead("T0", "web-api", "", "", -1); thread_lead("T1", "firmware", "", "", -1); assert(!card_send());
+ assert(swarm_sent == 1 && !strcmp(swarm_wire[0], "recap.get s1 T0")); // and one that ends it (the app closed it) asks the main chat's
+ // Now on the main chat, the same swipe moves to the next project as before.
+ swarm_sent = 0; swipe_next();
+ assert(!strcmp(sw.lead, "T1") && swarm_sent >= 1 && !strcmp(swarm_wire[0], "select s1 T1"));
+ puts("Swarm thread face: title, waiting, a recap only for the thread, swipe out sends the leave and the main recap ask and selects nothing, then swipes move on PASS");
+}
static void swarm_buddy_checks(const char *dir) {
// 7a the PM side: today's face and two dots, the upper one lit.
buddy_setup();
@@ -2177,7 +2301,7 @@ static void swarm_buddy_checks(const char *dir) {
{ int n = swarm_sent; buddy_card("lead"); assert(swarm_sent == n); }
buddy_setup();
// The PM chat's recap is on the face.
- ui_supertab_recap("s1", "B0", "lead-web", "Merged.", 1792560000u, false); scene_take(); assert(scene_says("Merged."));
+ ui_supertab_recap("s1", "B0", "lead-web", "", "Merged.", 1792560000u, false); scene_take(); assert(scene_says("Merged."));
// 7b swipe up: the dial says so, and draws the Buddy side at once: the ring, the avatar, the lower dot lit.
swipe_up();
// A flick is the side's: it scrolls nothing (it used to scroll the pane still active behind it).
@@ -2187,25 +2311,25 @@ static void swarm_buddy_checks(const char *dir) {
// The Buddy chat's recap can come before the frame that puts that chat on the face (a card is held 300 ms, a recap is
// not), and is refused as another chat's. The frame then asks for it again: the Buddy side showed no last message
// (Diego's dial, 2026-10-29).
- ui_supertab_recap("s1", "B0", "b0", "Too early.", 1792560000u, false);
+ ui_supertab_recap("s1", "B0", "b0", "", "Too early.", 1792560000u, false);
// The daemon puts the Buddy chat on the face; its recap is the Buddy's last message.
buddy_card("buddy");
assert(swarm_sent == 2 && !strcmp(swarm_wire[1], "recap.get s1 B0"));
- ui_supertab_recap("s1", "B0", "b0", "Two ways: cache the read, or move it to the host. I'd cache it.", 1792560000u, false); scene_take();
+ ui_supertab_recap("s1", "B0", "b0", "", "Two ways: cache the read, or move it to the host. I'd cache it.", 1792560000u, false); scene_take();
assert(scene_says("Two ways") && lilac_ring() && avatar());
// Without a recap it stands at 233, 158 exactly.
{ const ht_run_t *a = avatar_sprite(); assert(a); }
{
// A four-line recap: the card rises, the avatar with it.
- ui_supertab_recap("s1", "B0", "b0", "Two ways: cache the read, or move it to the host. I'd cache it. Want me to write it up and send it to the PM?", 1792560000u, false);
+ ui_supertab_recap("s1", "B0", "b0", "", "Two ways: cache the read, or move it to the host. I'd cache it. Want me to write it up and send it to the PM?", 1792560000u, false);
scene_take(); assert(avatar() && card_top());
// With the bell too (an unread notice off the face) every run still fits the scene.
assert(ui_supertab_notice("s1", "B1", HT_CHAT_LEAD, "lead-fw", "Flashed.", 1792560001u));
scene_take(); assert(avatar() && scene.count < HT_RUNS);
- ui_supertab_recap("s1", "B0", "b0", "", 1792560000u, true);
+ ui_supertab_recap("s1", "B0", "b0", "", "", 1792560000u, true);
// Nothing said yet: whatever the face writes instead stands clear of the avatar, at any of its captions.
for (int k = 0; k < 40; k++) { fake_ms += 9000; scene_take(); assert(avatar() && clear_of_text()); }
- ui_supertab_recap("s1", "B0", "b0", "Two ways: cache the read, or move it to the host. I'd cache it.", 1792560000u, false); scene_take();
+ ui_supertab_recap("s1", "B0", "b0", "", "Two ways: cache the read, or move it to the host. I'd cache it.", 1792560000u, false); scene_take();
}
FOCUS_PAGE("buddy-7b");
{
@@ -2302,7 +2426,7 @@ static void swarm_buddy_checks(const char *dir) {
// 7d the quiet notice: on the PM side the Buddy's word turns the lower dot lilac and writes a line on the lower arc, with
// no beep, no inbox entry and no wake. The run count holds.
buddy_setup();
- ui_supertab_recap("s1", "B0", "lead-web", "Assigned #2083 to web-api. I'll post here when the PR is up.", 1792560000u, false);
+ ui_supertab_recap("s1", "B0", "lead-web", "", "Assigned #2083 to web-api. I'll post here when the PR is up.", 1792560000u, false);
scene_take(); pm_runs = scene.count;
assert(!badge() && pm_dots() && !offset_disc() && !scene_says("Your Buddy replied"));
int entries = s.notice_count; int woke = wakes;
@@ -2316,7 +2440,7 @@ static void swarm_buddy_checks(const char *dir) {
// Opening the Buddy side reads it.
swipe_up(); assert(!badge()); swipe_down(); assert(!badge() && !scene_says("Your Buddy replied"));
// The resting face keeps its own line on the lower arc: there the badge alone tells it.
- ui_supertab_recap("s1", "B0", "lead-web", "", 1792560000u, true);
+ ui_supertab_recap("s1", "B0", "lead-web", "", "", 1792560000u, true);
assert(!ui_supertab_notice("s1", "B0", HT_CHAT_BUDDY, "b0", "Later.", 1792560002u));
scene_take(); assert(badge() && !offset_disc() && !scene_says("Your Buddy replied"));
swipe_up(); swipe_down(); assert(!badge() && pm_dots());
@@ -3932,6 +4056,7 @@ int main(int argc, char **argv) {
swarm_chat_checks(argc>1 ? argv[1] : NULL);
swarm_restart_checks();
swarm_buddy_checks(argc>1 ? argv[1] : NULL);
+ swarm_thread_checks(argc>1 ? argv[1] : NULL);
}
'''
extra_sources = []
diff --git a/docs/naming-system.md b/docs/naming-system.md
index eb9b8bf22..f0ed2551a 100644
--- a/docs/naming-system.md
+++ b/docs/naming-system.md
@@ -113,7 +113,10 @@ after the label and an add action at the right. Project rows read as channels, f
**# product-managers** row was removed on 2026-10-31: it was not a project.) A click on a project row
opens its product manager chat and reveals its workgroups; a second click on the open project
hides them. Workgroups are shown by their number in grey with no **#**
-and then their title (`12 Offline editing`), aligned with the project name. An expanded project
+and then their title (`12 Offline editing`), aligned with the project name, under four headings
+with their counts, in this order: **Needs you** (waiting on the person or tagging them),
+**Working**, **Waiting on others** and **The rest**, which starts folded (`▾ Needs you 1`); a
+click on a heading folds or unfolds it, each project keeping its own. An expanded project
without workgroups says **No workgroups yet**. An open channel's heading reads as its row
(`# openharness`). **Buddies** holds the person's **Buddy chat** for each project, from the
start, listed by their Buddy's name and avatar, or while none runs by the name they chose for it,
diff --git a/docs/plans/2026-11-02-swarm-agent-purge-plan.md b/docs/plans/2026-11-02-swarm-agent-purge-plan.md
new file mode 100644
index 000000000..e7417355d
--- /dev/null
+++ b/docs/plans/2026-11-02-swarm-agent-purge-plan.md
@@ -0,0 +1,165 @@
+# Swarm agents: a live-agent index and a purge of old tombstones Implementation Plan
+
+Task #2150, asked for by Ken on 2026-11-02 from his production database profile (Atlas primary, 10:50-12:38 UTC, backend
+v1.3.86). Written by the writing-plans skill, implemented by this project's Engineer in this session, test first; no
+execution handoff.
+
+**Goal:** `SwarmAgent` reads of a Swarm's live agents examine only live agents, and removed agents' tombstones stop
+piling up.
+
+**Architecture:** a `[tabId, deleted]` index serves `findMany({ tabId, deleted: false })` (parts/light.ts:88, load.ts,
+read/host.ts). The hourly sweep deletes an agent tombstone past its `purgeAt` instead of compacting it for good, unless an
+open conversation or a live start still names the agent; those are compacted and checked again a day later. Before a
+tombstone goes, its Swarm's agent floor (`SwarmHead.agentFloor`) rises to its version, and an agent added with no tombstone
+starts above that floor, so versions still never go back (postmortem 2026-10-27 D6). A one-release startup step gives the tombstones compacted before this change a purge time.
+
+**Tech Stack:** TypeScript, Prisma on MongoDB 7, vitest with a loopback `MongoMemoryReplSet` and Mongo's profiler.
+
+**Spec:** the task brief (#2150): index `{tabId, deleted}`; purge deleted agents past `purgeAt` in batches, never one still
+referenced by an open group or a record that needs it; tests for the read and the purge; prod slow logs before and after.
+
+## Global Constraints
+
+- Creating the production index is a production write: it runs only with Ken's go (the worker's schema step builds it
+ when the release deploys).
+- Measurements use the read-only production login only, from its environment file, never printed.
+- The purge deletes data: two independent security reviews before merge.
+- Full Super Tab integration suite (`npm run test:super-tabs`) before Ready.
+- A tombstone is deleted only after `purgeAt` (removal + `RETENTION_MS`, 7 days): a change cursor that old reloads
+ (read/cursor.ts), so no reader misses the removal.
+
+## Review Focus
+
+- Versions never go back (postmortem 2026-10-27 D6, design ruling 6). Agent tombstones were kept for good so a key
+ added again continues above its old version: an agent's key is `stableId(machineId, harnessId)`, so a reopened session
+ comes back under it. Deleting the tombstone loses that version, and two things still hold it: Desktop keeps the newest
+ version it saw of every part, a tombstone's too, until it reloads (desktop/lib/super_tabs/parts.dart `_newer`; a Desktop
+ open for weeks never reloads), and `SuperTabConfiguration.revision` is ordered by it (store.ts). So the purge first raises
+ the Swarm's `agentFloor` to the version it deletes, and an agent inserted with no row starts above it (Task 2). A first
+ draft started above the configuration revisions only; the integration suite's version test showed that lands at the
+ tombstone's own version, which Desktop ignores. Reviewers: check nothing else persists an agent's version across its
+ removal.
+- An agent added again while the sweep deletes its tombstone: the add must not reset its version or be lost. Pinned by the
+ re-add test in Task 2 and the guarded delete in Task 3 (the same due match on the delete).
+- A tombstone named by a conversation's Lead or assignee but not in `agentIds`: kept. Pinned in Task 3.
+- A Swarm with no live agents or only tombstones: the read returns none and still uses the index. Pinned in Task 1.
+- A tombstone kept for a reference must not be read every hour forever: its next check is a day later. Pinned in Task 3.
+- Members' and machines' tombstones keep today's compaction. Pinned by the updated sweep plans test in Task 3.
+
+## Design
+
+- growth: agent tombstones go 7 days after removal (`purgeAt`); one named by an open conversation or a live start is
+ compacted and checked again each day, so it goes once those end. Members and machines keep today's compacted tombstones.
+- concurrency: no new lock. The delete repeats the due match (`deleted: true, purgeAt < now`), so a tombstone revived
+ since the read stays; a revival that read the tombstone before the delete hits `PartConflict` and runs again on the
+ new state.
+- read cost: the live-agent read examines only live agents through `[tabId, deleted]` (before: 1,070 examined for 40
+ returned in production). The sweep reads only due tombstones through the purge index, then for each Swarm with due
+ ones its open conversations naming them (`dormancy` index) and its starts naming them (`[tabId, agentId]`).
+- scale: at 10x agents per Swarm the read stays at its live count; the first warning is the read's examined/returned
+ ratio in the slow log, and the sweep's `agentTombstones.kept` count in the worker log.
+- compatibility: a re-added agent after a purge arrives above every version a client saw of it (the Swarm's agent floor),
+ so the CLI and a Desktop that never reloaded both take it. A cursor older than 7 days reloads, as for conversations.
+- migration + rollback: the release builds one index and adds an optional head column; a rollback leaves both (harmless)
+ and old code compacts the rest. Deleted tombstones do not come back, and old code ignores the floor: an agent re-added
+ under rolled-back code after its tombstone was purged starts at the Swarm's first version, which a long-open Desktop
+ ignores until it reloads. Roll forward instead where possible.
+- audience: N/A because no read or endpoint changes who sees what; the sweep runs in the singleton worker.
+- identity: N/A because no login is used; the sweep acts as the worker.
+- failure: the sweep logs its counts and any failure (`[swarm-sweeps]`); the startup step logs how many it queued.
+- platforms: backend only.
+
+---
+
+### Task 1: The live-agent index
+
+**Files:**
+- Modify: `backend/prisma/schema.prisma` (model `SwarmAgent`)
+- Create: `backend/integration/swarmAgentTombstones.test.ts`
+- Modify: `backend/vitest.super-tabs.config.ts` (add the file)
+
+**Interfaces:**
+- Produces: index `@@index([tabId, deleted])` on `SwarmAgent`, Mongo key `{ tabId: 1, deleted: 1 }`.
+
+- [ ] **Step 1: Write the failing test** `the live-agent read uses the [tabId, deleted] index`: a Swarm made by
+ `SuperTabStore.create`, 40 live agents and 1,000 removed ones in it, 200 live in another Swarm. Profile
+ `loadDeliveryParts(db, tabId, [], [])`; the `SwarmAgent` read's `planSummary` matches `IXSCAN { tabId: 1, deleted: 1 }`,
+ `docsExamined` is 40, and the returned agents' keys are the 40 live ones. A second case: a Swarm of tombstones only
+ returns none, through the same index.
+- [ ] **Step 2: Run it and watch it fail:** `npx vitest run --config vitest.super-tabs.config.ts integration/swarmAgentTombstones.test.ts`;
+ expected: another index, ~1,040 examined.
+- [ ] **Step 3: Add `@@index([tabId, deleted])` to `SwarmAgent`**, with a `///` line naming the reads it serves.
+- [ ] **Step 4: Run it and watch it pass.**
+- [ ] **Step 5: Commit** the test first, then the schema.
+
+### Task 2: A re-added agent starts above its Swarm's agent floor
+
+**Files:**
+- Modify: `backend/prisma/schema.prisma` (`SwarmHead.agentFloor Int?`)
+- Modify: `backend/src/superTabs/parts/write.ts` (`guardedWrite`, insert with no prior row)
+- Modify: `backend/integration/superTabs.test.ts` (the "never lets ... come back at a lower version" test: the tombstone
+ goes, and the agent comes back above it)
+- Test: `backend/integration/swarmAgentTombstones.test.ts`
+
+**Interfaces:**
+- Produces: an agent inserted with no row starts at `max(write.first ?? 1, SwarmHead.agentFloor + 1)`; Task 3 raises the
+ floor with `$max` before it deletes.
+
+- [ ] **Step 1: Failing test** `starts above every version its Swarm's purged agents reached`: the head's `agentFloor` is
+ 900, no `SwarmAgent` row; `guardedWrite` an insert with `first: 1`; the stored version is 901. In a Swarm that purged
+ none it starts at `first`.
+- [ ] **Step 2: Watch it fail** (version 1).
+- [ ] **Step 3: Implement**: for `kind === 'agent'`, read the head's `agentFloor` by id.
+- [ ] **Step 4: Watch it pass.** **Step 5: Commit** test, then code.
+
+### Task 3: The hourly sweep purges agent tombstones
+
+**Files:**
+- Create: `backend/src/superTabs/agentTombstones.ts`
+- Modify: `backend/src/superTabs/sweeps.ts` (`compactTombstones` leaves agents; `sweepSwarms` adds `agentTombstones`)
+- Modify: `backend/integration/swarmSweepPlans.test.ts` (agents are no longer compacted)
+- Test: `backend/integration/swarmAgentTombstones.test.ts`
+
+**Interfaces:**
+- Produces: `purgeAgentTombstones(db: PrismaClient, now: number): Promise<{ purged: number; kept: number }>` and
+ `AGENT_RECHECK_MS = 86_400_000`; `sweepSwarms(...).agentTombstones`.
+
+- [ ] **Step 1: Failing tests:**
+ - `purges only agent tombstones past their purge time`: due unnamed tombstones are gone; a not-yet-due one keeps its data
+ and purge time; live agents are untouched; another Swarm's due one goes too.
+ - `keeps a tombstone an open conversation or a live start names`: named in `agentIds`, as `leadId`, as the assignee, and
+ by a live start: kept with `data: {}` and `purgeAt = now + AGENT_RECHECK_MS`; named only by a dormant or removed
+ conversation, or a removed start: purged. A second sweep at the same time reads none of the kept ones.
+ - `reads due tombstones by the purge index`: the profiled `SwarmAgent` read is `IXSCAN { purgeAt: 1 }` and examines only
+ due rows; the conversation read names the `dormancy` index.
+ - `swarmSweepPlans`: `tombstonesCompacted` counts members and machines only (4) and `agentTombstones.purged` is 2.
+ - `raises each Swarm's agent floor to the highest version it purged`: a purged tombstone at version 90 sets the floor
+ to 90; a kept one at 500 does not; a Swarm that purged none has no floor.
+- [ ] **Step 2: Watch them fail.**
+- [ ] **Step 3: Implement** in batches of 500 by the purge index (`readBy(db, 'SwarmAgent', 'purge', ...)`), grouped by
+ Swarm; named keys from `groupsBy(db, 'dormancy', [{ $match: { tabId, deleted: false, dormant: false, $or: [agentIds,
+ data.leadId, data.assignment.agentId in keys] } }])` and live starts by `readBy(db, 'SwarmStart', 'agents', ...)` on
+ `{ tabId, agentId: { $in }, deleted: false }` (a new named index: unnamed, Mongo planned it on `[deleted, finishedAt]`). Delete the rest with `delete` repeating the due match; compact the named ones with `update`, same match.
+- [ ] **Step 4: Watch them pass.** **Step 5: Commit** tests, then code.
+
+### Task 4: Tombstones compacted before this change get a purge time
+
+**Files:**
+- Modify: `backend/src/superTabs/agentTombstones.ts` (`requeueCompactedAgents`)
+- Modify: `backend/src/worker.ts` (run once at startup, logged; "remove in the release after the one that runs it")
+- Test: `backend/integration/swarmAgentTombstones.test.ts`
+
+**Interfaces:**
+- Produces: `requeueCompactedAgents(db: PrismaClient, now: number): Promise<number>`.
+
+- [ ] **Step 1: Failing test** `gives tombstones compacted before the purge a purge time`: compacted agent tombstones
+ (`deleted: true, purgeAt: null`) get `purgeAt = now`; live agents and member tombstones are untouched; the next sweep
+ purges the unnamed ones. The update reads each agent at most once (no index leads with `deleted`; about 1,300 agents in
+ prod), once per worker start for one release.
+- [ ] **Step 2: Watch it fail.** **Step 3: Implement** one `update` `{ deleted: true, purgeAt: null }`. **Step 4: Watch it pass.** **Step 5: Commit.**
+
+### Measurement
+
+Before (now, v1.3.86) and after (the release with this change, once Ken creates the index), the same window length: the
+slow log's `SwarmAgent` operations (count, seconds, examined per returned) and the collection's count of deleted rows,
+through `scripts/atlas-snapshot.ts` and the read-only login. Results go in a PR comment.
diff --git a/docs/plans/2026-11-03-dial-thread-face-plan.md b/docs/plans/2026-11-03-dial-thread-face-plan.md
new file mode 100644
index 000000000..cb9b8c35f
--- /dev/null
+++ b/docs/plans/2026-11-03-dial-thread-face-plan.md
@@ -0,0 +1,107 @@
+# Round Dial Thread Face Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** The round dial goes into the thread its own words started (or the app opened), shows it unmistakably, and leaves it with a horizontal swipe.
+
+**Architecture:** The daemon's cards service keeps one face thread per Swarm (the app's `threadRoot` from #2718, or the dial's own after a voice post), sends it on the face chat and on recaps to dials with the `swarmThread` capability, and asks the window to open or close the thread. The round dial firmware draws the thread face and sends `supertab.thread.leave`. Desktop opens or closes the thread on `dial_super_tab`.
+
+**Tech Stack:** TypeScript (cli daemon, vitest), Dart/Flutter (Desktop), C + ESP-IDF (round dial firmware, host tests in `devices/harness-device/firmware/test`).
+
+**Spec:** `docs/specs/2026-11-03-dial-thread-face.md`
+
+## Global Constraints
+
+- Branch `feat/dial-thread-face`, based on PR #2718's head (5c4a5aeb4); rebase on `main` once #2718 merges. Worktree `.claude/worktrees/dialthread`.
+- Capability name `swarmThread`; inbound frame `supertab.thread.leave {tab, lead}`; lead fields `thread` (root id), `threadTitle`, `threadReplies`; recap field `thread`.
+- Thread title: first line, at most 80 bytes (daemon); dial wraps on words to 2 lines of ~22 characters, "…" when longer.
+- Colours: thread teal `#2dd4bf`; Buddy lilac unchanged. Copy: "↳ Thread", "↳ Thread · Buddy", "PM · N replies" ("Buddy · …" on the Buddy side; "1 reply"), "Waiting for the PM…", "Waiting for your Buddy…", "‹ chat".
+- Thread face: no pet, no bottom arc text; bell pill kept.
+- No backend change. Harness Pro firmware untouched. Never force-flash; any device check uses the repo's flash procedure and dev version `0.0.99`, only on Diego's go.
+
+## Review Focus
+
+1. The app closes its thread while the dial is in the dial's own thread of the same root: the dial leaves too (the focus moved) — Task 1 test "a focus move clears the dial's thread".
+2. Words said while already in a thread reply there and do not start a nested thread — Task 1 test "words said in a thread reply in it and start nothing".
+3. A recap for the main chat arriving after the face entered a thread (or the reverse) is refused by the dial — Task 4 test "a recap for another thread than the face's is refused".
+4. One project with a thread: a horizontal swipe leaves the thread and does not reopen or reselect the project on the desktop — Task 4 test "a swipe on a thread face leaves it and selects nothing".
+5. A dial without `swarmThread` gets no thread fields and its leave frames are ignored — Task 2 test "an older dial is sent no thread and its leave is ignored".
+
+---
+
+### Task 1: Face thread in the cards service (daemon)
+
+**Files:**
+- Modify: `cli/src/superTabs/cards.ts` (`want`, `side`, `target`, `recap`, `say`, the face chat built in `leadsOf`/`faceOf` path, new `threadLeave`)
+- Modify: `cli/src/core/api.ts` (`SwarmChat`, `LeadRecap`, `SaidOnCard`)
+- Test: `cli/src/superTabs/cards.spec.ts`
+
+**Interfaces:**
+- Produces: `SwarmChat.thread?: { root: string; title: string; replies?: number }`; `LeadRecap.thread?: string`; `SaidOnCard` success becomes `{ said: true; thread?: { tabId: string; projectId: string; root: string } }` (set only when the post started the dial's thread); `SuperTabCards.threadLeave(tabId: string, leadId: string): { tabId: string; projectId: string } | null` (the project whose thread the window should close, or null when there was none).
+
+- [ ] **Step 1: Write the failing tests** in `cards.spec.ts`, `describe('the face thread')`:
+ - "words said at top level start the dial's thread": `say()` on a face with no thread; the backend answers `{ result: { messageId: 'm9' } }` → resolves `{ said: true, thread: { tabId, projectId, root: 'm9' } }`; the next emitted card's face chat has `thread: { root: 'm9', title: <the words, first line> }`; the next `recap()` reads the thread and answers with `thread: 'm9'`.
+ - "words said in a thread reply in it and start nothing": face already in thread `m9` → the post has `replyTo: 'm9'` and the answer has no `thread`.
+ - "the app's thread is the face's": focus `{ conversationId: lead chat, threadRoot: 'r1' }` → face chat `thread.root === 'r1'`, title from the root's text in the thread read.
+ - "a focus move clears the dial's thread": dial's thread `m9`, then `want(..., focus without threadRoot)` from the desktop → no `thread` on the face.
+ - "threadLeave clears the dial's thread and names the project": returns `{ tabId, projectId }`; the face has no `thread`; a second call returns null.
+ - "a thread lives only while its conversation is on the face": side swiped to buddy → no PM thread on the Buddy face.
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/superTabs/cards.spec.ts -t "the face thread"` — Expected: FAIL.
+- [ ] **Step 3: Implement**: a `threads = new Map<string, { conversationId: string; root: string; title: string }>()` beside `sides`, cleared where `sides` is (device gone, account change, lost Swarm) and on a desktop refocus (`want` with `!fromDevice`); `target()` takes the focus's `threadRoot` when it names the face's conversation, else the dial's thread when its `conversationId` is the face's; the face chat gets `thread` (title cut to 80 bytes on a character, first line); `recap()` sets `LeadRecap.thread`; `say()` starts the thread when the post had no `replyTo` and the answer's `result.messageId` is an id; `threadLeave` deletes and re-emits. Replies count from the thread read's summary when present.
+- [ ] **Step 4: Run** the same command, then `npx vitest run src/superTabs/cards.spec.ts` — Expected: PASS.
+- [ ] **Step 5: Commit** `feat(cli): the dial's face keeps the thread its words started`.
+
+### Task 2: Cable, host and service pass-through (daemon)
+
+**Files:**
+- Modify: `cli/src/cable/cableSession.ts` (caps: `swarmThread`; `chatLead` adds `thread`, `threadTitle`, `threadReplies` for a `swarmThread` dial; `fitFrame` trims `threadTitle` like `chatName`; recap frame adds `thread`; `case 'supertab.thread.leave'`; after a voice post that returns `thread`, open it in the window)
+- Modify: `cli/src/cable/cableHost.ts`, `cli/src/services/devices.ts`, `cli/src/superTabs/inCore/cards.ts`, `cli/src/superTabs/service.ts` (new `cardThreadLeave` action and its answer; `superTabSelected(tab, projectId, chat?, threadRoot?: string | null)`; `swarmSay` passes `thread` through)
+- Test: `cli/src/cable/cableSession.spec.ts`, `cli/src/services/devices.spec.ts`, `cli/src/superTabs/inCore/cards.spec.ts`, `cli/src/superTabs/service.spec.ts`
+
+**Interfaces:**
+- Consumes: Task 1's `SwarmChat.thread`, `LeadRecap.thread`, `SaidOnCard.thread`, `threadLeave`.
+- Produces: window frame `dial_super_tab` payload `{ superTabId, projectId, chat?, threadRoot?: string | null }`.
+
+- [ ] **Step 1: Write the failing tests**: cableSession "a swarmThread dial is sent the face's thread and its recap's thread"; "an older dial is sent no thread and its leave is ignored"; "supertab.thread.leave asks the service and closes the window's thread" (`superTabSelected(tab, projectId, chat, null)`); "a voice post that starts a thread opens it in the window" (`superTabSelected(..., 'm9')`); service/inCore/devices: "cardThreadLeave reaches the cards and answers the project".
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/cable/cableSession.spec.ts src/services/devices.spec.ts src/superTabs/inCore/cards.spec.ts src/superTabs/service.spec.ts` — Expected: FAIL.
+- [ ] **Step 3: Implement** the pass-through in the files above, in each file's existing style for `cardSide` / `supertab.side`.
+- [ ] **Step 4: Run** the same command, then `npx tsc --noEmit -p .` and `npm run test:core` — Expected: PASS (the known `src/services/devicesProcess.ts` branch gap on main aside).
+- [ ] **Step 5: Commit** `feat(cli): the dial is told its thread and may leave it`.
+
+### Task 3: Desktop opens and closes the dial's thread
+
+**Files:**
+- Modify: `desktop/lib/state/app_state.dart` (`case 'dial_super_tab'`, `_openSuperTabProject`)
+- Test: `desktop/test/super_tab_dial_test.dart`
+
+**Interfaces:**
+- Consumes: `dial_super_tab.threadRoot` (Task 2).
+
+- [ ] **Step 1: Write the failing tests**: "a dial pick with threadRoot opens that thread beside the chat" (controller `openedThread.root == 'm9'` after the frame); "threadRoot null closes the open thread"; "no threadRoot keeps today's pick".
+- [ ] **Step 2: Run** `cd desktop && flutter test test/super_tab_dial_test.dart` — Expected: FAIL.
+- [ ] **Step 3: Implement**: after the project's chat is open, `threadRoot` string → `controller.openThread(root)`; `null` → close the thread pane through the controller's existing close (find the method the thread pane's close button calls).
+- [ ] **Step 4: Run** the same command and `flutter analyze lib/state/app_state.dart` — Expected: PASS, no new issues.
+- [ ] **Step 5: Commit** `feat(desktop): the dial opens and closes its thread in the app`.
+
+### Task 4: Round dial firmware: thread face and swipe out
+
+**Files:**
+- Modify: `devices/harness-device/firmware/main/ui/habitat/supertab.h`, `supertab.c` (`ht_lead_t`: `thread_root[ID_MAX]`, `thread_title[HT_SUPERTAB_NAME * 2]`, `thread_replies` (-1 unknown); `ht_lead_in_t` the same as `const char *`/`long`; recap `thread[ID_MAX]`; `ht_supertabs_recap_put(..., const char *thread, ...)` compares it; `ht_supertabs_recap_open` keeps a held recap only for the same chat and thread)
+- Modify: `devices/harness-device/firmware/main/cable_client.c`, `cable_client.h` (announce `swarmThread`; parse `thread`, `threadTitle`, `threadReplies` on leads and `thread` on `supertab.recap`; `cable_client_supertab_thread_leave(tab, lead)`)
+- Modify: `devices/harness-device/firmware/main/ui/habitat/ui_habitat.c` (thread face drawing in the Swarm face path ~1440-1530; horizontal swipe ~3796-3802; the "face chat moved" re-ask ~5300 also on a thread change)
+- Test: `devices/harness-device/firmware/test/test_supertab.c`, `devices/harness-device/firmware/test/test_cable_supertab.py`
+
+**Interfaces:**
+- Consumes: Task 2's frames.
+
+- [ ] **Step 1: Write the failing tests**: `test_supertab.c` "a lead keeps its thread root, title and replies"; "a recap for another thread than the face's is refused"; "leaving the thread re-opens the main chat's recap"; `test_cable_supertab.py` "the hello names swarmThread", "lead thread fields parse", "recap thread parses", "the leave frame is {t: supertab.thread.leave, tab, lead}".
+- [ ] **Step 2: Run** `cd devices/harness-device/firmware && test/run.sh` — Expected: FAIL on the new cases.
+- [ ] **Step 3: Implement** the model and cable changes; then the face: when the face Lead's `thread_root[0]`, draw the teal ring, "↳ Thread"/"↳ Thread · Buddy", the title (2 lines, ~22 chars, "…"), no pet, no bottom arc text, the recap card with a teal spine and the meta line ("PM · N replies"/"1 reply", omitted when unknown), "Waiting for the PM…"/"Waiting for your Buddy…" when the recap is empty, "‹ chat" at the left edge; bell pill as today. Horizontal swipe on a thread face: send the leave, clear the face's thread locally, `ht_supertabs_recap_open` and `SUPERTAB_RECAP_GET`, select nothing. Test "a swipe on a thread face leaves it and selects nothing" in `test_supertab.c` if the swipe decision can be reached there, else in the cable test by the frames sent.
+- [ ] **Step 4: Run** `test/run.sh` — Expected: PASS. Build: `idf.py build` with IDF 5.5.4 and the xtensa toolchain on PATH (see the round release toolchain notes) — Expected: success.
+- [ ] **Step 5: Commit** `feat(round): the dial shows the thread it is in and swipes out of it`.
+
+### Task 5: Pull request and device check
+
+- [ ] Push `feat/dial-thread-face`; open a PR to `main` that depends on #2718 (rebase once it merges), with the spec, the checks run per component, and the mockup path.
+- [ ] Only on Diego's go: dev build `-DPROJECT_VER=0.0.99`, flash his round dial with the repo procedure, and check: voice a task → thread face; PM reply shows; swipe sideways → main chat; app opens a thread → dial follows. Record the result in the PR.
+- [ ] Send the PR to Diego's Buddy for the PM to merge with `make merge-pr` once `ci/required` is green.
diff --git a/docs/plans/2026-11-03-plain-chat-shots/desktop-chat-dark.png b/docs/plans/2026-11-03-plain-chat-shots/desktop-chat-dark.png
new file mode 100644
index 000000000..7e8c7138f
Binary files /dev/null and b/docs/plans/2026-11-03-plain-chat-shots/desktop-chat-dark.png differ
diff --git a/docs/plans/2026-11-03-plain-chat-shots/desktop-chat-light.png b/docs/plans/2026-11-03-plain-chat-shots/desktop-chat-light.png
new file mode 100644
index 000000000..cd8707be4
Binary files /dev/null and b/docs/plans/2026-11-03-plain-chat-shots/desktop-chat-light.png differ
diff --git a/docs/plans/2026-11-03-plain-chat-shots/desktop-thread-dark.png b/docs/plans/2026-11-03-plain-chat-shots/desktop-thread-dark.png
new file mode 100644
index 000000000..5be4d4cde
Binary files /dev/null and b/docs/plans/2026-11-03-plain-chat-shots/desktop-thread-dark.png differ
diff --git a/docs/plans/2026-11-03-plain-chat-shots/desktop-thread-light.png b/docs/plans/2026-11-03-plain-chat-shots/desktop-thread-light.png
new file mode 100644
index 000000000..f8da95eb4
Binary files /dev/null and b/docs/plans/2026-11-03-plain-chat-shots/desktop-thread-light.png differ
diff --git a/docs/plans/2026-11-03-plain-chat-shots/phone-chat-dark.png b/docs/plans/2026-11-03-plain-chat-shots/phone-chat-dark.png
new file mode 100644
index 000000000..b22f03ae2
Binary files /dev/null and b/docs/plans/2026-11-03-plain-chat-shots/phone-chat-dark.png differ
diff --git a/docs/plans/2026-11-03-plain-chat-shots/phone-chat-light.png b/docs/plans/2026-11-03-plain-chat-shots/phone-chat-light.png
new file mode 100644
index 000000000..0d44fea12
Binary files /dev/null and b/docs/plans/2026-11-03-plain-chat-shots/phone-chat-light.png differ
diff --git a/docs/plans/2026-11-03-plain-chat-shots/phone-thread-dark.png b/docs/plans/2026-11-03-plain-chat-shots/phone-thread-dark.png
new file mode 100644
index 000000000..b420872dd
Binary files /dev/null and b/docs/plans/2026-11-03-plain-chat-shots/phone-thread-dark.png differ
diff --git a/docs/plans/2026-11-03-plain-chat-shots/phone-thread-light.png b/docs/plans/2026-11-03-plain-chat-shots/phone-thread-light.png
new file mode 100644
index 000000000..5fcb8fa67
Binary files /dev/null and b/docs/plans/2026-11-03-plain-chat-shots/phone-thread-light.png differ
diff --git a/docs/plans/2026-11-03-plain-chat-work-plan.md b/docs/plans/2026-11-03-plain-chat-work-plan.md
new file mode 100644
index 000000000..9946f6810
--- /dev/null
+++ b/docs/plans/2026-11-03-plain-chat-work-plan.md
@@ -0,0 +1,125 @@
+# Plain chat proposals and tasks Implementation Plan
+
+> **For agentic workers:** Follow the project Engineer workflow: plan first in a draft PR; implement task by task with a committed failing test before its passing code; one independent Review step and user Test step at the end. Independent client tasks may run in parallel.
+
+**Goal:** Show proposals and tasks as one ordinary requester-authored “Let's build: <name>” chat message, with details and updates in its ordinary thread on Desktop and phone.
+
+**Architecture:** Keep existing messages, replies, thread summaries, and task conversations. Post proposal roots as their person and proposal details as their Buddy. Link a task to a single project-chat root, reuse its proposal root where supplied, and publish updates as replies without state edits. Both clients use their ordinary message/thread widgets, including for legacy stored shapes.
+
+**Tech Stack:** TypeScript, Zod, Prisma/MongoDB, Vitest; Flutter/Dart Desktop and phone.
+
+**Spec:** Task #2294 in Super Tab conversation 1e4d3f730a915adc0c541e14 (Dee, 2026-11-03); requirements preserved below.
+
+## Global Constraints
+
+- Root copy is exactly `Let's build: <name>`, with the requester's ordinary avatar/name. No special rows, state word, status line or mark.
+- Proposal title is optional, trimmed, at most 80 characters. Without it use the goal's first sentence after removing a leading `Requested by X.`.
+- Full proposal (Goal, Scope, Priority, attachments) is the first thread reply from the Buddy; PM receives the full text. Full task brief is a thread reply; proposal-to-task conversion reuses its root.
+- Later progress and PR/merge news are ordinary replies, at most one per change. Ordinary reactions, Activity, unread counts, mentions, and Threads continue working.
+- Stored old messages remain readable; phone model/parts retain Desktop parity.
+- PR body begins `Requested by [email protected] through Harness.` Include red/green evidence and Desktop/phone screenshots.
+- Never sign out the real CLI; use memory/fake sign-in for Desktop tests. No Swarm code in cli/src/core, no production writes, releases, firmware publication, or manifest edits. Stop only owned process IDs. Temporary folders use mktemp -d.
+
+## Design
+
+- Growth: use existing message retention/deletion; no new log/table. One root plus details and actual updates only; repeated unchanged status emits none.
+- Concurrency: existing per-Swarm transactional command lock and operation-id idempotency commit roots/details/link state atomically.
+- Read cost: normal incremental message/thread pages and summaries; no whole-history scans. Task links live in existing task card metadata.
+- Scale: 10x tasks adds bounded messages per transition; first warning is command latency/message write volume. Avoid per-task database lookups on unrelated commands.
+- Compatibility: optional title only; retain existing task-line/proposal source interpretation and old stored roots. New roots contain useful plain text for older clients. Keep task CLI conversations functional.
+- Migration + rollback: no destructive migration or schema change; old and new roots coexist. Rollback reads useful root/reply text, with old special styling until updated again.
+- Audience: existing server project access, proposal validation, attachment validation, and thread routing apply; no cross-project message reuse.
+- Identity: server derives proposer from Buddy owner and requester from validated Swarm membership, never machine owner login. Keep membership generation.
+- Failure: transaction rollback leaves neither half-posted proposal nor task link. Existing command errors and delivery failures remain visible.
+- Platforms: backend, Desktop, phone, and CLI proposal instructions. No platform-specific APIs.
+
+## Review Focus
+
+1. Empty/overlong titles, sentence-less goals and a leading requester prefix: fallback stays useful and bounded (Task 1).
+2. Proposal conversion, duplicate retries, repeated status and repeated merge: one root, one update per actual change (Tasks 1–2).
+3. Private projects, departed requesters and a removed Buddy: author attribution and reuse never bypass read access (Tasks 1–2).
+4. Old task-line and Buddy proposal records: full text remains available in ordinary message/thread widgets (Tasks 3–4).
+5. Thread summaries, unread marks, mentions, reactions and attachments: details stay out of main stream and replies stay usable (Tasks 1–4).
+
+### Task 1: Ordinary proposal roots and details
+
+**Files:** Modify backend/src/superTabs/buddies.ts, commands.ts; test buddies.test.ts and integration/superTabBuddies.test.ts. Update cli/src/lib/swarmSkills.ts and cli/src/superTabs/service.ts proposal instructions.
+
+**Interfaces:** Consumes existing buddy.propose and validated proposalAsk/attachments. Produces optional `title?: string` on buddy.propose, one person-authored root with existing buddy-proposal source plus Buddy attribution, one Buddy-authored reply (`replyTo` and `thread` equal root id) with full proposal and attachments. Existing command result/message ids remain stable.
+
+- [x] Write/commit failing tests: explicit title produces `Let's build: Offline drafts` from the Buddy owner; first reply has full Goal/Scope/Priority and attachments and PM recipient. Test fallback `Requested by Dee. Save drafts. Keep them.` gives `Let's build: Save drafts.`; title boundary; owner generation; duplicate asks; project access.
+- [x] Run `cd backend && npm test -- src/superTabs/buddies.test.ts src/superTabs/buddyNews.test.ts --maxWorkers=2`; record expected missing-root/details failures.
+- [x] Add title schema and root-name helper in buddies.ts; write two ordinary messages in buddy.propose preserving validated owner/attachment/PM delivery. Update Buddy instructions/help to supply a short title.
+- [x] Run affected tests and proposal integration tests; commit passing code and push.
+
+### Task 2: One task root and ordinary progress thread
+
+**Files:** Modify backend/src/superTabs/taskLine.ts, commands.ts, store.ts as needed; test taskLine.test.ts, buddyNews.test.ts, integration/superTabTaskLines.test.ts and related thread tests.
+
+**Interfaces:** Consumes existing Conversation/cards.line, proposalMessageId and proposal context; produces one linked ordinary project root at conversation.create, first brief reply, and append-only transition replies. Existing task conversation ids and CLI work commands stay valid. Reused proposal source carries Buddy id for credit. Existing source kind remains readable; no client needs new rendering fields.
+
+- [x] Write/commit failing tests: opening a task immediately posts requester-authored `Let's build: Offline drafts` plus brief reply; no requester uses PM. Assignment/status/PR/merge produce replies, no root edit; unchanged/retried status and repeated merge produce none. Proposal conversion reuses root. Exclude steps/project/Buddy chats; private project isolation; old lines remain readable. Verify task posts appear in linked thread without repeated delivery.
+- [x] Run `cd backend && npm test -- src/superTabs/taskLine.test.ts src/superTabs/buddyNews.test.ts --maxWorkers=2`; record red.
+- [x] Replace root-state editing with transactional root/link/reply handling. Preserve legacy metadata and assignment tracking, validate proposal reuse and stable operation IDs. Use existing ordinary thread summary/read/delivery paths.
+- [x] Run affected tests and `npm run test:super-tabs -- --maxWorkers=2` (full integration suite); commit passing code and push.
+
+### Task 3: Desktop ordinary message/thread rendering
+
+**Files:** Modify desktop/lib/super_tabs/view.dart, task_line.dart and related ordinary message filtering only as needed; tests desktop/test/super_tab_task_line_test.dart and a screenshot fixture.
+
+**Interfaces:** Consumes existing SuperTabMessage text, author, thread, replyTo and source. Produces ordinary SuperTabMessageRow and normal thread opener for proposal/task roots, including legacy source kinds. No backend or phone file changes.
+
+- [x] Write/commit failing widget tests proving requester avatar/name, full root text, ordinary Reply/reactions/thread affordances, and root-to-normal-thread navigation. Include legacy proposal/task-line fixtures and narrow viewport.
+- [x] Run bounded affected widget tests and record red before implementation.
+- [x] Remove special proposal/task rendering and task-panel navigation from the chat row path; use ordinary message/thread behavior. Preserve unrelated task management surfaces.
+- [x] Run affected tests and capture Desktop screenshot with fake sign-in/memory state. Commit passing code and push.
+
+### Task 4: Phone ordinary message/thread rendering
+
+**Files:** Modify mobile/lib/swarm/swarm_message_row.dart, swarm_conversation_page.dart, swarm_task_line.dart as needed; tests mobile/test/swarm/swarm_task_line_test.dart and screenshot fixture.
+
+**Interfaces:** Consumes existing phone SuperTabMessage ordinary author/text/thread fields; produces ordinary SwarmMessageRow with standard avatar, reactions, reply and thread opening. No backend or Desktop file changes; no new model fields required.
+
+- [x] Write/commit failing widget tests for ordinary task/proposal roots and legacy messages, requester identity, reactions, reply/thread affordance, and narrow screen reading.
+- [x] Run affected Flutter tests and record red before implementation.
+- [x] Remove special task row routing/rendering, retaining unrelated task status screens and legacy text; use existing thread navigation.
+- [x] Run affected tests, `test/swarm/desktop_parity_test.dart`, and capture phone screenshot. Commit passing code and push.
+
+## Validation and handoff
+
+- Record implementation, validation, review/CI waiting, merge and publication durations separately from task start (2026-11-03 04:15 UTC). Engineer does not merge or release.
+- Inputs: complete backend source/schema/lockfiles with Node 22.23.2; Desktop and phone complete component trees, shared fixtures, Flutter 3.47.2 and pub locks; CLI source/lockfiles for proposal instruction change. Deterministic evidence reuse requires matching these inputs/toolchain and `--reuse` receipt.
+- Choose checks before running: backend typecheck and affected unit tests; full Super Tab integration suite; bounded Desktop/phone affected widget tests and phone parity; CLI affected swarmSkills/command tests. Automatic ready PR CI supplies full affected component Linux suites. Native user testing on Mac/simulator supplies screenshots and ordinary thread interaction evidence.
+- Start independent checks within machine capacity, maximum two local workers per check. Time-bound each scoped check to 180–300 seconds, integration suite to 900 seconds. Investigate new failures; record known unrelated failures explicitly without claiming a pass.
+- Post red/green PR evidence, make the stable head Ready, route/assign independent Review and Test steps, and request both directly. Complete acceptance checks only with actual evidence; read task before setting Done for PM batch merge.
+
+### Task 5: Dee's approved thread copy and chat-asked roots (resumed by Sorrel, 2026-11-03)
+
+Dee approved the exact thread lines on 2026-11-03 (task conversation, River's copy). Tasks 1–4 posted their own wording and
+copied every plain post of the task's conversation into the chat thread; this task replaces both.
+
+**Files:** Modify backend/src/superTabs/taskLine.ts, buddies.ts, commands.ts, store.ts (load the asked-in message as the
+proposal is loaded); tests taskLine.test.ts, buddies.test.ts, integration/superTabTaskLines.test.ts,
+integration/superTabBuddies.test.ts, integration/superTabSwarmBuddy.test.ts. Update cli/src/lib/swarmSkills.ts and
+cli/src/superTabs/service.ts help text.
+
+**Interfaces:** conversation.create takes optional `requestMessageId`: a person's own top-level message in the project's chat
+that asked for the work. It becomes the task's root (no new message, no brief reply) and its author the requester when none
+is named. Every thread reply is authored by the project's coordinator, wakes nobody, and is one of:
+
+- assigned: `On it: <agent> is building it.`
+- needs a person (with ask): `@<user> Your call: <question>. Default: <recommended option>.`
+- review: `Ready for review: PR #<n>` (`Ready for review.` without a pull request)
+- review → working: `Changes needed: <first line of the result>. <agent> is fixing it.`
+- blocked: `Stuck: <first line of the result>. Next: <PM> is looking at it.`; lost: `Stuck: <agent> stopped. Next: another engineer takes it over.`
+- merged: `Merged: PR #<n>. Ships in the next release.`
+- cancelled or stopped: `Not building this: <reason>.`
+- done without a pull request: `Done.`; done with one says nothing (the merge reply follows).
+
+Agents' posts in the task's own conversation stay there. A proposal's first reply is `Goal: …\nScope: …\nPriority: …` from the
+Buddy, and a task from it adds no brief reply. Queued, Released and Duplicate have no server event yet and are not posted.
+
+- [x] Write/commit failing tests for each line, coordinator authorship, no mirrored chatter, no brief reply under a proposal,
+ the chat-asked root (and refusals: another chat, a reply, a server row, an agent's message), and the proposal details text.
+- [x] Run `cd backend && npm test -- src/superTabs/taskLine.test.ts src/superTabs/buddies.test.ts`; record red.
+- [x] Implement; run affected tests, typecheck and `npm run test:super-tabs -- --maxWorkers=2`; commit and push.
diff --git a/docs/plans/2026-11-03-sidebar-task-groups-plan.md b/docs/plans/2026-11-03-sidebar-task-groups-plan.md
new file mode 100644
index 000000000..23b45daed
--- /dev/null
+++ b/docs/plans/2026-11-03-sidebar-task-groups-plan.md
@@ -0,0 +1,130 @@
+# Swarm sidebar: a project's tasks in foldable groups — Implementation Plan
+
+> **For agentic workers:** this plan is carried out by the task's Engineer, task by task, test first, as the project's
+> instructions (Engineer role) say. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Under each expanded project, the open tasks are listed in four foldable groups, in this order: Needs you,
+Working, Waiting on others, The rest. Each heading has a count, The rest starts folded, and each group's fold is
+remembered per project the way Closed is.
+
+**Architecture:** A pure function sorts each open task into its group, using what the row already shows: the reader's
+tags, the task's liveness (`waiting` on whom, `quiet`, `orphaned`), its assignment status, and the view's
+`needsHuman`. `ProjectSidebar._workgroups` draws a heading row per non-empty group, then that group's rows newest first.
+This replaces the "8 newest, then … N more" list (`_NewestConversations`). The controller keeps each fold in memory,
+per project, like `closedOpenProjects`. `superTabSidebarOrder` lists tasks in the same group order, so
+Option+Shift+Down/Up walks the sidebar top to bottom. The web app draws the same `ProjectSidebar`, so one change covers
+Desktop and web.
+
+**Tech Stack:** Flutter/Dart (desktop/, also built for the web), flutter_test.
+
+**Spec:** Task #2309 brief (Super Tab conversation 315b5716849b495258977518), requested by [email protected];
+mockup in Huy's proposal thread (`▾ Needs you 1` headings above the existing two-line rows).
+
+## Global Constraints
+
+- PR body first line: "Requested by [email protected] through Harness."
+- Out of scope: the project row, Buddy rows, Activity. Closed stays as it is.
+- Harness design language. Headings are drawn like the Closed row: muted text, a chevron, 36 px minimum height. They
+ are not `SuperTabSectionHeading`s; those are the sidebar's sections.
+- Keyboard: each heading is a focusable button (Tab reaches it), and Enter or Space toggles its fold.
+- Desktop tests use a memory store and a fake sign-in. Temp files go only in mktemp -d folders.
+
+## Groups (the rule, in order; the first that applies wins)
+
+1. **Needs you**: the reader is tagged in it (`attention.mentionsIn > 0`); or its liveness is `waiting`/`person` on the
+ reader, or on no one named; or, with no liveness, `needsHuman > 0` (a question in its agent's terminal).
+2. **Waiting on others**: liveness `waiting` on another person, or on `review`, `revision`, `blocked` or `queued`;
+ or `quiet`/`orphaned` (stuck: waits on the PM).
+3. **Working**: liveness `waiting`/`starting`; or no liveness and assignment status `working` or `planned`.
+4. **The rest**: everything else (no work, finished but still open, unknown states).
+
+## Review Focus
+
+- The open conversation sits in a folded group: its row still shows under that heading, so the reader never loses it.
+- With the unread filter on, groups list only the rows the filter keeps, counts count those rows, and a group left
+ empty has no heading.
+- A project with no open tasks still reads "No workgroups yet", with no headings.
+- Folding a group in one project leaves the same group in another project as it was. Collapsing and expanding the
+ project keeps the fold.
+- A task changing state (Working to Waiting on others) moves under its new heading on the next state read, with no
+ stale fold.
+
+---
+
+### Task 1: Which group a task is in
+
+**Files:**
+- Create: `desktop/lib/super_tabs/task_groups.dart`
+- Test: `desktop/test/super_tab_task_groups_test.dart`
+
+**Interfaces:**
+- Produces: `enum SuperTabTaskGroup { needsYou, working, waitingOnOthers, rest }` with a `label` getter
+ (`'Needs you'`, `'Working'`, `'Waiting on others'`, `'The rest'`), declared in display order, and
+ `bool get foldedByDefault` (true only for `rest`).
+- Produces: `SuperTabTaskGroup superTabTaskGroupOf(SuperTabConversation group, {required String readerId, int mentions = 0, int needsHuman = 0})`.
+
+- [ ] **Step 1: Failing tests**, one per rule line above: tagged → needsYou; waiting/person on `readerId` → needsYou,
+ on no one → needsYou, on `'other'` → waitingOnOthers; review/revision/blocked/queued → waitingOnOthers;
+ quiet and orphaned → waitingOnOthers; starting → working; working/planned with no liveness → working;
+ `needsHuman: 1` with no liveness → needsYou; `needsHuman: 1` with a person wait on `'other'` → waitingOnOthers;
+ no assignment → rest; done → rest; a tag beats a wait on another person (needsYou).
+- [ ] **Step 2:** `flutter test test/super_tab_task_groups_test.dart`: fails (no such library).
+- [ ] **Step 3:** Implement `task_groups.dart`.
+- [ ] **Step 4:** Tests pass. Commit the tests first, then the code.
+
+### Task 2: The sidebar draws the groups
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/project_sidebar.dart` (`_workgroups`, remove `_NewestConversations` and `_moreRow`,
+ add `_taskGroupHeading`, `superTabOpenWorkgroups` unchanged)
+- Modify: `desktop/lib/super_tabs/controller.dart` (fold memory, beside `closedOpenProjects`)
+- Test: `desktop/test/super_tab_task_groups_test.dart`; update the tests that relied on "… N more" or on a
+ no-work task being listed while The rest starts folded.
+
+**Interfaces:**
+- Consumes: Task 1.
+- Produces: `bool SuperTabController.taskGroupFolded(String projectId, SuperTabTaskGroup group)` and
+ `void toggleTaskGroup(String projectId, SuperTabTaskGroup group)` (in memory, not saved, like `toggleClosed`).
+- Keys: heading `super-task-group-<projectId>-<group.name>`; rows keep `super-group-<id>`.
+
+- [ ] **Step 1: Failing widget tests** (1300×1600, `pmChatSwarm`-style fixture with one task per group, plus two in Working):
+ - Headings in order `Needs you`, `Working`, `Waiting on others`, `The rest`, each with its count (`1`, `2`, `1`, `1`).
+ Each task's row sits between its heading and the next one, and the two Working rows are newest first.
+ - The rest starts folded: its heading shows and its row doesn't. A tap shows it, and a second tap hides it.
+ - Folding Working in project A leaves project B's Working open. Collapsing and expanding A keeps Working folded.
+ - The open conversation in a folded The rest still shows under its heading.
+ - Unread filter on: only unread rows are listed; counts are of those rows; a group with none has no heading.
+ - Tab from the project row reaches the first heading, and Enter folds it.
+ - A phone-width (390 px) layout, as the web app draws it on a phone, shows the same headings.
+- [ ] **Step 2:** Run: fails (no headings).
+- [ ] **Step 3:** Implement. Group `superTabOpenWorkgroups(...).where(_keptByFilter)` by `superTabTaskGroupOf`, using
+ `controller.accountId`, `attention?.mentionsIn` and `needsHuman`. For each non-empty group, draw a heading (chevron
+ in the icon column, label, count; `Semantics(button, expanded)`), then its rows. A folded group shows only the open
+ conversation's row, if it is in that group.
+- [ ] **Step 4:** Run the new tests and the whole `test/super_tab_*` suite. Update the tests that assumed the old
+ list, each with its reason in the commit.
+- [ ] **Step 5:** Commit the tests, then the code.
+
+### Task 3: Option+Shift+Down/Up follows the groups
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/project_sidebar.dart` (`superTabSidebarOrder`)
+- Modify: `desktop/lib/super_tabs/view.dart` (`_jumpUnread` passes `needsHuman`)
+- Test: `desktop/test/super_tab_task_groups_test.dart`
+
+**Interfaces:**
+- Produces: `List<String> superTabSidebarOrder(SuperTabController controller, {int Function(SuperTabConversation)? needsHuman})`.
+ Each project's chat comes first, then its tasks in group order, each group newest first; tags are read with
+ `SuperTabAttention.of(controller)`.
+
+- [ ] **Step 1: Failing test:** with one task per group, the order is
+ `[lead, needsYou-task, working-task, waiting-task, rest-task]`, whatever their numbers.
+- [ ] **Step 2:** Fails (newest-first order).
+- [ ] **Step 3:** Implement.
+- [ ] **Step 4:** Passes; `test/super_tab_activity_test.dart` still passes. Commit the test, then the code.
+
+### Task 4: Pictures for Huy
+
+- [ ] Add the groups to `test/super_tab_sidebar_shots_test.dart` (written only with `SUPER_TAB_SIDEBAR_SHOTS`), at
+ desktop width and at phone width, light and dark. Attach the pictures to the PR, along with red/green evidence and
+ the full Desktop test run.
diff --git a/docs/specs/2026-11-03-dial-thread-face.md b/docs/specs/2026-11-03-dial-thread-face.md
new file mode 100644
index 000000000..123a49068
--- /dev/null
+++ b/docs/specs/2026-11-03-dial-thread-face.md
@@ -0,0 +1,110 @@
+# Round dial: the thread you started is on the face (Diego, 2026-11-03)
+
+## What Diego asked
+
+Talking to the PM (or the Buddy) is threaded: a task said on the dial is answered in a thread rooted at the words said,
+so the app opens that thread while the dial stays on the PM's main chat and never shows the answer. The dial should go
+into that thread, and look unmistakably different while it is in one.
+
+Choices Diego made (mockup `devices/harness-device/mockup/round-thread/index.html`, option A):
+
+- After words said on the dial are posted, the dial's face goes into the thread rooted at that message. The app opens the
+ same thread beside the chat.
+- When the app opens a thread (a click there), the dial follows it, as it follows the app's chat today.
+- A **horizontal swipe** in a thread leaves it, back to the main chat of the same Lead (it does not change project);
+ the app closes the thread too. The next horizontal swipe changes project, as today.
+- The app moving to another chat or thread moves the dial with it (the newest move wins, as the focus rule does today).
+- The thread face: teal ring, "↳ Thread" (or "↳ Thread · Buddy") under the project's name, the thread's title on up to
+ two lines, **no pet and no bottom arc**, the recap card with a teal spine and a small "PM · N replies" line, and "‹ chat"
+ at the left edge. With no agent reply yet the card says "Waiting for the PM…" ("Waiting for your Buddy…").
+- The PM face keeps no chat label (the project's name is enough); the Buddy face keeps "Your Buddy".
+
+## Builds on
+
+PR #2718 (round dial: recap answers at once, app order, threads): Desktop announces `threadRoot` while a thread pane is
+on screen; the cards service carries it in its focus; a face whose conversation has that thread reads its recap from the
+thread and posts words there (`replyTo: root`). This work adds the dial's own thread (started by its words), shows it on
+the dial, and lets the dial leave it.
+
+## Behaviour
+
+### Where the face's thread comes from (cards service)
+
+Each Swarm's face has at most one thread, kept per Swarm like the side a swarmBuddy dial keeps (`sides`):
+
+1. **The app's thread** — the window's focus names `threadRoot` in the conversation on the face (#2718).
+2. **The dial's thread** — set when words said on the dial are posted at top level (no thread on the face yet): its
+ root is the posted message's id (`result.messageId` of the `message.send`), its title the words said.
+
+The newest wins: the app's focus changing (another conversation, another thread, a thread closed) clears the dial's
+thread, as a desktop move clears the dial's side today; the dial starting a thread sets it and asks the window to open it
+(so the focus then names the same root). A thread lives only while its conversation is the one on the face.
+
+The dial leaves with `supertab.thread.leave {tab, lead}`: the dial's thread is cleared and the window is asked to close
+its thread pane (so the focus stops naming it).
+
+### What the dial is told
+
+- The face chat (`SwarmChat`) carries `thread: { root, title, replies? }` while the face is in a thread. `title` is the
+ dial's words for its own thread, else the root message's text; its first line, at most 80 bytes. `replies` is the
+ thread's reply count when the read that answers the recap gives it.
+- A recap read from a thread names it (`LeadRecap.thread = root`), so the dial never takes a thread's recap for its main
+ chat or the other way round.
+- Only a dial that announces the capability `swarmThread` is sent `thread` fields and may send `supertab.thread.leave`.
+ An older dial keeps #2718's behaviour (it follows the app's thread with no mark).
+
+### What the dial does (round dial firmware)
+
+- A Lead whose face chat has `thread` draws the thread face described above (teal `#2dd4bf`). The title wraps on words to
+ two lines of about 22 characters, ending "…" when longer. The recap card shows up to three lines.
+- The recap for a thread face is accepted only when its `thread` matches the face's root (and its chat id the face's
+ chat), so a face that leaves its thread asks for the main chat's recap again.
+- A horizontal swipe on a thread face sends `supertab.thread.leave` and shows the main chat at once (the thread drawn off
+ locally, the recap asked again); it does not change project. Vertical swipes are unchanged (up: Buddy side, which
+ leaves the PM's thread; down: inbox on the PM side, PM side from the Buddy side).
+- The bell pill for unread notices still shows on a thread face; the bottom arc text does not.
+
+### Desktop
+
+- The window names the open thread (`threadRoot` on its Swarm row) while the thread pane is open in the selected
+ conversation, whether or not the pane is on screen; read marks still wait for the pane to be shown.
+- `dial_super_tab { superTabId, conversationId, threadRoot: string | null, threadOnly: true }` (no `projectId`, so an older
+ Desktop ignores it): a string opens that thread in that conversation (any kind: Lead, Buddy, group) once its chat has read
+ the root, without raising the window, switching the Swarm or reselecting the Lead chat; `null` closes that conversation's
+ thread pane and nothing else. A newer thread-only frame, a leave, or the person opening another thread cancels a pending
+ open. A thread opened this way marks nothing read until its pane is shown.
+- Ordinary dial picks keep today's `{ superTabId, projectId, chat? }`.
+
+### Voice
+
+- Words start the dial's thread only when spoken from the Swarm face (not from a Lead's terminal tile picked in the window).
+- The thread on the face when the words are spoken is pinned: if the face's thread changed by the time they are sent, they
+ are refused with `CHAT_MOVED` ("Say it again"), unless the person reviewed and pressed Send, in which case they go to the
+ pinned thread (or top level when none was pinned). A thread starts only if nothing moved while the words were posted.
+- The dial's own thread waits for the window to open it: a selection announce with no thread in that conversation does not
+ end it until the window has named the thread once (or 15 s have passed).
+
+### Known limits
+
+- Words said from the dial's own AGENT view of a Lead's terminal tile still count as the Swarm face (the dial does not say
+ which view it spoke from).
+- Two round dials on one daemon share the face thread; an older dial without `swarmThread` follows it unmarked.
+
+## Design
+
+- **Growth:** none stored. The dial's thread is in memory per Swarm in the cards service, cleared with the device, the
+ account, a lost Swarm, or a focus move.
+- **Concurrency:** one service, one map; the device's leave and the window's focus are ordered by arrival (newest wins).
+- **Read cost:** no new reads for a dial-started thread (title from the words). An app-opened thread's title comes from the
+ thread read the recap already makes (#2718), read again only when the root changes.
+- **Scale:** one thread per Swarm face; the cards frame grows by at most ~120 bytes on one Lead, inside `fitFrame`'s cap
+ (`threadTitle` is trimmed like `chatName`).
+- **Compatibility:** gated by the dial's `swarmThread` capability; an old dial or daemon ignores the new fields; an old
+ Desktop ignores `threadRoot` in `dial_super_tab` (the dial still shows its thread; the app just does not open it).
+- **Migration + rollback:** none; nothing persisted.
+- **Audience:** a thread is only ever in a conversation already on this reader's face; the backend checks the reply as for
+ typing.
+- **Identity:** the signed-in person's own reads and posts, as the dial's voice today.
+- **Failure:** a post whose answer has no `messageId` starts no thread (the face stays on the main chat, as today). A leave
+ the window cannot apply leaves its pane open; the dial is off the thread either way until the app moves again.
+- **Platforms:** round dial (harness-device) firmware, the daemon (cli), Desktop on every OS. Harness Pro: not in scope.
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index a92379a0c..7ee995ddf 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -1289,10 +1289,11 @@ class SuperTabMessage {
SuperTabRoute? get route => SuperTabRoute.fromSource(source);
bool get routeOverride => source['kind'] == 'route-override';
- /// The person a Buddy's proposal speaks for, from the tag the server writes
- /// on it; null for every other message, whatever its text says.
- String? get proposalOwnerId =>
- source['kind'] == 'buddy-proposal' ? source['personId'] as String? : null;
+ /// A "Let's build" root the server posted in its person's name (plain chat,
+ /// #2294): theirs to read, not their own writing, so it reads nothing
+ /// before it and is unread for them as anyone else's message is.
+ bool get postedForAuthor =>
+ source['kind'] == 'task-line' || source['kind'] == 'buddy-proposal';
/// The agent a "waiting at a prompt" note is about; null for any other row.
String? get promptAlertAgentId =>
diff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dart
index a9945e6f2..57783e3c3 100644
--- a/mobile/lib/swarm/swarm_conversation.dart
+++ b/mobile/lib/swarm/swarm_conversation.dart
@@ -1304,11 +1304,15 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
bool _receiptCurrent = false;
Future<void>? _readingReceipt;
- /// The person's newest message here, written by them and not by an agent or
- /// a terminal: the only one that can carry a delivery line.
+ /// The person's newest message here, written by them and not by an agent, a
+ /// terminal or the server in their name: the only one that can carry a
+ /// delivery line (Desktop's `isOwn`).
SuperTabMessage? get latestOwn {
for (final m in messages.reversed) {
- if (!m.fromAgent && !m.fromTerminal && m.authorId == reader.accountId) {
+ if (!m.fromAgent &&
+ !m.fromTerminal &&
+ !m.postedForAuthor &&
+ m.authorId == reader.accountId) {
return m;
}
}
diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dart
index c4ad8d0fb..83470ce7e 100644
--- a/mobile/lib/swarm/swarm_conversation_page.dart
+++ b/mobile/lib/swarm/swarm_conversation_page.dart
@@ -52,7 +52,6 @@ import 'swarm_reactions.dart';
import 'swarm_read_marks.dart';
import 'swarm_session.dart';
import 'swarm_style.dart';
-import 'swarm_task_line.dart';
import 'swarm_thread.dart';
import 'swarm_thread_line.dart';
import 'swarm_thread_page.dart';
@@ -948,20 +947,6 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
);
}
- VoidCallback? _taskOpener(SwarmConversation c, SuperTabMessage message) {
- final taskId = message.source['taskId'];
- if (!swarmIsTaskLine(message) ||
- taskId is! String ||
- c.reader.snapshot?.conversation(taskId) == null) {
- return null;
- }
- return () {
- if (c.reader.snapshot?.conversation(taskId) != null) {
- openSwarmConversation(context, widget.swarmId, taskId);
- }
- };
- }
-
void _openNumberedConversation(SwarmConversation c, String id) {
final reader = _session?.inbox.reader(c.reader.tabId);
if (mounted && swarmCanOpenNumberedConversation(reader, id)) {
@@ -1013,7 +998,6 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
tagged: _taggedOf(c, m).keys.toList(),
taggedAddresses: _taggedOf(c, m),
readerId: c.reader.accountId,
- onOpenTask: _taskOpener(c, m),
references: _numberedReferences(c, m.text).references,
onOpenConversation: (id) => _openNumberedConversation(c, id),
grouped: grouped,
@@ -1827,14 +1811,12 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
stream,
(agentId) => snapshot?.agent(agentId),
);
- final messages = swarmTaskLineMessages(
- answered.isEmpty
- ? stream
- : [
- for (final m in stream)
- if (!answered.contains(m.id)) m,
- ],
- );
+ final messages = answered.isEmpty
+ ? stream
+ : [
+ for (final m in stream)
+ if (!answered.contains(m.id)) m,
+ ];
// The notes hidden are part of what the rows were made from: a warning
// goes once its agent's prompt is answered, with no new message.
final from = (
@@ -1984,7 +1966,6 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
tagged: tagged.keys.toList(),
taggedAddresses: tagged,
readerId: c.reader.accountId,
- onOpenTask: _taskOpener(c, m),
references: references,
onOpenConversation: (id) => _openNumberedConversation(c, id),
grouped: grouped,
@@ -2014,9 +1995,6 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
? () => _openThread(c, root)
: () => _reply(c, m),
inThread: root != null,
- onOpenProposal: m.proposalOwnerId == null
- ? null
- : () => _openThread(c, m.id),
card: card == null
? null
: SwarmLiveCard(
@@ -2861,11 +2839,9 @@ String swarmDayLabel(DateTime day, DateTime now) {
Set<String> swarmGroupedMessages(List<SuperTabMessage> messages) {
bool joins(SuperTabMessage current, SuperTabMessage previous) {
bool plain(SuperTabMessage m) =>
- !swarmIsTaskLine(m) &&
m.source['kind'] != 'ship' &&
m.route == null &&
!m.terminalEvent &&
- m.proposalOwnerId == null &&
m.replyTo == null &&
m.text.length <= 280 &&
!m.text.contains('\n') &&
diff --git a/mobile/lib/swarm/swarm_home_view.dart b/mobile/lib/swarm/swarm_home_view.dart
index a3a4ee76f..e71cb381b 100644
--- a/mobile/lib/swarm/swarm_home_view.dart
+++ b/mobile/lib/swarm/swarm_home_view.dart
@@ -45,11 +45,12 @@ SwarmHomeSwarm swarmHomeSwarm(
for (final a in snapshot.agents)
// A thread's own session is not drawn: kept, it would read as the
// Buddy until the next read.
- if (a.buddySession == null) {
- ..._agent(a),
- if (buddies.buddyOwners[a.id] case final owner?)
- 'buddyOf': {'personId': owner},
- },
+ if (a.buddySession == null)
+ {
+ ..._agent(a),
+ if (buddies.buddyOwners[a.id] case final owner?)
+ 'buddyOf': {'personId': owner},
+ },
],
'conversations': [
for (final c in snapshot.conversations)
diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dart
index c72111bd7..66a814f2b 100644
--- a/mobile/lib/swarm/swarm_message_row.dart
+++ b/mobile/lib/swarm/swarm_message_row.dart
@@ -24,7 +24,6 @@ import 'swarm_message_style.dart';
import 'swarm_face.dart';
import 'swarm_ship_row.dart';
import 'swarm_special_rows.dart';
-import 'swarm_task_line.dart';
/// `@name` or `@name@domain`, as people tag in chat. Never right after a
/// letter, digit, `@` or `/` (an address, a path, a link), and a name never
@@ -275,8 +274,6 @@ class SwarmMessageRow extends StatelessWidget {
this.receipt,
this.card,
this.onLongPress,
- this.onOpenTask,
- this.onOpenProposal,
this.references = const {},
this.onOpenConversation,
});
@@ -312,13 +309,6 @@ class SwarmMessageRow extends StatelessWidget {
final Widget? quote;
final VoidCallback onTap;
- /// Opens a task held by the current reader; null for an unavailable target.
- final VoidCallback? onOpenTask;
-
- /// Opens a Buddy's proposal's thread: given in the chat, where a proposal is
- /// one line; none in its thread, where it reads whole.
- final VoidCallback? onOpenProposal;
-
/// The numbered conversations `#N` links in a message can open.
final Map<int, String> references;
@@ -376,14 +366,6 @@ class SwarmMessageRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
- if (swarmIsTaskLine(message)) {
- return SwarmTaskLine(
- key: ValueKey('swarm-message-${message.id}'),
- message: message,
- readerId: readerId,
- onOpen: onOpenTask,
- );
- }
// A ship line is a card, not a message from its author.
if (swarmShips(message)) {
return SwarmShipRow(
@@ -393,13 +375,6 @@ class SwarmMessageRow extends StatelessWidget {
}
// Notes that are not chat from their author, as Desktop draws them.
final special = ValueKey('swarm-message-${message.id}');
- if (message.proposalOwnerId != null && onOpenProposal != null) {
- return SwarmProposalLine(
- key: special,
- message: message,
- onOpen: onOpenProposal!,
- );
- }
if (message.terminalEvent) {
return SwarmTerminalRow(key: special, message: message);
}
@@ -441,8 +416,6 @@ class SwarmMessageRow extends StatelessWidget {
body: [
if (lit) SizedBox(key: ValueKey('swarm-lit-${message.id}')),
?quote,
- if (message.proposalOwnerId != null)
- SwarmProposalLabel(owner: swarmProposalOwner(context, message)),
?swarmTerminalNote(message),
for (final part in swarmTextParts(message.text))
if (part.code)
diff --git a/mobile/lib/swarm/swarm_request.dart b/mobile/lib/swarm/swarm_request.dart
index 8efe58994..07fb0d566 100644
--- a/mobile/lib/swarm/swarm_request.dart
+++ b/mobile/lib/swarm/swarm_request.dart
@@ -42,16 +42,15 @@ String superTabOperationId() {
/// [file] is read as it goes, never whole when it is large. [onProgress] is
/// told the part sent, from 0 to 1. A refusal throws a [SuperTabFailure]
/// carrying the backend's code.
-typedef SwarmUpload =
- Future<Map<String, dynamic>> Function({
- required String tabId,
- required String conversationId,
- required String name,
- required String mime,
- required SwarmOutgoingFile file,
- required CancelToken cancel,
- required void Function(double sent) onProgress,
- });
+typedef SwarmUpload = Future<Map<String, dynamic>> Function({
+ required String tabId,
+ required String conversationId,
+ required String name,
+ required String mime,
+ required SwarmOutgoingFile file,
+ required CancelToken cancel,
+ required void Function(double sent) onProgress,
+});
/// The upload of a phone that cannot reach the backend with a file.
Future<Map<String, dynamic>> refuseSwarmUpload({
diff --git a/mobile/lib/swarm/swarm_special_rows.dart b/mobile/lib/swarm/swarm_special_rows.dart
index 8574903be..7f1303841 100644
--- a/mobile/lib/swarm/swarm_special_rows.dart
+++ b/mobile/lib/swarm/swarm_special_rows.dart
@@ -295,105 +295,6 @@ String _time(DateTime at) {
return fullDateTime(at);
}
-/// The person a proposal speaks for, by username; "its owner" for one no
-/// longer in the Swarm (Desktop's `buddyPersonName`).
-String swarmProposalOwner(BuildContext context, SuperTabMessage message) {
- final id = message.proposalOwnerId!;
- return swarmReaderOf(
- context,
- message.conversationId,
- )?.snapshot?.people.where((p) => p.id == id).firstOrNull?.username ??
- 'its owner';
-}
-
-/// A proposal's name: its Goal line, else its first line (Desktop's
-/// `_proposalName`).
-String swarmProposalName(String text) {
- final lines = text.split('\n').map((line) => line.trim());
- for (final line in lines) {
- if (line.startsWith('Goal: ')) return line.substring(6).trim();
- }
- return lines.first;
-}
-
-/// "Proposal from dee: …", one line that opens its thread, where it reads
-/// whole (Desktop's `SuperTabProposalLine`, Quiet Swarm).
-class SwarmProposalLine extends StatelessWidget {
- const SwarmProposalLine({
- super.key,
- required this.message,
- required this.onOpen,
- });
- final SuperTabMessage message;
- final VoidCallback onOpen;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final text =
- 'Proposal from ${swarmProposalOwner(context, message)}: '
- '${swarmProposalName(message.text)}';
- return Semantics(
- button: true,
- label: text,
- excludeSemantics: true,
- child: Material(
- color: Colors.transparent,
- child: InkWell(
- onTap: onOpen,
- child: ConstrainedBox(
- constraints: const BoxConstraints(minHeight: 44),
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: AppSpace.l,
- vertical: AppSpace.s,
- ),
- child: Row(
- children: [
- Icon(
- LucideIcons.chevronRight300,
- size: 16,
- color: AppPalette.textSecondary,
- ),
- const SizedBox(width: AppSpace.s),
- Expanded(
- child: Text(
- text,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: swarmChatText(16),
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- );
- }
-}
-
-/// Above a proposal read whole: whom it speaks for (Desktop's label).
-class SwarmProposalLabel extends StatelessWidget {
- const SwarmProposalLabel({super.key, required this.owner});
- final String owner;
-
- @override
- Widget build(BuildContext context) => Padding(
- padding: const EdgeInsets.only(top: SwarmMessageFrame.bodyGap),
- child: Container(
- key: const ValueKey('swarm-proposal-label'),
- padding: const EdgeInsets.symmetric(horizontal: AppSpace.s),
- decoration: BoxDecoration(
- border: Border.all(color: AppPalette.textFaint),
- borderRadius: BorderRadius.circular(AppSpace.s),
- ),
- child: Text("Proposal · on $owner's behalf", style: _quiet()),
- ),
- );
-}
-
/// The quiet line a terminal's answer starts with, and the one under a
/// response that was cut short (Desktop's view.dart).
Widget? swarmTerminalNote(SuperTabMessage message) =>
diff --git a/mobile/lib/swarm/swarm_task_line.dart b/mobile/lib/swarm/swarm_task_line.dart
deleted file mode 100644
index b92c4afc6..000000000
--- a/mobile/lib/swarm/swarm_task_line.dart
+++ /dev/null
@@ -1,141 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
-
-import 'package:harness_mobile/shared/theme/app_space.dart';
-import 'package:harness_mobile/shared/theme/app_theme.dart';
-
-import 'model.dart';
-import 'swarm_message_row.dart' show swarmChatText;
-
-/// The server edits this message in place as its task moves.
-bool swarmIsTaskLine(SuperTabMessage message) =>
- message.source['kind'] == 'task-line';
-
-/// A task's line replaces its older Shipped card in the loaded chat window.
-/// A ship for another task, or without a replacement here, remains visible.
-List<SuperTabMessage> swarmTaskLineMessages(List<SuperTabMessage> messages) {
- final lined = <String>{
- for (final message in messages)
- if (swarmIsTaskLine(message) && message.source['taskId'] is String)
- message.source['taskId'] as String,
- };
- if (lined.isEmpty) return messages;
- return [
- for (final message in messages)
- if (!(message.source['kind'] == 'ship' &&
- lined.contains(message.source['conversationId'])))
- message,
- ];
-}
-
-/// Desktop's task words; a future state makes no claim this build cannot keep.
-String _word(SuperTabMessage message, String readerId) =>
- switch (message.source['state']) {
- 'planned' => 'planned',
- 'working' => 'working',
- 'waiting' =>
- message.source['answerFor'] == readerId ? 'Answer' : 'working',
- 'review' => 'in review',
- 'ready' => 'ready',
- 'shipped' => 'shipped',
- 'done' => 'done',
- 'stopped' => 'stopped',
- _ => '',
- };
-
-IconData _mark(SuperTabMessage message) => switch (message.source['state']) {
- 'planned' => LucideIcons.circleDashed,
- 'shipped' || 'done' => LucideIcons.check,
- 'stopped' => LucideIcons.circleSlash,
- _ => LucideIcons.circleDot,
-};
-
-/// One quiet, thumb-sized row: mark, task name and word. Opening the task is
-/// available only while the caller's current read holds that conversation.
-class SwarmTaskLine extends StatelessWidget {
- const SwarmTaskLine({
- super.key,
- required this.message,
- required this.readerId,
- this.onOpen,
- });
-
- final SuperTabMessage message;
- final String readerId;
- final VoidCallback? onOpen;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final title = switch (message.source['title']) {
- final String title when title.isNotEmpty => title,
- _ => message.text,
- };
- final word = _word(message, readerId);
- final answer = word == 'Answer';
- return Semantics(
- label: word.isEmpty ? title : '$title, $word',
- button: onOpen != null,
- onTap: onOpen,
- excludeSemantics: true,
- child: Material(
- color: Colors.transparent,
- child: InkWell(
- onTap: onOpen,
- child: ConstrainedBox(
- constraints: const BoxConstraints(minHeight: 44),
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: AppSpace.l,
- vertical: AppSpace.s,
- ),
- child: Row(
- children: [
- Icon(
- _mark(message),
- size: 16,
- color: AppPalette.textSecondary,
- ),
- const SizedBox(width: AppSpace.s),
- Expanded(
- child: Text(
- title,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: swarmChatText(
- 16,
- weight: answer ? FontWeight.w600 : FontWeight.w400,
- ),
- ),
- ),
- if (word.isNotEmpty) ...[
- const SizedBox(width: AppSpace.s),
- Text(
- word,
- maxLines: 1,
- style: swarmChatText(
- 14,
- color: answer
- ? AppPalette.textPrimary
- : AppPalette.textSecondary,
- weight: answer ? FontWeight.w600 : FontWeight.w400,
- ),
- ),
- ],
- if (onOpen != null) ...[
- const SizedBox(width: AppSpace.s),
- Icon(
- LucideIcons.chevronRight300,
- size: 18,
- color: AppPalette.textFaint,
- ),
- ],
- ],
- ),
- ),
- ),
- ),
- ),
- );
- }
-}
diff --git a/mobile/lib/swarm/swarm_unread_line.dart b/mobile/lib/swarm/swarm_unread_line.dart
index 75bf3e64b..66ad873ba 100644
--- a/mobile/lib/swarm/swarm_unread_line.dart
+++ b/mobile/lib/swarm/swarm_unread_line.dart
@@ -22,7 +22,8 @@ String? swarmFirstUnread(
}) {
if (mark == null || mark <= 0 || messages.isEmpty) return null;
if (hasOlder && messages.first.sequence > mark + 1) return null;
- bool own(SuperTabMessage m) => !m.fromAgent && m.authorId == accountId;
+ bool own(SuperTabMessage m) =>
+ !m.fromAgent && !m.postedForAuthor && m.authorId == accountId;
var read = mark;
for (final m in messages) {
if (own(m) && m.inMainStream && m.sequence > read) read = m.sequence;
diff --git a/mobile/test/swarm/swarm_attachment_keeper_test.dart b/mobile/test/swarm/swarm_attachment_keeper_test.dart
index 624359db4..f88aaec21 100644
--- a/mobile/test/swarm/swarm_attachment_keeper_test.dart
+++ b/mobile/test/swarm/swarm_attachment_keeper_test.dart
@@ -221,7 +221,9 @@ class _ListingDirectory implements Directory {
for (final entry in entries) {
listed.add(entry);
if (recursive && entry is Directory) {
- listed.addAll(entry.listSync(recursive: true, followLinks: followLinks));
+ listed.addAll(
+ entry.listSync(recursive: true, followLinks: followLinks),
+ );
}
}
return listed;
diff --git a/mobile/test/swarm/swarm_buddy_session_parse_test.dart b/mobile/test/swarm/swarm_buddy_session_parse_test.dart
index ecf44c97e..9dde0b592 100644
--- a/mobile/test/swarm/swarm_buddy_session_parse_test.dart
+++ b/mobile/test/swarm/swarm_buddy_session_parse_test.dart
@@ -46,58 +46,61 @@ void main() {
's',
);
});
- test('session fields read as Desktop reads them (project, lookup, ended)', () {
- expect(
- SuperTabBuddySessionOf.fromJson({
- 'thread': 'r',
- 'from': 1,
- 'projectId': 'p',
- })!.projectId,
- 'p',
- );
- expect(
- SuperTabBuddySessionOf.fromJson({'thread': 'r', 'projectId': ''})!
- .projectId,
- isNull,
- );
- expect(
- SuperTabBuddySessionOf.fromJson({'thread': 'r', 'projectId': 3})!
- .projectId,
- isNull,
- );
- final chat = SuperTabConversation.fromJson({
- 'id': 'c',
- 'kind': 'buddy',
- 'buddyOwnerId': 'p',
- 'title': 'Wren',
- 'agentIds': <String>[],
- 'archived': false,
- 'brief': '',
- 'checks': <dynamic>[],
- 'assignment': null,
- 'lastMessageSequence': 0,
- 'buddySessions': [
- {'thread': 'r', 'startId': 's'},
- ],
- });
- expect(chat.sessionFor('r')!.startId, 's');
- expect(chat.sessionFor('x'), isNull);
- SuperTabMessage message(Map<String, dynamic> extra) =>
- SuperTabMessage.fromJson({
- 'id': 'm',
- 'conversationId': 'c',
- 'text': 't',
- 'sequence': 1,
- 'author': {'kind': 'agent', 'id': 'a'},
- 'thread': 'm',
- ...extra,
- });
- final ended = message({
- 'buddySession': true,
- 'source': {'kind': 'buddy-session-ended', 'reason': 'idle'},
- });
- expect([ended.sessionEnded, ended.sessionEndReason], [true, 'idle']);
- final plain = message({'buddySession': true});
- expect([plain.sessionEnded, plain.sessionEndReason], [false, null]);
- });
+ test(
+ 'session fields read as Desktop reads them (project, lookup, ended)',
+ () {
+ expect(
+ SuperTabBuddySessionOf.fromJson({
+ 'thread': 'r',
+ 'from': 1,
+ 'projectId': 'p',
+ })!.projectId,
+ 'p',
+ );
+ expect(
+ SuperTabBuddySessionOf.fromJson({'thread': 'r', 'projectId': ''})!
+ .projectId,
+ isNull,
+ );
+ expect(
+ SuperTabBuddySessionOf.fromJson({'thread': 'r', 'projectId': 3})!
+ .projectId,
+ isNull,
+ );
+ final chat = SuperTabConversation.fromJson({
+ 'id': 'c',
+ 'kind': 'buddy',
+ 'buddyOwnerId': 'p',
+ 'title': 'Wren',
+ 'agentIds': <String>[],
+ 'archived': false,
+ 'brief': '',
+ 'checks': <dynamic>[],
+ 'assignment': null,
+ 'lastMessageSequence': 0,
+ 'buddySessions': [
+ {'thread': 'r', 'startId': 's'},
+ ],
+ });
+ expect(chat.sessionFor('r')!.startId, 's');
+ expect(chat.sessionFor('x'), isNull);
+ SuperTabMessage message(Map<String, dynamic> extra) =>
+ SuperTabMessage.fromJson({
+ 'id': 'm',
+ 'conversationId': 'c',
+ 'text': 't',
+ 'sequence': 1,
+ 'author': {'kind': 'agent', 'id': 'a'},
+ 'thread': 'm',
+ ...extra,
+ });
+ final ended = message({
+ 'buddySession': true,
+ 'source': {'kind': 'buddy-session-ended', 'reason': 'idle'},
+ });
+ expect([ended.sessionEnded, ended.sessionEndReason], [true, 'idle']);
+ final plain = message({'buddySession': true});
+ expect([plain.sessionEnded, plain.sessionEndReason], [false, null]);
+ },
+ );
}
diff --git a/mobile/test/swarm/swarm_drafts_unsent_test.dart b/mobile/test/swarm/swarm_drafts_unsent_test.dart
index 3f3cd70d6..c1616b5cb 100644
--- a/mobile/test/swarm/swarm_drafts_unsent_test.dart
+++ b/mobile/test/swarm/swarm_drafts_unsent_test.dart
@@ -460,11 +460,8 @@ void main() {
test('a thread draft written after the chat is lost is refused', () async {
final inbox = await app();
final c = await chat(inbox);
- swarm.routes[messages] = (_) => throw const SuperTabFailure(
- 'FORBIDDEN',
- 'No.',
- statusCode: 403,
- );
+ swarm.routes[messages] = (_) =>
+ throw const SuperTabFailure('FORBIDDEN', 'No.', statusCode: 403);
await c.load();
c.setThreadDraft('root-1', 'too late');
expect(inbox.kept.draft(tab, 'g1', 'root-1'), isNull);
diff --git a/mobile/test/swarm/swarm_home_test.dart b/mobile/test/swarm/swarm_home_test.dart
index cbb229c38..14a47ee5f 100644
--- a/mobile/test/swarm/swarm_home_test.dart
+++ b/mobile/test/swarm/swarm_home_test.dart
@@ -640,21 +640,24 @@ void main() {
expect(find.byType(SwarmActivityPage), findsOneWidget);
});
- testWidgets('back within five minutes and using the app on: the time stays, '
- 'as only time in the background is time away', (tester) async {
- var now = _halfHourIn();
- await pump(tester, backend(), now: () => now);
- await away(tester, const Duration(minutes: 4), (d) => now = now.add(d));
- expect(inside('swarm-away', find.text('4m')), findsOneWidget);
+ testWidgets(
+ 'back within five minutes and using the app on: the time stays, '
+ 'as only time in the background is time away',
+ (tester) async {
+ var now = _halfHourIn();
+ await pump(tester, backend(), now: () => now);
+ await away(tester, const Duration(minutes: 4), (d) => now = now.add(d));
+ expect(inside('swarm-away', find.text('4m')), findsOneWidget);
- now = now.add(const Duration(minutes: 2));
- await tester.pump(const Duration(minutes: 2));
- expect(
- inside('swarm-away', find.text('4m')),
- findsOneWidget,
- reason: 'two minutes in the foreground are no time away',
- );
- });
+ now = now.add(const Duration(minutes: 2));
+ await tester.pump(const Duration(minutes: 2));
+ expect(
+ inside('swarm-away', find.text('4m')),
+ findsOneWidget,
+ reason: 'two minutes in the foreground are no time away',
+ );
+ },
+ );
testWidgets('opened four minutes after the app was last left, and used '
'on: four minutes', (tester) async {
@@ -684,7 +687,13 @@ void main() {
.subtract(const Duration(minutes: 20))
.millisecondsSinceEpoch,
});
- await pump(tester, backend(), now: () => now, store: store, settle: false);
+ await pump(
+ tester,
+ backend(),
+ now: () => now,
+ store: store,
+ settle: false,
+ );
expect(key('swarm-away'), findsNothing);
store.release.complete();
@@ -2837,7 +2846,11 @@ void main() {
expect(find.text('Buddies'), findsNothing);
expect(find.text('Projects'), findsOneWidget);
expect(find.textContaining('Reading'), findsNothing);
- expect(key('swarm-away'), findsOneWidget, reason: 'its figures skeletons');
+ expect(
+ key('swarm-away'),
+ findsOneWidget,
+ reason: 'its figures skeletons',
+ );
listed.complete();
await tester.pumpAndSettle();
diff --git a/mobile/test/swarm/swarm_inbox_test.dart b/mobile/test/swarm/swarm_inbox_test.dart
index 3e9a855f1..74a17157f 100644
--- a/mobile/test/swarm/swarm_inbox_test.dart
+++ b/mobile/test/swarm/swarm_inbox_test.dart
@@ -763,22 +763,25 @@ void main() {
addTearDown(() => appLog = before);
});
- test('a Swarm that could not be read, once however many reads fail', () async {
- final fake = backend({'a': []});
- fake.routes['/api/super-tabs/a/parts'] = (_) =>
- throw SuperTabFailure('INTERNAL', 'Broken', statusCode: 500);
- final i = inbox(fake);
-
- await i.refresh();
- final reader = i.reader('a')!;
- await reader.refresh();
- await reader.refresh();
+ test(
+ 'a Swarm that could not be read, once however many reads fail',
+ () async {
+ final fake = backend({'a': []});
+ fake.routes['/api/super-tabs/a/parts'] = (_) =>
+ throw SuperTabFailure('INTERNAL', 'Broken', statusCode: 500);
+ final i = inbox(fake);
- expect(reader.error, 'Broken');
- expect(log.events, hasLength(1));
- expect(log.events.single.level, AppLogLevel.warn);
- expect(log.events.single.message, contains('Swarm a not read: Broken'));
- });
+ await i.refresh();
+ final reader = i.reader('a')!;
+ await reader.refresh();
+ await reader.refresh();
+
+ expect(reader.error, 'Broken');
+ expect(log.events, hasLength(1));
+ expect(log.events.single.level, AppLogLevel.warn);
+ expect(log.events.single.message, contains('Swarm a not read: Broken'));
+ },
+ );
test('what threw, with its stack, once however many polls fail, and '
'again after a read that worked', () async {
diff --git a/mobile/test/swarm/swarm_invitations_shots_test.dart b/mobile/test/swarm/swarm_invitations_shots_test.dart
index dddde9220..20a8080c1 100644
--- a/mobile/test/swarm/swarm_invitations_shots_test.dart
+++ b/mobile/test/swarm/swarm_invitations_shots_test.dart
@@ -82,9 +82,8 @@ void main() {
'This invitation has expired.',
statusCode: 409,
);
- final features = ExperimentalFeaturesStore(
- storage: MemoryKeyValueStore(),
- )..value = {PhoneExperiment.swarm};
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
final account = ValueNotifier<String?>(me);
final host = SwarmHost(
accountId: () => account.value,
@@ -113,9 +112,8 @@ void main() {
as RenderRepaintBoundary)
.toImage(pixelRatio: 3);
final png = await image.toByteData(format: ui.ImageByteFormat.png);
- await File(
- '$shots/invitations-$name-${brightness.name}.png',
- ).writeAsBytes(png!.buffer.asUint8List());
+ await File('$shots/invitations-$name-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
image.dispose();
});
await capture('home');
diff --git a/mobile/test/swarm/swarm_outgoing_files_test.dart b/mobile/test/swarm/swarm_outgoing_files_test.dart
index 3dcb12ea9..d818fd092 100644
--- a/mobile/test/swarm/swarm_outgoing_files_test.dart
+++ b/mobile/test/swarm/swarm_outgoing_files_test.dart
@@ -128,11 +128,10 @@ void main() {
files.addNumbered([file('photo.jpg', 2)]);
files.addNumbered([file('photo.jpg', 3)]);
- expect([for (final f in files.files) f.name], [
- 'photo.jpg',
- 'photo-2.jpg',
- 'photo-3.jpg',
- ]);
+ expect(
+ [for (final f in files.files) f.name],
+ ['photo.jpg', 'photo-2.jpg', 'photo-3.jpg'],
+ );
});
test('remove and clear tell their listeners', () {
diff --git a/mobile/test/swarm/swarm_request_test.dart b/mobile/test/swarm/swarm_request_test.dart
index 7a2a0565b..74df9478f 100644
--- a/mobile/test/swarm/swarm_request_test.dart
+++ b/mobile/test/swarm/swarm_request_test.dart
@@ -54,14 +54,17 @@ void main() {
expect(await rig.app.swarmRequest('GET', path), {'tabs': <Object>[]});
});
- test('a value of null is an answer, not a reason to ask a machine', () async {
- final rig = await signedInWith({'m': []});
- addTearDown(rig.app.dispose);
- rig.api.onSwarmRead = (_) async => null;
+ test(
+ 'a value of null is an answer, not a reason to ask a machine',
+ () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.api.onSwarmRead = (_) async => null;
- expect(await rig.app.swarmRequest('GET', path), isNull);
- expect(rig.conn('m').payloadsOf('super_tabs'), isEmpty);
- });
+ expect(await rig.app.swarmRequest('GET', path), isNull);
+ expect(rig.conn('m').payloadsOf('super_tabs'), isEmpty);
+ },
+ );
test('its query goes with it', () async {
final rig = await signedInWith({'m': []});
@@ -73,21 +76,24 @@ void main() {
expect(rig.api.swarmReads, ['/api/super-tabs/t/changes?cursor=c1']);
});
- test('without phone write credentials a machine forwards a command', () async {
- final rig = await signedInWith({'m': []});
- addTearDown(rig.app.dispose);
- rig.api.onSwarmRead = (_) async => fail('a command is not a read');
- rig.conn('m').answers['super_tabs'] = (_) => forwarded({'result': {}});
+ test(
+ 'without phone write credentials a machine forwards a command',
+ () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.api.onSwarmRead = (_) async => fail('a command is not a read');
+ rig.conn('m').answers['super_tabs'] = (_) => forwarded({'result': {}});
- await rig.app.swarmRequest(
- 'POST',
- '/api/super-tabs/t/commands',
- body: {'operationId': 'op'},
- );
+ await rig.app.swarmRequest(
+ 'POST',
+ '/api/super-tabs/t/commands',
+ body: {'operationId': 'op'},
+ );
- expect(rig.api.swarmReads, isEmpty);
- expect(rig.conn('m').payloadsOf('super_tabs'), hasLength(1));
- });
+ expect(rig.api.swarmReads, isEmpty);
+ expect(rig.conn('m').payloadsOf('super_tabs'), hasLength(1));
+ },
+ );
for (final (code, status) in const [
('FORBIDDEN', 403),
@@ -99,7 +105,8 @@ void main() {
final rig = await signedInWith({'m': []});
addTearDown(rig.app.dispose);
rig.api.onSwarmRead = (_) async => throw refusal(code, status);
- rig.conn('m').answers['super_tabs'] = (_) => forwarded('from a machine');
+ rig.conn('m').answers['super_tabs'] = (_) =>
+ forwarded('from a machine');
await expectLater(
rig.app.swarmRequest('GET', path),
@@ -127,7 +134,8 @@ void main() {
final rig = await signedInWith({'m': []});
addTearDown(rig.app.dispose);
rig.api.onSwarmRead = (_) async => throw failure;
- rig.conn('m').answers['super_tabs'] = (_) => forwarded('from a machine');
+ rig.conn('m').answers['super_tabs'] = (_) =>
+ forwarded('from a machine');
expect(await rig.app.swarmRequest('GET', path), 'from a machine');
expect(rig.conn('m').payloadsOf('super_tabs'), hasLength(1));
diff --git a/mobile/test/swarm/swarm_session_test.dart b/mobile/test/swarm/swarm_session_test.dart
index 6feec498a..580e4f868 100644
--- a/mobile/test/swarm/swarm_session_test.dart
+++ b/mobile/test/swarm/swarm_session_test.dart
@@ -108,48 +108,50 @@ void main() {
),
]);
- test('each Swarm sends its chats\' files with the upload handed in',
- () async {
- await features.set(PhoneExperiment.swarm, true);
- final sent = <String>[];
- final h = SwarmHost(
- accountId: () => account.value,
- account: account,
- request: backend().request,
- upload:
- ({
- required tabId,
- required conversationId,
- required name,
- required mime,
- required file,
- required cancel,
- required onProgress,
- }) async {
- sent.add('$tabId/$conversationId/$name');
- return {'attachment': <String, dynamic>{}};
- },
- notices: notices,
- features: features,
- homeCache: home,
- );
- addTearDown(h.dispose);
- final inbox = h.session!.inbox..shown = true;
- await until(() => inbox.reader('a') != null);
-
- final reader = inbox.reader('a')!;
- await reader.upload(
- tabId: reader.tabId,
- conversationId: 'g9',
- name: 'shot.jpg',
- mime: 'image/jpeg',
- file: SwarmOutgoingFile('shot.jpg', Uint8List(1)),
- cancel: CancelToken(),
- onProgress: (_) {},
- );
+ test(
+ 'each Swarm sends its chats\' files with the upload handed in',
+ () async {
+ await features.set(PhoneExperiment.swarm, true);
+ final sent = <String>[];
+ final h = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: backend().request,
+ upload:
+ ({
+ required tabId,
+ required conversationId,
+ required name,
+ required mime,
+ required file,
+ required cancel,
+ required onProgress,
+ }) async {
+ sent.add('$tabId/$conversationId/$name');
+ return {'attachment': <String, dynamic>{}};
+ },
+ notices: notices,
+ features: features,
+ homeCache: home,
+ );
+ addTearDown(h.dispose);
+ final inbox = h.session!.inbox..shown = true;
+ await until(() => inbox.reader('a') != null);
+
+ final reader = inbox.reader('a')!;
+ await reader.upload(
+ tabId: reader.tabId,
+ conversationId: 'g9',
+ name: 'shot.jpg',
+ mime: 'image/jpeg',
+ file: SwarmOutgoingFile('shot.jpg', Uint8List(1)),
+ cancel: CancelToken(),
+ onProgress: (_) {},
+ );
- expect(sent, ['a/g9/shot.jpg']);
- });
+ expect(sent, ['a/g9/shot.jpg']);
+ },
+ );
group('the photos drawn', () {
setUp(() => features.set(PhoneExperiment.swarm, true));
diff --git a/mobile/test/swarm/swarm_special_rows_test.dart b/mobile/test/swarm/swarm_special_rows_test.dart
index 5a468c1bf..a94006573 100644
--- a/mobile/test/swarm/swarm_special_rows_test.dart
+++ b/mobile/test/swarm/swarm_special_rows_test.dart
@@ -4,7 +4,6 @@ import 'package:harness_mobile/notify/system_notices.dart';
import 'package:harness_mobile/settings/experimental_features.dart';
import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
import 'package:harness_mobile/swarm/swarm_session.dart';
-import 'package:harness_mobile/swarm/swarm_thread_page.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../voice_fakes.dart';
@@ -290,7 +289,8 @@ void main() {
});
group('a proposal', () {
- // A message from threads on roots its own thread.
+ // A Buddy's proposal from before plain chat (#2294): its whole text, from
+ // the Buddy, rooting its own thread.
Map<String, dynamic> proposal() => {
...row(
'p1',
@@ -302,37 +302,40 @@ void main() {
'thread': 'p1',
};
- testWidgets('is one line, named by its goal, with no author', (
+ testWidgets('reads whole as an ordinary message from its author', (
tester,
) async {
await show(tester, backend([proposal()]));
- expect(textOf(tester, 'p1'), contains(': Activity read fix'));
- expect(textOf(tester, 'p1'), contains('Proposal from '));
- expect(textOf(tester, 'p1'), isNot(contains('Changes: more words')));
- expect(inRow('p1', find.text('Buddy')), findsNothing);
+ expect(textOf(tester, 'p1'), contains('Changes: more words'));
+ expect(textOf(tester, 'p1'), isNot(contains('Proposal from ')));
+ expect(inRow('p1', find.text('Buddy')), findsOneWidget);
+ expect(find.byKey(const ValueKey('swarm-proposal-label')), findsNothing);
});
- testWidgets('opens its thread, where it reads whole and says for whom', (
- tester,
- ) async {
- final fake = backend([proposal()]);
- fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] =
- (_) => {
- 'messages': [proposal()],
- 'threads': <Object>[],
- 'next': null,
- };
- await show(tester, fake);
- await tester.tap(find.byKey(const ValueKey('swarm-message-p1')));
- await tester.pumpAndSettle();
- expect(find.byType(SwarmThreadPage), findsOneWidget);
- expect(find.textContaining('on '), findsWidgets);
- expect(
- find.byKey(const ValueKey('swarm-proposal-label')),
- findsOneWidget,
- );
- expect(find.textContaining('Changes: more words'), findsOneWidget);
- });
+ testWidgets(
+ 'a plain root names no proposal and opens its thread as any message does',
+ (tester) async {
+ final root = {
+ ...row('p2', 2, "Let's build: Activity read fix", {
+ 'kind': 'buddy-proposal',
+ 'personId': me,
+ 'buddyId': 'buddy-1',
+ }),
+ 'author': {'kind': 'person', 'id': me, 'name': 'Dee'},
+ 'thread': 'p2',
+ };
+ await show(tester, backend([root]));
+ expect(
+ textOf(tester, 'p2'),
+ contains("Let's build: Activity read fix"),
+ );
+ expect(textOf(tester, 'p2'), isNot(contains('Proposal from ')));
+ expect(
+ find.byKey(const ValueKey('swarm-proposal-label')),
+ findsNothing,
+ );
+ },
+ );
});
group('an ordinary message says', () {
diff --git a/mobile/test/swarm/swarm_task_line_shots_test.dart b/mobile/test/swarm/swarm_task_line_shots_test.dart
new file mode 100644
index 000000000..7275e927b
--- /dev/null
+++ b/mobile/test/swarm/swarm_task_line_shots_test.dart
@@ -0,0 +1,140 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+
+import 'swarm_fixture.dart';
+import 'swarm_task_line_test.dart' show taskLine, taskLineBackend, pumpTaskChat;
+
+// Scripted project chat and normal thread, without account or daemon access.
+final shots = Platform.environment['SWARM_TASK_CHAT_SHOTS'];
+
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final emoji = ByteData.sublistView(
+ await File('/System/Library/Fonts/Apple Color Emoji.ttc').readAsBytes(),
+ );
+ // Flutter widget tests have no OS fallback font registry.
+ for (final family in ['Apple Color Emoji', 'Arial']) {
+ await (FontLoader(family)..addFont(Future.value(emoji))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ testWidgets('ordinary task root and details in its phone thread', (
+ tester,
+ ) async {
+ final paletteBefore = AppTheme.palette.value;
+ final brightnessBefore = AppTheme.brightness.value;
+ addTearDown(() {
+ AppTheme.palette.value = paletteBefore;
+ AppTheme.brightness.value = brightnessBefore;
+ });
+ Future<void> capture(GlobalKey boundary, String name) async {
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/$name.png').writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = palette.brightness;
+ final root = {
+ ...taskLine(),
+ 'text': "Let's build: Offline drafts",
+ 'author': {'kind': 'person', 'id': me, 'name': 'Dee'},
+ 'source': {
+ 'kind': 'task-line',
+ 'taskId': 'task-1',
+ 'title': 'Offline drafts',
+ },
+ 'thread': 'line-1',
+ 'reactions': [
+ {
+ 'emoji': 'heart',
+ 'count': 1,
+ 'by': [
+ {'kind': 'person', 'id': me},
+ ],
+ },
+ ],
+ };
+ final boundary = GlobalKey();
+ await pumpTaskChat(
+ tester,
+ taskLineBackend(
+ [root],
+ // Dee's approved thread: the Buddy's proposal, then the PM.
+ replies: [
+ {
+ 'text':
+ 'Goal: Save edits while offline.\n'
+ 'Scope: Desktop and phone drafts.\nPriority: normal',
+ 'author': {
+ 'kind': 'agent',
+ 'id': 'buddy-1',
+ 'name': 'Buddy',
+ 'displayName': "Dee's Buddy",
+ },
+ 'source': {'kind': 'message'},
+ },
+ for (final text in [
+ 'On it: Dune is building it.',
+ 'Ready for review: PR #2710',
+ 'Merged: PR #2710. Ships in the next release.',
+ ])
+ {
+ 'text': text,
+ 'source': {'kind': 'system'},
+ },
+ ],
+ ),
+ boundary: boundary,
+ theme: buildAppTheme(brightness: palette.brightness),
+ );
+ expect(find.text("Let's build: Offline drafts"), findsOneWidget);
+ await capture(boundary, 'task-chat-${palette.brightness.name}');
+ await tester.tap(find.byKey(const ValueKey('swarm-thread-line-line-1')));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Merged: PR #2710. Ships in the next release.'),
+ findsOneWidget,
+ );
+ await capture(boundary, 'task-thread-${palette.brightness.name}');
+ await tester.pumpWidget(const SizedBox());
+ }
+ }, skip: shots == null || !Platform.isMacOS);
+}
diff --git a/mobile/test/swarm/swarm_task_line_test.dart b/mobile/test/swarm/swarm_task_line_test.dart
index 4b10c216f..fd4e994c4 100644
--- a/mobile/test/swarm/swarm_task_line_test.dart
+++ b/mobile/test/swarm/swarm_task_line_test.dart
@@ -1,5 +1,3 @@
-import 'dart:ui' show SemanticsAction;
-
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/notify/system_notices.dart';
@@ -8,7 +6,7 @@ import 'package:harness_mobile/swarm/model.dart';
import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
import 'package:harness_mobile/swarm/swarm_message_row.dart';
import 'package:harness_mobile/swarm/swarm_session.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:harness_mobile/swarm/swarm_thread_page.dart';
import '../voice_fakes.dart';
import 'swarm_fixture.dart';
@@ -46,20 +44,62 @@ Map<String, dynamic> legacyShip(String target, int sequence) => {
FakeSwarm taskLineBackend(
List<Map<String, dynamic>> page, {
bool target = true,
+ List<Map<String, dynamic>>? replies,
}) {
final fake = FakeSwarm();
+ final root = page.firstWhere(
+ (m) => m['thread'] == m['id'],
+ orElse: () => page.first,
+ );
+ final rootId = root['id'] as String;
+ final thread = [
+ for (final (i, reply)
+ in (replies ??
+ [
+ {
+ 'text': 'Goal: Save edits while offline.',
+ 'source': {'kind': 'message'},
+ },
+ ])
+ .indexed)
+ {
+ ...taskLine(id: i == 0 ? 'details' : 'reply-$i', sequence: 3 + i),
+ 'thread': rootId,
+ 'replyTo': rootId,
+ ...reply,
+ },
+ ];
+ final summary = {
+ 'id': rootId,
+ 'replies': thread.length,
+ 'lastSequence': 3,
+ 'authors': <Object>[],
+ 'people': <Object>[],
+ };
fake.routes['/api/super-tabs/list'] = (_) => {
'tabs': [
{'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
],
'next': null,
};
- fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(
- groups: [
- groupData(leadChat, title: 'Project chat', lastMessageSequence: 10),
- if (target) groupData('task-1', title: 'Fix login'),
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ groups: [
+ groupData(
+ leadChat,
+ title: 'Project chat',
+ lastMessageSequence: 10,
+ // Its PM, as a project chat has one.
+ leadId: 'agent-lead',
+ agentIds: ['agent-lead'],
+ ),
+ if (target) groupData('task-1', title: 'Fix login'),
+ ],
+ ),
+ 'members': [
+ part(me, 1, {...person(me), 'email': '[email protected]'}),
],
- );
+ };
fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
fake.routes['/api/super-tabs/$tab/decisions'] = (_) => {
'decisions': <Object>[],
@@ -68,7 +108,17 @@ FakeSwarm taskLineBackend(
'mentions': <Object>[],
};
fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] = (_) =>
- {'messages': page.reversed.toList(), 'threads': <Object>[], 'next': null};
+ {
+ 'messages': page.reversed.toList(),
+ 'threads': [if (root['thread'] != null) summary],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages?thread=$rootId'] =
+ (_) => {
+ 'messages': [root, ...thread],
+ 'threads': [summary],
+ 'next': null,
+ };
fake.routes['/api/super-tabs/$tab/conversations/task-1/messages'] = (_) => {
'messages': [
{
@@ -88,7 +138,12 @@ FakeSwarm taskLineBackend(
return fake;
}
-Future<SwarmHost> pumpTaskChat(WidgetTester tester, FakeSwarm fake) async {
+Future<SwarmHost> pumpTaskChat(
+ WidgetTester tester,
+ FakeSwarm fake, {
+ ThemeData? theme,
+ GlobalKey? boundary,
+}) async {
await tester.binding.setSurfaceSize(const Size(390, 844));
addTearDown(() => tester.binding.setSurfaceSize(null));
final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
@@ -104,9 +159,17 @@ Future<SwarmHost> pumpTaskChat(WidgetTester tester, FakeSwarm fake) async {
)..foreground = false;
addTearDown(host.dispose);
await tester.pumpWidget(
- MaterialApp(
- builder: (context, child) => SwarmScope(notifier: host, child: child!),
- home: const SwarmConversationPage(swarmId: tab, conversationId: leadChat),
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: theme,
+ builder: (context, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmConversationPage(
+ swarmId: tab,
+ conversationId: leadChat,
+ ),
+ ),
),
);
await tester.pumpAndSettle();
@@ -119,6 +182,7 @@ Future<void> pumpRow(
String readerId = me,
double width = 390,
double scale = 1,
+ VoidCallback? onReply,
}) async {
await tester.binding.setSurfaceSize(Size(width, 844));
addTearDown(() => tester.binding.setSurfaceSize(null));
@@ -134,7 +198,11 @@ Future<void> pumpRow(
children: [
SwarmMessageRow(
message: SuperTabMessage.fromJson(data),
- name: 'River',
+ name:
+ data['author'] is Map &&
+ (data['author'] as Map)['kind'] == 'person'
+ ? 'Dee'
+ : 'River',
look: (picture: null, status: null),
role: 'PM',
readerId: readerId,
@@ -142,9 +210,9 @@ Future<void> pumpRow(
grouped: false,
lit: false,
quote: null,
- actions: false,
+ actions: onReply != null,
onTap: () {},
- onReply: null,
+ onReply: onReply,
),
],
),
@@ -154,156 +222,158 @@ Future<void> pumpRow(
}
void main() {
- // Removing dispatch, using fallback text, or mapping any state incorrectly
- // breaks these consumer-visible widget assertions.
- for (final (state, word, mark) in [
- ('planned', 'planned', LucideIcons.circleDashed),
- ('working', 'working', LucideIcons.circleDot),
- ('waiting', 'working', LucideIcons.circleDot),
- ('review', 'in review', LucideIcons.circleDot),
- ('ready', 'ready', LucideIcons.circleDot),
- ('shipped', 'shipped', LucideIcons.check),
- ('done', 'done', LucideIcons.check),
- ('stopped', 'stopped', LucideIcons.circleSlash),
- ]) {
- testWidgets('$state shows the task name, Desktop word and mark', (
+ // Intercepting source kinds before the ordinary row hides the author,
+ // actual text and normal message interactions this contract requires.
+ for (final kind in ['task-line', 'buddy-proposal']) {
+ testWidgets('$kind root keeps requester, actual text and Reply', (
tester,
) async {
- await pumpRow(tester, taskLine(state: state));
- expect(find.text('Fix login'), findsOneWidget);
- expect(find.text(word), findsOneWidget);
- expect(find.byIcon(mark), findsOneWidget);
- expect(find.text('River'), findsNothing);
- expect(find.text('Fix login · $state'), findsNothing);
+ final data = {
+ ...taskLine(),
+ 'text': "Let's build: Offline drafts",
+ 'author': {'kind': 'person', 'id': me, 'name': 'Dee'},
+ 'source': {
+ 'kind': kind,
+ 'title': 'Old metadata title',
+ 'taskId': 'task-1',
+ },
+ };
+ var replies = 0;
+ await pumpRow(tester, data, onReply: () => replies++);
+ expect(find.text('Dee'), findsOneWidget);
+ final avatar = tester.widget<SwarmChatAvatar>(
+ find.byType(SwarmChatAvatar),
+ );
+ expect(avatar.name, 'Dee');
+ expect(avatar.id, me);
+ expect(avatar.agent, isFalse);
+ expect(find.text("Let's build: Offline drafts"), findsOneWidget);
+ expect(find.text('Old metadata title'), findsNothing);
+ await tester.tap(find.byKey(const ValueKey('swarm-reply-line-1')));
+ expect(replies, 1);
+ expect(find.text('Copy'), findsOneWidget);
});
- }
- testWidgets('waiting asks only the named reader to Answer', (tester) async {
- final semantics = tester.ensureSemantics();
- final data = taskLine(state: 'waiting', answerFor: me);
- await pumpRow(tester, data);
- expect(find.text('Answer'), findsOneWidget);
- expect(find.bySemanticsLabel('Fix login, Answer'), findsOneWidget);
- expect(
- tester.widget<Text>(find.text('Answer')).style?.fontWeight,
- FontWeight.w600,
+ testWidgets(
+ '$kind legacy text remains complete on a narrow large-text phone',
+ (tester) async {
+ final text =
+ 'Goal: Save drafts offline.\nScope: Keep edits and attachments after reconnecting.\nPriority: High.';
+ await pumpRow(
+ tester,
+ {
+ ...taskLine(),
+ 'text': text,
+ 'source': {
+ 'kind': kind,
+ 'title': 'Truncated old title',
+ 'taskId': 'missing',
+ },
+ },
+ width: 320,
+ scale: 2,
+ );
+ final body = find.text(text);
+ expect(body, findsOneWidget);
+ expect(tester.widget<Text>(body).maxLines, isNull);
+ expect(find.text('River'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ },
);
- await pumpRow(tester, data, readerId: 'someone-else');
- expect(find.text('Answer'), findsNothing);
- expect(find.text('working'), findsOneWidget);
- semantics.dispose();
- });
-
- testWidgets('unknown state keeps fallback text without inventing a word', (
- tester,
- ) async {
- await pumpRow(tester, taskLine(state: 'future', title: null));
- expect(find.text('Fix login · future'), findsOneWidget);
- expect(find.byIcon(LucideIcons.circleDot), findsOneWidget);
- expect(find.text('working'), findsNothing);
- expect(find.text('River'), findsNothing);
- });
- testWidgets(
- 'long name keeps the word and thumb target on a narrow large-text phone',
- (tester) async {
- final name = List.filled(12, 'A long task name').join(' ');
- await pumpRow(
+ for (final openWith in ['replies', 'Reply']) {
+ testWidgets('$kind $openWith opens the ordinary project thread', (
tester,
- taskLine(title: name, state: 'review'),
- width: 320,
- scale: 2,
- );
- expect(find.text(name), findsOneWidget);
- expect(find.text('in review'), findsOneWidget);
- expect(tester.takeException(), isNull);
- final row = find.byKey(const ValueKey('swarm-message-line-1'));
- expect(tester.getSize(row).height, greaterThanOrEqualTo(44));
- },
- );
-
- testWidgets('tapping a line opens its task chat without a reply action', (
- tester,
- ) async {
- final semantics = tester.ensureSemantics();
- await pumpTaskChat(tester, taskLineBackend([taskLine()]));
- expect(
- tester
- .getSemantics(find.bySemanticsLabel('Fix login, working'))
- .getSemanticsData()
- .hasAction(SemanticsAction.tap),
- isTrue,
- );
- semantics.dispose();
- await tester.tap(find.byKey(const ValueKey('swarm-message-line-1')));
- await tester.pumpAndSettle();
- expect(find.text('Inside the task chat'), findsOneWidget);
- expect(
- tester
- .widget<SwarmConversationPage>(
- find.byType(SwarmConversationPage).last,
- )
- .conversationId,
- 'task-1',
- );
- expect(find.text('Reply in thread'), findsNothing);
- });
-
- for (final target in <Object?>['task-1', 7, null]) {
- testWidgets(
- 'a target absent from the read stays readable without navigation: $target',
- (tester) async {
- final semantics = tester.ensureSemantics();
- final fake = taskLineBackend([taskLine(target: target)], target: false);
+ ) async {
+ final root = {
+ ...taskLine(),
+ 'text': "Let's build: Offline drafts",
+ 'author': {'kind': 'person', 'id': me, 'name': 'Dee'},
+ 'thread': 'line-1',
+ 'source': {'kind': kind, 'taskId': 'task-1', 'title': 'Wrong title'},
+ 'reactions': [
+ {
+ 'emoji': 'heart',
+ 'count': 1,
+ 'by': [
+ {'kind': 'person', 'id': me},
+ ],
+ },
+ ],
+ };
+ final fake = taskLineBackend([root]);
await pumpTaskChat(tester, fake);
- expect(find.text('Fix login'), findsOneWidget);
+ // A person is named by their username ([email protected]).
+ expect(find.text('dee'), findsOneWidget);
expect(
- tester
- .getSemantics(find.bySemanticsLabel('Fix login, working'))
- .getSemanticsData()
- .hasAction(SemanticsAction.tap),
- isFalse,
+ find.byKey(const ValueKey('swarm-author-line-1')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('swarm-reaction-line-1-heart')),
+ findsOneWidget,
);
- await tester.tap(find.byKey(const ValueKey('swarm-message-line-1')));
+ expect(find.text('1 reply'), findsOneWidget);
+ if (openWith == 'Reply') {
+ await tester.tap(find.text("Let's build: Offline drafts"));
+ await tester.pumpAndSettle();
+ expect(find.text('Reply in thread'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('swarm-reply-line-1')));
+ } else {
+ await tester.tap(
+ find.byKey(const ValueKey('swarm-thread-line-line-1')),
+ );
+ }
await tester.pumpAndSettle();
- expect(find.byType(SwarmConversationPage), findsOneWidget);
+ final page = tester.widget<SwarmThreadPage>(
+ find.byType(SwarmThreadPage),
+ );
+ expect(page.root, 'line-1');
+ expect(page.chat.id, leadChat);
+ expect(find.text('Goal: Save edits while offline.'), findsOneWidget);
+ expect(
+ fake.paths,
+ contains(
+ '/api/super-tabs/$tab/conversations/$leadChat/messages?thread=line-1',
+ ),
+ );
expect(
fake.paths.any((p) => p.contains('/conversations/task-1/messages')),
isFalse,
);
- expect(find.text('Copy'), findsNothing);
- semantics.dispose();
- },
- );
+ expect(find.byKey(const ValueKey('swarm-author-line-1')), findsWidgets);
+ });
+ }
}
- for (final lineFirst in [true, false]) {
- testWidgets('a line hides only its task’s legacy ship, order $lineFirst', (
- tester,
- ) async {
- final line = taskLine(sequence: lineFirst ? 1 : 3);
- final ship = legacyShip('task-1', 2);
- await pumpTaskChat(
- tester,
- taskLineBackend([
- if (lineFirst) line,
- ship,
- if (!lineFirst) line,
- legacyShip('other-task', 4),
- ]),
- );
- expect(find.text('Fix login'), findsOneWidget);
- expect(find.text('Shipped: task-1'), findsNothing);
- expect(find.text('Shipped: other-task'), findsOneWidget);
- });
- }
+ testWidgets('legacy task without a target opens ordinary inline Reply', (
+ tester,
+ ) async {
+ final fake = taskLineBackend([taskLine(target: null)], target: false);
+ await pumpTaskChat(tester, fake);
+ expect(find.text('Fix login · working'), findsOneWidget);
+ await tester.tap(find.text('Fix login · working'));
+ await tester.pumpAndSettle();
+ expect(find.text('Reply'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('swarm-reply-line-1')));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('swarm-quote-line-1')), findsNothing);
+ expect(find.textContaining('Reply to'), findsOneWidget);
+ expect(find.byType(SwarmConversationPage), findsOneWidget);
+ });
- testWidgets('a legacy ship stays when no line replaces it', (tester) async {
- await pumpTaskChat(tester, taskLineBackend([legacyShip('task-1', 2)]));
+ testWidgets('legacy ship text stays readable beside an ordinary task root', (
+ tester,
+ ) async {
+ await pumpTaskChat(
+ tester,
+ taskLineBackend([taskLine(), legacyShip('task-1', 3)]),
+ );
+ expect(find.text('Fix login · working'), findsOneWidget);
expect(find.text('Shipped: task-1'), findsOneWidget);
});
- test('a normal message after a task line keeps its author header', () {
+ test('task source follows ordinary same-author grouping', () {
final line = taskLine(sequence: 1);
final normal = {
...taskLine(id: 'normal', sequence: 2),
@@ -315,7 +385,7 @@ void main() {
SuperTabMessage.fromJson(line),
SuperTabMessage.fromJson(normal),
]),
- isEmpty,
+ {'normal'},
);
});
}
diff --git a/mobile/test/swarm/swarm_task_status_shots_test.dart b/mobile/test/swarm/swarm_task_status_shots_test.dart
index bbbf63cf4..8ac61420a 100644
--- a/mobile/test/swarm/swarm_task_status_shots_test.dart
+++ b/mobile/test/swarm/swarm_task_status_shots_test.dart
@@ -254,9 +254,8 @@ void main() {
as RenderRepaintBoundary)
.toImage(pixelRatio: 3);
final png = await image.toByteData(format: ui.ImageByteFormat.png);
- await File(
- '$shots/task-status-$name-${brightness.name}.png',
- ).writeAsBytes(png!.buffer.asUint8List());
+ await File('$shots/task-status-$name-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
image.dispose();
});
await tester.tap(find.byKey(const ValueKey('swarm-menu')));
diff --git a/mobile/test/swarm/swarm_unread_line_test.dart b/mobile/test/swarm/swarm_unread_line_test.dart
index dc54e536b..d5897b72a 100644
--- a/mobile/test/swarm/swarm_unread_line_test.dart
+++ b/mobile/test/swarm/swarm_unread_line_test.dart
@@ -81,4 +81,22 @@ void main() {
reason: 'nothing is older than what was read',
);
});
+
+ test("a message the server posted in the person's name reads nothing "
+ 'before it (plain chat, #2294)', () {
+ SuperTabMessage posted(int sequence, String kind) =>
+ SuperTabMessage.fromJson({
+ 'id': 'm$sequence',
+ 'conversationId': 'g1',
+ 'text': "Let's build: Offline drafts",
+ 'sequence': sequence,
+ 'author': {'kind': 'person', 'id': me, 'name': me},
+ 'source': {'kind': kind},
+ });
+ for (final kind in ['task-line', 'buddy-proposal']) {
+ expect(first([message(1), message(2), posted(3, kind)], 1), 'm2');
+ expect(posted(3, kind).postedForAuthor, isTrue);
+ }
+ expect(mine(4).postedForAuthor, isFalse);
+ });
}
diff --git a/mobile/test/swarm/team_glance_test.dart b/mobile/test/swarm/team_glance_test.dart
index 5ddddbf85..65a232f38 100644
--- a/mobile/test/swarm/team_glance_test.dart
+++ b/mobile/test/swarm/team_glance_test.dart
@@ -150,8 +150,10 @@ void main() {
String? running(
List<Map<String, dynamic>> agents, [
List<Map<String, dynamic>> groups = const [],
- ]) =>
- swarmTeamGlance(swarm(agents: agents, groups: groups), now: now).running;
+ ]) => swarmTeamGlance(
+ swarm(agents: agents, groups: groups),
+ now: now,
+ ).running;
expect(running([]), isNull, reason: 'no agents');
expect(running([agent('a1')]), isNull, reason: 'idle');