The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 10-29 ae: 6 reviewed PRs (#2177, #2202, #2190, #2192, #2214, #2212) (#2220)
0xken15266605782035
diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.tsindex c2f550781..7aea64c65 100644--- a/backend/integration/superTabBuddies.test.ts+++ b/backend/integration/superTabBuddies.test.ts@@ -285,9 +285,11 @@ describe('a Buddy through the store', () => {const pmRead = await new SwarmReads(f.store).firstLoad(owner, f.tab, f.lead)expect(pmRead.groups.find(g => g.key === group)!.data.assignment).toMatchObject({ status: 'lost', lost: { reason: 'its session on Kens-MacBook-Pro.local stopped' } })+ // The lost task's notices are the PM's and its agent's alone (Ken, 2026-10-29): a Buddy reads none of them, and reads the+ // loss on the task and its agent, without the machine.const seen = (await f.store.messages(peer, f.tab, group, {}, agentId)).messages.filter(m => (m.source as { kind?: string } | null)?.kind === 'work-lost')- expect(seen.map(m => m.id).sort()).toEqual(lost.map(m => m.id).sort())- expect(seen.every(m => m.text.includes('its session stopped'))).toBe(true)+ expect(seen).toEqual([])+ for (const m of lost) expect((await f.store.messages(peer, f.tab, group, { messageId: m.id }, agentId)).messages).toEqual([])const read = await new SwarmReads(f.store).firstLoad(peer, f.tab, agentId)expect(read.groups.find(g => g.key === group)!.data.assignment).toMatchObject({ status: 'lost', lost: { reason: 'its session stopped' } })expect(read.agents.find(a => a.key === builder)!.data.lostTask).toMatchObject({ reason: 'its session stopped' })diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.tsindex 67c175615..bfc1590a6 100644--- a/backend/integration/superTabLiveness.test.ts+++ b/backend/integration/superTabLiveness.test.ts@@ -216,7 +216,11 @@ describe('work that loses its owner', () => {await resume()expect(await f.assignment()).toMatchObject({ id: f.assignmentId, agentId: f.worker, status: 'working' })expect((await row()).resume).toBeNull()- expect((await f.leadInbox()).map(m => m.text)).toContain(`${await f.name(f.worker)} resumed its task after its usage limit reset.`)+ const said = `${await f.name(f.worker)} resumed its task after its usage limit reset.`+ const resumed = (await f.leadInbox()).find(m => m.text === said)!+ // The Lead's alone, like the loss it follows: people read the task working again on its status line.+ expect((await f.timed.messages(host, f.tab, resumed.conversationId, {}, f.lead)).messages.map(m => m.id)).toContain(resumed.id)+ expect((await f.timed.messages(owner, f.tab, resumed.conversationId, {})).messages.map(m => m.id)).not.toContain(resumed.id)})// 2026-10-28: a resumed task keeps its id. When its session then stopped, the second loss wrote the first loss's notice@@ -422,6 +426,90 @@ describe('work that loses its owner', () => {expect(notice.text).toBe('Your task "Ship the parser" moved: its session on Worker Mac stopped. Stop working on it; your status and results for it are no longer accepted.')})+ // Ken, 2026-10-29: a notice telling an agent to stop is the agent's alone; people read the cancel on the task itself.+ it('tells the worker of a cancelled task to stop, a notice no person reads, and shows a cancel with nobody to tell', async () => {+ const f = await swarm()+ await f.execute({ type: 'work.cancel', conversationId: f.group, assignmentId: f.assignmentId, reason: 'Not needed' })+ const told = await f.timed.deliveries(host, f.tab, f.worker)+ const notice = (await db.superTabMessage.findMany({ where: { id: { in: told.map(d => d.messageId) } } }))+ .find(m => m.text === 'The tab owner cancelled this task: Not needed. Stop working on it.')!+ const page = async (user: AuthUser, asAgentId?: string) => (await f.timed.messages(user, f.tab, f.group, {}, asAgentId)).messages.map(m => m.id)+ expect(await page(host, f.worker)).toContain(notice.id)+ for (const user of [owner, host]) expect(await page(user)).not.toContain(notice.id)+ expect(await page(host, f.lead)).not.toContain(notice.id)+ expect(await f.assignment()).toMatchObject({ status: 'cancelled', result: 'Not needed' })++ // A lost task's agent was told already: its cancel reaches no agent, so it stays the task's record for people.+ const lost = await swarm()+ await lost.observe('test-host', [], { stoppedHarnessIds: [lost.harness.worker] })+ await lost.execute({ type: 'work.cancel', conversationId: lost.group, assignmentId: lost.assignmentId, reason: 'Not needed' })+ expect((await lost.timed.messages(owner, lost.tab, lost.group, {})).messages.map(m => m.text)).toContain('The tab owner cancelled this task: Not needed.')+ })++ /** A second task whose chat the Lead left before its worker was assigned (a Lead outside a task's chat), or one in+ * `projectId`, a project with no Lead. */+ const withoutLead = async (f: Awaited<ReturnType<typeof swarm>>, projectId?: string) => {+ const group = String((await f.execute({ type: 'conversation.create', title: 'Write the docs', brief: 'Document it', ...(projectId ? { projectId } : {}),+ checks: [{ description: 'Read', independent: false }] } as Command)).result.conversationId)+ if (!projectId) await f.execute({ type: 'conversation.agent', conversationId: group, agentId: f.lead, present: false, lead: false })+ const harness = randomUUID()+ const worker = await f.add(group, 'test-host', harness, 'Writer')+ await f.execute({ type: 'work.assign', conversationId: group, agentId: worker })+ return { group, worker, harness }+ }++ // Review of #2177: a notice that reaches no agent is the people's to act on, so they read it. The old agent's notice still+ // reaches it alone.+ it('shows people a lost-task notice no Lead receives, and keeps the moved notice the agent\'s', async () => {+ const f = await swarm()+ const projectId = String((await f.execute({ type: 'project.create', name: 'No Lead yet', visibility: 'public', brief: '' })).result.projectId)+ const { group, worker, harness } = await withoutLead(f, projectId)+ await f.observe('test-host', [harness], { stoppedHarnessIds: [harness] })+ const rows = (await f.lostRows()).filter(m => m.conversationId === group || m.recipientIds.includes(worker))+ const wake = rows.filter(m => m.text.includes('lost its task'))+ const moved = rows.find(m => m.recipientIds.includes(worker))!+ expect(wake.length).toBeGreaterThan(0)+ expect(wake.every(m => !m.recipientIds.length)).toBe(true)+ const shown = (await f.timed.messages(owner, f.tab, group, {})).messages.map(m => m.id)+ expect(wake.filter(m => m.conversationId === group).map(m => m.id).every(id => shown.includes(id))).toBe(true)+ expect(shown).not.toContain(moved.id)+ })++ // The Lead outside the task's chat hears in its own chat; the task's chat keeps a copy for no one, which is that same notice.+ it('hides the task chat\'s copy of a lost-task notice whose Lead hears it in the project chat', async () => {+ const f = await swarm()+ const { group, harness } = await withoutLead(f)+ await f.observe('test-host', [harness], { stoppedHarnessIds: [harness] })+ const rows = (await f.lostRows()).filter(m => m.text.includes('lost its task "Write the docs"'))+ expect(rows.map(m => [m.conversationId, m.recipientIds])).toEqual(expect.arrayContaining([[group, []], ['lead', [f.lead]]]))+ for (const conversationId of [group, 'lead']) {+ const shown = (await f.timed.messages(owner, f.tab, conversationId, {})).messages.map(m => m.id)+ expect(rows.filter(m => shown.includes(m.id))).toEqual([])+ }+ expect((await f.timed.messages(host, f.tab, 'lead', {}, f.lead)).messages.map(m => m.id)).toEqual(expect.arrayContaining(rows.filter(m => m.conversationId === 'lead').map(m => m.id)))+ })++ // Re-check of #2177: such copies stored before the mark carry none. One whose Lead copy reached the Lead is that same+ // notice and stays hidden; a reply someone wrote in its thread while it was shown reads in the chat.+ it('hides a task chat\'s copy stored without the mark when its Lead copy reached the Lead, and keeps replies under it', async () => {+ const f = await swarm()+ const { group, harness } = await withoutLead(f)+ await f.observe('test-host', [harness], { stoppedHarnessIds: [harness] })+ const copy = (await f.lostRows()).find(m => m.conversationId === group && m.text.includes('lost its task'))!+ const { recipientsOnly: _mark, ...source } = copy.source as Record<string, unknown>+ expect(_mark).toBe(true)+ await db.superTabMessage.update({ where: { id: copy.id }, data: { source: source as Prisma.InputJsonValue } })+ const id = randomUUID().replaceAll('-', '').slice(0, 24)+ await db.superTabMessage.create({ data: { id, tabId: f.tab, conversationId: group, sequence: copy.sequence + 1, author: { kind: 'person', id: owner.sub, name: owner.email },+ text: 'Who takes this?', replyTo: copy.id, thread: copy.id, recipientIds: [], mentions: [] } })+ const page = await f.timed.messages(owner, f.tab, group, {})+ expect(page.messages.map(m => m.id)).not.toContain(copy.id)+ expect(await f.timed.messages(owner, f.tab, group, { messageId: copy.id })).toMatchObject({ messages: [] })+ const reply = page.messages.find(m => m.id === id)!+ expect(reply.thread ?? reply.id).toBe(reply.id)+ expect(page.threads.map(t => t.id)).not.toContain(copy.id)+ })+it('lets the Lead assign the lost work to another agent, and keeps the old one fenced', async () => {const f = await swarm()await f.observe('test-host', [], { stoppedHarnessIds: [f.harness.worker] })@@ -825,6 +913,82 @@ describe('a task that stalls', () => {expect((await f.assignment()).status).toBe('working')})+ // Ken, 2026-10-29: these showed under the Lead's name in the project chat, and people read them as requests to act. They+ // reach only the Lead and the agent; people read the task's state on its status line.+ it('wakes the Lead and tells the worker, but no person or other agent reads the stalled, lost or moved notice', async () => {+ const f = await swarm()+ const posted = f.clock.now+ await f.beat(posted)+ await f.execute({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status: 'working', result: 'Started' }, host, f.worker)+ const inbox = await tick(f, posted + 30 * MINUTE)+ const [stalled] = await stalledRows(f)+ expect(inbox.map(m => m.id)).toContain(stalled!.id)+ f.clock.now += MINUTE+ await f.observe('test-host', [], { stoppedHarnessIds: [f.harness.worker] })+ const wake = (await f.leadInbox()).find(m => (m.source as { kind?: string }).kind === 'work-lost')!+ const told = await f.timed.deliveries(host, f.tab, f.worker)+ const moved = (await db.superTabMessage.findMany({ where: { id: { in: told.map(d => d.messageId) } } }))+ .find(m => (m.source as { kind?: string }).kind === 'work-lost')!+ expect(moved.text).toContain('Stop working on it')+ const notices = [stalled!, wake, moved]+ const ids = notices.map(m => m.id)+ const page = async (user: AuthUser, conversationId: string, asAgentId?: string, messageId?: string) =>+ (await f.timed.messages(user, f.tab, conversationId, messageId ? { messageId } : {}, asAgentId)).messages.map(m => m.id)+ // Each recipient reads its own notice where it was written.+ expect(await page(host, stalled!.conversationId, f.lead)).toContain(stalled!.id)+ expect(await page(host, wake.conversationId, f.lead)).toContain(wake.id)+ expect(await page(host, moved.conversationId, f.worker)).toContain(moved.id)+ // People read none of them: not in the project chat, not in the task's chat, not by its id, which reads as no such message.+ // Neither the Lead's owner (the tab's owner added it) nor its machine's owner: each reads as a person, not as the agent.+ expect((await f.timed.read(owner, f.tab)).state.agents.find(a => a.id === f.lead)).toMatchObject({ contributorId: owner.sub, machineOwnerId: host.sub })+ for (const user of [owner, host]) {+ for (const conversationId of new Set(notices.map(m => m.conversationId))) {+ expect((await page(user, conversationId)).filter(id => ids.includes(id))).toEqual([])+ }+ for (const m of notices) expect(await page(user, m.conversationId, undefined, m.id)).toEqual([])+ }+ // Nor does an agent it is not for: the worker never reads the Lead's wake, nor the Lead the worker's notice.+ expect(await page(host, wake.conversationId, f.worker, wake.id)).toEqual([])+ expect(await page(host, moved.conversationId, f.lead, moved.id)).toEqual([])+ // Nothing a person must act on is hidden: the task's own state says it is lost.+ expect(await liveness(f)).toBeDefined()+ expect((await f.assignment()).status).toBe('lost')+ })++ // Its delivery invites the Lead to reply to it. A reply joins its message's thread, which people open from its root: under+ // a notice they cannot read, the Lead's answer to them would be hidden too.+ it('lists the Lead\'s reply to a stalled alert in the chat people read, not in a thread under the alert', async () => {+ const f = await swarm()+ const posted = f.clock.now+ await f.beat(posted)+ await f.execute({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status: 'working', result: 'Started' }, host, f.worker)+ await tick(f, posted + 30 * MINUTE)+ const [stalled] = await stalledRows(f)+ const sent = await f.execute({ type: 'message.send', conversationId: stalled!.conversationId, text: 'I nudged the worker.', replyTo: stalled!.id,+ recipientIds: [] } as Command, host, f.lead)+ const shown = (await f.timed.messages(owner, f.tab, stalled!.conversationId, {})).messages.find(m => m.id === sent.result.messageId)!+ expect(shown.thread ?? shown.id).toBe(shown.id)+ expect(shown.text).toBe('I nudged the worker.')+ })++ // Review of #2177: before the fix above, a Lead's reply to a stalled alert was stored in the alert's thread. With the alert+ // hidden, people could not open that thread, so such a reply reads as one in the chat.+ it('lists a reply already stored in a stalled alert\'s thread in the chat people read', async () => {+ const f = await swarm()+ const posted = f.clock.now+ await f.beat(posted)+ await f.execute({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status: 'working', result: 'Started' }, host, f.worker)+ await tick(f, posted + 30 * MINUTE)+ const [stalled] = await stalledRows(f)+ const id = randomUUID().replaceAll('-', '').slice(0, 24)+ await db.superTabMessage.create({ data: { id, tabId: f.tab, conversationId: stalled!.conversationId, sequence: stalled!.sequence + 1,+ author: stalled!.author as Prisma.InputJsonValue, text: 'I nudged the worker.', replyTo: stalled!.id, thread: stalled!.id, recipientIds: [], mentions: [] } })+ const page = await f.timed.messages(owner, f.tab, stalled!.conversationId, {})+ const reply = page.messages.find(m => m.id === id)!+ expect(reply.thread ?? reply.id).toBe(reply.id)+ expect(page.threads.map(t => t.id)).not.toContain(stalled!.id)+ })+it('is orphaned when its agent is removed, and the Lead is woken once by the next time checks', async () => {const f = await swarm()await f.beat(f.clock.now)@@ -929,6 +1093,10 @@ describe('the delivery poll of an agent with nothing waiting', () => {f.clock.now += 5 * MINUTEconst told = await f.leadInbox()expect(told.map(m => (m.source as { kind?: string }).kind)).toEqual(['update-request'])+ // It is the Lead's to act on, with a command to run: the Lead reads it in its chat, and the people there do not.+ const read = async (asAgentId?: string) => (await f.timed.messages(asAgentId ? host : owner, f.tab, told[0]!.conversationId, {}, asAgentId)).messages.map(m => m.id)+ expect(await read(f.lead)).toContain(told[0]!.id)+ expect(await read()).not.toContain(told[0]!.id)})// Prod, 2026-10-28: a Lead's host received an update request on 26 Oct and the Lead never answered it. Every later poll@@ -1185,7 +1353,8 @@ describe('the delivery poll of an agent with a held delivery', () => {expect(first).toHaveLength(3)await f.timed.delivery(host, f.tab, f.lead, first[0]!.id, { type: 'claim', claimId: 'claim-1' })await f.timed.delivery(host, f.tab, f.lead, first[0]!.id, { type: 'hold', claimId: 'claim-1', reason: 'team_waiting_user' })- const page = (await f.timed.messages(owner, f.tab, 'lead', {})).messages.filter(row => expectedIds.includes(row.id))+ // The Lead's alone, so it reads their order (people do not read them).+ const page = (await f.timed.messages(host, f.tab, 'lead', {}, f.lead)).messages.filter(row => expectedIds.includes(row.id))f.clock.now += 1_000await f.timed.deliveries(host, f.tab, f.lead)// Stored later sequence first, so insertion order cannot stand in for the tie-break; no Swarm write, so the stamp stays.@@ -1261,7 +1430,8 @@ describe('the push for a new delivery', () => {expect(first).toHaveLength(3)expect(new Set(first.map(row => row.messageId))).toEqual(new Set(expectedIds))expect(new Set(first.map(row => row.createdAt.getTime())).size).toBe(1)- const page = (await f.timed.messages(owner, f.tab, 'lead', {})).messages.filter(row => expectedIds.includes(row.id))+ // The Lead's alone, so it reads their order (people do not read them).+ const page = (await f.timed.messages(host, f.tab, 'lead', {}, f.lead)).messages.filter(row => expectedIds.includes(row.id))expect(page).toHaveLength(3)expect(page[1]!.sequence).toBe(page[0]!.sequence + 1)expect(page[2]!.sequence).toBe(page[1]!.sequence + 1)@@ -1411,6 +1581,10 @@ describe('the morning digest', () => {expect(counted.ops).not.toContain('SuperTabDecision.groupBy')const digest = (await db.superTabMessage.findMany({ where: { tabId: f.tab } })).find(m => (m.source as { kind?: string } | null)?.kind === 'digest-request')!expect(digest.text).toMatch(/\nDecisions waiting:\n- #1 Ship the parser: 2 for owner@example\.com$/)+ // The Lead's to write up: the people in its chat read the digest it posts, not this request.+ const read = async (asAgentId?: string) => (await f.timed.messages(asAgentId ? host : owner, f.tab, digest.conversationId, {}, asAgentId)).messages.map(m => m.id)+ expect(await read(f.lead)).toContain(digest.id)+ expect(await read()).not.toContain(digest.id)})it('lists a decision still waiting in a conversation that has gone quiet', async () => {diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.tsindex 5088aa309..90bdbe0cf 100644--- a/backend/integration/superTabRead.test.ts+++ b/backend/integration/superTabRead.test.ts@@ -20,6 +20,7 @@ import { decisionsWaiting } from '../src/superTabs/decisions.js'import { buddyChatId } from '../src/superTabs/buddies.js'import { HostReads } from '../src/superTabs/read/host.js'import type { Conversation, SuperTabState } from '../src/superTabs/model.js'+import { sendsEmptyIn, watched, type Query } from '../src/lib/queryRecorder.test-support.js'import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'import { NOW, outsider as outsiderActor, owner as ownerActor, peer as peerActor, swarm } from '../src/superTabs/read/fixture.test-support.js'@@ -345,6 +346,18 @@ describe('Swarm list and old routes (design 4.9, 4.11)', () => {expect(body.data.tabs).toContainEqual({ id: s.tabId, name: 'Pilot', ownerId: owner.sub, workspaceId: null, paused: false, lastChangedAt: MIGRATED })})+ it('sends no empty id list to the database, for a person with no Swarm or with Swarms all in parts', async () => {+ await scene()+ const queries: Query[] = []+ const reads = new SwarmReads(new SuperTabStore(watched(db, queries)), { now: () => clock })++ expect((await reads.list(outsider)).tabs.length).toBeGreaterThan(0)+ expect((await reads.list({ ...outsider, sub: 'u-without-swarms' })).tabs).toEqual([])++ expect(queries.some(q => q.model === 'superTab')).toBe(true)+ expect(queries.filter(sendsEmptyIn)).toEqual([])+ })+it('reads each Swarm\'s newest change over all its parts, without a groupBy (it once panicked the engine on Mongo)', async () => {const [a, b] = [await scene(), await scene()]await writeGroup(b.tabId, b.web, MIGRATED + 5_000, group => { group.title = 'Web, renamed' })diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 922b293bf..88a898634 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -916,6 +916,39 @@ describe('Super Tabs on a real Mongo replica set', () => {expect(await runs()).toEqual([['moonshotai/kimi-k3', true], ['moonshotai/kimi-k3', true]])})+ it('rates a Reviewer launched on its engine\'s default by the default row after it reports its model, its start finished', async () => {+ // Live bug 10-29: a command does not load a finished start, so a Codex Reviewer that reported gpt-6.1-sol was rated 1.+ const tab = (await store.create(owner, randomUUID(), 'Default pool')).id+ const invitation = await run(tab, { type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)+ await db.machine.create({ data: { machineId: 'default-host', userId: host.sub, apiKey: 'fixture-default-host', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ const team = await teamMachine('default-host')+ await run(tab, { type: 'machine.contribute', machineId: 'default-host', name: 'Default laptop', cwd: '/project', engines: ['codex'], maxAgents: 2 }, host)+ const generation = (await poolRows(store, team.session, 'default-host'))[0]!.machine.generation+ await store.observeMachine(team.session, tab, 'default-host', { generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,+ diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture CPU', os: 'macOS', gpuPercent: null },+ quotas: [], tools: { git: true }, runningHarnessIds: [], stoppedHarnessIds: [], privacy: team.privacy })+ const group = String((await run(tab, { type: 'conversation.create', title: 'Fix', brief: 'Fix it.',+ checks: [{ description: 'Independent review', independent: true }] })).result.conversationId)+ const review = async () => String((await run(tab, { type: 'conversation.create', title: 'Review', brief: 'Review it.', reviewOf: group,+ checks: [{ description: 'Verdict', independent: false }] })).result.conversationId)+ const first = await review()+ const startId = String((await run(tab, { type: 'agent.start', request: { conversationId: first, role: 'reviewer', machineId: 'default-host', engine: 'codex',+ name: 'Reviewer', cwd: '/project', worktree: true, requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } })).result.startId)+ const hostRun = (command: Command) => store.execute(team.session, tab, { operationId: randomUUID(), command }, undefined, 'default-host')+ await hostRun({ type: 'agent.startDispatch', startId })+ const agentId = String((await hostRun({ type: 'agent.started', startId, harnessId: 'default-reviewer',+ configuration: { engine: 'codex', model: null, effort: null, contextWindow: null, engineVersion: null } })).result.agentId)+ await hostRun({ type: 'agent.startSettled', startId, warning: null })+ const assign = async (conversationId: string) => (await run(tab, { type: 'work.assign', conversationId, agentId })).result.warnings+ expect(await assign(first)).toBeUndefined()+ const previousVersion = (await storedState(tab)).agents.find(a => a.id === agentId)!.configurationVersion!+ await run(tab, { type: 'agent.configuration', previousVersion, configuration: { engine: 'codex', model: 'gpt-6.1-sol', effort: null, contextWindow: null, engineVersion: null } }, team.session, agentId)+ const firstWork = (await store.read(owner, tab)).state.conversations.find(c => c.id === first)!.assignment!.id+ await run(tab, { type: 'work.cancel', conversationId: first, assignmentId: firstWork, reason: 'Again.' })+ expect(await assign(await review())).toBeUndefined()+ })+it('tells a contributed machine its start\'s project skills, which its host cannot read from the Swarm', async () => {// Prod logs 2026-10-28: the host asked for a Swarm status read it may not make (a 400 at every start), then launched// every agent on Harness orchestration, whatever its project ran.@@ -996,6 +1029,51 @@ describe('Super Tabs on a real Mongo replica set', () => {await expect(store.start(team.session, tab, startId, undefined, 'pool-host')).rejects.toMatchObject({ code: 'FORBIDDEN' })})+ // Ken, 2026-10-28: work kept landing on engines that could not run on their machine. Two failed starts suspend the engine+ // there, saved with the machine; a reading that shows it signed in with quota, or its owner, offers it again.+ it('suspends an engine after two failed starts on a machine, keeps why its allowance is unknown, and offers it again', async () => {+ const tab = (await store.create(owner, randomUUID(), 'Engine health')).id+ const invitation = await run(tab, { type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)+ await db.machine.create({ data: { machineId: 'health-host', userId: host.sub, apiKey: 'fixture-health-only', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ const team = await teamMachine('health-host')+ await run(tab, { type: 'machine.contribute', machineId: 'health-host', name: 'Health laptop', cwd: '/project', engines: ['codex'], maxAgents: 2 }, host)+ const generation = (await poolRows(store, team.session, 'health-host'))[0]!.machine.generation+ const observation = { generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9, diskTotalBytes: 500e9,+ projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture CPU', os: 'macOS', gpuPercent: null }, tools: { git: true }, runningHarnessIds: [], stoppedHarnessIds: [],+ privacy: team.privacy, quotas: [{ engine: 'codex', known: false, windows: [] }], quotaReasons: { codex: 'OpenAI could not be reached.' } }+ await store.observeMachine(team.session, tab, 'health-host', observation)+ const pool = async () => (await store.read(owner, tab)).state.machines!.find(m => m.machineId === 'health-host')! as Record<string, any>+ expect((await pool()).observation.quotaReasons).toEqual({ codex: 'OpenAI could not be reached.' })+ const request = { permissionMode: 'full', conversationId: 'lead', machineId: 'health-host', engine: 'codex', name: 'Builder', cwd: '/project', worktree: true,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }+ const hostRun = (command: Command) => store.execute(team.session, tab, { operationId: randomUUID(), command }, undefined, 'health-host')+ for (let i = 0; i < 2; i++) {+ const startId = (await run(tab, { type: 'agent.start', request })).result.startId as string+ await hostRun({ type: 'agent.startDispatch', startId })+ await hostRun({ type: 'agent.startFailed', startId, error: 'Codex could not launch.' })+ }+ expect((await pool()).suspendedEngines).toEqual({ codex: expect.stringContaining('Codex is suspended on this machine for new work') })+ const notices = (await store.messages(owner, tab, 'lead', {})).messages.filter(m => m.text.includes('Codex is suspended'))+ expect(notices.map(m => m.mentions)).toEqual([[host.sub]])+ await expect(run(tab, { type: 'agent.start', request })).rejects.toMatchObject({ code: 'ENGINE_UNAVAILABLE' })+ // Signed in, with quota left: the reading offers it again.+ await store.observeMachine(team.session, tab, 'health-host', { ...observation, quotaReasons: undefined,+ quotas: [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 10, resetsAt: null }] }],+ readiness: { engines: [{ engine: 'codex', installed: true, signedIn: true }] } })+ expect((await pool()).suspendedEngines).toBeUndefined()+ // Suspended again, and resumed by its owner.+ for (let i = 0; i < 2; i++) {+ const startId = (await run(tab, { type: 'agent.start', request })).result.startId as string+ await hostRun({ type: 'agent.startDispatch', startId })+ await hostRun({ type: 'agent.startFailed', startId, error: 'Codex could not launch.' })+ }+ expect((await pool()).suspendedEngines).toHaveProperty('codex')+ await expect(run(tab, { type: 'machine.engineResume', machineId: 'health-host', engine: 'codex' })).rejects.toMatchObject({ code: 'OWNER_REQUIRED' })+ await run(tab, { type: 'machine.engineResume', machineId: 'health-host', engine: 'codex' }, host)+ expect((await pool()).suspendedEngines).toBeUndefined()+ })+it('resolves a reply beyond recent history without crossing conversation or membership boundaries', async () => {const { tab, lead } = await fixture()const question = (await run(tab, message('Should pending edits survive restart?'), host, lead)).result.messageId as stringdiff --git a/backend/src/lib/agentMessageShares.test.ts b/backend/src/lib/agentMessageShares.test.tsindex fd37deeae..2f21a4e70 100644--- a/backend/src/lib/agentMessageShares.test.ts+++ b/backend/src/lib/agentMessageShares.test.ts@@ -241,6 +241,20 @@ describe('agent message shares', () => {expect((await pendingWith('text'))[0].tabName).toBe('')})+ it('asks for no share and no account when the person has no invitation', async () => {+ p.agentMessageInvite.findMany.mockResolvedValue([])+ expect(await pendingInvites('[email protected]', 'prod')).toEqual([])+ expect(p.agentMessageShare.findMany).not.toHaveBeenCalled()+ expect(p.user.findMany).not.toHaveBeenCalled()+ })++ it('asks for no account when every invitation is of a stopped share', async () => {+ p.agentMessageInvite.findMany.mockResolvedValue([{ id: 'i1', shareId: S, ownerUserId: 'alice', ownerMachineId: 'm1', expiresAt: new Date('2030-01-01T00:00:00Z') }])+ p.agentMessageShare.findMany.mockResolvedValue([])+ expect(await pendingInvites('[email protected]', 'prod')).toEqual([])+ expect(p.user.findMany).not.toHaveBeenCalled()+ })+it('hides the invitations of a stopped share', async () => {const expiresAt = new Date('2030-01-01T00:00:00Z')p.agentMessageInvite.findMany.mockResolvedValue([{ id: 'i1', shareId: S, ownerUserId: 'alice', ownerMachineId: 'm1', expiresAt }])@@ -445,6 +459,14 @@ describe('agent message shares', () => {select: { id: true, email: true, expiresAt: true } })})+ it('lists nothing for a person with no share, asking for no account and sending no empty id list', async () => {+ p.agentMessageMember.findMany.mockResolvedValue([])+ p.agentMessageShare.findMany.mockResolvedValue([])+ expect(await listShares('bob', 'prod')).toEqual([])+ expect(p.agentMessageShare.findMany).toHaveBeenCalledWith({ where: { autonomousEnv: 'prod', stoppedAt: null, OR: [{ ownerUserId: 'bob' }] } })+ expect(p.user.findMany).not.toHaveBeenCalled()+ })+it('falls back to an empty owner email in a listing', async () => {p.agentMessageMember.findMany.mockResolvedValue([])p.agentMessageShare.findMany.mockResolvedValue([{ id: 'S2', ownerUserId: 'gone', ownerMachineId: 'm7', tabId: 't', rosterVersion: 1, roster: null }])diff --git a/backend/src/lib/agentMessageShares.ts b/backend/src/lib/agentMessageShares.tsindex 051aae6d9..ca4b8ac34 100644--- a/backend/src/lib/agentMessageShares.ts+++ b/backend/src/lib/agentMessageShares.ts@@ -130,9 +130,10 @@ export async function pendingInvites(email: string, autonomousEnv: string): Promconst found = await prisma.agentMessageInvite.findMany({ where: { email: email.trim().toLowerCase(), autonomousEnv,acceptedAt: null, revokedAt: null, expiresAt: { gt: new Date() } } })// One read for every listed invitation's share: the liveness and the name come from the same rows.- const live = new Map((await prisma.agentMessageShare.findMany({ where: { id: { in: found.map(r => r.shareId) }, stoppedAt: null }, select: { id: true, roster: true } })).map(s => [s.id, s.roster]))+ const shares = found.length ? await prisma.agentMessageShare.findMany({ where: { id: { in: found.map(r => r.shareId) }, stoppedAt: null }, select: { id: true, roster: true } }) : []+ const live = new Map(shares.map(s => [s.id, s.roster]))const rows = found.filter(r => live.has(r.shareId))- const owners = await prisma.user.findMany({ where: { id: { in: rows.map(r => r.ownerUserId) } }, select: { id: true, email: true } })+ const owners = rows.length ? await prisma.user.findMany({ where: { id: { in: rows.map(r => r.ownerUserId) } }, select: { id: true, email: true } }) : []const emailOf = new Map(owners.map(o => [o.id, o.email]))return rows.map(r => ({ id: r.id, sharedTabId: r.shareId, ownerEmail: emailOf.get(r.ownerUserId) ?? '',ownerMachineId: r.ownerMachineId, expiresAt: r.expiresAt.toISOString(), tabName: rosterName(live.get(r.shareId)) }))@@ -195,8 +196,8 @@ export async function moveShare(ownerUserId: string, shareId: string, machineId:export async function listShares(userId: string, autonomousEnv: string): Promise<ShareView[]> {const memberships = await prisma.agentMessageMember.findMany({ where: { userId, removedAt: null }, select: { shareId: true } })const shares = await prisma.agentMessageShare.findMany({ where: { autonomousEnv, stoppedAt: null,- OR: [{ ownerUserId: userId }, { id: { in: memberships.map(m => m.shareId) } }] } })- const owners = await prisma.user.findMany({ where: { id: { in: shares.map(s => s.ownerUserId) } }, select: { id: true, email: true } })+ OR: [{ ownerUserId: userId }, ...memberships.length ? [{ id: { in: memberships.map(m => m.shareId) } }] : []] } })+ const owners = shares.length ? await prisma.user.findMany({ where: { id: { in: shares.map(s => s.ownerUserId) } }, select: { id: true, email: true } }) : []const emailOf = new Map(owners.map(o => [o.id, o.email]))return Promise.all(shares.map(async (s): Promise<ShareView> => {const view = { sharedTabId: s.id, owner: s.ownerUserId === userId, ownerEmail: emailOf.get(s.ownerUserId) ?? '',diff --git a/backend/src/lib/emptyInList.test-support.ts b/backend/src/lib/emptyInList.test-support.tsnew file mode 100644index 000000000..cf31b9d56--- /dev/null+++ b/backend/src/lib/emptyInList.test-support.ts@@ -0,0 +1,84 @@+/**+ * Finds reads that can send an empty `in` list to Prisma on MongoDB (Database optimization roadmap, phase 0.3). Prisma turns+ * `in: []` into `$or: []`, which no index serves: a scan of the whole collection that returns nothing, seen in the slow log on+ * machines, users and SuperTab. A read of one of those models (or a raw `$in`) that names a list held in a variable must test+ * that list's `.length` or `.size` first in the same function (an `if`, a `?:` or `&&`), or pass a literal list or a constant.+ * A `.map` or a `new Set` of a list is empty exactly when that list is, so a test of the source list counts; a `.filter` is+ * not: name the filtered list and test that.+ */+import ts from 'typescript'++/** The collections the slow log names. */+export const GUARDED_MODELS = new Set(['machine', 'user', 'superTab'])++export interface Unguarded { file: string; line: number; list: string }++const isCondition = (node: ts.Node): boolean => ts.isIfStatement(node) || ts.isConditionalExpression(node)+ || (ts.isBinaryExpression(node) && (node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken || node.operatorToken.kind === ts.SyntaxKind.BarBarToken))+const conditionText = (node: ts.Node): string => ts.isIfStatement(node) || ts.isConditionalExpression(node) ? node.getChildAt(ts.isIfStatement(node) ? 2 : 0).getText() : node.getText()+const isListName = (node: ts.Expression): boolean => ts.isIdentifier(node) || (ts.isPropertyAccessExpression(node) && isListName(node.expression))+const CONSTANT = /^[A-Z][A-Z0-9_]*$/++/** The list a `.map(...)` or `[...new Set(list)]` is as long as; the expression itself for anything else. */+function listOf(node: ts.Expression): ts.Expression {+ if (ts.isParenthesizedExpression(node)) return listOf(node.expression)+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === 'map') return listOf(node.expression.expression)+ if (ts.isArrayLiteralExpression(node) && node.elements.length === 1 && ts.isSpreadElement(node.elements[0]!)) {+ const spread = node.elements[0].expression+ if (ts.isNewExpression(spread) && spread.expression.getText() === 'Set' && spread.arguments?.length === 1) return listOf(spread.arguments[0]!)+ }+ return node+}++export function unguardedInLists(source: string, file: string): Unguarded[] {+ const sf = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true)+ const found: Unguarded[] = []+ /** The lists whose emptiness is the list's: itself, its source, and what a `const` it names was built from. */+ const sameAs = (scope: ts.Node, expression: ts.Expression): string[] => {+ const base = listOf(expression)+ const names = [base.getText()]+ if (ts.isIdentifier(base)) {+ const declared = (node: ts.Node) => {+ if (ts.isVariableDeclaration(node) && node.name.getText() === base.text && node.initializer) names.push(...sameAs(scope, node.initializer))+ ts.forEachChild(node, declared)+ }+ declared(scope)+ }+ return names+ }+ const guarded = (call: ts.Node, expression: ts.Expression): boolean => {+ let scope: ts.Node | undefined = call.parent+ while (scope && !ts.isFunctionLike(scope)) scope = scope.parent+ const names = sameAs(scope ?? sf, expression)+ const tests = (node: ts.Node) => names.some(list => [`${list}.length`, `${list}.size`].some(text => conditionText(node).includes(text)))+ let ok = false+ const visit = (node: ts.Node) => {+ if (node.getStart() >= call.getStart()) return+ if (isCondition(node) && tests(node)) ok = true+ ts.forEachChild(node, visit)+ }+ ts.forEachChild(scope ?? sf, visit)+ // A guard around the call itself: `ids.length ? await read(ids) : []`.+ for (let up: ts.Node | undefined = call.parent; up && up !== scope; up = up.parent) if (isCondition(up) && tests(up)) ok = true+ return ok+ }+ const visitCall = (node: ts.Node) => {+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isPropertyAccessExpression(node.expression.expression)+ && GUARDED_MODELS.has(node.expression.expression.name.text)) {+ const lookFor = (inner: ts.Node) => {+ if (ts.isPropertyAssignment(inner) && ['in', '$in'].includes(inner.name.getText().replaceAll(/['"]/g, ''))+ && !ts.isArrayLiteralExpression(inner.initializer) && !(ts.isIdentifier(inner.initializer) && CONSTANT.test(inner.initializer.text))) {+ const list = inner.initializer.getText()+ if (!(isListName(listOf(inner.initializer)) && guarded(node, inner.initializer))) {+ found.push({ file, line: sf.getLineAndCharacterOfPosition(inner.getStart()).line + 1, list })+ }+ }+ ts.forEachChild(inner, lookFor)+ }+ node.arguments.forEach(lookFor)+ }+ ts.forEachChild(node, visitCall)+ }+ visitCall(sf)+ return found+}diff --git a/backend/src/lib/emptyInList.test.ts b/backend/src/lib/emptyInList.test.tsnew file mode 100644index 000000000..bd7be6664--- /dev/null+++ b/backend/src/lib/emptyInList.test.ts@@ -0,0 +1,54 @@+import { readdirSync, readFileSync, statSync } from 'node:fs'+import { join, relative } from 'node:path'+import { describe, expect, it } from 'vitest'+import { unguardedInLists } from './emptyInList.test-support.js'++const lint = (code: string) => unguardedInLists(code, 'case.ts').map(f => f.list)++describe('the empty id list check', () => {+ it('flags a list in a variable that is never tested first', () => {+ expect(lint(`async function f(tx, ids: string[]) { return tx.machine.findMany({ where: { machineId: { in: ids } } }) }`)).toEqual(['ids'])+ expect(lint(`async function f(tx, rows) { return tx.user.findMany({ where: { id: { in: rows.map(r => r.id) } } }) }`)).toEqual(['rows.map(r => r.id)'])+ expect(lint(`async function f(db, ids) { return db.superTab.findMany({ where: { id: { in: ids } } }) }`)).toEqual(['ids'])+ expect(lint(`async function f(db, ids) { return db.superTab.aggregateRaw({ pipeline: [{ $match: { _id: { $in: ids } } }] }) }`)).toEqual(['ids'])+ })++ it('accepts a list tested earlier in the function, or around the call', () => {+ expect(lint(`async function f(tx, ids) { if (!ids.length) return []; return tx.machine.findMany({ where: { machineId: { in: ids } } }) }`)).toEqual([])+ expect(lint(`async function f(tx, share) { return share.emails.length ? tx.user.findMany({ where: { email: { in: share.emails } } }) : [] }`)).toEqual([])+ expect(lint(`async function f(tx, ids) { return ids.size && tx.user.findMany({ where: { id: { in: ids } } }) }`)).toEqual([])+ })++ it('does not count a test in another function, or one after the read', () => {+ expect(lint(`function a(ids) { if (!ids.length) return }\nasync function f(tx, ids) { return tx.machine.findMany({ where: { machineId: { in: ids } } }) }`)).toEqual(['ids'])+ expect(lint(`async function f(tx, ids) { const rows = await tx.machine.findMany({ where: { machineId: { in: ids } } }); if (!ids.length) return [] }`)).toEqual(['ids'])+ })++ it('counts a test of the list a map or a set was built from, not of a filtered one', () => {+ expect(lint(`async function f(tx, rows) { if (!rows.length) return []; return tx.user.findMany({ where: { id: { in: rows.map(r => r.id) } } }) }`)).toEqual([])+ expect(lint(`async function f(tx, rows) { if (!rows.length) return []; return tx.user.findMany({ where: { id: { in: [...new Set(rows.map(r => r.id))] } } }) }`)).toEqual([])+ expect(lint(`async function f(tx, rows) { if (!rows.length) return []; return tx.user.findMany({ where: { id: { in: rows.filter(r => r.ok).map(r => r.id) } } }) }`))+ .toEqual(['rows.filter(r => r.ok).map(r => r.id)'])+ })++ it('follows a const to what it was built from', () => {+ expect(lint(`async function f(tx, usable) { if (!usable.length) return []; const ids = [...new Set(usable.map(u => u.id))]; return tx.user.findMany({ where: { id: { in: ids } } }) }`)).toEqual([])+ expect(lint(`async function f(tx, usable) { const ids = usable.filter(u => u.ok); return tx.user.findMany({ where: { id: { in: ids } } }) }`)).toEqual(['ids'])+ })++ it('accepts a literal list, a constant and other models', () => {+ expect(lint(`async function f(tx) { return tx.machine.findMany({ where: { authMode: { in: BILLED_MODES } } }) }`)).toEqual([])+ expect(lint(`async function f(tx) { return tx.machine.findMany({ where: { sessionKind: { in: ['team', 'person'] } } }) }`)).toEqual([])+ expect(lint(`async function f(tx, ids) { return tx.swarmMachine.findMany({ where: { tabId: { in: ids } } }) }`)).toEqual([])+ })++ it('finds none in the backend: no read of machines, users or SuperTab can send an empty list', () => {+ const root = join(process.cwd(), 'src')+ const files = (dir: string): string[] => readdirSync(dir).flatMap(name => {+ const path = join(dir, name)+ return statSync(path).isDirectory() ? files(path) : /\.ts$/.test(name) && !/\.test(-support)?\.ts$/.test(name) ? [path] : []+ })+ const found = files(root).flatMap(file => unguardedInLists(readFileSync(file, 'utf8'), relative(process.cwd(), file)))+ expect(found.map(f => `${f.file}:${f.line} ${f.list}`)).toEqual([])+ })+})diff --git a/backend/src/lib/queryRecorder.test-support.ts b/backend/src/lib/queryRecorder.test-support.tsnew file mode 100644index 000000000..d178c7f06--- /dev/null+++ b/backend/src/lib/queryRecorder.test-support.ts@@ -0,0 +1,43 @@+/** Records the model calls a function sends to Prisma, to prove a read is not sent at all (empty id lists, phase 0.3). */+export interface Query { model: string; op: string; args: unknown }++/** Whether a query holds an empty `in` or `$in` list anywhere: what Prisma turns into `$or: []`, a scan of the collection. */+export function sendsEmptyIn(query: Query): boolean {+ const walk = (value: unknown): boolean => Array.isArray(value) ? value.some(walk)+ : value && typeof value === 'object' ? Object.entries(value).some(([key, inner]) => (['in', '$in'].includes(key) && Array.isArray(inner) && !inner.length) || walk(inner))+ : false+ return walk(query.args)+}++/** A client or transaction that answers every model call with nothing (`[]` for lists and raw reads, null for one row), unless+ * `answers` gives `model.op`, and records each call. */+export function recordingDb(queries: Query[], answers: Record<string, unknown> = {}): never {+ const model = (name: string) => new Proxy({}, { get: (_, op: string) => async (args: unknown) => {+ queries.push({ model: name, op, args })+ return `${name}.${op}` in answers ? answers[`${name}.${op}`] : /^(findMany|aggregateRaw)$/.test(op) ? [] : op === 'count' ? 0 : null+ } })+ const models = new Map<string, unknown>()+ const db: object = new Proxy({}, { get: (_, key: string) => {+ if (key === '$transaction') return async (run: (tx: unknown) => unknown) => run(db)+ if (key === 'then') return undefined+ if (!models.has(key)) models.set(key, model(key))+ return models.get(key)+ } })+ return db as never+}++/** The same client with every call still running, and recorded. */+export function watched<T extends object>(db: T, queries: Query[]): T {+ const models = new Map<string, unknown>()+ return new Proxy(db, { get: (target, key) => {+ const value = Reflect.get(target, key, target)+ if (typeof key === 'string' && key.startsWith('$') && typeof value === 'function') return value.bind(target)+ if (typeof key !== 'string' || key.startsWith('$') || !value || typeof value !== 'object') return value+ if (!models.has(key)) models.set(key, new Proxy(value, { get: (delegate, op, r) => {+ const method = Reflect.get(delegate, op, r)+ return typeof method === 'function' && typeof op === 'string'+ ? (args: unknown) => { queries.push({ model: key, op, args }); return method.call(delegate, args) } : method+ } }))+ return models.get(key)+ } })+}diff --git a/backend/src/superTabs/cards.test.ts b/backend/src/superTabs/cards.test.tsnew file mode 100644index 000000000..4b5efdb76--- /dev/null+++ b/backend/src/superTabs/cards.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it } from 'vitest'+import { applyCommand, type Command, type CommandContext } from './commands.js'+import { bindPullRequestCards } from './cards.js'+import { agentOnly, appendPullRequestUrls, createSuperTab, visibleState, type Actor, type AgentConfiguration, type Conversation, type MessageDraft } from './model.js'++const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const config: AgentConfiguration = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }+const PR = 'https://github.com/example/app/pull/7'+const OTHER = 'https://github.com/example/app/pull/8'++function fixture() {+ let state = createSuperTab('tab', 'Office', { id: 'owner', email: owner.email }, 'prod')+ let sequence = 0+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {+ const effects = applyCommand(state, actor, command, { now: 1000, operationId: `op-${++sequence}`, ...context })+ state = effects.state+ // As the store does after every command: a shown message's links are the group's linked pull requests.+ for (const group of state.conversations) {+ appendPullRequestUrls(group, effects.messages.filter(m => m.conversationId === group.id && !agentOnly(m.source, m.recipients)).map(m => m.text))+ }+ return effects+ }+ const add = (name: string, group: string, lead = false) => run({ type: 'agent.add', conversationId: group, machineId: 'host', harnessId: name,+ name, configuration: config, lead }, owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string+ const lead = add('River', 'lead', true)+ const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })+ const create = () => run({ type: 'conversation.create', title: 'Avatars', brief: 'Add avatars.',+ checks: [{ description: 'Tests pass', independent: false }] } as Command)+ const post = (conversationId: string, text: string, actor: Actor = owner, extra: Record<string, unknown> = {}, context: Partial<CommandContext> = {}) =>+ run({ type: 'message.send', conversationId, text, replyTo: null, recipientIds: [], ...extra } as Command, actor, context).messages.at(-1)!+ const group = (id: string) => state.conversations.find(c => c.id === id)!+ return { run, add, as, create, post, group, lead, get state() { return state } }+}++describe('live cards', () => {+ it('makes the brief its task card, and a new brief takes the card over', () => {+ 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 })+ 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)+ })++ it('makes the first message linking a pull request its card, and later links of it plain messages', () => {+ const f = fixture()+ const id = f.create().result.conversationId as string+ const builder = f.add('Kai', id)+ const first = f.post(id, `Opened ${PR}`, f.as(builder))+ f.post(id, `CI is running on ${PR}`, f.as(builder))+ const both = f.post(id, `Split into ${PR} and ${OTHER}`, f.as(builder))+ expect(f.group(id).cards?.pullRequests).toEqual([{ url: PR, messageId: first.id }, { url: OTHER, messageId: both.id }])+ })++ it('never makes a thread reply or an agent-only notice a card', () => {+ const f = fixture()+ const id = f.create().result.conversationId as string+ const builder = f.add('Kai', id)+ const root = f.post(id, 'Starting.', f.as(builder))+ f.post(id, `Opened ${PR}`, f.as(builder), { replyTo: root.id },+ { reply: { id: root.id, conversationId: id, author: root.author, createdAt: 1000, thread: root.id } })+ f.post(id, `Notice ${OTHER}`, f.as(builder), { agentOnly: true, recipientIds: [builder] })+ expect(f.group(id).cards?.pullRequests).toBeUndefined()+ })++ it('never makes a Lead-only notice a card, such as a resumed task notice, and reads its recipients', () => {+ // Batch #2220: #2177 made agentOnly read the notice's recipients; a resumed task's notice to the Lead reaches card binding.+ const group = { id: 'g' } as Conversation+ const notice = { id: 'n', conversationId: 'g', text: `Resumed ${PR}`, recipients: ['lead'],+ source: { kind: 'work-resumed', agentId: 'kai', assignmentId: 'a1' } } as unknown as MessageDraft+ expect(() => bindPullRequestCards(group, notice)).not.toThrow()+ expect(group.cards?.pullRequests).toBeUndefined()+ })++ it('records a merge on the card and posts the merged line in its thread, not the main chat', () => {+ const f = fixture()+ const id = f.create().result.conversationId as string+ const card = f.post(id, `Opened ${PR}`, f.as(f.add('Kai', id)))+ const [line] = f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: PR }, f.as(f.lead)).messages+ expect(line).toMatchObject({ text: `Merged ${PR}`, thread: card.id, replyTo: card.id })+ expect(f.group(id).cards?.pullRequests).toEqual([{ url: PR, messageId: card.id, mergedAt: 1000 }])+ })++ it('keeps the first merge when one is recorded again, and posts nothing more', () => {+ const f = fixture()+ const id = f.create().result.conversationId as string+ const card = f.post(id, `Opened ${PR}`, f.as(f.add('Kai', id)))+ f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: PR }, f.as(f.lead), { now: 900 })+ const again = f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: PR }, f.as(f.lead), { now: 2000 })+ expect(again.messages).toEqual([])+ expect(f.group(id).cards?.pullRequests).toEqual([{ url: PR, messageId: card.id, mergedAt: 900 }])+ })++ it('posts each pull request\'s merge in its own card\'s thread, a later second merge too', () => {+ const f = fixture()+ const id = f.create().result.conversationId as string+ const builder = f.add('Kai', id)+ const first = f.post(id, `Opened ${PR}`, f.as(builder))+ const second = f.post(id, `Opened ${OTHER}`, f.as(builder))+ f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: PR }, f.as(f.lead), { now: 900 })+ const [line] = f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: OTHER }, f.as(f.lead), { now: 2000 }).messages+ expect(line).toMatchObject({ text: `Merged ${OTHER}`, thread: second.id, replyTo: second.id })+ expect(f.group(id).cards?.pullRequests).toEqual([{ url: PR, messageId: first.id, mergedAt: 900 }, { url: OTHER, messageId: second.id, mergedAt: 2000 }])+ })++ it('makes the merged line the card of a pull request no message linked yet', () => {+ const f = fixture()+ const id = f.create().result.conversationId as string+ const [line] = f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: PR }, f.as(f.lead)).messages+ expect(line!.thread).toBeUndefined()+ expect(f.group(id).cards?.pullRequests).toEqual([{ url: PR, messageId: line!.id, mergedAt: 1000 }])+ })++ it('shows a card only to readers of its own conversation', () => {+ const f = fixture()+ const id = f.create().result.conversationId as string+ const peer: Actor = { kind: 'person', userId: 'peer', email: '[email protected]' }+ f.state.people.push({ id: 'peer', email: peer.email, role: 'collaborator', generation: 'first' })+ f.post(id, `Opened ${PR}`)+ expect(f.group(id).cards?.pullRequests).toHaveLength(1)+ f.group(id).audience = { people: [{ id: 'owner', generation: f.state.people[0]!.generation }] }+ const seen = visibleState(f.state, peer, 1000)+ expect(seen.conversations.some(c => c.id === id)).toBe(false)+ expect(JSON.stringify(seen.conversations.map(c => c.cards ?? null))).not.toContain(PR)+ })+})diff --git a/backend/src/superTabs/cards.ts b/backend/src/superTabs/cards.tsnew file mode 100644index 000000000..ff400e9e0--- /dev/null+++ b/backend/src/superTabs/cards.ts@@ -0,0 +1,45 @@+import { agentOnly, pullRequestLinks, type Conversation, type MessageDraft } from './model.js'++/**+ * Live cards (Slack parity, Dee 10-29): like a Slack app's message that updates itself, a task or a pull request is one+ * message in its conversation, drawn as a card that changes in place, and later events go in that message's thread.+ * The group names its card messages; clients draw them from the group state they already read, so a card reaches only+ * readers of its own conversation, and its pull request facts come from each reader's own GitHub (Desktop). A card names+ * only messages of its own group: no other conversation is ever looked up for it.+ */+export interface GroupCards {+ /** The message that is the task card: its newest brief. */+ task?: string+ /** Each linked pull request's card: the first main-chat message that linked it, and when a merge was recorded. */+ pullRequests?: PullRequestCard[]+}+export interface PullRequestCard { url: string; messageId: string; mergedAt?: number }++/** Rows that may become a card: an agent's or person's own post, or the system's line. A celebration, a route or another+ * structured row has its own drawing. */+const cardable = (message: MessageDraft) => !message.source || message.source.kind === 'system'++/** [brief] is [group]'s newest brief: it is the task card from now on. */+export function bindTaskCard(group: Conversation, brief: MessageDraft): void {+ group.cards = { ...group.cards, task: brief.id }+}++/** A main-chat row linking a pull request this group has no card for becomes its card. A thread reply or an agent-only+ * notice never does: people read the main chat. */+export function bindPullRequestCards(group: Conversation, message: MessageDraft): void {+ if (message.thread || agentOnly(message.source, message.recipients) || !cardable(message)) return+ const known = new Set(group.cards?.pullRequests?.map(card => card.url))+ const fresh = pullRequestLinks(message.text).filter(url => !known.has(url))+ if (fresh.length) group.cards = { ...group.cards, pullRequests: [...group.cards?.pullRequests ?? [], ...fresh.map(url => ({ url, messageId: message.id }))] }+}++/** The card of [url] in [group], if a message already is one. */+export const pullRequestCard = (group: Conversation, url: string): PullRequestCard | undefined =>+ group.cards?.pullRequests?.find(card => card.url === url)++/** A merge of [url] was recorded at [mergedAt]: its card shows it, even to a reader whose computer cannot read GitHub. The+ * earliest record stands, as the leaderboard's does (leaderboard/record.ts recordMerged). */+export function recordCardMerged(group: Conversation, url: string, mergedAt: number): void {+ const card = pullRequestCard(group, url)+ if (card) card.mergedAt = Math.min(card.mergedAt ?? mergedAt, mergedAt)+}diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 4ac2f0aa5..50a60fc6d 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -1,9 +1,11 @@import { describe, expect, it } from 'vitest'import { applyCommand, commandSchema, PAIR_CHAIN_LIMIT, swarmGridName, withoutCredentials, type Command, type CommandContext } from './commands.js'import { CREDENTIAL_MARKER, type CredentialKind } from './credentials.js'+import { sweepLiveness } from './liveness.js'import { hostLocalGrid, machineSlots, removalPreview, swarmGridRow } from './machines.js'import { activeWork, agentRole, createSuperTab, visibleState, type Actor, type AgentConfiguration } from './model.js'import type { RouteDecision } from './routeRecord.js'+import { startFinished } from './parts/write.js'import { agentTarget, broken } from './rules.js'import { DEFAULT_ROUTING_POLICY, effectivePolicy } from './routingPolicy.js'@@ -1292,10 +1294,46 @@ describe('Reviewer role', () => {// A known small model it reports is never promoted by its launch (review of ee4ee6c9a).expect(member({ engine: 'codex', model: 'gpt-5.5-mini' })).toThrow('Codex gpt-5.5-mini is 1.')expect(member({ engine: 'codex', model: 'gpt-5-nano' })).toThrow('Codex gpt-5-nano is 1.')+ // An agent from before the flag was kept is judged by its start: one that named the model is rated by that model's row.+ delete f.state.agents.find(a => a.id === reviewer)!.launchedDefault+ expect(member({ engine: 'codex', model: 'gpt-6.1-sol' })).not.toThrow()f.state.starts!.find(s => s.harnessId === 'native-reviewer')!.request.model = 'gpt-6.1-sol'expect(member({ engine: 'codex', model: 'gpt-6.1-sol' })).toThrow('Codex gpt-6.1-sol is 1.')})+ it('rates a Reviewer launched on its engine\'s default by the default row after it reports its model, once its start has finished', () => {+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), group = f.group()+ const leadActor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' } as const+ f.run({ type: 'conversation.agent', conversationId: group, agentId: lead, present: true, lead: true })+ // Started with no model: Codex runs its own default and reports none yet.+ const startId = f.run({ type: 'agent.start', request: request(group, { role: 'reviewer' }), ...via } as Command, leadActor, { contribution, ...decisionIn(group) }).result.startId as string+ f.run({ type: 'agent.startDispatch', startId }, leadActor, { contribution })+ const reviewer = f.run({ type: 'agent.started', startId, harnessId: 'native-reviewer', configuration: { ...config, model: null } }, leadActor, { contribution }).result.agentId as string+ // A command loads only unfinished starts (parts/load.ts loadActive): the finished one is gone from its state.+ f.state.starts = f.state.starts!.filter(s => !startFinished(s))+ const builder = f.add('builder', 'owner', group)+ f.state.agents.find(a => a.id === builder)!.configuration.engine = 'claude'+ f.run({ type: 'work.assign', conversationId: group, agentId: builder })+ const review = f.run({ type: 'conversation.create', title: 'Review', brief: 'Review it.', reviewOf: group, checks: [{ description: 'Verdict', independent: false }] },+ leadActor).result.conversationId as string+ const pick = () => f.run({ type: 'route.record', conversationId: review, decision: record({ candidates: [candidate('c0', { kind: 'member', agentId: reviewer, machineId: 'host' })], pick: 'c0' }) } as Command, leadActor)+ expect(pick).not.toThrow()+ // Codex then reports its slug.+ const reviewerActor = { kind: 'agent', agentId: reviewer, machineOwnerId: f.state.agents.find(a => a.id === reviewer)!.machineOwnerId } as const+ const before = f.state.agents.find(a => a.id === reviewer)!.configurationVersion!+ f.run({ type: 'agent.configuration', previousVersion: before, configuration: { ...config, model: 'gpt-6.1-sol' } }, reviewerActor)+ expect(pick).not.toThrow()+ // A small model it reports is still never promoted (review of ee4ee6c9a).+ const now = f.state.agents.find(a => a.id === reviewer)!.configurationVersion!+ f.run({ type: 'agent.configuration', previousVersion: now, configuration: { ...config, model: 'gpt-5.5-mini' } }, reviewerActor)+ expect(pick).toThrow('Codex gpt-5.5-mini is 1.')+ // A replaced terminal (Change agent) is not the session its start launched: it is rated by the model it reports.+ f.run({ type: 'agent.rebind', agentId: reviewer, machineId: 'host', projectId: 'lead', previousHarnessId: 'native-reviewer', harnessId: 'native-reviewer-2',+ configuration: { ...config, model: 'gpt-6.1-sol' } }, reviewerActor)+ expect(f.state.agents.find(a => a.id === reviewer)).not.toHaveProperty('launchedDefault')+ expect(pick).toThrow('Codex gpt-6.1-sol is 1.')+ })+it('stores the role chosen at start and reads agents without one as Builders', () => {const { f, reviewer, builder } = reviewed()expect(f.state.agents.find(a => a.id === reviewer)).toHaveProperty('role', 'reviewer')@@ -3430,3 +3468,101 @@ describe('stepping up from a cheap model', () => {expect(again.messages.some(m => m.text.includes('stepped up'))).toBe(false)})})++// Ken, 2026-10-28: work kept landing on engines that could not run on their machine (Codex with no tokens on Diego's Mac),+// until a person told the Product Manager. The server counts failed starts per engine and machine, and the start check+// refuses an engine its machine reads as signed out, out of quota or suspended.+describe('an engine that cannot run on a contributed machine', () => {+ const grid = 'swarm-0123456789ab'+ const setup = (reading: Record<string, unknown> = {}) => {+ const f = fixture()+ const lead = f.add('lead', 'owner', 'lead', true)+ const leadActor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }+ f.state.machines = [{ machineId: 'mac', name: 'Mac', contributorId: 'owner', membershipGeneration: f.state.people[0]!.generation, generation: 'g1',+ cwd: '/repo', engines: ['codex'], maxAgents: 8, paused: false, observation: { generation: 'g1', receivedAt: 1000,+ resources: { cpuPercent: null, memoryTotalBytes: null, memoryUsedBytes: null, diskFreeBytes: null, diskTotalBytes: null, projectDiskFreeBytes: null,+ deviceType: null, chip: null, os: null, gpuPercent: null }, tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [], ...reading } }] as never+ const start = (id: string, extra: Record<string, unknown> = {}) => ({ id, actorKey: 'person:owner', contributorId: 'owner',+ membershipGeneration: f.state.people[0]!.generation, machineOwnerId: 'owner', hostGrant: null, poolGeneration: 'g1',+ request: { conversationId: 'lead', machineId: 'mac', engine: 'codex', name: 'Builder', cwd: '/repo', ...extra }, harnessId: null, dispatched: true, error: null })+ f.state.starts = ['s1', 's2', 's3', 's4'].map(id => start(id)) as never+ const fail = (startId: string) => f.run({ type: 'agent.startFailed', startId, error: 'Codex could not launch.' }, owner).messages[0]!+ const request = (extra: Record<string, unknown> = {}) => ({ conversationId: 'lead', machineId: 'mac', engine: 'codex', name: 'Builder', cwd: '/repo',+ worktree: true, requirements: { memoryBytes: 1, diskBytes: 1, maxCpuPercent: 100, tools: ['git'], devices: [], quotaRequired: false }, ...extra })+ const begin = (extra: Record<string, unknown> = {}) => f.run({ type: 'agent.start', request: request(extra), ...via } as Command, leadActor,+ { contribution: { machineOwnerId: 'owner', contributorId: 'owner' }, ...decisionIn('lead') })+ return { f, lead, fail, begin, start }+ }++ it('is suspended by its second failed start in a row, telling the Lead and tagging the machine owner once', () => {+ const { f, lead, fail } = setup()+ const first = fail('s1')+ expect(first.mentions).toBeUndefined()+ expect(first.text).not.toContain('suspended')+ const second = fail('s2')+ expect(second).toMatchObject({ recipients: [lead], mentions: ['owner'] })+ expect(second.text).toContain('Codex is suspended on this machine for new work: its last 2 starts there failed.')+ for (const later of ['s3', 's4']) {+ const notice = fail(later)+ expect(notice.mentions).toBeUndefined()+ expect(notice.text).not.toContain('suspended')+ }+ expect(Object.keys(f.state.machines![0]!.engineSuspensions!)).toEqual(['codex'])+ })++ it('counts only failures in a row: a start that ran in between resets the count', () => {+ const { f, fail } = setup()+ fail('s1')+ f.run({ type: 'agent.started', startId: 's2', harnessId: 'native-2', configuration: config }, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner', hostGrant: null } })+ expect(fail('s3').mentions).toBeUndefined()+ expect(fail('s4').mentions).toEqual(['owner'])+ })++ // Review of 4ddd0a1e0: the server timed a start out, then its host reported it failed too; one flaky start suspended Codex.+ it('counts a start once: a host failure after the server timed the same start out is not a second failure', () => {+ const { f, fail } = setup()+ const timedOut = f.state.starts![0]!+ timedOut.dispatchedAt = 0+ sweepLiveness(f.state, 3 * 60_000 + 1)+ expect(timedOut.error).toBeTruthy()+ const late = fail('s1')+ expect(late.mentions).toBeUndefined()+ expect(late.text).not.toContain('suspended')+ expect(f.state.machines![0]!.engineSuspensions ?? {}).toEqual({})+ // A different start that fails next is the second in a row.+ expect(fail('s2').mentions).toEqual(['owner'])+ })++ it('is refused by the start check while suspended, signed out or out of quota, and a grid model there is not', () => {+ const suspended = setup()+ suspended.fail('s1'); suspended.fail('s2')+ expect(() => suspended.begin()).toThrow('Codex is suspended on this machine')+ const signedOut = setup({ readiness: { engines: [{ engine: 'codex', installed: true, signedIn: false }] }, localModels: [{ grid, model: 'qwen3', kind: 'local' }] })+ expect(() => signedOut.begin()).toThrow('Codex is not signed in to a subscription on this machine.')+ signedOut.f.state.localModels = { grid, enabled: true }+ expect(signedOut.begin({ gridModel: 'qwen3', gridName: grid }).result.startId).toBeTruthy()+ const exhausted = setup({ quotas: [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 100, resetsAt: null }] }] })+ expect(() => exhausted.begin()).toThrow('Codex has no subscription quota left on this machine until its usage window resets.')+ // A reading that says nothing of the engine keeps today's behaviour.+ expect(setup().begin().result.startId).toBeTruthy()+ })++ it('is resumed by the machine owner, or by a Lead passing on the owner\'s message, and by nobody else', () => {+ const { f, lead, fail } = setup()+ fail('s1'); fail('s2')+ const leadActor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }+ const resume = { type: 'machine.engineResume', machineId: 'mac', engine: 'codex' } as Command+ f.invite()+ expect(() => f.run(resume, peer)).toThrow('Only the machine\'s owner')+ expect(() => f.run(resume, leadActor)).toThrow('Only the machine\'s owner')+ const askedIn = { conversationId: 'lead', messageId: 'm-owner' }+ expect(() => f.run({ ...resume, askedIn } as Command, leadActor, { askedIn: { author: { kind: 'person', id: 'peer' } as never, source: false, createdAt: 1000 } }))+ .toThrow('Only the machine\'s owner')+ f.run({ ...resume, askedIn } as Command, leadActor, { askedIn: { author: { kind: 'person', id: 'owner' } as never, source: false, createdAt: 1000 } })+ expect(f.state.machines![0]!.engineSuspensions).toEqual({})+ fail('s3'); fail('s4')+ f.run(resume, owner)+ expect(f.state.machines![0]!.engineSuspensions).toEqual({})+ expect(commandSchema.safeParse({ ...resume, engine: 'Not An Engine' }).success).toBe(false)+ })+})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 7cfea2910..afe740e56 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -5,7 +5,7 @@ import { z } from 'zod'import { tokensByModelSchema } from './costs/tokens.js'import {activeWork, actorKey, agent, agentRole, appendPullRequestUrls, author, conversation, crossProjectActive, fail, isLeads, person, stableId, syncLeads, numberConversations, nextConversationNumber, renderWorkTask,- finishWorker, requireWorkerDecisions, reviewing, seenMachineIds, swarmGridName, visibleState, AGENT_ONLY,+ finishWorker, requireWorkerDecisions, reviewing, seenMachineIds, swarmGridName, visibleState, AGENT_ONLY, forRecipients,type Actor, type AgentStartRequest, type WorkTask, type Agent, type Author, type CommandEffects, type Conversation, type SuperTabState,} from './model.js'import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'@@ -15,8 +15,9 @@ import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'import { checkMentions, MAX_MENTIONS, type MentionTarget } from './mentions.js'import { answerDecision, askDecisions, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'import { TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, toLead, type TerminalRequest } from './terminal.js'-import { loseTasks, recordTaskState, renewLease, renewOwnTask } from './liveness.js'+import { leadNoticeRows, loseTasks, recordTaskState, renewLease, renewOwnTask } from './liveness.js'import { ABANDONED, failureNotice, MACHINE_REMOVED } from './startFailure.js'+import { noteStartFailed, noteStartSucceeded, resumeEngine } from './engineHealth.js'import { digestStartsAfter, knownTimeZone } from './digest.js'import { credentialResult, redactCredentials, type CredentialKind } from './credentials.js'import { dirtyGroups, reportGroups, summarize } from './projectUpdates.js'@@ -26,6 +27,7 @@ import { LEDGER_WEEKS, PULL_REQUEST_URL, recordAsked, recordDecision, recordMergimport { WEEK_MS } from './leaderboard/week.js'import { react, reactionSchema, type ReactionTarget } from './reactions.js'import { shipNotice, shippedAt } from './ship.js'+import { bindPullRequestCards, bindTaskCard, pullRequestCard, recordCardMerged } from './cards.js'import { openReview, openReviewOf, projectPullRequest, verdictPending } from './autoReview.js'import { carryOver, cheapAttempt, GRID_START_FAILED, REVIEW_FAILED, stepUp, stepUpRefusal } from './stepUp.js'import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema, type AvatarUpload } from './profile.js'@@ -89,6 +91,7 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('machine.contribute'), machineId: id, name: title, cwd: path, scope: z.literal('swarm').optional(), engines: z.array(swarmEngine).min(1).max(2), maxAgents,ifMissing: z.literal(true).optional(), teamAccountOnly: z.literal(true).optional() }).strict(),z.object({ type: z.literal('machine.pause'), machineId: id, paused: z.boolean() }).strict(),+ z.object({ type: z.literal('machine.engineResume'), machineId: id, engine: z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/), askedIn: askedInSchema.optional() }).strict(),z.object({ type: z.literal('machine.remove'), machineId: id }).strict(),z.object({ type: z.literal('machine.cleaned'), machineId: id, removalId: id }).strict(),z.object({ type: z.literal('localModels.set'), enabled: z.boolean() }).strict(),@@ -279,7 +282,8 @@ export interface CommandContext {hostMachineId?: string }/** Loaded from this tab and conversation by the store. *//** `thread` is the replied message's thread root, null for a message written before threads (it keeps inline replies). */- reply?: { id: string; conversationId: string; author: Author; createdAt: number; thread?: string | null }+ /** `agentOnly`: a notice people cannot read (model.ts agentOnly), whose thread a reply does not join. */+ reply?: { id: string; conversationId: string; author: Author; createdAt: number; thread?: string | null; agentOnly?: true }/** For a person's `message.send`: the tags waiting on them in that conversation, read by the store (leaderboard/record.ts). */openTags?: Array<{ messageId: string; createdAt: number }>/** The proposal a new group names as its origin (conversation.create proposalMessageId), loaded from this tab by the store. */@@ -459,7 +463,8 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, commaif ('projectId' in command && command.projectId) readProject(state, actor, command.projectId)if ('agentId' in command) readAgent(state, actor, command.agentId)if (command.type === 'agent.start') readConversation(state, actor, command.request.conversationId)- if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy') && command.askedIn) {+ if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'+ || command.type === 'machine.engineResume') && command.askedIn) {readConversation(state, actor, command.askedIn.conversationId)}if ('startId' in command && command.type !== 'route.modelResult') {@@ -1118,6 +1123,20 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commafor (const team of teamPoolsOf(state, pool)) if (!team.removal) team.paused = command.pausedbreak}+ case 'machine.engineResume': {+ // A suspended engine (engineHealth.ts) is offered again at its owner's word: theirs, or a Lead's passing on a chat+ // message they wrote in the last day, as routing rules are. No new button: the only visible change is the struck name.+ const pool = machineContribution(state, command.machineId) ?? fail('NOT_FOUND', 'This machine has not been contributed.', 404)+ const asked = actor.kind === 'agent' && command.askedIn && context.askedIn+ const ownerAsked = !!asked && asked.author.kind === 'person' && asked.author.id === pool.contributorId && !asked.source+ && context.now - asked.createdAt <= RULE_MESSAGE_MS && !!state.conversations.find(c => c.id === command.askedIn!.conversationId)?.leadId+ && state.conversations.find(c => c.id === command.askedIn!.conversationId)!.leadId === actor.agentId+ if (!(actor.kind === 'person' && actor.userId === pool.contributorId) && !ownerAsked) {+ fail('OWNER_REQUIRED', "Only the machine's owner, or the Lead passing on a chat message the owner wrote in the last day, resumes an engine there.", 403)+ }+ resumeEngine(pool, command.engine)+ break+ }case 'machine.remove': {// Its owner takes the machine out with every Swarm agent on it, each removed like one agent (its host closes the// session; a Product Manager refuses it, protectLead). A contributed machine then stays listed, paused, while its@@ -1233,7 +1252,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (command.proposalMessageId) recordProposal(state.conversations.at(-1)!, proposalOf(state, project, context.proposal))result.conversationId = operationIdresult.number = number- if (brief) message(operationId, brief, [], null, SYSTEM_ROW)+ if (brief) {+ message(operationId, brief, [], null, SYSTEM_ROW)+ bindTaskCard(state.conversations.at(-1)!, effects.messages.at(-1)!)+ }break}case 'decision.ask': {@@ -1283,7 +1305,15 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst shippedAt = group.ledger?.shippedAt, linked = group.pullRequestUrls?.includes(command.pullRequestUrl)appendPullRequestUrls(group, [command.pullRequestUrl])recordMerged(group, mergedAt)- if (!linked || group.ledger!.shippedAt !== shippedAt) message(group.id, `Merged ${command.pullRequestUrl}`, [], null, SYSTEM_ROW)+ // Like a Slack app's update: the card shows the merge, and the line goes in the card's thread, once per pull request.+ // Without a card yet, the group's first ship or a new link still says so, and the line becomes the card.+ const card = pullRequestCard(group, command.pullRequestUrl)+ if (card ? card.mergedAt === undefined : !linked || group.ledger!.shippedAt !== shippedAt) {+ message(group.id, `Merged ${command.pullRequestUrl}`, [], card?.messageId ?? null, SYSTEM_ROW)+ if (card) effects.messages.at(-1)!.thread = card.messageId+ else bindPullRequestCards(group, effects.messages.at(-1)!)+ }+ recordCardMerged(group, command.pullRequestUrl, mergedAt)break}case 'conversation.archive': {@@ -1564,7 +1594,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma}if (command.type === 'agent.startFailed') {if (start.harnessId) fail('ALREADY_STARTED', 'This agent already started.')+ // Only its first failure counts against its engine: the server may have timed it out before its host said so (liveness.ts).+ const counted = !start.errorstart.error = command.error+ const suspended = counted ? noteStartFailed(state, start, context.now) : null// A Product Manager's start says so in its project's conversation only when it stops trying (leadStart.ts).if (start.request.leadFor) {const ended = leadStartFailed(state, start, command.error, context.now)@@ -1575,7 +1608,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma// name for nobody, this notice left the round-device group without a worker for an hour (2026-10-27).const group = conversation(state, start.request.conversationId)const lead = group.leadId && group.agentIds.includes(group.leadId) ? group.leadId : null- message(group.id, failureNotice(start.request.name, command.error), lead ? [lead] : [], null, SYSTEM_ROW)+ // The failure that suspends its engine there says so once, and tags the machine's owner (engineHealth.ts).+ message(group.id, `${failureNotice(start.request.name, command.error)}${suspended ? `\n\n${suspended}` : ''}`, lead ? [lead] : [], null, SYSTEM_ROW,+ undefined, suspended && start.machineOwnerId ? [start.machineOwnerId] : undefined)if (start.request.gridModel && !activeWork(group)) steppedUp(group, GRID_START_FAILED, start.id)break}@@ -1594,11 +1629,13 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: CommahostGrant: start.hostGrant, name: start.request.name, configuration: command.configuration, configurationVersion: operationId,...(start.request.role ? { role: start.request.role } : {}), ...(start.request.roleId ? { roleId: start.request.roleId } : {}),...(start.request.gridModel ? { gridModel: start.request.gridModel } : {}),+ ...(!start.request.gridModel && (start.request.model ?? 'default') === 'default' ? { launchedDefault: true as const } : {}),...(start.request.buddyOf ? { buddyOf: start.request.buddyOf } : {}),...(teamAccountPool(machineContribution(state, start.request.machineId)) ? { teamAccount: true as const } : {}),...(command.startedSession ? { startedSession: { ...command.startedSession, creationId: start.creationId } } : {}) })group.agentIds.push(agentId)start.harnessId = command.harnessId+ noteStartSucceeded(state, start)result.agentId = agentIdif (start.request.leadFor) {// Taking over from a Lead that left, as agent.add does.@@ -1642,6 +1679,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma// A new terminal is not the session that lost its task, nor one started on a grid model: it reports its own.delete target.lostTaskdelete target.gridModel+ delete target.launchedDefaulttarget.configuration = command.configurationtarget.configurationVersion = operationIdif (command.startedSession) target.startedSession = command.startedSession@@ -1865,8 +1903,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma}// The transcript still accepts a human message while the lead is unavailable. The UI can say why no delivery was created.message(group.id, command.text, recipients, command.replyTo, command.agentOnly ? AGENT_ONLY : undefined, attachments, mentions)- // A reply joins its message's thread, always at the root, so threads never nest.- const thread = command.replyTo ? context.reply?.thread : null+ // A reply joins its message's thread, always at the root, so threads never nest. A reply to a notice only its+ // recipients read (the Lead answering a stalled alert) stays in the chat: people open a thread from its root.+ const thread = command.replyTo && !context.reply?.agentOnly ? context.reply?.thread : nullif (thread) Object.assign(effects.messages.at(-1)!, { thread, ...(command.alsoSend ? { alsoInChat: true } : {}) })recordPost(state, group, actor, { replyTo: command.replyTo, text: command.text, reply: context.reply, openTags: context.openTags }, context.now)if (actor.kind === 'agent') renewOwnTask(group, actor.agentId, context.now)@@ -1983,6 +2022,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaelse delete group.taskgroup.checks = command.checks.map((c, i) => ({ ...c, id: stableId(operationId, String(i)), evidence: null, passedBy: null }))message(group.id, group.brief, [], null, SYSTEM_ROW)+ bindTaskCard(group, effects.messages.at(-1)!)break}case 'work.assign': {@@ -2127,7 +2167,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaassignment.result = command.reasonif (!lost) finishWorker(state, assignment.agentId, group)message(group.id, `${isLead ? 'The Lead' : 'The tab owner'} cancelled this task: ${command.reason.replace(/[.\s]+$/, '')}.${gone ? '' : ' Stop working on it.'}`,- gone ? [] : [assignment.agentId], null, SYSTEM_ROW)+ // Telling its agent to stop is the agent's alone; people read the cancel and its reason on the task itself.+ gone ? [] : [assignment.agentId], null, gone ? SYSTEM_ROW : forRecipients(SYSTEM_ROW))break}case 'work.resume': {@@ -2150,9 +2191,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commadelete group.lostAttemptdelete worker.lostTaskrenewLease(assignment, context.now)- effects.messages.push(...toLead(state, worker, { id: stableId(operationId, 'resumed'), conversationId: group.id, author: sender, replyTo: null,+ effects.messages.push(...leadNoticeRows(toLead(state, worker, { id: stableId(operationId, 'resumed'), conversationId: group.id, author: sender, replyTo: null,recipients: [], text: `${worker.displayName ?? worker.name} resumed its task after its usage limit reset.`,- source: { kind: 'work-resumed', agentId: worker.id, assignmentId: assignment.id } }))+ source: { kind: 'work-resumed', agentId: worker.id, assignmentId: assignment.id } })))break}case 'work.check': {@@ -2201,6 +2242,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (clean.removed.length) { draft.text = clean.text; removed.push(...clean.removed) }}if (removed.length) Object.assign(result, credentialResult(removed))+ for (const draft of effects.messages) {+ const group = state.conversations.find(c => c.id === draft.conversationId)+ if (group) bindPullRequestCards(group, draft)+ }return effects}diff --git a/backend/src/superTabs/emptyIdLists.test.ts b/backend/src/superTabs/emptyIdLists.test.tsnew file mode 100644index 000000000..a632aa26a--- /dev/null+++ b/backend/src/superTabs/emptyIdLists.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest'+import type { PrismaClient } from '@prisma/client'+import { recordingDb, sendsEmptyIn, type Query } from '../lib/queryRecorder.test-support.js'+import { GrantReads, SuperTabStore } from './store.js'+import { HostReads } from './read/host.js'+import { listWorkspaces } from './workspaceStore.js'++const user = { sub: 'u1', email: '[email protected]', autonomousEnv: 'prod', role: 'user' } as never++describe('reads of machines, users and SuperTab with nothing to look up', () => {+ it('asks for no machine when the Swarm has no pending machine cleanup', async () => {+ const queries: Query[] = []+ const store = new SuperTabStore(recordingDb(queries) as PrismaClient)++ expect(await store['deletedMachines'](recordingDb(queries) as never, { machineCleanups: [], environment: 'prod' } as never)).toEqual([])+ expect(queries).toEqual([])+ })++ it('still asks which cleanup machines are alive when there are some', async () => {+ const queries: Query[] = []+ const tx = recordingDb(queries, { 'machine.findMany': [{ machineId: 'm1' }] })++ const gone = await new SuperTabStore(recordingDb([]) as PrismaClient)['deletedMachines'](tx as never,+ { machineCleanups: [{ machineId: 'm1' }, { machineId: 'm2' }], environment: 'prod' } as never)++ expect(gone).toEqual(['m2'])+ expect(queries).toHaveLength(1)+ })++ it('asks for no account when a Swarm lists no people for a host', async () => {+ const queries: Query[] = []+ const reads = new HostReads(new SuperTabStore(recordingDb([]) as PrismaClient))++ const lookups = await reads['lookups'](recordingDb(queries) as never, { id: 't1', people: [], agents: [], environment: 'prod' } as never, [], new GrantReads({} as never))++ expect(lookups.people).toEqual([])+ expect(queries.filter(q => q.model === 'user')).toEqual([])+ expect(queries.filter(sendsEmptyIn)).toEqual([])+ })++ it('asks for nothing when a host has no Swarm to look for changes in', async () => {+ const queries: Query[] = []+ const reads = new HostReads(new SuperTabStore(recordingDb([]) as PrismaClient))++ expect(await reads['woken'](recordingDb(queries) as never, [], 'host-1', 0)).toEqual(new Set())+ expect(queries).toEqual([])+ })++ it('lists a person in no Workspace without asking for Workspaces, Swarms or heads', async () => {+ const queries: Query[] = []++ expect(await listWorkspaces(recordingDb(queries) as PrismaClient, user)).toEqual([])+ expect(queries.map(q => q.model)).toEqual(['swarmWorkspaceMember'])+ })++ it('lists Workspaces with no Swarm without asking for heads', async () => {+ const queries: Query[] = []+ const db = recordingDb(queries, { 'swarmWorkspaceMember.findMany': [{ workspaceId: 'w1', role: 'member' }],+ 'swarmWorkspace.findMany': [{ id: 'w1', name: 'W', deletedAt: null, ownerId: 'u2' }] })++ await listWorkspaces(db as PrismaClient, user)++ expect(queries.filter(sendsEmptyIn)).toEqual([])+ expect(queries.map(q => q.model)).not.toContain('swarmHead')+ })+})diff --git a/backend/src/superTabs/engineHealth.test.ts b/backend/src/superTabs/engineHealth.test.tsnew file mode 100644index 000000000..7b46def4c--- /dev/null+++ b/backend/src/superTabs/engineHealth.test.ts@@ -0,0 +1,114 @@+import { describe, expect, it } from 'vitest'+import type { ContributedMachine } from './machines.js'+import type { AgentStart, SuperTabState } from './model.js'+import { ABANDONED, MACHINE_REMOVED } from './startFailure.js'+import { engineUnusable, noteStartFailed, noteStartSucceeded, readingClearsSuspensions, resumeEngine, SUSPENSION_MS, suspendedEngines } from './engineHealth.js'++const NOW = 10_000_000+const fine = { quotas: [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 40, resetsAt: null }] }],+ readiness: { engines: [{ engine: 'codex', installed: true, signedIn: true }] } }+const exhausted = { quotas: [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 100, resetsAt: null }] }],+ readiness: { engines: [{ engine: 'codex', installed: true, signedIn: true }] } }+function machine(reading: Record<string, unknown> = {}): ContributedMachine {+ return { machineId: 'm1', name: "Diego's Mac", contributorId: 'owner', membershipGeneration: 'g', generation: 'p', cwd: '/x', engines: ['claude', 'codex'],+ maxAgents: 2, paused: false, observation: { generation: 'p', receivedAt: NOW, resources: {} as never, tools: {}, quotas: [], runningHarnessIds: [],+ stoppedHarnessIds: [], ...reading } as never }+}+const stateWith = (pool: ContributedMachine) => ({ machines: [pool] }) as unknown as SuperTabState+let n = 0+const start = (extra: Partial<AgentStart['request']> = {}, error = 'Codex could not launch.'): AgentStart => ({ id: `s${++n}`, error,+ request: { conversationId: 'g1', machineId: 'm1', engine: 'codex', name: 'Builder', cwd: '/x', ...extra } }) as unknown as AgentStart++describe('an engine whose starts fail on a machine', () => {+ it('is suspended there by its second failed start in a row, with one sentence for the notice', () => {+ const pool = machine(), state = stateWith(pool)+ expect(noteStartFailed(state, start(), NOW)).toBeNull()+ expect(suspendedEngines(pool, NOW)).toEqual({})+ const notice = noteStartFailed(state, start(), NOW)+ expect(notice).toContain('Codex is suspended on this machine for new work: its last 2 starts there failed.')+ expect(suspendedEngines(pool, NOW)).toEqual({ codex: expect.stringContaining('Codex is suspended on this machine') })+ expect(engineUnusable(pool, 'codex', NOW)).toContain('Codex is suspended on this machine')+ expect(engineUnusable(pool, 'claude', NOW)).toBeNull()+ })++ it('says so once per suspension, never on a later failed start or report', () => {+ const pool = machine(), state = stateWith(pool)+ noteStartFailed(state, start(), NOW)+ expect(noteStartFailed(state, start(), NOW)).not.toBeNull()+ expect(noteStartFailed(state, start(), NOW + 1)).toBeNull()+ expect(noteStartFailed(state, start(), NOW + 2)).toBeNull()+ readingClearsSuspensions(pool, NOW + 3)+ expect(noteStartFailed(state, start(), NOW + 4)).toBeNull()+ })++ it('counts only failures in a row: a start that ran in between resets the count', () => {+ const pool = machine(), state = stateWith(pool)+ noteStartFailed(state, start(), NOW)+ noteStartSucceeded(state, start({}, ''))+ expect(noteStartFailed(state, start(), NOW)).toBeNull()+ expect(suspendedEngines(pool, NOW)).toEqual({})+ })++ it('counts each engine apart, and never a grid model, a removal, an abandoned start, a memory refusal, a Product Manager or a Buddy', () => {+ const pool = machine(), state = stateWith(pool)+ noteStartFailed(state, start({ engine: 'claude' }), NOW)+ expect(noteStartFailed(state, start(), NOW)).toBeNull()+ for (const failed of [start({ gridModel: 'qwen3' }), start({}, MACHINE_REMOVED), start({}, ABANDONED), start({}, 'Removed by its owner before it started.'),+ start({}, 'Not enough free memory: 1.2 GiB free, 2 GiB needed.'),+ start({ leadFor: 'p1' } as never), start({ buddyOf: 'owner' } as never)]) {+ expect(noteStartFailed(state, failed, NOW)).toBeNull()+ }+ expect(suspendedEngines(pool, NOW)).toEqual({})+ })++ it('ends after 6 hours', () => {+ const pool = machine(), state = stateWith(pool)+ noteStartFailed(state, start(), NOW); noteStartFailed(state, start(), NOW)+ expect(suspendedEngines(pool, NOW + SUSPENSION_MS - 1)).not.toEqual({})+ expect(suspendedEngines(pool, NOW + SUSPENSION_MS)).toEqual({})+ expect(engineUnusable(pool, 'codex', NOW + SUSPENSION_MS)).toBeNull()+ })++ it('ends on the next reading that shows it signed in with quota left, when it did not read so as it was suspended', () => {+ const pool = machine(exhausted), state = stateWith(pool)+ noteStartFailed(state, start(), NOW); noteStartFailed(state, start(), NOW)+ readingClearsSuspensions(pool, NOW + 1)+ expect(suspendedEngines(pool, NOW + 1)).toHaveProperty('codex')+ Object.assign(pool.observation!, fine)+ readingClearsSuspensions(pool, NOW + 2)+ expect(suspendedEngines(pool, NOW + 2)).toEqual({})+ })++ it('stands through readings that already read fine as it was suspended, since its starts failed anyway', () => {+ const pool = machine(fine), state = stateWith(pool)+ noteStartFailed(state, start(), NOW); noteStartFailed(state, start(), NOW)+ const reason = suspendedEngines(pool, NOW).codex+ expect(reason).toContain('within 6 hours')+ expect(reason).not.toContain('reading')+ readingClearsSuspensions(pool, NOW + 1)+ expect(suspendedEngines(pool, NOW + 1)).toHaveProperty('codex')+ })++ it('ends when its owner resumes it', () => {+ const pool = machine(), state = stateWith(pool)+ noteStartFailed(state, start(), NOW); noteStartFailed(state, start(), NOW)+ expect(resumeEngine(pool, 'codex')).toBe(true)+ expect(suspendedEngines(pool, NOW)).toEqual({})+ expect(noteStartFailed(state, start(), NOW)).toBeNull()+ expect(resumeEngine(pool, 'codex')).toBe(false)+ })+})++describe('an engine a machine cannot run', () => {+ it('is one its reading says is signed out or out of quota; unknown and older readings keep today\'s behaviour', () => {+ expect(engineUnusable(machine({ readiness: { engines: [{ engine: 'codex', installed: true, signedIn: false }] } }), 'codex', NOW))+ .toBe('Codex is not signed in to a subscription on this machine.')+ expect(engineUnusable(machine(exhausted), 'codex', NOW)).toBe('Codex has no subscription quota left on this machine until its usage window resets.')+ expect(engineUnusable(machine(fine), 'codex', NOW)).toBeNull()+ expect(engineUnusable(machine({ readiness: { engines: [{ engine: 'codex', installed: true, signedIn: null }] },+ quotas: [{ engine: 'codex', known: false, windows: [] }] }), 'codex', NOW)).toBeNull()+ expect(engineUnusable(machine(), 'codex', NOW)).toBeNull()+ const none = machine(); delete none.observation+ expect(engineUnusable(none, 'codex', NOW)).toBeNull()+ })+})diff --git a/backend/src/superTabs/engineHealth.ts b/backend/src/superTabs/engineHealth.tsnew file mode 100644index 000000000..f4696f8ff--- /dev/null+++ b/backend/src/superTabs/engineHealth.ts@@ -0,0 +1,96 @@+/** Whether an engine on a contributed machine can take new work: what its reading says (signed out, out of quota) and the+ * server's own count of its failed starts there. Work kept landing on engines that could not run, Codex with no tokens on+ * Diego's Mac among them, until a person told the Product Manager (Ken, 2026-10-28). Unknown is never unusable: a+ * machine from before these readings keeps today's behaviour. */+import type { ContributedMachine } from './machines.js'+import type { AgentStart, SuperTabState } from './model.js'+import { ABANDONED, MACHINE_REMOVED } from './startFailure.js'++/** Failed starts in a row that suspend an engine on a machine. */+export const SUSPEND_AFTER = 2+/** How long a suspension stands at most. */+export const SUSPENSION_MS = 6 * 3_600_000+const NAME: Record<string, string> = { claude: 'Claude Code', codex: 'Codex' }+const named = (engine: string) => NAME[engine] ?? engine+/** Failures that say nothing of the engine: the machine was removed, the start was dropped, or it lacked memory. Read at+ * call time: machines.ts imports this file, and startFailure.ts reaches machines.ts, so its constants may not exist yet+ * while this file loads. */+const notTheEngine = (error: string) => error === MACHINE_REMOVED || error === ABANDONED || error === 'Removed by its owner before it started.'+ || MEMORY_SHORT.test(error)+const MEMORY_SHORT = /^Not enough free memory: /++function pool(state: SuperTabState, machineId: string) { return state.machines?.find(m => m.machineId === machineId) }+/** Only a routed worker's start: a Product Manager's start has its own retries (leadStart.ts), and a Buddy is its owner's own. */+const counts = (start: AgentStart) => !!start.error && !start.request.gridModel && !start.request.leadFor && !start.request.buddyOf && !notTheEngine(start.error)++/** Signed in, with every usage window below its limit (or metered, with none), in the machine's latest reading. */+function readsFine(machine: ContributedMachine, engine: string): boolean {+ const reading = machine.observation+ const quota = reading?.quotas?.find(q => q.engine === engine)+ return reading?.readiness?.engines?.find(e => e.engine === engine)?.signedIn === true+ && quota?.known === true && quota.windows.every(w => w.usedPercent < 100)+}+function active(machine: ContributedMachine, engine: string, now: number) {+ const suspension = machine.engineSuspensions?.[engine]+ return suspension && now - suspension.at < SUSPENSION_MS ? suspension : null+}+function suspensionReason(engine: string, fine: boolean): string {+ return `${named(engine)} is suspended on this machine for new work: its last ${SUSPEND_AFTER} starts there failed. `+ + (fine ? 'It is offered again within 6 hours, or once its owner resumes it.'+ : 'It is offered again once a reading shows it signed in with quota left, within 6 hours, or once its owner resumes it.')+}++/** Counts a failed start against its engine on its machine. Returns the suspension's sentence when this failure suspends+ * the engine, and null otherwise, so its notice is posted once per suspension, never on a later failure. */+export function noteStartFailed(state: SuperTabState, start: AgentStart, now: number): string | null {+ const machine = pool(state, start.request.machineId), engine = start.request.engine+ if (!machine || !counts(start) || active(machine, engine, now)) return null+ const failures = (machine.engineFailures?.[engine] ?? 0) + 1+ if (failures < SUSPEND_AFTER) { machine.engineFailures = { ...machine.engineFailures, [engine]: failures }; return null }+ const { [engine]: _done, ...others } = machine.engineFailures ?? {}+ machine.engineFailures = others+ const fine = readsFine(machine, engine)+ machine.engineSuspensions = { ...machine.engineSuspensions, [engine]: { at: now, fine } }+ return suspensionReason(engine, fine)+}++/** A start that ran: its engine's failures there are no longer in a row. */+export function noteStartSucceeded(state: SuperTabState, start: AgentStart): void {+ const machine = pool(state, start.request.machineId)+ if (!machine?.engineFailures?.[start.request.engine]) return+ const { [start.request.engine]: _reset, ...others } = machine.engineFailures+ machine.engineFailures = others+}++/** After a reading is stored: a suspension ends once the engine reads fine, unless it already read fine as it was suspended+ * (its starts failed for another reason, and every report would end it at once). Ended and expired ones are dropped. */+export function readingClearsSuspensions(machine: ContributedMachine, now: number): void {+ if (!machine.engineSuspensions) return+ const kept = Object.entries(machine.engineSuspensions).filter(([engine, s]) => now - s.at < SUSPENSION_MS && (s.fine || !readsFine(machine, engine)))+ machine.engineSuspensions = Object.fromEntries(kept)+}++/** The machine owner's resume: true when there was a suspension to end. */+export function resumeEngine(machine: ContributedMachine, engine: string): boolean {+ const had = !!machine.engineSuspensions?.[engine]+ if (machine.engineSuspensions) { const { [engine]: _ended, ...others } = machine.engineSuspensions; machine.engineSuspensions = others }+ if (machine.engineFailures) { const { [engine]: _reset, ...others } = machine.engineFailures; machine.engineFailures = others }+ return had+}++/** Each engine suspended on the machine now, with why: what the route leaves out and Desktop strikes through. */+export function suspendedEngines(machine: ContributedMachine, now: number): Record<string, string> {+ return Object.fromEntries(Object.entries(machine.engineSuspensions ?? {}).filter(([engine]) => active(machine, engine, now))+ .map(([engine, s]) => [engine, suspensionReason(engine, s.fine)]))+}++/** Why a new start of [engine] on the machine is refused, or null: signed out or out of quota in its reading, or suspended.+ * What the reading does not say stays usable. */+export function engineUnusable(machine: ContributedMachine, engine: string, now: number): string | null {+ const reading = machine.observation+ if (reading?.readiness?.engines?.find(e => e.engine === engine)?.signedIn === false) return `${named(engine)} is not signed in to a subscription on this machine.`+ const quota = reading?.quotas?.find(q => q.engine === engine)+ if (quota?.known && quota.windows.some(w => w.usedPercent >= 100)) return `${named(engine)} has no subscription quota left on this machine until its usage window resets.`+ const suspension = active(machine, engine, now)+ return suspension ? suspensionReason(engine, suspension.fine) : null+}diff --git a/backend/src/superTabs/liveness.test.ts b/backend/src/superTabs/liveness.test.tsindex 6ff2794ff..93c11e903 100644--- a/backend/src/superTabs/liveness.test.ts+++ b/backend/src/superTabs/liveness.test.ts@@ -87,6 +87,19 @@ describe('a start its machine has launched', () => {expect(sweep(launched(), at + 1).error).toBe('Worker Mac did not start it within 3 minutes')})+ // A start its machine never started counts against its engine there as a host's failure does (engineHealth.ts).+ it('suspends its engine on its machine with the second one, saying so once and tagging the machine owner', () => {+ const at = LAUNCHED + 3 * MINUTE + 1+ const state = launched([{ receivedAt: at }], { machineOwnerId: 'o', request: { conversationId: 'lead', machineId: 'm', engine: 'codex', name: 'Builder' } })+ state.starts!.push(...['s2', 's3'].map(id => ({ ...structuredClone(state.starts![0]!), id })))+ const rows = () => sweepLiveness(state, at).filter(row => row.source?.kind === 'start-timeout')+ // All three time out in this one sweep: the second suspends Codex there, the third says nothing more.+ const told = rows()+ expect(told.map(row => row.mentions)).toEqual([undefined, ['o'], undefined])+ expect(told[1]!.text).toContain('Codex is suspended on this machine for new work: its last 2 starts there failed.')+ expect(told[2]!.text).not.toContain('suspended')+ })+it('steps its group up when it ran a grid model, and tells the Lead in the same notice', () => {const at = LAUNCHED + 3 * MINUTE + 1const state = launched([{ receivedAt: at }], { request: { conversationId: 'lead', machineId: 'm', name: 'Builder', gridModel: 'moonshotai/kimi-k3' } })diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.tsindex 5b2127dac..67fc24c21 100644--- a/backend/src/superTabs/liveness.ts+++ b/backend/src/superTabs/liveness.ts@@ -1,5 +1,6 @@-import { activeWork, stableId, type Agent, type AgentStart, type Assignment, type Author, type Conversation, type MessageDraft,+import { activeWork, forRecipients, stableId, type Agent, type AgentStart, type Assignment, type Author, type Conversation, type MessageDraft,type SuperTabState, type TaskLiveness } from './model.js'+import { noteStartFailed } from './engineHealth.js'import { machineOffline, sessionStopped } from './lostReason.js'import { agentDisplayName } from './agentNames.js'import { failureNotice, LEAD_PICKUP_SUFFIX, STILL_PREPARING_SUFFIX, STOPPED_REPORTING_SUFFIX, TIMED_OUT_SUFFIX } from './startFailure.js'@@ -48,6 +49,12 @@ const reachable = (state: SuperTabState, row: MessageDraft): MessageDraft => ({return !!target && state.people.find(p => p.id === target.contributorId)?.generation === target.membershipGeneration}) })+/** A notice for the Lead (terminal.ts toLead): when the Lead hears it in its own chat, the copy left in the task's chat for+ * no one is that same notice, read by no one either. With no Lead to hear it, people read it (review of #2177). */+export function leadNoticeRows(rows: MessageDraft[]): MessageDraft[] {+ return rows.some(row => row.recipients.length) ? rows.map(row => row.recipients.length ? row : { ...row, source: forRecipients(row.source ?? {}) }) : rows+}+/** The agent's own progress (an assignment, a status, a check, a post) renews the lease stored on its assignment. */export function renewLease(assignment: Assignment, now: number): void {assignment.leaseUntil = now + LEASE_MS@@ -143,10 +150,10 @@ function loseTask(state: SuperTabState, group: Conversation, worker: Agent, reas: 'Assign it to another agent now, or cancel it.')// Named by the loss, not the task: a task resumed after a usage limit keeps its id and can be lost again (2026-10-28).const loss = String(now)- return [...toLead(state, worker, { id: stableId('work-lost', assignment.id, loss), conversationId: group.id, author: sender, replyTo: null, recipients: [], text: wake, source }),- { id: stableId('work-lost', assignment.id, loss, 'agent'), conversationId: group.id, author: sender, replyTo: null, recipients: [worker.id], source,- text: `Your task "${group.title}" moved: ${reason}. Stop working on it; your status and results for it are no longer accepted.` }]- .map(row => reachable(state, row))+ return [...leadNoticeRows(toLead(state, worker, { id: stableId('work-lost', assignment.id, loss), conversationId: group.id, author: sender, replyTo: null,+ recipients: [], text: wake, source }).map(row => reachable(state, row))),+ reachable(state, { id: stableId('work-lost', assignment.id, loss, 'agent'), conversationId: group.id, author: sender, replyTo: null, recipients: [worker.id], source,+ text: `Your task "${group.title}" moved: ${reason}. Stop working on it; your status and results for it are no longer accepted.` })]}/** Loses at once the tasks of the workers `which` picks that have a reason now: an agent that just reported a usage limit,@@ -363,6 +370,8 @@ function failStalledStarts(state: SuperTabState, now: number): MessageDraft[] {if (named && !silent && now - start.dispatchedAt <= START_PREPARE_MS) return []const machine = machineName(state, start.request.machineId)start.error = `${machine}${!named ? TIMED_OUT_SUFFIX : silent ? STOPPED_REPORTING_SUFFIX : STILL_PREPARING_SUFFIX}`+ // Counted as a host's failure is (commands.ts agent.startFailed); the one that suspends its engine says so once.+ const suspended = noteStartFailed(state, start, now)if (start.request.leadFor) return leadNotice(state, start, leadStartFailed(state, start, start.error, now))// Never a lookup that throws: these checks run inside every machine's report.if (start.request.buddyOf) return buddyNotice(state, start)@@ -375,6 +384,7 @@ function failStalledStarts(state: SuperTabState, now: number): MessageDraft[] {if (!group || !lead) return []return [reachable(state, { id: stableId('start-timeout', start.id), conversationId: group.id, replyTo: null,recipients: group.agentIds.includes(lead.id) ? [lead.id] : [], author: writtenBy(state, lead),- text: `${failureNotice(start.request.name, start.error)}${stepped ? `\n\n${stepped.notice}` : ''}`, source: { kind: 'start-timeout', startId: start.id } })]+ text: `${failureNotice(start.request.name, start.error)}${stepped ? `\n\n${stepped.notice}` : ''}${suspended ? `\n\n${suspended}` : ''}`,+ ...(suspended && start.machineOwnerId ? { mentions: [start.machineOwnerId] } : {}), source: { kind: 'start-timeout', startId: start.id } })]})}diff --git a/backend/src/superTabs/machines.test.ts b/backend/src/superTabs/machines.test.tsindex c6a888c43..c83c78bfd 100644--- a/backend/src/superTabs/machines.test.ts+++ b/backend/src/superTabs/machines.test.ts@@ -37,6 +37,16 @@ it('accepts the served models Builders are not offered, with why', () => {expect(machineObservationSchema.safeParse({ ...sent, refusedModels: Array(17).fill(refused) }).success).toBe(false)})+it('accepts why an allowance is unknown, and a reading from before it', () => {+ const { receivedAt: _receivedAt, ...sent } = observation+ expect(machineObservationSchema.safeParse(sent).success).toBe(true)+ expect(machineObservationSchema.safeParse({ ...sent, quotaReasons: { claude: 'Anthropic is limiting how often the allowance can be read.' } }).success).toBe(true)+ expect(machineObservationSchema.safeParse({ ...sent, quotaReasons: { claude: '' } }).success).toBe(false)+ expect(machineObservationSchema.safeParse({ ...sent, quotaReasons: { claude: 'x'.repeat(301) } }).success).toBe(false)+ expect(machineObservationSchema.safeParse({ ...sent, quotaReasons: { 'Not An Engine': 'why' } }).success).toBe(false)+ expect(machineObservationSchema.safeParse({ ...sent, quotaReasons: Object.fromEntries(Array.from({ length: 9 }, (_, i) => [`e${i}`, 'why'])) }).success).toBe(false)+})+it('accepts what a machine is ready for, and a reading from before it', () => {const { receivedAt: _receivedAt, ...sent } = observationconst readiness = { engines: [{ engine: 'claude', installed: true, signedIn: false }, { engine: 'codex', installed: null, signedIn: null }],diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex 5129b90d6..ceda5ddd1 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -1,4 +1,5 @@import { z } from 'zod'+import { engineUnusable } from './engineHealth.js'import { MAX_HARNESSES, tokensByModelSchema } from './costs/tokens.js'import { activeWork, fail, person, stableId, type Actor, type Agent, type AgentStart, type AgentStartRequest, type MessageDraft, type SuperTabState } from './model.js'import { WORKSPACE_LABEL } from './workspaces.js'@@ -37,6 +38,10 @@ export interface ContributedMachine {teamAccountOnly?: true/** Agent-time Swarm agents here spent on other people's tasks, by leaderboard week, kept by its readings (leaderboard/lent.ts). */lent?: import('./leaderboard/lent.js').LentWeek[]+ /** Per engine, its failed starts here in a row, until one runs or they suspend it (engineHealth.ts). */+ engineFailures?: Record<string, number>+ /** Per engine, a suspension after failed starts: when, and whether its reading already said signed in with quota then. */+ engineSuspensions?: Record<string, { at: number; fine: boolean }>}/** A removed machine whose host never acknowledged in time: its records are gone, its host still cleans up on its next poll.* [requestedAt]: when its removal was asked for; none on one recorded before 2026-10-28. */@@ -99,7 +104,11 @@ const readiness = z.object({export const machineObservationSchema = z.object({ generation: z.string().max(160), resources: resource,tools: z.record(z.string().max(80), z.boolean()).refine(v => Object.keys(v).length <= 20),toolProbeErrors: z.record(z.string().max(80), z.string().max(200)).refine(v => Object.keys(v).length <= 20).optional(),- quotas: z.array(quota).max(32), runningHarnessIds: z.array(z.string().max(160)).max(1000),+ quotas: z.array(quota).max(32),+ /** Per engine whose allowance is unknown, why, in plain words naming no account, token or plan (cli superTabs/capacity.ts+ * quotaUnknownReason): what the route says of it. Absent from hosts before it. */+ quotaReasons: z.record(z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/), z.string().min(1).max(300)).refine(v => Object.keys(v).length <= 8).optional(),+ runningHarnessIds: z.array(z.string().max(160)).max(1000),stoppedHarnessIds: z.array(z.string().max(160)).max(1000),stoppedReservations: z.array(z.object({ harnessId: z.string().min(1).max(160), generation: z.string().min(1).max(160) }).strict()).max(1000).optional(),/** When each running agent's screen or transcript last changed (epoch ms); its lease renews on recent progress@@ -564,5 +573,8 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque}if (machineOffline(pool, now)) fail('MACHINE_OFFLINE', 'Wait for a fresh reading from the contributed machine.')if (!start && machineSlots(state, pool) >= pool.maxAgents) fail('MACHINE_FULL', 'This machine has reached its contributed agent limit.')+ // A new start only: a grid model runs without the engine's subscription, and one already asked for is settled by its host.+ const unusable = !start && !local ? engineUnusable(pool, request.engine, now) : null+ if (unusable) fail('ENGINE_UNAVAILABLE', unusable)return pool}diff --git a/backend/src/superTabs/migration/workspaces.ts b/backend/src/superTabs/migration/workspaces.tsindex dbac4bd02..be34e23de 100644--- a/backend/src/superTabs/migration/workspaces.ts+++ b/backend/src/superTabs/migration/workspaces.ts@@ -124,7 +124,7 @@ async function machinesInTwoWorkspaces(db: PrismaClient, owners: Map<string, Penconst pools = await db.swarmMachine.findMany({ where: { deleted: false, contributed: true }, select: { tabId: true, machineId: true } })const workspaceOf = new Map<string, string>()for (const [workspaceId, swarms] of owners) for (const swarm of swarms) workspaceOf.set(swarm.id, workspaceId)- for (const row of await db.superTab.findMany({ where: { id: { in: pools.map(p => p.tabId) } }, select: { id: true, workspaceId: true } })) {+ for (const row of pools.length ? await db.superTab.findMany({ where: { id: { in: pools.map(p => p.tabId) } }, select: { id: true, workspaceId: true } }) : []) {if (row.workspaceId) workspaceOf.set(row.id, row.workspaceId)}const byMachine = new Map<string, string[]>()diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 7b2c7544f..07ec0d861 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -57,6 +57,9 @@ export interface Agent {/** The model on the Swarm's grid its start named, which its engine never reports. Kept here because a command does not* load a finished start (parts/load.ts loadActive), and the leaderboard counts every assignment by it (review of #1808). */gridModel?: string+ /** Its start named no model, so it runs its engine's own: rated by the policy's `default` row for life (rules.ts+ * agentTarget). Kept here for the same reason as [gridModel]: a command never sees the finished start (live bug 10-29). */+ launchedDefault?: trueconfiguration: AgentConfiguration/** The last configuration operation fences delayed observations, including re-contribution. */configurationVersion?: string@@ -220,6 +223,8 @@ export interface Conversation {lastMainSequence?: number/** Linked GitHub pull requests, including links older than the latest message page. Absent in older snapshots. */pullRequestUrls?: string[]+ /** Its messages drawn as live cards: its task and each linked pull request (cards.ts). Absent until its first card. */+ cards?: import('./cards.js').GroupCards/** The last sequence given to a message here. Each conversation numbers its own messages (store by parts). */messageSeq?: number/** The sequence of its last message that counts toward its project's reports (projectUpdates.ts). */@@ -259,14 +264,13 @@ export interface TaskLiveness {personId?: string}+/** The GitHub pull request links in [text], each once, in order. */+export const pullRequestLinks = (text: string): string[] => [...new Set([...text.matchAll(/https:\/\/github\.com\/[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+\/pull\/([1-9][0-9]*)\b/g)]+ .filter(match => Number(match[1]) <= Number.MAX_SAFE_INTEGER).map(match => match[0]))]+export function appendPullRequestUrls(group: Conversation, texts: Iterable<string | null | undefined>): void {const urls = new Set(group.pullRequestUrls ?? [])- for (const text of texts) {- if (!text) continue- for (const match of text.matchAll(/https:\/\/github\.com\/[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+\/pull\/([1-9][0-9]*)\b/g)) {- if (Number(match[1]) <= Number.MAX_SAFE_INTEGER) urls.add(match[0])- }- }+ for (const text of texts) if (text) for (const url of pullRequestLinks(text)) urls.add(url)group.pullRequestUrls = [...urls]}export interface Invitation {@@ -376,7 +380,21 @@ export interface MessageDraft {}/** A notice for one agent alone (a skill update): delivered to it like any message, never shown to people or other agents. */export const AGENT_ONLY = { kind: 'agent-only' }-export const agentOnly = (source: unknown): boolean => (source as { kind?: unknown } | null | undefined)?.kind === AGENT_ONLY.kind+/** Notices written for the Lead or an agent, read only by their recipients like an agent-only notice, under their own kind+ * so their recipients receive them as before: the Lead's wake for a stalled, lost or resumed task, the old agent's moved+ * notice, and the Lead's scheduled report and digest requests. People read the task's state on its status line (Ken,+ * 2026-10-29: shown under the Lead's name in the project chat, they read as requests to act). By kind, so the ones already+ * stored are hidden as well; but only one that reaches an agent: with no Lead to hear it, a person is the only one who can+ * act, so people read it (review of #2177). */+const RECIPIENT_NOTICES = new Set<unknown>(['work-stalled', 'work-lost', 'work-resumed', 'update-request', 'digest-request'])+/** Marks a notice of a kind people also read (a cancel to its worker), or a copy for no one of a notice its recipient hears+ * elsewhere, as its recipients' alone. */+export const forRecipients = (source: Record<string, unknown>) => ({ ...source, recipientsOnly: true as const })+/** Whether only the message's recipients read it: never people, nor other agents. */+export const agentOnly = (source: unknown, recipients: readonly string[]): boolean => {+ const notice = source as { kind?: unknown; recipientsOnly?: unknown } | null | undefined+ return notice?.kind === AGENT_ONLY.kind || notice?.recipientsOnly === true || (RECIPIENT_NOTICES.has(notice?.kind) && recipients.length > 0)+}/** What a Buddy reads of an agent and of a task: no machine or terminal ids (review 1 of #2115: no machines means none). *//** A lost task's reason without the machine it ran on (lostReason.ts). */export const agentWithoutMachine = <T extends Pick<Agent, 'machineId' | 'harnessId' | 'replacement' | 'lostTask'>>(target: T): T => {diff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.tsindex 321288ddf..d86569e2c 100644--- a/backend/src/superTabs/pageReads.ts+++ b/backend/src/superTabs/pageReads.ts@@ -1,7 +1,7 @@import type { Prisma, SuperTabDelivery } from '@prisma/client'import { ms } from './parts/light.js'import type { ReactionRow } from './reactions.js'-import { agentOnly, type Author } from './model.js'+import { agentOnly, stableId, type Author } from './model.js'type Transaction = Prisma.TransactionClient@@ -57,6 +57,27 @@ export async function inConversationOrder<T extends Pick<SuperTabDelivery, 'convreturn ordered}+/** The Lead's notices that leave a copy in a task's chat when the Lead hears them in its own chat (terminal.ts toLead). */+const LEAD_COPY_KINDS = new Set<unknown>(['work-lost', 'work-resumed'])++/** Of `rows`, the task chat copies stored before #2177 marked them (liveness.ts leadNoticeRows) whose project chat copy+ * reached the Lead: that same notice, so read by no one either (re-check of #2177). A copy whose Lead copy reached no one,+ * or that has none, stays shown: a person is then the only one who can act. Each Lead copy is read by its id alone, its+ * Swarm checked here (inConversationOrder), and only when a row could be such a copy. */+export async function deliveredCopies(tx: Transaction, tabId: string, rows: ReadonlyArray<{ id: string; source: unknown; recipientIds: readonly string[] }>):+ Promise<Set<string>> {+ const copies = rows.filter(row => {+ const source = row.source as { kind?: unknown; recipientsOnly?: unknown } | null | undefined+ return !row.recipientIds.length && LEAD_COPY_KINDS.has(source?.kind) && source?.recipientsOnly !== true+ })+ if (!copies.length) return new Set()+ const leads = await tx.superTabMessage.aggregateRaw({ pipeline: [+ { $match: { _id: { $in: copies.map(row => stableId(row.id, 'lead')) } } }, { $project: { tabId: 1, recipientIds: 1 } }] }) as+ unknown as Array<{ _id: string; tabId: string; recipientIds?: string[] }>+ const reached = new Set(leads.filter(lead => lead.tabId === tabId && lead.recipientIds?.length).map(lead => lead._id))+ return new Set(copies.filter(row => reached.has(stableId(row.id, 'lead'))).map(row => row.id))+}+export interface ThreadReply { thread: string; id: string; author: Author; mentions: string[]; sequence: number; createdAt: Date; agentOnly: boolean }/** Every message of the threads rooted at `roots` in one conversation, roots included, oldest first: what the page's thread@@ -64,8 +85,10 @@ export interface ThreadReply { thread: string; id: string; author: Author; mentiexport async function pageThreads(tx: Transaction, tabId: string, conversationId: string, roots: string[]): Promise<ThreadReply[]> {// Sorted here: a $sort in the pipeline makes the planner walk the conversation's sequence index instead.const rows = await tx.superTabMessage.aggregateRaw({ pipeline: [{ $match: { tabId, conversationId, thread: { $in: roots } } },- { $project: { thread: 1, author: 1, mentions: 1, sequence: 1, createdAt: 1, source: 1 } }] }) as unknown as Array<Record<string, unknown>>+ { $project: { thread: 1, author: 1, mentions: 1, sequence: 1, createdAt: 1, source: 1, recipientIds: 1 } }] }) as unknown as Array<Record<string, unknown>>+ const copies = await deliveredCopies(tx, tabId, rows.filter(row => row._id === row.thread)+ .map(row => ({ id: row._id as string, source: row.source, recipientIds: (row.recipientIds ?? []) as string[] })))return rows.map(row => ({ thread: row.thread as string, id: row._id as string, author: row.author as Author,mentions: (row.mentions ?? []) as string[], sequence: row.sequence as number, createdAt: new Date(ms(row.createdAt)),- agentOnly: agentOnly(row.source) })).sort((a, b) => a.sequence - b.sequence || (a.id < b.id ? -1 : 1))+ agentOnly: copies.has(row._id as string) || agentOnly(row.source, (row.recipientIds ?? []) as string[]) })).sort((a, b) => a.sequence - b.sequence || (a.id < b.id ? -1 : 1))}diff --git a/backend/src/superTabs/parts/commit.ts b/backend/src/superTabs/parts/commit.tsindex 037b33d90..dba0f4baf 100644--- a/backend/src/superTabs/parts/commit.ts+++ b/backend/src/superTabs/parts/commit.ts@@ -94,7 +94,7 @@ export function numberMessages(state: SuperTabState, messages: MessageDraft[], nconst sequence = (group.messageSeq ?? state.sequenceBase ?? 0) + 1group.messageSeq = sequencesequences.set(message.id, sequence)- if (agentOnly(message.source)) continue+ if (agentOnly(message.source, message.recipients)) continuegroup.lastMessageSequence = sequenceif (!message.thread || message.alsoInChat) group.lastMainSequence = sequencegroup.lastActivityAt = new Date(now).toISOString()diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.tsindex 9fbe29bea..6ee87a8bd 100644--- a/backend/src/superTabs/parts/light.test.ts+++ b/backend/src/superTabs/parts/light.test.ts@@ -11,7 +11,7 @@ const assignment: Required<Assignment> = {}const conversation: Required<Conversation> = {id: 'g', kind: 'leads', projectId: 'p', number: 1, title: 't', leadId: null, agentIds: [], archived: false, brief: '',- task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, pullRequestUrls: [],+ task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, pullRequestUrls: [], cards: {},messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' }, reactionSeq: 0,requesterId: 'p', ledger: {}, proposals: [], liveness: { state: 'quiet', why: 'silent', since: 1 }, leadAction: { kind: 'post', at: 1 },stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' },diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex a07e99df2..94a7ad713 100644--- a/backend/src/superTabs/parts/light.ts+++ b/backend/src/superTabs/parts/light.ts@@ -27,7 +27,7 @@ export const GROUP_FIELDS = {always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status','assignment.lost'],whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],- unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'lastMainSequence', 'pullRequestUrls', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'liveness', 'leadAction', 'stepUp',+ unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'lastMainSequence', 'pullRequestUrls', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'liveness', 'leadAction', 'stepUp','assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf'],} as constconst LIGHT_GROUP = {diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex 7e2829a83..86b4b4a7c 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -59,7 +59,9 @@ export interface Derived {agents: Record<string, { downSince: string | null; limitedUntil: string | null; workDecision: 'awaiting' | null; roleId: string | null }>/** Every contributed machine the reader can see. *//** `clientVersion`: the CLI version its daemon last connected with (routing reads a machine updated since its failed starts). */- machines: Record<string, { availableSlots: number; teamWork: { allowed: true } | { allowed: false; reason: string; [key: string]: unknown }; clientVersion?: string }>+ machines: Record<string, { availableSlots: number; teamWork: { allowed: true } | { allowed: false; reason: string; [key: string]: unknown }; clientVersion?: string+ /** Engines suspended there now after failed starts, with why (engineHealth.ts); absent when none. */+ suspendedEngines?: Record<string, string> }>/** A Lead agent only. */otherProjectsWork?: OtherProjectWorkView[]/** A person only. */diff --git a/backend/src/superTabs/read/host.ts b/backend/src/superTabs/read/host.tsindex e4f640bf5..d187cc36e 100644--- a/backend/src/superTabs/read/host.ts+++ b/backend/src/superTabs/read/host.ts@@ -95,6 +95,8 @@ export class HostReads {* part when its settings or ledger changed, never when only its reading did (every 15 s; group 5's run, 2026-10-26).*/private async woken(tx: Transaction, ids: string[], machineId: string, since: number): Promise<Set<string>> {+ // A host with no Swarm polls every second: an empty list would reach Prisma as `$or: []`, a scan of the whole collection.+ if (!ids.length) return new Set()const after = new Date(since)const [changed, groups, machines] = await Promise.all([parts.loadChanged(tx, ids, after, PLAIN_KINDS),@@ -166,7 +168,7 @@ export class HostReads {}private async lookups(tx: Transaction, state: SuperTabState, teams: Array<{ machineId: string }>, grants: GrantReads): Promise<HostLookups> {- const people = await tx.user.findMany({ where: { id: { in: state.people.map(p => p.id) }, autonomousEnv: state.environment }, select: { id: true, email: true } })+ const people = state.people.length ? await tx.user.findMany({ where: { id: { in: state.people.map(p => p.id) }, autonomousEnv: state.environment }, select: { id: true, email: true } }) : []const confidential = await confidentialSessions(tx, state.agents.map(a => a.id), state.id)return { people, confidential, teams, githubApp: !!this.options.githubApp, agentGrant: target => this.store.agentGrant(tx, state, target, grants) }}diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex a683510a7..6dc7dd4e7 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -188,11 +188,12 @@ export class SwarmReads {...(after ? { id: { gt: after } } : {}) }, orderBy: { id: 'asc' }, take: 101, select: { id: true, ownerId: true, format: true, workspaceId: true } })// A Swarm of a Workspace the person is no longer in is not theirs to list, even before their removal from it has run.const workspaceIds = [...new Set(rows.flatMap(r => r.workspaceId ? [r.workspaceId] : []))]- const current = new Set((await this.db.swarmWorkspaceMember.findMany({ where: { workspaceId: { in: workspaceIds }, userId: user.sub, removedAt: null },- select: { workspaceId: true } })).map(m => m.workspaceId))+ const current = new Set((workspaceIds.length ? await this.db.swarmWorkspaceMember.findMany({ where: { workspaceId: { in: workspaceIds }, userId: user.sub, removedAt: null },+ select: { workspaceId: true } }) : []).map(m => m.workspaceId))const page = rows.slice(0, 100).filter(r => r.workspaceId ? current.has(r.workspaceId) : !workspacesRequired())// A Swarm not yet in parts is migrated when it is opened; until then the list names it from its old row.- const legacy = await this.db.superTab.findMany({ where: { id: { in: page.filter(r => r.format !== 2).map(r => r.id) } }, select: { id: true, state: true } })+ const unsplit = page.filter(r => r.format !== 2).map(r => r.id)+ const legacy = unsplit.length ? await this.db.superTab.findMany({ where: { id: { in: unsplit } }, select: { id: true, state: true } }) : []const ids = page.filter(r => r.format === 2).map(r => r.id)// Every head changed after the epoch: one read of each listed Swarm's head part.const [heads, newest] = await transaction(this.db, tx => Promise.all([parts.loadChanged(tx, ids, new Date(0), ['head']), parts.lastChangedAt(tx, ids)]))diff --git a/backend/src/superTabs/read/views.test.ts b/backend/src/superTabs/read/views.test.tsindex a04890289..5cd5d3910 100644--- a/backend/src/superTabs/read/views.test.ts+++ b/backend/src/superTabs/read/views.test.ts@@ -104,6 +104,15 @@ describe('reader view of the parts (design 4.1, 4.3)', () => {expect(view.derived.machines).toEqual({ mac: { availableSlots: 1, teamWork: { allowed: true } } })})+ // The route leaves a suspended engine out and Desktop strikes it through (engineHealth.ts); 6 hours on it no longer shows.+ it('derives the engines suspended on a machine now, with why, and none once the suspension has run out', () => {+ const s = richSwarm()+ s.contribute('mac', 'swarm')+ s.edit(state => { state.machines![0]!.engineSuspensions = { codex: { at: NOW - MINUTE, fine: true }, claude: { at: NOW - 7 * 60 * MINUTE, fine: false } } })+ const view = readerView(store.split(s.state, { tabId: 'tab', version: R, now: NOW }), peer, NOW, { teamMachines: [] })+ expect(view.derived.machines.mac!.suspendedEngines).toEqual({ codex: expect.stringContaining('Codex is suspended on this machine for new work') })+ })+it('gives a Lead the other projects\' work and a person the mentions waiting', () => {const { s, parts } = scene()expect(readerView(parts, agentActor(s.lead), NOW, { teamMachines: [] }).derived).toHaveProperty('otherProjectsWork', [])diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.tsindex 9a7a1a2a8..47040455d 100644--- a/backend/src/superTabs/read/views.ts+++ b/backend/src/superTabs/read/views.ts@@ -3,6 +3,7 @@* plus the private-conversation check, each record sent in its part's envelope. Time-based and cross-part values go only* in `derived`, so a part never changes without a new version (Lead's ruling).*/+import { suspendedEngines } from '../engineHealth.js'import { isBuddyChat, isBuddyReader } from '../buddies.js'import { agentWithoutMachine, groupWithoutMachines, isLeads, seenMachineIds, visibleState, withSeenRequirement, type Actor, type Agent, type Conversation, type SuperTabState } from '../model.js'import { machineSlots, machineTeamWork, teamAccountSwarm, type ContributedMachine } from '../machines.js'@@ -114,8 +115,10 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:const stored = state.machines!.find(m => m.machineId === pool.machineId)!const refusal = machineTeamWork(state, stored, now, extras.teamMachines, extras.otherWorkspaceMachines ?? [])const version = extras.machineVersions?.[pool.machineId]+ const suspended = suspendedEngines(stored, now)return [pool.machineId, { availableSlots: Math.max(0, pool.maxAgents - machineSlots(state, stored)),- teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const }, ...(version ? { clientVersion: version } : {}) }] as const+ teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const }, ...(version ? { clientVersion: version } : {}),+ ...(Object.keys(suspended).length ? { suspendedEngines: suspended } : {}) }] as const}return {agents: Object.fromEntries(visible.agents.map(seen => [seen.id, { downSince: seen.downSince ?? null, limitedUntil: seen.limitedUntil ?? null,diff --git a/backend/src/superTabs/rules.ts b/backend/src/superTabs/rules.tsindex 8b2e0eb2b..b73d7b3f0 100644--- a/backend/src/superTabs/rules.ts+++ b/backend/src/superTabs/rules.ts@@ -95,14 +95,16 @@ export const startTarget = (request: { machineId: string; engine: string; model?...(request.requirements ? { devices: request.requirements.devices } : {}), ...(request.gridModel ? { gridModel: request.gridModel } : {}) })/** A started agent was launched with `--effort`, which Claude never reports back, so its configuration may say `auto`; its- * start record still holds what it was launched with (manual run 2026-10-19). */+ * start record still holds what it was launched with (manual run 2026-10-19). A command loads only unfinished starts, so+ * whether it was launched on the engine's default is read from the agent itself; the start only for one from before that. */export function agentTarget(state: SuperTabState, worker: Agent): RunTarget {const reported = worker.configuration.effortconst start = state.starts?.find(s => s.harnessId === worker.harnessId && s.request.machineId === worker.machineId)const launched = start?.request.effortreturn { machineId: worker.machineId, engine: worker.configuration.engine, model: worker.configuration.model,effort: reported && reported !== 'auto' ? reported : launched ?? reported, devices: start?.request.requirements?.devices ?? [],- ...(worker.gridModel ? { gridModel: worker.gridModel } : {}), ...(start && !worker.gridModel && !start.request.gridModel && (start.request.model ?? 'default') === 'default' ? { launchedDefault: true as const } : {}) }+ ...(worker.gridModel ? { gridModel: worker.gridModel } : {}), ...(!worker.gridModel && (worker.launchedDefault || (start && !start.request.gridModel && (start.request.model ?? 'default') === 'default'))+ ? { launchedDefault: true as const } : {}) }}/** The policy's strength of a subscription model, as the CLI's route rates it (cli superTabs/route.ts rateFor): its named rowdiff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex fa20d4194..00c2d8fd9 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1,4 +1,5 @@import { contributedEngines, expireRemovals, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, machineSlots, machineTeamWork, observedPrivacy, recordAgentPresence, removalPreview, startPreparing, swarmGridRow, teamAccountRequired, teamWorkRefusal, type MachineObservation } from './machines.js'+import { readingClearsSuspensions, suspendedEngines } from './engineHealth.js'import { createHash } from 'node:crypto'import { isDeepStrictEqual } from 'node:util'import type { Machine, Prisma, PrismaClient, SuperTabDelivery, SuperTabMessage } from '@prisma/client'@@ -11,7 +12,7 @@ import { applyCommand, authorizeCommandAccess, operationSchema, PAIR_CHAIN_LIMITimport { redactCredentials } from './credentials.js'import type { AvatarUpload } from './profile.js'import { reactionCounts, type ReactionTarget } from './reactions.js'-import { inConversationOrder, pageDeliveries, pageReactions, pageThreads } from './pageReads.js'+import { deliveredCopies, inConversationOrder, pageDeliveries, pageReactions, pageThreads } from './pageReads.js'import { threadSummaries } from './threads.js'import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVATAR_TYPES, checkedType, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, objectKeyFor, peekType, publicUrl, trimPrefix,type Attachment, type Attachments, type AttachmentStore, type AvatarStore } from './attachments.js'@@ -463,7 +464,7 @@ export class SuperTabStore {if (target && target.machineId !== team) refuse()}switch (command.type) {- case 'machine.contribute': case 'machine.pause': case 'machine.remove': return refuse()+ case 'machine.contribute': case 'machine.pause': case 'machine.remove': case 'machine.engineResume': return refuse()case 'machine.cleaned': case 'tab.project': case 'agent.add':if (command.machineId !== team) refuse()return@@ -488,6 +489,7 @@ export class SuperTabStore {* Swarm again to confirm (read/host.ts asks for a live account), so applyCommand drops their cleanups. */private async deletedMachines(tx: Transaction, state: SuperTabState): Promise<string[]> {const ids = [...new Set((state.machineCleanups ?? []).map(c => c.machineId))]+ if (!ids.length) return []const live = new Set((await tx.machine.findMany({ where: { machineId: { in: ids }, autonomousEnv: state.environment, ...machineAlive },select: { machineId: true } })).map(m => m.machineId))return ids.filter(id => !live.has(id))@@ -939,9 +941,12 @@ export class SuperTabStore {// Whether it takes teammates' projects now, and if not why (machines.ts teamWorkRefusal): what routing leaves it// out for, and what Desktop can show on the machine.const refusal = machineTeamWork(state, stored, now, teamMachines, otherWorkspace)+ const suspended = suspendedEngines(stored, now)return { ...pool, availableSlots: Math.max(0, pool.maxAgents - machineSlots(state, stored)),teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const },- ...(facts.versions[pool.machineId] ? { clientVersion: facts.versions[pool.machineId] } : {}) }+ ...(facts.versions[pool.machineId] ? { clientVersion: facts.versions[pool.machineId] } : {}),+ // What the route leaves out (cli superTabs/routeCommand.ts unreadyPool).+ ...(Object.keys(suspended).length ? { suspendedEngines: suspended } : {}) }}) } }}@@ -1118,10 +1123,11 @@ export class SuperTabStore {if (command.type === 'message.send' && command.replyTo) {const reply = await tx.superTabMessage.findFirst({ where: { id: command.replyTo, tabId, conversationId: command.conversationId } })if (reply) context.reply = { id: reply.id, conversationId: reply.conversationId, author: reply.author as unknown as Author, createdAt: reply.createdAt.getTime(),- thread: reply.thread }+ thread: reply.thread, ...(agentOnly(reply.source, reply.recipientIds) ? { agentOnly: true } : {}) }}if (command.type === 'message.send' && actor.kind === 'person') context.openTags = await openTags(tx, tabId, command.conversationId, actor.userId, context.now)- if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy') && command.askedIn) {+ if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'+ || command.type === 'machine.engineResume') && command.askedIn) {const asked = await tx.superTabMessage.findFirst({ where: { id: command.askedIn.messageId, tabId, conversationId: command.askedIn.conversationId } })if (asked) context.askedIn = { author: asked.author as unknown as Author, source: !!asked.source, createdAt: asked.createdAt.getTime() }}@@ -1209,7 +1215,7 @@ export class SuperTabStore {if (dispatched) context.routeDecision = await readDecision(tx, tabId, dispatched) ?? undefinedconst effects = applyCommand(original, actor, command, context)// An agent-only notice changes nothing people see: no link, no unread mark, no project report.- const shown = effects.messages.filter(message => !agentOnly(message.source))+ const shown = effects.messages.filter(message => !agentOnly(message.source, message.recipients))for (const group of effects.state.conversations) {appendPullRequestUrls(group, [...shown.filter(message => message.conversationId === group.id).map(message => message.text),@@ -1630,7 +1636,8 @@ export class SuperTabStore {private async reactionTarget(tx: Transaction, tabId: string, actor: Actor, command: ReactCommand): Promise<ReactionTarget | undefined> {const message = await tx.superTabMessage.findFirst({ where: { id: command.messageId, tabId, conversationId: command.conversationId },select: { id: true, source: true, recipientIds: true } })- if (!message || (agentOnly(message.source) && !(actor.kind === 'agent' && message.recipientIds.includes(actor.agentId)))) return undefined+ if (!message || (agentOnly(message.source, message.recipientIds) && !(actor.kind === 'agent' && message.recipientIds.includes(actor.agentId)))) return undefined+ if ((await deliveredCopies(tx, tabId, [message])).size) return undefinedreturn { messageId: message.id, reacted: !!await tx.superTabReaction.findUnique({ where: { id: reactionId(tabId, actor, command) } }) }}@@ -1931,7 +1938,9 @@ export class SuperTabStore {for (let edge: SuperTabMessage | undefined; rows.length <= 100;) {const batch = await tx.superTabMessage.findMany({ where: edge ? { AND: [where, past(edge.sequence, edge.id, forward ? 'gt' : 'lt')] } : where,orderBy: [{ sequence: order }, { id: order }], take: 101 })- rows.push(...batch.filter(m => (!agentOnly(m.source) || (actor.kind === 'agent' && m.recipientIds.includes(actor.agentId)))+ // A task chat's copy of a Lead's notice stored before it was marked is that notice: read by no one (pageReads.ts).+ const copies = await deliveredCopies(tx, tabId, batch)+ rows.push(...batch.filter(m => !copies.has(m.id) && (!agentOnly(m.source, m.recipientIds) || (actor.kind === 'agent' && m.recipientIds.includes(actor.agentId)))&& !(buddy && routingRow(m.source))))if (batch.length < 101) breakedge = batch.at(-1)@@ -1945,8 +1954,13 @@ export class SuperTabStore {const shown = buddy ? page.map(withoutMachineNames) : page// The threads the page's rows are in, so a poll that brings only a reply still moves its root's reply line.const roots = [...new Set(page.flatMap(m => m.thread ? [m.thread] : []))]- const threads = roots.length ? threadSummaries(state, group, await pageThreads(tx, tabId, conversationId, roots)) : []- return { messages: shown.map(m => ({ ...m, mentions: m.mentions ?? [], reactions: reactions.get(m.id) ?? [],+ const threadRows = roots.length ? await pageThreads(tx, tabId, conversationId, roots) : []+ // A reply stored in the thread of a notice only its recipients read (the Lead answering a stalled alert before such+ // replies started no thread, commands.ts) reads as one in the chat: nobody else can open that thread (review of #2177).+ const hiddenRoots = new Set(threadRows.filter(row => row.id === row.thread && row.agentOnly).map(row => row.id))+ const threads = threadRows.length ? threadSummaries(state, group, threadRows.filter(row => !hiddenRoots.has(row.thread))) : []+ const inChat = (m: SuperTabMessage) => m.thread && m.thread !== m.id && hiddenRoots.has(m.thread) ? { ...m, thread: m.id } : m+ return { messages: shown.map(inChat).map(m => ({ ...m, mentions: m.mentions ?? [], reactions: reactions.get(m.id) ?? [],deliveries: deliveries.filter(d => d.messageId === m.id) })), next, threads,// A poll for new messages learns here that a reaction changed on a message it already shows (reactions.ts).reactionSeq: group.reactionSeq ?? 0 }@@ -2169,6 +2183,8 @@ export class SuperTabStore {sessionKind: team ? 'team' : 'computer', ...(privacy ? { privacy } : {}), ...(progress ? { harnessProgress: progress } : {}),...(tokens ? { harnessTokens: tokens } : {}),...(preparing ? { preparingStartIds: preparing } : {}) }+ // A reading that shows a suspended engine signed in with quota offered again (engineHealth.ts); posts nothing.+ readingClearsSuspensions(pool, now)// Current-generation physical stop proof also finishes a close whose membership was already withdrawn.for (const proof of observation.stoppedReservations ?? []) {if (!observation.stoppedHarnessIds.includes(proof.harnessId)) continuediff --git a/backend/src/superTabs/workspaceStore.ts b/backend/src/superTabs/workspaceStore.tsindex a3f5d40cf..ae24f272a 100644--- a/backend/src/superTabs/workspaceStore.ts+++ b/backend/src/superTabs/workspaceStore.ts@@ -103,11 +103,14 @@ export interface WorkspaceSummary {* every one for owners and admins (names only: reading still needs the Swarm's own membership). */export async function listWorkspaces(db: PrismaClient, user: AuthUser): Promise<WorkspaceSummary[]> {const memberships = await db.swarmWorkspaceMember.findMany({ where: { userId: user.sub, removedAt: null }, take: 100 })+ // An empty list would reach Prisma as `$or: []`, a scan of the whole collection that finds nothing.+ if (!memberships.length) return []// Filtered here, not in the query: Prisma's `null` on Mongo misses a field that was never written.const workspaces = (await db.swarmWorkspace.findMany({ where: { id: { in: memberships.map(m => m.workspaceId) }, autonomousEnv: user.autonomousEnv } })).filter(o => !o.deletedAt)- const rows = await db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, workspaceId: { in: workspaces.map(o => o.id) } },- select: { id: true, workspaceId: true, memberIds: true, format: true } })- const heads = await db.swarmHead.findMany({ where: { id: { in: rows.filter(r => r.format === 2).map(r => `${r.id}:head`) } }, select: { tabId: true, data: true } })+ const rows = workspaces.length ? await db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, workspaceId: { in: workspaces.map(o => o.id) } },+ select: { id: true, workspaceId: true, memberIds: true, format: true } }) : []+ const split = rows.filter(r => r.format === 2).map(r => `${r.id}:head`)+ const heads = split.length ? await db.swarmHead.findMany({ where: { id: { in: split } }, select: { tabId: true, data: true } }) : []const headOf = new Map(heads.map(h => [h.tabId, h.data as { name?: string; workspaceVisibility?: 'invite-only' | 'workspace' }]))return workspaces.map(workspace => {const role = memberships.find(m => m.workspaceId === workspace.id)!.role as WorkspaceRolediff --git a/cli/src/lib/pullRequestsStatus.spec.ts b/cli/src/lib/pullRequestsStatus.spec.tsindex e9a7c7f70..5d1be0115 100644--- a/cli/src/lib/pullRequestsStatus.spec.ts+++ b/cli/src/lib/pullRequestsStatus.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest'import { ciCounts, type Run } from './github.js'-import { createPullRequestsStatusReader, PULL_REQUESTS_FRESH_MS, PULL_REQUESTS_MAX } from './pullRequestsStatus.js'+import { createPullRequestsStatusReader, ghAccount, PULL_REQUESTS_FRESH_MS, PULL_REQUESTS_MAX } from './pullRequestsStatus.js'const url = (n = 1) => `https://github.com/o/r/pull/${n}`const view = (over = {}) => ({ title: 'Fix reconnect', state: 'OPEN', isDraft: false, mergedAt: null, closedAt: null,@@ -11,7 +11,7 @@ const runner = (over = {}) => vi.fn<Run>(async () => ({ stdout: JSON.stringify(vdescribe('linked pull requests read directly from GitHub', () => {it('reads by URL and retains title, change counts, times and merge/review inputs', async () => {const run = runner(), read = createPullRequestsStatusReader(run, () => 0)- expect(await read([url()])).toEqual({ checkedAt: '1970-01-01T00:00:00.000Z', rows: [{+ expect(await read([url()])).toEqual({ checkedAt: '1970-01-01T00:00:00.000Z', account: expect.stringMatching(/^[0-9a-f]{16}$/), rows: [{url: url(), status: 'found', title: 'Fix reconnect', state: 'Open', mergedAt: '', closedAt: '',updatedAt: '2026-10-22T07:00:00Z', additions: 32, deletions: 6, ci: 'passing',checks: { passed: 1, failed: 0, pending: 0, total: 1 }, reviewDecision: 'APPROVED', mergeStateStatus: 'CLEAN', autoMerge: false,@@ -107,9 +107,11 @@ describe('linked pull requests read directly from GitHub', () => {const run = vi.fn<Run>(() => new Promise(resolve => { release = resolve }))const read = createPullRequestsStatusReader(run)const a = read([url()]), b = read([url()])- expect(run).toHaveBeenCalledTimes(1)+ // Each read first asks which account gh reads as, so the flight starts a moment later; it is still one.+ await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1))release({ stdout: JSON.stringify(view()) })expect(await a).toEqual(await b)+ expect(run).toHaveBeenCalledTimes(1)})it('caches final states permanently, open/no-access briefly, and failures for five seconds', async () => {let now = 0@@ -129,6 +131,51 @@ describe('linked pull requests read directly from GitHub', () => {now += 365 * 86400_000; await read(urls)expect(run).toHaveBeenCalledTimes(12)})+ it('forgets every answer, final ones too, when the GitHub account changes or signs out', async () => {+ let account: string | null = 'ada', answer: 'merged' | 'hidden' | 'signed-out' = 'merged'+ const run = vi.fn<Run>(async () => {+ if (answer === 'hidden') throw { stderr: 'HTTP 404: Not Found' }+ if (answer === 'signed-out') throw { stderr: 'To get started run gh auth login' }+ return { stdout: JSON.stringify(view({ state: 'MERGED', title: 'Private fix' })) }+ })+ const read = createPullRequestsStatusReader(run, () => 0, async () => account)+ expect((await read([url()])).rows[0]).toMatchObject({ status: 'found', title: 'Private fix', state: 'Merged' })+ expect((await read([url()])).rows[0]).toMatchObject({ title: 'Private fix' })+ expect(run).toHaveBeenCalledTimes(1)+ account = 'grace'; answer = 'hidden'+ expect((await read([url()])).rows[0]).toEqual({ url: url(), status: 'no_access' })+ account = null; answer = 'signed-out'+ expect(await read([url()])).toMatchObject({ error: 'GH_SIGNED_OUT', rows: [{ status: 'unavailable' }] })+ })+ it('names the account every answer was read as, so a switch shows even when the reads then fail', async () => {+ let account: string | null = 'ada', fail = false+ const run = vi.fn<Run>(async () => {+ if (fail) throw { killed: true }+ return { stdout: JSON.stringify(view({ title: 'Private fix' })) }+ })+ const read = createPullRequestsStatusReader(run, () => 0, async () => account)+ const ada = await read([url()])+ expect(ada.account).toMatch(/^[0-9a-f]{16}$/)+ expect((await read([url()])).account).toBe(ada.account)+ account = 'grace'; fail = true+ const grace = await read([url()])+ expect(grace).toMatchObject({ error: 'TIMEOUT', rows: [{ status: 'unavailable' }] })+ expect(grace.account).toMatch(/^[0-9a-f]{16}$/)+ expect(grace.account).not.toBe(ada.account)+ account = null+ const none = await read([url()])+ expect([none.account, none.account === grace.account]).toEqual([expect.stringMatching(/^[0-9a-f]{16}$/), false])+ expect(none.account).not.toContain('ada')+ })+ it('reads the account as a hash of the token gh holds, and none without one', async () => {+ const tokens = vi.fn<Run>(async () => ({ stdout: 'gho_secret\n' }))+ const id = await ghAccount(tokens)()+ expect(tokens).toHaveBeenCalledWith(['auth', 'token'])+ expect(id).toMatch(/^[0-9a-f]{64}$/)+ expect(id).not.toContain('gho_secret')+ expect(await ghAccount(async () => { throw { stderr: 'no oauth token found' } })()).toBeNull()+ expect(await ghAccount(async () => ({ stdout: ' ' }))()).toBeNull()+ })it('caps simultaneous subprocesses across overlapping lists', async () => {let active = 0, peak = 0const run: Run = async () => {diff --git a/cli/src/lib/pullRequestsStatus.ts b/cli/src/lib/pullRequestsStatus.tsindex 0665757fb..90cc78f82 100644--- a/cli/src/lib/pullRequestsStatus.ts+++ b/cli/src/lib/pullRequestsStatus.ts@@ -1,4 +1,5 @@/** Read linked PRs as this computer's own GitHub account, independent of running agents or checked-out branches. */+import { createHash, randomBytes } from 'node:crypto'import { ciCounts, ciOf, ghError, ghRun, MERGE_STATES, pooled, type CiCounts, type Run } from './github.js'import { validPullRequestUrl } from './sessionWorkWire.js'import { cleanText } from './cleanText.js'@@ -14,14 +15,32 @@ export interface PullRequestRow {reviewDecision?: string; mergeStateStatus?: string; autoMerge?: booleanerror?: string}-export interface PullRequestsResult extends Record<string, unknown> { rows: PullRequestRow[]; checkedAt: string; error?: string; detail?: string }+/** `account`: which GitHub account the answer was read as, failed reads included, so a reader forgets another account's+ * answers before taking this one's. Opaque: a hash under this reader's own random salt, never the token. */+export interface PullRequestsResult extends Record<string, unknown> { rows: PullRequestRow[]; checkedAt: string; account?: string; error?: string; detail?: string }const FIELDS = 'title,state,isDraft,mergedAt,closedAt,updatedAt,additions,deletions,statusCheckRollup,reviewDecision,mergeStateStatus,autoMergeRequest'const text = (value: unknown, max = 40): string => cleanText(value, max)const lines = (value: unknown): number => Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : 0-export function createPullRequestsStatusReader(run: Run = ghRun, now: () => number = Date.now) {+/** Who `gh` reads as: a hash of the token it holds (the token itself is never kept), or null when it holds none. Read from+ * gh's own store, without the network. */+export const ghAccount = (run: Run = ghRun) => async (): Promise<string | null> => {+ try {+ const token = (await run(['auth', 'token'])).stdout.trim()+ return token ? createHash('sha256').update(token).digest('hex') : null+ } catch {+ return null+ }+}++export function createPullRequestsStatusReader(run: Run = ghRun, now: () => number = Date.now, account: () => Promise<string | null> = ghAccount()) {const cache = new Map<string, { until: number; value: Promise<PullRequestRow> }>()+ // The account the cache was read as. Its answers, final ones too, are that account's: a private title must not outlive a+ // sign-out or a switch to another account.+ let readAs: string | null | undefined+ const salt = randomBytes(16).toString('hex')+ const named = (id: string | null) => createHash('sha256').update(`${salt}:${id ?? 'signed-out'}`).digest('hex').slice(0, 16)// Several panes can ask together. Their distinct URLs still share four subprocess slots.let active = 0const waiting: (() => void)[] = []@@ -71,10 +90,13 @@ export function createPullRequestsStatusReader(run: Run = ghRun, now: () => numbif (!Array.isArray(urls) || urls.length > PULL_REQUESTS_MAX || !urls.every(validPullRequestUrl)) {return { rows: [], checkedAt: new Date(now()).toISOString(), error: 'INVALID_URLS', detail: `Supply at most ${PULL_REQUESTS_MAX} GitHub pull request URLs.` }}+ const current = await account()+ if (readAs !== undefined && current !== readAs) cache.clear()+ readAs = currentconst unique = [...new Set(urls)] as string[], rows = new Map<string, PullRequestRow>()await pooled(unique, 4, async url => { rows.set(url, await read(url)) })const ordered = unique.map(url => rows.get(url)!)const error = ['GH_MISSING', 'GH_SIGNED_OUT', 'RATE_LIMITED', 'TIMEOUT', 'GH_FAILED'].find(code => ordered.some(row => row.error === code))- return { rows: ordered, checkedAt: new Date(now()).toISOString(), ...(error ? { error } : {}) }+ return { rows: ordered, checkedAt: new Date(now()).toISOString(), account: named(current), ...(error ? { error } : {}) }}}diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.tsindex 6e92ee771..b3f6c6779 100644--- a/cli/src/lib/swarmSkills.spec.ts+++ b/cli/src/lib/swarmSkills.spec.ts@@ -92,6 +92,12 @@ describe('built-in Swarm skills', () => {const sharedLast = `\n${shared.trimEnd()}\n`// The update-request line (Ken, 2026-10-28): the Lead's alone, in both modes, right after its cadence rule.const report = '- Answer each scheduled project update request as soon as it arrives: project.report through the revisions it names, with text null when nothing changed. An unanswered request blocks the later ones and keeps finished groups from archiving.\n'+ // The live-card lines (Dee's Slack parity, 2026-10-29; backend superTabs/cards.ts): a task and each linked pull request are one+ // card that updates itself, so no role posts a line that only repeats it. Each role's own line, in both modes: the Lead's after+ // its update-request line, the Builder's after its checkpoint line, the Reviewer's after its independent check.+ const cardLead = '- Each task and each pull request linked in its chat is one card there that updates itself: status, checks passed, CI, review verdict and merge. Post a pull request\'s link once, and never a line that only repeats what a card shows (opened, CI running or green, reviewed, merged); people and agents read the card and the Swarm\'s status instead.\n'+ const cardDev = '- Your task and each pull request you link are cards in the group chat that update themselves: status, checks, CI, review verdict and merge. Post a pull request\'s link once, in the main chat; never post a line that only repeats what a card shows (opened, CI running or green, merged). Progress lines carry what a card does not: the step, the commit, the test result, a ruling or a blocker.\n'+ const cardReview = '- The task\'s card in the group chat shows your verdict, CI and merge as they change. Post the verdict once, with its findings; never a line that only repeats what the card shows.\n'const twoHours = '- A Builder or Reviewer that has been down for 2 hours (machine offline, session gone or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).\n'// A failed start is never left (the round-device group, 2026-10-27; superTabs/start.ts): the Lead's alone, in both modes.const failedStart = '- A failed start is retried elsewhere or reported, never left: when one fails, resume it; it starts once on the route\'s next machine, or tells the group and its requester. A task that requires a machine or device never moves: when its route says it waits, keep it queued and route it again once that machine can take it.\n'@@ -191,11 +197,23 @@ describe('built-in Swarm skills', () => {expect(text.split(reviewCheck)).toHaveLength(role === 'review' ? 2 : 1)expect(text.split(moveMissing)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(thread)).toHaveLength(role === 'lead' ? 2 : 1)+ expect([cardLead, cardDev, cardReview].map(line => text.split(line).length)).toEqual([role === 'lead' ? 2 : 1, role === 'dev' ? 2 : 1, role === 'review' ? 2 : 1])expect(sha(approved(text, 'orchestration', role).replace(twoHours, '').replace(terminal, '').replace(update, '').replace(overlap, '').replace(local, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '').replace(limit, '').replace(digest, '').replace(decision, '').replace(ask, '').replace(requests, '').replace(shared, '').replace(report, '')- .replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, '').replace(thread, ''))).toBe(sha256)+ .replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, '').replace(thread, '')+ .replace(cardLead, '').replace(cardDev, '').replace(cardReview, ''))).toBe(sha256)}})+ it('adds each role\'s live-card line where it posts, in both modes', () => {+ const read = (role: 'lead' | 'dev' | 'review', mode: 'orchestration' | 'default') =>+ readFileSync(prepareSwarmSkill(fixture(), { role, key: 'session', mode }).file, 'utf8')+ for (const mode of ['orchestration', 'default'] as const) {+ expect(read('lead', mode)).toContain(`${report}${cardLead}`)+ expect(read('dev', mode)).toContain(`${checkpoint}${cardDev}`)+ }+ expect(read('review', 'orchestration')).toContain(`- Pass or fail the independent check, with the revision and verdict as evidence.\n${cardReview}`)+ expect(read('review', 'default')).toContain(`- Pass or fail the independent check with the revision and verdict.\n${cardReview}`)+ })it('adds the 2-hour line to section 7 right after the stall rule', () => {const text = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session' }).file, 'utf8')expect(text).toContain(`post in its chat why it waits; report on-screen trust, sign-in or permission questions in chat, naming the machine owner who can answer.\n${twoHours}`)@@ -342,9 +360,11 @@ describe('built-in Swarm skills', () => {expect(text.split(reviewCheck)).toHaveLength(role === 'review' ? 2 : 1)expect(text.split(moveMissing)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(thread)).toHaveLength(role === 'lead' ? 2 : 1)+ expect([cardLead, cardDev, cardReview].map(line => text.split(line).length)).toEqual([role === 'lead' ? 2 : 1, role === 'dev' ? 2 : 1, role === 'review' ? 2 : 1])expect(sha(approved(text, 'default', role).replace(terminal, '').replace(update, '').replace(overlap, '').replace(localDefault, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '').replace(limit, '').replace(digest, '').replace(decision, '').replace(ask, '').replace(requestsLast, '').replace(sharedLast, '').replace(report, '')- .replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, '').replace(thread, ''))).toBe(sha256)+ .replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, '').replace(thread, '')+ .replace(cardLead, '').replace(cardDev, '').replace(cardReview, ''))).toBe(sha256)expect(prepared.instructions).toBe(`Use the swarm-${role} skill for this session: the team process; otherwise work your usual way. Before working, read ${JSON.stringify(prepared.file)} with your file or shell tool.`)})diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.tsindex beb71e3bc..1ef0b1670 100644--- a/cli/src/lib/swarmSkills.ts+++ b/cli/src/lib/swarmSkills.ts@@ -151,6 +151,7 @@ For large work, post the group plan and get the owner's ok before assigning; onc## 10. Keep people informed- At project cadence, post progress, blockers and next steps in the project chat; if nothing changed, post nothing.- Answer each scheduled project update request as soon as it arrives: project.report through the revisions it names, with text null when nothing changed. An unanswered request blocks the later ones and keeps finished groups from archiving.+- Each task and each pull request linked in its chat is one card there that updates itself: status, checks passed, CI, review verdict and merge. Post a pull request's link once, and never a line that only repeats what a card shows (opened, CI running or green, reviewed, merged); people and agents read the card and the Swarm's status instead.- Progress is a scored table: one row per group with a score from 0 to 1, its owner, and what it waits on. Only done and verified scores 1.0. Every row below 1.0 has an owner or says what it waits on.- Answer questions, blockers and completions immediately.- Summarize long threads once; record important decisions once.@@ -214,6 +215,7 @@ You finish one group's work completely, inside its brief, with proof. Work as if- The approved spec outranks the brief, and the brief outranks your plan. When they conflict, or a step turns out wrong, take the smallest change that satisfies the spec and post "Ruling: what — why — cost if wrong". An unrecorded deviation is a decision made in secret.- After each committed step, post one progress line (step, commit, test result) so a fresh session can resume. After a restart, trust those lines and git log over memory, and never redo a committed step.- Push your work branch at least every 30 minutes, and set your work status to working with a one-line note of what is done and what is next, so another agent can continue if you stop.+- Your task and each pull request you link are cards in the group chat that update themselves: status, checks, CI, review verdict and merge. Post a pull request's link once, in the main chat; never post a line that only repeats what a card shows (opened, CI running or green, merged). Progress lines carry what a card does not: the step, the commit, the test result, a ruling or a blocker.- Before handoff: every test the brief names exists and ran, every expected result was compared with the real one, and every deviation has a Ruling.## 3. Test first@@ -343,6 +345,7 @@ Look outside the changes only for a risk you can name: one focused check per ris- Cannot verify: requirements you could not check from these changes alone, and what the Lead should check.- Verdict: meets the brief (yes/no) and quality (yes/no), then "Ready: yes | with fixes | no — revision <rev>". With findings, add one or two sentences of reasoning; with none, "No findings on <rev>" is the verdict.- Pass or fail the independent check, with the revision and verdict as evidence.+- The task's card in the group chat shows your verdict, CI and merge as they change. Post the verdict once, with its findings; never a line that only repeats what the card shows.- Tell the Lead directly about anything risky: private data, changed defaults, releases.- When talking to people, call the roles Product Manager, Engineer and Reviewer.@@ -442,6 +445,7 @@ When the project owner asks in chat to switch this project's skills (Default or## 7. Keep people informed- At the project's cadence, post a scored table: one row per group, 0 to 1, its owner and what it waits on. Only merged and tried scores 1.0. If nothing changed, post nothing.- Answer each scheduled project update request as soon as it arrives: project.report through the revisions it names, with text null when nothing changed. An unanswered request blocks the later ones and keeps finished groups from archiving.+- Each task and each pull request linked in its chat is one card there that updates itself: status, checks passed, CI, review verdict and merge. Post a pull request's link once, and never a line that only repeats what a card shows (opened, CI running or green, reviewed, merged); people and agents read the card and the Swarm's status instead.- Answer questions, blockers and completions at once.- Every post carries a result, a decision asked for with your recommendation, a question, or a fault; never an acknowledgement alone.- Write like a colleague: short, in their language, no commands or internal ids. Call the roles Product Manager, Engineer and Reviewer.@@ -479,6 +483,7 @@ You finish one group's work completely, inside its brief, as if nobody will come- Name a known flaky test instead of letting it block you.- Have something to show at least every 20 minutes: a push or a short progress line.- Push your work branch at least every 30 minutes, and set your work status to working with a one-line note of what is done and what is next, so another agent can continue if you stop.+- Your task and each pull request you link are cards in the group chat that update themselves: status, checks, CI, review verdict and merge. Post a pull request's link once, in the main chat; never post a line that only repeats what a card shows (opened, CI running or green, merged). Progress lines carry what a card does not: the step, the commit, the test result, a ruling or a blocker.- When an answer is unclear, take its narrowest safe reading and say so. Keep working on whatever doesn't depend on a question, and don't ask twice.- To split the work or take more, ask the Lead. You may propose new work; the Lead decides.@@ -537,6 +542,7 @@ Start within 30 minutes of being asked; oldest ready work first. If you cannot,- Findings P1 (must fix), P2 (fix before accepting), P3 (later), each with file:line, what is wrong and the fix.- Verdict: "No finding on <rev>", or "Hold — <rev>" with the findings. A re-review covers only the new changes.- Pass or fail the independent check with the revision and verdict.+- The task's card in the group chat shows your verdict, CI and merge as they change. Post the verdict once, with its findings; never a line that only repeats what the card shows.- Tell the Lead at once about privacy, interface breaks, default-on changes to safety or updates, and device behaviour nobody could show.- Keep posts short, in the people's language, without commands or internal ids. Call the roles Product Manager, Engineer and Reviewer.diff --git a/cli/src/superTabs/capacity.spec.ts b/cli/src/superTabs/capacity.spec.tsindex 6e41616fa..2d7acb28f 100644--- a/cli/src/superTabs/capacity.spec.ts+++ b/cli/src/superTabs/capacity.spec.ts@@ -1,5 +1,5 @@import { expect, it, vi } from 'vitest'-import { admission, quotaOf, readCapabilities } from './capacity.js'+import { admission, quotaOf, quotaUnknownReason, readCapabilities } from './capacity.js'const requirements = { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: ['git'], devices: ['/dev/test'], quotaRequired: false }it('uses the destination filesystem and reports missing tools/devices without executing commands', async () => {const deps = { resources: vi.fn(async () => ({ cpuPercent: 25, memoryTotalBytes: 1000, memoryUsedBytes: 300 })),@@ -61,3 +61,28 @@ it('says how much memory is free and how much a start needs, in GiB', () => {expect(admission(capacity, { installed: true }, quotaOf({}, 'codex', false), { ...requirements, memoryBytes: 2 * GiB, devices: [] }).reasons).toEqual(['Not enough free memory: 1.8 GiB free, 2 GiB needed.'])})++// Ken's MacBook Pro showed no Claude allowance while Claude agents ran there (2026-10-28). Every way the reading can fail+// now says why, in words that name no account, token or plan.+it('says why an allowance is unknown, for each way its reading fails', () => {+ const reply = (claude: Record<string, unknown>) => ({ providers: [{ provider: 'claude', account: 'k', ...claude }] })+ expect(quotaUnknownReason({}, 'claude', false)).toBe('The allowance reader on this machine did not answer.')+ expect(quotaUnknownReason({ error: 'USAGE_READ_FAILED' }, 'claude', false)).toBe('The allowance reader on this machine did not answer.')+ expect(quotaUnknownReason(reply({ outcome: 'signedOut' }), 'claude', false)).toBe('No subscription sign-in is stored on this machine.')+ expect(quotaUnknownReason(reply({ outcome: 'signedOut', message: 'Claude session expired — run claude to sign in again' }), 'claude', false))+ .toBe('The stored sign-in has expired; it renews the next time the engine runs here.')+ expect(quotaUnknownReason(reply({ outcome: 'unreachable' }), 'claude', false)).toBe('Anthropic could not be reached.')+ expect(quotaUnknownReason(reply({ outcome: 'answered', httpStatus: 429, body: { error: {} } }), 'claude', false))+ .toBe('Anthropic is limiting how often the allowance can be read.')+ expect(quotaUnknownReason(reply({ outcome: 'answered', httpStatus: 401 }), 'claude', false)).toBe('Anthropic refused the stored sign-in.')+ expect(quotaUnknownReason(reply({ outcome: 'answered', httpStatus: 403 }), 'claude', false)).toBe('Anthropic refused the stored sign-in.')+ expect(quotaUnknownReason(reply({ outcome: 'answered', httpStatus: 503 }), 'claude', false)).toBe('Anthropic answered with an error (HTTP 503).')+ expect(quotaUnknownReason(reply({ outcome: 'answered', httpStatus: 200, body: { five_hour: null } }), 'claude', false))+ .toBe('Anthropic answered without usage windows.')+ expect(quotaUnknownReason({ providers: [{ provider: 'codex', outcome: 'unreachable' }] }, 'codex', false)).toBe('OpenAI could not be reached.')+ // A Harness Team account spends its owner's subscription through the owner's relay; its own home holds no sign-in.+ expect(quotaUnknownReason({ providers: [{ provider: 'codex', outcome: 'signedOut' }] }, 'codex', true))+ .toBe("This account runs on its owner's subscription; its allowance is read on the owner's machine.")+ // A readable allowance has no reason.+ expect(quotaUnknownReason(reply({ outcome: 'answered', httpStatus: 200, body: { five_hour: { utilization: 5 } } }), 'claude', false)).toBeNull()+})diff --git a/cli/src/superTabs/capacity.ts b/cli/src/superTabs/capacity.tsindex d8f2bea87..0ca827937 100644--- a/cli/src/superTabs/capacity.ts+++ b/cli/src/superTabs/capacity.ts@@ -102,6 +102,28 @@ export function quotaOf(reply: Json, engine: string, customAccount: boolean) {}return { known: windows.length > 0, account: typeof reading?.account === 'string' ? reading.account : null, windows }}+const VENDOR: Record<string, string> = { claude: 'Anthropic', codex: 'OpenAI' }+/** Why [engine]'s allowance could not be read from the account reader's [reply], or null when it was. Words only: no+ * account, token or plan. [relayed]: a Harness Team account, whose engines spend the owner's subscription through the+ * owner's relay, so its own home holds no sign-in to read. */+export function quotaUnknownReason(reply: Json, engine: string, relayed: boolean): string | null {+ if (quotaOf(reply, engine, false).known) return null+ const reading = Array.isArray(reply.providers) ? reply.providers.map(object).find(r => r.provider === engine) : undefined+ const vendor = VENDOR[engine] ?? 'The vendor'+ if (!reading) return 'The allowance reader on this machine did not answer.'+ if (reading.outcome === 'signedOut') {+ if (relayed) return "This account runs on its owner's subscription; its allowance is read on the owner's machine."+ return typeof reading.message === 'string' && /expired/i.test(reading.message)+ ? 'The stored sign-in has expired; it renews the next time the engine runs here.'+ : 'No subscription sign-in is stored on this machine.'+ }+ if (reading.outcome !== 'answered') return `${vendor} could not be reached.`+ const status = reading.httpStatus+ if (status === 429) return `${vendor} is limiting how often the allowance can be read.`+ if (status === 401 || status === 403) return `${vendor} refused the stored sign-in.`+ if (status === 200) return `${vendor} answered without usage windows.`+ return `${vendor} answered with an error (HTTP ${finite(status) ? status : 'unknown'}).`+}/** An engine that runs on an API key or a gateway's base URL has no subscription windows to read: it is metered, not unknown.* `env` is the machine's own, so the host reads its own and a key never leaves it. */export function meteredEngine(engine: string, env: NodeJS.ProcessEnv): boolean {diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex cf01dea41..573de9870 100644--- a/cli/src/superTabs/machines.spec.ts+++ b/cli/src/superTabs/machines.spec.ts@@ -1962,3 +1962,93 @@ describe('removed machine cleanup', () => {expect(backend.mock.calls.some(c => JSON.stringify(c[3] ?? '').includes('agent.startSettled'))).toBe(true)})})++// 2026-10-29: Anthropic answered 5 quick allowance reads, then refused them for 5 minutes (HTTP 429, retry-after 300). Each+// machine read the allowance on every 15-second report, so Claude's showed as unknown on Ken's MacBook Pro while its+// agents ran there. The reading is now kept for a while, and an unknown one says why.+describe('the allowance a machine reports', () => {+ const reads = (f: ReturnType<typeof fixture>) => f.request.mock.calls.filter(c => c[0] === 'usage_read').length+ const last = (f: ReturnType<typeof fixture>) => f.backend.mock.calls.filter(c => c[1] === 'POST' && String(c[2]).includes('/machines/')).at(-1)![3] as Record<string, unknown>+ const answer = (codex: Record<string, unknown>) => async (type: string): Promise<Record<string, unknown>> =>+ type === 'usage_read' ? { providers: [{ provider: 'codex', account: 'k', ...codex }] } : {}+ const limited = answer({ outcome: 'answered', httpStatus: 429, body: { error: {} } })++ it('is read from the vendor at most once in 3 minutes, however often the machine reports', async () => {+ const f = fixture()+ await f.machine.tick(); f.advance(); await f.machine.tick(); f.advance(); await f.machine.tick()+ expect(f.backend.mock.calls.filter(c => c[1] === 'POST' && String(c[2]).includes('/machines/')).length).toBe(3)+ expect(reads(f)).toBe(1)+ f.step(180_000); await f.machine.tick()+ expect(reads(f)).toBe(2)+ })++ it('keeps the last good windows while the vendor limits reads, and asks again only after 5 minutes', async () => {+ const f = fixture()+ await f.machine.tick()+ f.request.mockImplementation(limited)+ f.step(180_000); await f.machine.tick()+ expect(reads(f)).toBe(2)+ expect(last(f)).toMatchObject({ quotas: [{ engine: 'codex', known: true, windows: [{ usedPercent: 25 }] }] })+ expect(last(f).quotaReasons).toBeUndefined()+ f.step(180_000); await f.machine.tick()+ expect(reads(f)).toBe(2)+ f.step(120_000); await f.machine.tick()+ expect(reads(f)).toBe(3)+ })++ it('says unknown, and why, once the last good windows are 20 minutes old', async () => {+ const f = fixture()+ await f.machine.tick()+ f.request.mockImplementation(limited)+ for (let i = 0; i < 4; i++) { f.step(300_000); await f.machine.tick() }+ expect(last(f)).toMatchObject({ quotas: [{ engine: 'codex', known: true }] })+ // The next report, past the 15-second beat, still on the 429 read: the kept windows are now too old.+ f.step(16_000); await f.machine.tick()+ expect(last(f)).toMatchObject({ quotas: [{ engine: 'codex', known: false, windows: [] }],+ quotaReasons: { codex: 'OpenAI is limiting how often the allowance can be read.' } })+ })++ it('drops the kept windows at once when the engine signs out', async () => {+ const f = fixture()+ await f.machine.tick()+ f.request.mockImplementation(answer({ outcome: 'signedOut' }))+ f.step(180_000); await f.machine.tick()+ expect(last(f)).toMatchObject({ quotas: [{ engine: 'codex', known: false, windows: [] }],+ quotaReasons: { codex: 'No subscription sign-in is stored on this machine.' } })+ })++ it('reads again a minute after the reader did not answer', async () => {+ const f = fixture()+ f.request.mockImplementation(async type => { if (type === 'usage_read') throw new Error('timed out'); return {} })+ await f.machine.tick()+ expect(last(f)).toMatchObject({ quotas: [{ engine: 'codex', known: false }], quotaReasons: { codex: 'The allowance reader on this machine did not answer.' } })+ f.step(61_000); await f.machine.tick()+ expect(reads(f)).toBe(2)+ })++ it("says a Harness Team account's allowance is read on its owner's machine", async () => {+ const f = fixture({}, () => null, () => true)+ f.request.mockImplementation(answer({ outcome: 'signedOut' }))+ await f.machine.tick()+ expect(last(f).quotaReasons).toEqual({ codex: "This account runs on its owner's subscription; its allowance is read on the owner's machine." })+ })++ it('drops the reasons for a backend that refuses them, keeping the allowance, and offers them again ten minutes later', async () => {+ const f = fixture()+ f.request.mockImplementation(limited)+ const original = f.backend.getMockImplementation()!+ f.backend.mockImplementation(async (core, method, path, body) => {+ if (method === 'POST' && (body as Record<string, unknown>)?.quotaReasons) throw new SuperTabHostError('VALIDATION_ERROR', 'Unrecognized key: quotaReasons', 400)+ return original(core, method, path, body)+ })+ const posts = () => f.backend.mock.calls.filter(c => c[1] === 'POST' && String(c[2]).includes('/machines/')).map(c => 'quotaReasons' in (c[3] as object))+ await f.machine.tick()+ expect(posts()).toEqual([true, false])+ expect(last(f)).toMatchObject({ quotas: [{ engine: 'codex', known: false }] })+ f.advance(); await f.machine.tick()+ expect(posts().at(-1)).toBe(false)+ expect(posts()).toHaveLength(3)+ f.step(600_000); await f.machine.tick()+ expect(posts().slice(-2)).toEqual([true, false])+ })+})diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex e6de1d68a..69060fd9f 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -9,7 +9,7 @@ import { backend, identifier, object, SuperTabHostError } from './wire.js'import type { SwarmSources } from './host.js'import { HostFeed } from './hostFeed.js'import { SwarmReads } from './swarmReads.js'-import { readCapabilities, quotaOf, meteredEngine } from './capacity.js'+import { readCapabilities, quotaOf, meteredEngine, quotaUnknownReason } from './capacity.js'import { startAgent, type ScopedRequest } from './start.js'import { prepareSwarmStart } from './projectFolder.js'import { readAuthSession } from '../lib/authSession.js'@@ -208,6 +208,12 @@ export class ContributedMachines {/** Whether each engine is installed and signed in, and until when that stands: one probe starts login shells and reads* the engines' accounts, so it runs every [READINESS_MS] (a failed one again after [READINESS_RETRY_MS]). */private engineRead: { value: ReadyEngine[] | null; until: number } | null = null+ /** The account reader's last answer, when it was read and until when it stands ([USAGE_FRESH_MS] and the rest). */+ private usageRead: { value: Record<string, unknown>; at: number; until: number } | null = null+ /** Per engine, its last readable allowance windows and when they were read, kept [USAGE_KEEP_MS] through failed reads. */+ private readonly goodQuota = new Map<string, { windows: ReturnType<typeof quotaOf>['windows']; at: number }>()+ /** Until when the reading leaves out why an allowance is unknown, which the backend refused. */+ private quotaReasonsRefusedUntil = 0/** Per Swarm folder, its checkouts' readiness and until when it stands, and the folders being read now. A push check* asks the remote, so it is read beside the pass, never holding up a start. */private readonly checkoutReads = new Map<string, { value: ReadyCheckout[] | null; until: number }>()@@ -229,6 +235,29 @@ export class ContributedMachines {this.engineRead = { value, until: now + (value ? READINESS_MS : READINESS_RETRY_MS) }return value}+ /** The account reader's answer, read again only once the last one is [USAGE_FRESH_MS] old: sooner, and Anthropic refuses+ * the reads for 5 minutes. A refused or failed read is not repeated sooner than its own wait. */+ private async allowance(local: { request: (type: string, payload: Record<string, unknown>, timeoutMs: number) => Promise<unknown> }) {+ const now = this.deps.now()+ if (this.usageRead && now < this.usageRead.until) return this.usageRead+ const value = object(await local.request('usage_read', {}, 20_000).catch(() => null))+ const providers = list(value.providers)+ const wait = !Array.isArray(value.providers) ? USAGE_RETRY_MS+ : providers.some(p => p.outcome === 'answered' && p.httpStatus === 429) ? USAGE_LIMITED_MS : USAGE_FRESH_MS+ return this.usageRead = { value, at: now, until: now + wait }+ }+ /** What the reading says of [engine]'s allowance. Windows that could not be read again stand for [USAGE_KEEP_MS] after+ * they were read, unless the engine signed out; past that, unknown says why. */+ private quotaFor(read: { value: Record<string, unknown>; at: number }, engine: string) {+ const q = quotaOf(read.value, engine, false)+ if (q.known) { this.goodQuota.set(engine, { windows: q.windows, at: read.at }); return { engine, known: true, windows: q.windows } }+ // Windows that could not be read on an API key are metered: known, with none (route.ts quotaOf2).+ if (meteredEngine(engine, this.deps.env ?? process.env)) return { engine, known: true, windows: [] }+ if (list(read.value.providers).find(p => p.provider === engine)?.outcome === 'signedOut') this.goodQuota.delete(engine)+ const kept = this.goodQuota.get(engine)+ if (kept && this.deps.now() - kept.at <= USAGE_KEEP_MS) return { engine, known: true, windows: kept.windows }+ return { engine, known: false, windows: [], reason: quotaUnknownReason(read.value, engine, (this.deps.relayed ?? teamRelayed)()) ?? undefined }+ }/** The last readiness of [root]'s checkouts, reading them again beside the pass once it is [READINESS_MS] old. Null* until the first read is in. */private checkoutReadiness(root: string): ReadyCheckout[] | null {@@ -346,7 +375,7 @@ export class ContributedMachines {? await (this.deps.modelsStamp ?? (() => localModelsStamp(this.core.dataDir, this.deps.env ?? process.env)))().catch(() => '') : ''// The local daemon is reached only for a reading to send, never for a pass that has nothing to say.let local: Awaited<ReturnType<typeof openDaemon>> | null = null- let usage: Record<string, unknown> | null = null+ let usage: { value: Record<string, unknown>; at: number } | null = nulltry {for (const row of pools) {try {@@ -378,9 +407,8 @@ export class ContributedMachines {if (!last || last.signature !== signature || last.starting || began - last.at >= MACHINE_HEARTBEAT_MS) {try {local ??= await this.deps.open(where)- // The existing usage reader owns its provider cache. Raw responses and- // account credentials never leave this machine.- const readings = usage ??= await local.request('usage_read', {}, 20_000).catch(() => ({}))+ // Raw responses and account credentials never leave this machine.+ const readings = usage ??= await this.allowance(local)const sampledAt = this.deps.now()const probeTools = tools.filter(name => (this.toolCache.get(name)?.until ?? 0) <= sampledAt)const observed = await this.deps.capabilities({ cwd: pool.cwd, tools: probeTools, devices: [] })@@ -433,9 +461,13 @@ export class ContributedMachines {const progress = Object.fromEntries(running.flatMap(id => typeof shown[id] === 'number' ? [[id, shown[id]]] : []))const uncommitted = began >= this.uncommittedRefusedUntil ? this.uncommitted(running, began, shown) : {}const tokens = began >= this.tokensRefusedUntil ? await this.tokensOf(running) : {}+ const allowances = engines.map(engine => this.quotaFor(readings, engine))+ const quotaReasons = began >= this.quotaReasonsRefusedUntil+ ? Object.fromEntries(allowances.flatMap(q => 'reason' in q && q.reason ? [[q.engine, q.reason]] : [])) : {}// Only to a backend that asks for them (backend read/hostRows.ts): an older one refuses the field, and would refuse// every reading with it.const observation = { generation: pool.generation, tools: reportedTools, ...(Object.keys(tokens).length ? { harnessTokens: tokens } : {}),+ ...(Object.keys(quotaReasons).length ? { quotaReasons } : {}),...(row.capabilitiesWanted === true ? { capabilities: CAPABILITIES } : {}),...(preparing.length ? { preparingStartIds: preparing } : {}),...(Object.keys(uncommitted).length ? { harnessUncommitted: uncommitted } : {}),@@ -449,11 +481,7 @@ export class ContributedMachines {deviceType: typeof resources.deviceType === 'string' ? resources.deviceType : null,chip: typeof resources.chip === 'string' ? resources.chip : null, os: typeof resources.os === 'string' ? resources.os : null,gpuPercent: gpus.length ? Math.max(...gpus) : null },- quotas: engines.map(engine => {- const q = quotaOf(readings, engine, false)- // Windows that could not be read on an API key are metered: known, with none (route.ts quotaOf2).- return { engine, known: q.known || meteredEngine(engine, this.deps.env ?? process.env), windows: q.windows }- }), runningHarnessIds: running, stoppedHarnessIds: stopped,+ quotas: allowances.map(q => ({ engine: q.engine, known: q.known, windows: q.windows })), runningHarnessIds: running, stoppedHarnessIds: stopped,...(Array.isArray(row.reservations) ? { stoppedReservations: list(row.reservations).filter(r => stopped.includes(String(r.harnessId))&& identifier(r.harnessId) && identifier(r.generation)).map(r => ({ harnessId: r.harnessId, generation: r.generation })) } : {}) }this.sending.add(String(row.tabId))@@ -465,7 +493,8 @@ export class ContributedMachines {// readiness, progress, then privacy): a backend that takes everything else keeps the local models it reads. Their// boolean-only view still safely refuses an unverified tool, and a reading without privacy is never one a Team// machine passes on.- const { harnessTokens: _tokens, ...untokened } = observation+ const { quotaReasons: _reasons, ...unreasoned } = observation+ const { harnessTokens: _tokens, ...untokened } = unreasonedconst { preparingStartIds: _preparing, ...unprepared } = untokenedconst { harnessUncommitted: _uncommitted, ...known } = unpreparedconst { readiness: _readiness, ...ready } = known@@ -475,7 +504,7 @@ export class ContributedMachines {// A backend before `starting` refuses it: it gets the models the grid lists, as before, not none at all.const listedOnly = localModels?.some(m => m.starting)? [{ ...withoutPrivacy, localModels: localModels.filter(m => !m.starting) }] : []- const attempts = [...('harnessTokens' in observation ? [observation] : []), ...('preparingStartIds' in untokened ? [untokened] : []),+ const attempts = [...('quotaReasons' in observation ? [observation] : []), ...('harnessTokens' in unreasoned ? [unreasoned] : []), ...('preparingStartIds' in untokened ? [untokened] : []),...('harnessUncommitted' in unprepared ? [unprepared] : []),...('readiness' in known ? [known] : []), ready, ...('harnessProgress' in ready ? [withoutProgress] : []),...('privacy' in withoutProgress ? [withoutPrivacy] : []), ...listedOnly,@@ -488,7 +517,8 @@ export class ContributedMachines {break} catch (error) {if (!refused(error) || index === attempts.length - 1) throw error- if ('harnessTokens' in attempt) this.tokensRefusedUntil = began + FIELD_REFUSED_MS+ if ('quotaReasons' in attempt) this.quotaReasonsRefusedUntil = began + FIELD_REFUSED_MS+ else if ('harnessTokens' in attempt) this.tokensRefusedUntil = began + FIELD_REFUSED_MSelse if ('preparingStartIds' in attempt) this.preparingRefusedUntil = began + FIELD_REFUSED_MSelse if ('harnessUncommitted' in attempt) this.uncommittedRefusedUntil = began + FIELD_REFUSED_MSelse if ('readiness' in attempt) this.readinessRefusedUntil = began + FIELD_REFUSED_MS@@ -832,6 +862,15 @@ export class ContributedMachines {* probe that failed is tried again. */const READINESS_MS = 10 * 60_000const READINESS_RETRY_MS = 60_000+/** How long an allowance reading stands. 2026-10-29: Anthropic answered 5 reads in a row, then refused them for 5 minutes+ * (HTTP 429, retry-after 300); read on every 15-second report, Claude's allowance showed as unknown. */+const USAGE_FRESH_MS = 3 * 60_000+/** After a refused read: Anthropic's own retry-after. */+const USAGE_LIMITED_MS = 5 * 60_000+/** After the reader on this machine did not answer at all. */+const USAGE_RETRY_MS = 60_000+/** How long the last readable windows stand while later reads fail; past it the allowance is unknown, with why. */+const USAGE_KEEP_MS = 20 * 60_000/** The backend's limit on one reading's checkouts (`machineObservationSchema`). */const MAX_CHECKOUTS = 64type ReadyEngine = { engine: string; installed: true | null; signedIn: boolean | null }diff --git a/cli/src/superTabs/route.ts b/cli/src/superTabs/route.tsindex 7c63a259a..b4b19365e 100644--- a/cli/src/superTabs/route.ts+++ b/cli/src/superTabs/route.ts@@ -33,7 +33,9 @@ export interface QuotaWindow { name: string | null; leftPercent: number; resetsA/** `leftPercent` and `resetsAt` are the tightest window's; `windows` is every window. `account` is the reading's hashed* account key, which models on one subscription share. `metered` is an engine on an API key or gateway: known, with no* usage window to run out. */-export interface Quota { known: boolean; leftPercent: number | null; resetsAt: number | null; windows?: QuotaWindow[]; account?: string; metered?: true }+export interface Quota { known: boolean; leftPercent: number | null; resetsAt: number | null; windows?: QuotaWindow[]; account?: string; metered?: true+ /** Why an unknown allowance could not be read, as its machine said (cli superTabs/capacity.ts quotaUnknownReason). */+ why?: string }/** The task's folder as the Lead's machine sees it. `unknown` means it could not be read, `none` that it is not a repository,* `missing` that the Lead's machine has no such folder (a member elsewhere may). */export interface TaskFolder { cwd: string; kind: 'git' | 'none' | 'missing' | 'unknown'; name: string | null; root: string | null; remote: string | null }@@ -161,9 +163,9 @@ function resetMs(value: unknown): number | null {if (typeof value === 'string') { const ms = Date.parse(value); return Number.isFinite(ms) ? ms : null }return null}-export function quotaOf2(q: { known: boolean; windows: Array<{ usedPercent: number; resetsAt: unknown; name?: string }>; account?: string | null }): Quota {+export function quotaOf2(q: { known: boolean; windows: Array<{ usedPercent: number; resetsAt: unknown; name?: string }>; account?: string | null; why?: string | null }): Quota {const account = q.account ? { account: q.account } : {}- if (!q.known) return { known: false, leftPercent: null, resetsAt: null, ...account }+ if (!q.known) return { known: false, leftPercent: null, resetsAt: null, ...account, ...(q.why ? { why: q.why } : {}) }if (!q.windows.length) return { known: true, leftPercent: null, resetsAt: null, metered: true, ...account }const tightest = q.windows.reduce((x, y) => y.usedPercent > x.usedPercent ? y : x)return { known: true, leftPercent: Math.max(0, 100 - tightest.usedPercent), resetsAt: resetMs(tightest.resetsAt),@@ -298,7 +300,7 @@ function span(ms: number): string {const resetsIn = (resetsAt: number, now: number) => span(Math.max(0, resetsAt - now))function quotaText(q: Quota, now: number): string {if (q.metered) return 'quota metered'- if (!q.known || q.leftPercent === null) return 'quota unknown'+ if (!q.known || q.leftPercent === null) return q.why ? `quota unknown (${q.why})` : 'quota unknown'if (q.windows?.length) {return `quota ${q.windows.map(w => `${w.name ?? 'window'} ${Math.round(w.leftPercent)}% left${w.resetsAt === null ? '' : ` (resets in ${resetsIn(w.resetsAt, now)})`}`).join(', ')}`}diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.tsindex 681e2112c..514f3f257 100644--- a/cli/src/superTabs/routeCommand.spec.ts+++ b/cli/src/superTabs/routeCommand.spec.ts@@ -1028,6 +1028,29 @@ describe('routing contributed capacity', () => {}})+ it('says why an engine\'s allowance is unknown, from the machine\'s reading', async () => {+ const pool = swarm()+ pool.observation.quotas = [{ engine: 'claude', known: false, windows: [] }]+ pool.observation.quotaReasons = { claude: 'Anthropic is limiting how often the allowance can be read.' }+ const { answer, s } = await runPool(pool, false, {}, project)+ expect(answer.ok).toBe(true)+ expect(JSON.stringify(recorded(s).command.decision)).toContain('quota unknown (Anthropic is limiting how often the allowance can be read.)')+ delete pool.observation.quotaReasons+ const older = JSON.stringify(recorded((await runPool(pool, false, {}, project)).s).command.decision)+ expect(older).toContain('quota unknown')+ expect(older).not.toContain('quota unknown (')+ })++ it('leaves out an engine the server says is suspended on the machine, with why, and keeps the others', async () => {+ const pool = swarm()+ pool.suspendedEngines = { claude: 'Claude Code is suspended on this machine: its last 2 starts there failed.' }+ const out = await runPool(pool, false, {}, project)+ expect(out.answer).toMatchObject({ error: 'NO_CANDIDATE' })+ expect(reasons(out.answer)[0]!.reason).toContain('Claude Code is suspended on this machine: its last 2 starts there failed.')+ pool.suspendedEngines = { codex: 'Codex is suspended on this machine: its last 2 starts there failed.' }+ expect((await runPool(pool, false, {}, project)).answer.ok).toBe(true)+ })+it('still offers a local model on a machine whose engine is signed out, since the grid needs no subscription', async () => {const grid = 'swarm-0123456789ab', pool = swarm(undefined, [{ engine: 'claude', installed: true, signedIn: false }])pool.observation.localModels = [{ grid, model: 'qwen3' }]diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.tsindex 217752cde..de261fd46 100644--- a/cli/src/superTabs/routeCommand.ts+++ b/cli/src/superTabs/routeCommand.ts@@ -82,6 +82,10 @@ export function unreadyPool(pool: Json, project: Json | undefined, projectId: st// Worded as a subscription's, so a Builder on a local model, which runs through the grid without one, is not kept out.else if (e.signedIn === false) engines[String(e.engine)] = `${name} is not signed in to a subscription on this machine. Its owner can sign in there; the next reading clears this.`}+ // The server's own count of failed starts (backend superTabs/engineHealth.ts), with its words; a server before it sends none.+ for (const [engine, reason] of Object.entries(object(pool.suspendedEngines))) {+ if (ENGINE_NAME[engine] && typeof reason === 'string' && !engines[engine]) engines[engine] = reason+ }// Only a Swarm folder's own checkout of the project is read; the repository's machine runs it from the Lead's checkout.const checkout = pool.scope === 'swarm' && repository.machineId !== pool.machineId ? list(readiness.checkouts).find(c => c.folder === projectId) : undefinedconst wanted = typeof repository.repositoryUrl === 'string' ? repositoryKey(repository.repositoryUrl) : null@@ -491,7 +495,8 @@ async function probeMachine(machineId: string, { name: machineName, status, accoconst observed = object(pool.observation), resources = object(observed.resources)const fresh = finite(observed.receivedAt) && Date.now() - observed.receivedAt < 45_000const quotas = list(observed.quotas)- const quota = (engine: string) => { const q = quotas.find(q => q.engine === engine); return fresh && q ? quotaOf2({ known: q.known === true, windows: list(q.windows).filter(w => finite(w.usedPercent)).map(w => ({ usedPercent: w.usedPercent as number, resetsAt: w.resetsAt, name: text(w.name) ?? undefined })) }) : UNKNOWN_QUOTA }+ const quota = (engine: string) => { const q = quotas.find(q => q.engine === engine); return fresh && q ? quotaOf2({ known: q.known === true, windows: list(q.windows).filter(w => finite(w.usedPercent)).map(w => ({ usedPercent: w.usedPercent as number, resetsAt: w.resetsAt, name: text(w.name) ?? undefined })),+ why: text(object(observed.quotaReasons)[engine]) }) : UNKNOWN_QUOTA }const blocked = [...(!fresh ? [OFFLINE] : []), ...(pool.paused ? ['New work is paused on this machine.'] : [])]const tools = object(observed.tools)/** Work for a project its owner does not run here: a new agent runs under the contribution, a member under its own grant. */diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex b3d26b8c6..d28da76df 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -70,7 +70,7 @@ const HELP = {capacity: 'capacity MACHINE_ID JSON: inspect machine, engine and quota headroom. JSON uses the start request fields below. Unknown allowances are not reported as free tokens.',startRequest: { conversationId: 'GROUP', machineId: 'MACHINE', engine: 'codex', name: 'Builder', cwd: '/absolute/repo/on/that/machine', worktree: true, branchRef: 'refs/remotes/origin/BASE_BRANCH', requirements: START_REQUIREMENTS,model: 'opus', effort: 'high', routeDecisionId: 'DECISION' },- command: 'command OPERATION_ID JSON: send one of the commands below. Reuse exactly the same ID and JSON after an interrupted request. On Custom skills, work.assign takes "roleId" too, a role of the agent\'s kind. When your assignment needs a person to decide, set work.status needs_human; when you cannot go on, blocked. Set working again once it moves. rule.set and rule.remove change one project\'s routing rules: only the project owner does (naming projectId), or that project\'s Lead passing on the project owner\'s request, with askedIn naming the project owner\'s message in that project\'s chat. project.skills switches a project between the Default, Harness orchestration and Custom skills (Custom once its owner has made the project\'s roles): only its project owner does, or its Lead passing on that owner\'s own chat message, with askedIn naming it. tab.tidy turns off, or back on, the Swarm\'s tidying: workers idle for 15 minutes stop and finished groups archive once their pull requests are merged or closed. Only the Swarm owner does, or a Lead passing on the owner\'s own chat message, with askedIn naming it. A start, assignment or route that breaks a hard rule (forbidModel, machines, minEffort) is refused for agents; preferEngine, preferIdle and noGridFirst only rank. Low-risk work that is not a review ranks models on the Swarm\'s grid first unless the owner set noGridFirst: low-difficulty work, and medium work of kind docs, copy, tests, fixtures, fix or refactor (a grid model rated 2, such as Kimi K3 or DeepSeek v4.1). A review never runs on a grid model, below quality 2 or on the reviewed Builder\'s engine. When a grid attempt\'s first review says Ready no, or its grid host never starts the agent, the Swarm closes it and steps the task up (no grid and quality 2, then quality 3, at most twice) and tells you: route it again, and the route and the server keep to the new floor.',+ command: 'command OPERATION_ID JSON: send one of the commands below. Reuse exactly the same ID and JSON after an interrupted request. On Custom skills, work.assign takes "roleId" too, a role of the agent\'s kind. When your assignment needs a person to decide, set work.status needs_human; when you cannot go on, blocked. Set working again once it moves. rule.set and rule.remove change one project\'s routing rules: only the project owner does (naming projectId), or that project\'s Lead passing on the project owner\'s request, with askedIn naming the project owner\'s message in that project\'s chat. project.skills switches a project between the Default, Harness orchestration and Custom skills (Custom once its owner has made the project\'s roles): only its project owner does, or its Lead passing on that owner\'s own chat message, with askedIn naming it. tab.tidy turns off, or back on, the Swarm\'s tidying: workers idle for 15 minutes stop and finished groups archive once their pull requests are merged or closed. Only the Swarm owner does, or a Lead passing on the owner\'s own chat message, with askedIn naming it. Two failed starts in a row suspend an engine on a machine for up to 6 hours (the route says so); machine.engineResume offers it there again: only the machine\'s owner does, or the Lead passing on the owner\'s chat message, with askedIn naming it. A start, assignment or route that breaks a hard rule (forbidModel, machines, minEffort) is refused for agents; preferEngine, preferIdle and noGridFirst only rank. Low-risk work that is not a review ranks models on the Swarm\'s grid first unless the owner set noGridFirst: low-difficulty work, and medium work of kind docs, copy, tests, fixtures, fix or refactor (a grid model rated 2, such as Kimi K3 or DeepSeek v4.1). A review never runs on a grid model, below quality 2 or on the reviewed Builder\'s engine. When a grid attempt\'s first review says Ready no, or its grid host never starts the agent, the Swarm closes it and steps the task up (no grid and quality 2, then quality 3, at most twice) and tells you: route it again, and the route and the server keep to the new floor.',commands: [{ type: 'project.report', projectId: 'PROJECT', through: { GROUP: 214031 }, text: 'What changed, what is blocked, and what comes next. Use null when nothing merits repeating.' },{ type: 'project.repository', projectId: 'PROJECT', repositoryUrl: 'https://github.com/OWNER/REPOSITORY' },@@ -93,6 +93,7 @@ const HELP = {{ type: 'rule.set', rule: { kind: 'preferIdle' }, text: 'Reuse idle agents first.', askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },{ type: 'rule.set', rule: { kind: 'noGridFirst' }, text: 'Subscriptions first, even for simple work.', askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },{ type: 'rule.remove', ruleId: 'RULE', askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },+ { type: 'machine.engineResume', machineId: 'MACHINE', engine: 'codex', askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },{ type: 'work.assign', conversationId: 'GROUP', agentId: 'AGENT', routeDecisionId: 'DECISION' },{ type: 'work.status', conversationId: 'GROUP', assignmentId: 'ATTEMPT', status: 'working', result: null },// Both reach the Lead and alert the Harness Pro on the machine running the agent until the status moves on.diff --git a/desktop/lib/super_tabs/attachment_chips.dart b/desktop/lib/super_tabs/attachment_chips.dartindex 9eb48a1b5..c886ec705 100644--- a/desktop/lib/super_tabs/attachment_chips.dart+++ b/desktop/lib/super_tabs/attachment_chips.dart@@ -1,11 +1,14 @@+import 'package:flutter/foundation.dart';import 'package:flutter/material.dart';import '../core/open_in_browser.dart';+import '../shared/theme/app_theme.dart' as grid;import '../shared/theme/file_type_icon.dart';import '../shared/widgets/app_dialog.dart';import '../widgets/desktop_chrome.dart';import '../widgets/finger_target.dart';import '../widgets/update_notice.dart' show formatDownloadSize;+import 'attachment_image.dart';import 'attachment_upload.dart';// A browser leaves the text viewer, and the Finder editor under it, out of main.dart.js.import 'attachment_text_viewer.dart'@@ -13,20 +16,40 @@ import 'attachment_text_viewer.dart'import 'attachment_viewer.dart';import 'model.dart';-/// The files a message carries, one chip each. The chat never loads a file by-/// itself: a chip only names it, and a click opens it — an image or a text-/// file in a viewer that fetches it then, anything else in the browser.-class SuperTabAttachmentChips extends StatelessWidget {- const SuperTabAttachmentChips(this.attachments, {super.key});+/// The files a message carries, as Slack shows them: each picture on the+/// attachments host in place (`attachment_image.dart`, on a computer), every+/// other file one chip. A chip only names its file, and a click opens it — a text file in a+/// viewer that fetches it then, anything else in the browser.+class SuperTabAttachments extends StatelessWidget {+ const SuperTabAttachments(this.attachments, {super.key});final List<SuperTabAttachment> attachments;@override- Widget build(BuildContext context) => Wrap(- spacing: 6,- runSpacing: 6,- children: [for (final file in attachments) _AttachmentChip(file: file)],- );+ Widget build(BuildContext context) {+ final pictures = <(SuperTabAttachment, Uri)>[];+ final chips = <SuperTabAttachment>[];+ for (final file in attachments) {+ // A browser's fetch follows a redirect off the attachments host, so+ // there a picture stays a chip that opens in a new tab.+ final url = file.isImage && !kIsWeb ? attachmentLink(file.url) : null;+ url == null ? chips.add(file) : pictures.add((file, url));+ }+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ spacing: grid.AppDesktop.controlGap,+ children: [+ for (final (file, url) in pictures)+ SuperTabInlineImage(file: file, url: url),+ if (chips.isNotEmpty)+ Wrap(+ spacing: grid.AppDesktop.menuInset,+ runSpacing: grid.AppDesktop.menuInset,+ children: [for (final file in chips) _AttachmentChip(file: file)],+ ),+ ],+ );+ }}class _AttachmentChip extends StatelessWidget {@@ -46,12 +69,7 @@ class _AttachmentChip extends StatelessWidget {);return;}- if (file.isImage) {- await showAppDialog<void>(- context: context,- builder: (_) => _ImageViewer(file: file, url: url),- );- } else if (opensAsText(file)) {+ if (opensAsText(file)) {await showAppDialog<void>(context: context,builder: (_) => AttachmentTextViewer(file: file, url: url),@@ -97,7 +115,9 @@ class _AttachmentChip extends StatelessWidget {),),if (size.isNotEmpty) ...[- const SizedBox(width: 6),+ const SizedBox(width: grid.AppDesktop.menuInset),+ Text('·', style: DesktopChrome.metadata()),+ const SizedBox(width: grid.AppDesktop.menuInset),Text(size, style: DesktopChrome.metadata()),],],@@ -107,51 +127,3 @@ class _AttachmentChip extends StatelessWidget {);}}--/// The picture, fetched when this opens.-class _ImageViewer extends StatelessWidget {- const _ImageViewer({required this.file, required this.url});-- final SuperTabAttachment file;- final Uri url;-- @override- Widget build(BuildContext context) => Dialog(- child: Padding(- padding: const EdgeInsets.all(16),- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Text(- file.name,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: DesktopChrome.control(medium: true),- ),- const SizedBox(height: 12),- Flexible(- child: InteractiveViewer(- child: Image.network(- url.toString(),- key: ValueKey('super-attachment-image:${file.id}'),- fit: BoxFit.contain,- loadingBuilder: (_, child, progress) => progress == null- ? child- : const Center(child: CircularProgressIndicator()),- errorBuilder: (_, _, _) => Center(- child: Text(- 'This image can’t be shown here.',- style: DesktopChrome.metadata(),- ),- ),- ),- ),- ),- const SizedBox(height: 12),- AttachmentViewerActions(file: file, url: url),- ],- ),- ),- );-}diff --git a/desktop/lib/super_tabs/attachment_image.dart b/desktop/lib/super_tabs/attachment_image.dartnew file mode 100644index 000000000..ccae889ba--- /dev/null+++ b/desktop/lib/super_tabs/attachment_image.dart@@ -0,0 +1,141 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_icons.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../widgets/desktop_chrome.dart';+import 'attachment_viewer.dart';+import 'model.dart';++/// A picture in a message, as Slack shows one: at most [maxSide] each way+/// with its shape kept, and a click opens it full screen. [url] is the+/// message's own link on the attachments host, which only members are given.+class SuperTabInlineImage extends StatelessWidget {+ const SuperTabInlineImage({super.key, required this.file, required this.url});++ static const maxSide = 360.0;++ final SuperTabAttachment file;+ final Uri url;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final radius = BorderRadius.circular(DesktopChrome.controlRadius);+ return Semantics(+ button: true,+ image: true,+ label: '${file.name}, open full screen',+ child: Material(+ color: Colors.transparent,+ borderRadius: radius,+ child: InkWell(+ key: ValueKey('super-attachment-inline:${file.id}'),+ borderRadius: radius,+ mouseCursor: SystemMouseCursors.click,+ onTap: () => showAppDialog<void>(+ context: context,+ builder: (_) => SuperTabImageViewer(file: file, url: url),+ ),+ child: ConstrainedBox(+ constraints: const BoxConstraints(+ maxWidth: maxSide,+ maxHeight: maxSide,+ ),+ child: ClipRRect(+ borderRadius: radius,+ child: ExcludeSemantics(+ child: Image(+ image: attachmentPicture(url),+ fit: BoxFit.contain,+ frameBuilder: (_, child, frame, synchronous) =>+ frame == null && !synchronous ? _loading() : child,+ errorBuilder: (_, _, _) => _broken(file),+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }++ /// Still, not pulsing: a picture's shape is unknown until it arrives.+ static Widget _loading() => SizedBox(+ width: maxSide * 2 / 3,+ height: maxSide / 2,+ child: ColoredBox(color: DesktopChrome.field),+ );++ static Widget _broken(SuperTabAttachment file) => Container(+ color: DesktopChrome.field,+ padding: const EdgeInsets.all(grid.AppDesktop.controlGap),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(+ AppIcons.fileImage,+ size: grid.AppDesktop.iconSize,+ color: DesktopChrome.muted,+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Flexible(+ child: Text(+ '${file.name} can’t be shown here.',+ style: DesktopChrome.metadata(),+ ),+ ),+ ],+ ),+ );+}++/// A message's picture over the whole window, fetched when it opens, with+/// Download, Open in browser and Close.+class SuperTabImageViewer extends StatelessWidget {+ const SuperTabImageViewer({super.key, required this.file, required this.url});++ final SuperTabAttachment file;+ final Uri url;++ @override+ Widget build(BuildContext context) => Dialog.fullscreen(+ key: ValueKey('super-attachment-viewer:${file.id}'),+ backgroundColor: DesktopChrome.surface,+ child: Padding(+ padding: const EdgeInsets.all(grid.AppDesktop.panelPadding),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(+ file.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(medium: true),+ ),+ const SizedBox(height: grid.AppDesktop.groupGap),+ Expanded(+ child: InteractiveViewer(+ child: Image(+ key: ValueKey('super-attachment-image:${file.id}'),+ image: attachmentPicture(url),+ fit: BoxFit.contain,+ loadingBuilder: (_, child, progress) => progress == null+ ? child+ : const Center(child: CircularProgressIndicator()),+ errorBuilder: (_, _, _) => Center(+ child: Text(+ 'This image can’t be shown here.',+ style: DesktopChrome.metadata(),+ ),+ ),+ ),+ ),+ ),+ const SizedBox(height: grid.AppDesktop.groupGap),+ AttachmentViewerActions(file: file, url: url),+ ],+ ),+ ),+ );+}diff --git a/desktop/lib/super_tabs/attachment_viewer.dart b/desktop/lib/super_tabs/attachment_viewer.dartindex 392c35dec..dfcb6bf31 100644--- a/desktop/lib/super_tabs/attachment_viewer.dart+++ b/desktop/lib/super_tabs/attachment_viewer.dart@@ -1,5 +1,6 @@import 'dart:io';import 'dart:typed_data';+import 'dart:ui' as ui;import 'package:dio/dio.dart';import 'package:file_selector/file_selector.dart';@@ -20,6 +21,16 @@ const kAttachmentTextMaxBytes = 2 * 1024 * 1024;Future<Uint8List> Function(Uri url, {int? maxBytes}) attachmentFetcher =fetchAttachment;+/// A picture off the attachments host, drawn where the chat shows it; tests+/// hand it bytes instead.+@visibleForTesting+ImageProvider Function(Uri url) attachmentImage = _networkImage;++ImageProvider _networkImage(Uri url) => AttachmentImage(url);++/// The picture at [url] through [attachmentImage].+ImageProvider attachmentPicture(Uri url) => attachmentImage(url);+/// The file at [url] through [attachmentFetcher], for the text viewer/// (`attachment_text_viewer.dart`), which a browser downloads apart.Future<Uint8List> readAttachment(Uri url, {int? maxBytes}) =>@@ -141,3 +152,37 @@ class _AttachmentViewerActionsState extends State<AttachmentViewerActions> {],);}++/// The picture at [url], read through [attachmentFetcher] like any chat file:+/// a redirect is refused, so nothing from another host is fetched or drawn+/// (`NetworkImage` follows one).+@immutable+class AttachmentImage extends ImageProvider<AttachmentImage> {+ const AttachmentImage(this.url);++ final Uri url;++ @override+ Future<AttachmentImage> obtainKey(ImageConfiguration configuration) =>+ SynchronousFuture(this);++ @override+ ImageStreamCompleter loadImage(+ AttachmentImage key,+ ImageDecoderCallback decode,+ ) => MultiFrameImageStreamCompleter(+ codec: _decode(decode),+ scale: 1,+ debugLabel: url.toString(),+ );++ Future<ui.Codec> _decode(ImageDecoderCallback decode) async =>+ decode(await ui.ImmutableBuffer.fromUint8List(await readAttachment(url)));++ @override+ bool operator ==(Object other) =>+ other is AttachmentImage && other.url == url;++ @override+ int get hashCode => url.hashCode;+}diff --git a/desktop/lib/super_tabs/code_block.dart b/desktop/lib/super_tabs/code_block.dartnew file mode 100644index 000000000..bb0577269--- /dev/null+++ b/desktop/lib/super_tabs/code_block.dart@@ -0,0 +1,101 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../shared/theme/app_icons.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../widgets/desktop_chrome.dart';++/// A fenced code block in a message, as Slack shows one: monospace, the+/// fence's name or language over it, Copy beside that, and a long one folded+/// to its first [foldedLines] lines behind Show more.+class SuperTabCodeBlock extends StatefulWidget {+ const SuperTabCodeBlock({super.key, required this.code, this.language});++ static const foldedLines = 12;++ final String code;++ /// The fence's info string — `dart`, `main.dart` — or null without one.+ final String? language;++ @override+ State<SuperTabCodeBlock> createState() => _SuperTabCodeBlockState();+}++class _SuperTabCodeBlockState extends State<SuperTabCodeBlock> {+ bool _unfolded = false;++ Future<void> _copy() async {+ await Clipboard.setData(ClipboardData(text: widget.code));+ if (!mounted) return;+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ const SnackBar(content: Text('Code copied'), duration: Durations.long4),+ );+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final lines = widget.code.split('\n');+ final long = lines.length > SuperTabCodeBlock.foldedLines;+ final shown = long && !_unfolded+ ? lines.take(SuperTabCodeBlock.foldedLines).join('\n')+ : widget.code;+ return Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.menuInset,+ grid.AppDesktop.menuInset,+ grid.AppDesktop.groupGap,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Expanded(+ child: Text(+ widget.language ?? '',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(),+ ),+ ),+ _quiet(label: 'Copy', icon: AppIcons.copy, onPressed: _copy),+ ],+ ),+ Padding(+ padding: const EdgeInsets.only(right: grid.AppDesktop.controlGap),+ child: Text(+ shown,+ softWrap: true,+ style: grid.AppType.mono(+ color: DesktopChrome.foreground,+ height: 1.5,+ ),+ ),+ ),+ if (long)+ _quiet(+ label: _unfolded ? 'Show less' : 'Show more',+ onPressed: () => setState(() => _unfolded = !_unfolded),+ ),+ ],+ ),+ );+ }+}++/// A quiet control in the block, in the accent: no fill or rim at rest.+Widget _quiet({+ required String label,+ required VoidCallback onPressed,+ IconData? icon,+}) => DesktopPill(+ label: label,+ icon: icon,+ onPressed: onPressed,+ quiet: true,+ compact: true,+ foregroundColor: DesktopChrome.accent,+);diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex a0b042774..7a32dfa8a 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -1113,20 +1113,41 @@ class SuperTabController extends ChangeNotifier {static bool _listed(SuperTabMessage m) =>m.source['kind'] != 'update-request';- /// "Reviewer: Ada · Ready: yes on 1a2b3c4d5", from the newest `Ready:` message a- /// reviewer of [group] posted in the loaded history. Null without a reviewer.+ /// "Reviewer: Ada · Ready: yes on 1a2b3c4d5". The verdict is the newest+ /// review group's for [group], as its Reviewer recorded it (its result or+ /// check evidence), else the newest `Ready:` message a reviewer of [group]+ /// posted in the loaded history. Null without a reviewer.String? reviewLine(SuperTabConversation? group) {final state = snapshot;- if (group == null) return null;- final reviewers = state?.reviewers(group) ?? const <SuperTabAgent>[];+ if (group == null || state == null) return null;+ final reviews =+ state.conversations.where((c) => c.reviewOf == group.id).toList()+ ..sort((a, b) => (b.number ?? 0).compareTo(a.number ?? 0));+ final reviewers = {+ for (final r in [+ ...state.reviewers(group),+ for (final review in reviews) ...state.reviewers(review),+ ])+ r.id: r,+ }.values;if (reviewers.isEmpty) return null;final ids = {for (final r in reviewers) r.id};- final verdict = messages(group.id).reversed+ final recorded = reviews+ .expand(+ (review) => [+ review.assignment?['result'],+ for (final check in review.checks) check['evidence'],+ ],+ )+ .whereType<String>();+ final posted = messages(group.id).reversed.where((m) => m.fromAgent && ids.contains(m.authorId))- .map((m) => parseSuperTabVerdict(m.text))- .nonNulls- .firstOrNull;- final names = reviewers.map((r) => state!.agentName(r.id)).join(', ');+ .map((m) => m.text);+ final verdict = [+ ...recorded,+ ...posted,+ ].map(parseSuperTabVerdict).nonNulls.firstOrNull;+ final names = reviewers.map((r) => state.agentName(r.id)).join(', ');return 'Reviewer: $names · ${verdict?.label ?? 'No verdict yet'}';}diff --git a/desktop/lib/super_tabs/live_card.dart b/desktop/lib/super_tabs/live_card.dartnew file mode 100644index 000000000..08fead88f--- /dev/null+++ b/desktop/lib/super_tabs/live_card.dart@@ -0,0 +1,168 @@+import 'package:flutter/material.dart';++import '../shared/theme/pull_request_icon.dart';+import '../widgets/desktop_chrome.dart';+import 'controller.dart';+import 'live_card_model.dart';+import 'live_card_pull_request.dart';+import 'model.dart';+import 'pull_request_facts.dart';++/// A task's state in a few words, from its assignment's status.+String superTabCardStatus(Map<String, dynamic>? assignment) =>+ switch (assignment?['status']) {+ 'planned' => 'Planned',+ 'working' => 'Working',+ 'needs_human' => 'Waiting on a person',+ 'blocked' => 'Blocked',+ 'review' => 'In review',+ 'done' => 'Done',+ 'stopped' || 'lost' => 'Stopped',+ 'cancelled' => 'Cancelled',+ 'reconciling' => 'Checking its agent',+ _ => 'Not started',+ };++/// Like a Slack app's message that updates itself (backend superTabs/cards.ts):+/// a task or a pull request drawn as one card under its message, changing in+/// place as the group's state and GitHub change. Agents read the same facts at+/// once in the Swarm's state, so they need no step-by-step lines.+class SuperTabLiveCard extends StatefulWidget {+ const SuperTabLiveCard({+ super.key,+ required this.group,+ required this.card,+ required this.controller,+ required this.facts,+ });+ final SuperTabConversation group;+ final SuperTabCard card;+ final SuperTabController controller;+ final SuperTabPullRequestFacts facts;++ @override+ State<SuperTabLiveCard> createState() => _SuperTabLiveCardState();+}++class _SuperTabLiveCardState extends State<SuperTabLiveCard> {+ late List<SuperTabPullRequestCard> _watched = _pullRequests;++ /// A task card lists every pull request its group linked; a PR card its own.+ List<SuperTabPullRequestCard> get _pullRequests {+ if (!widget.card.task) return widget.card.pullRequests;+ final cards = widget.group.cards.pullRequests;+ return [+ for (final url in widget.group.pullRequestUrls)+ cards.where((c) => c.url == url).firstOrNull ??+ SuperTabPullRequestCard(url, ''),+ ];+ }++ @override+ void initState() {+ super.initState();+ widget.facts.watch(_watched.map((c) => c.url));+ }++ @override+ void didUpdateWidget(SuperTabLiveCard old) {+ super.didUpdateWidget(old);+ // Watched again before the old ones are let go, so a rebuild never+ // stops the refresh of what it still shows.+ final next = _pullRequests;+ widget.facts.watch(next.map((c) => c.url));+ old.facts.unwatch(_watched.map((c) => c.url));+ _watched = next;+ }++ @override+ void dispose() {+ widget.facts.unwatch(_watched.map((c) => c.url));+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: widget.facts,+ builder: (context, _) {+ final pulls = [+ for (final card in _watched)+ SuperTabCardPullRequest(card, widget.facts.of(card.url)),+ ];+ final review = widget.controller.reviewLine(widget.group);+ return _Frame(+ bar: widget.card.task || pulls.isEmpty+ ? DesktopChrome.accent+ : pullRequestIconColor(+ pulls.first.state,+ null,+ brightness: Theme.of(context).brightness,+ ),+ children: [+ if (widget.card.task) ..._task(),+ for (final pull in pulls) SuperTabCardPullRequestRow(pull),+ if (review != null) Text(review, style: DesktopChrome.metadata()),+ ],+ );+ },+ );++ List<Widget> _task() {+ final checks = widget.group.checks;+ final passed = checks.where((c) => c['evidence'] != null).length;+ return [+ Text(widget.group.label, style: DesktopChrome.control(medium: true)),+ SuperTabCardLine([+ superTabCardStatus(widget.group.assignment),+ if (checks.isNotEmpty) '$passed of ${checks.length} checks passed',+ ]),+ ];+ }+}++/// The card's surface: a colored edge, as a Slack attachment has, then its+/// rows.+class _Frame extends StatelessWidget {+ const _Frame({required this.bar, required this.children});+ final Color bar;+ final List<Widget> children;++ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.only(top: DesktopChrome.controlGap),+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 560),+ child: DecoratedBox(+ decoration: BoxDecoration(+ color: DesktopChrome.surface,+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ border: Border.all(color: DesktopChrome.rim),+ ),+ child: ClipRRect(+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ child: IntrinsicHeight(+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ SizedBox(+ width: DesktopChrome.controlGap / 2,+ child: ColoredBox(color: bar),+ ),+ Expanded(+ child: Padding(+ padding: const EdgeInsets.all(DesktopChrome.controlGap),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ spacing: DesktopChrome.controlGap / 2,+ children: children,+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+}diff --git a/desktop/lib/super_tabs/live_card_model.dart b/desktop/lib/super_tabs/live_card_model.dartnew file mode 100644index 000000000..15ea82290--- /dev/null+++ b/desktop/lib/super_tabs/live_card_model.dart@@ -0,0 +1,67 @@+/// One linked pull request's card: the message that is it, and whether the+/// Swarm recorded its merge (backend superTabs/cards.ts).+class SuperTabPullRequestCard {+ const SuperTabPullRequestCard(+ this.url,+ this.messageId, {+ this.merged = false,+ });+ final String url, messageId;+ final bool merged;+}++/// What one message is a card of: its group's task, its pull requests, or both.+typedef SuperTabCard = ({+ bool task,+ List<SuperTabPullRequestCard> pullRequests,+});++/// The messages a group shows as live cards (Slack parity): its task card and+/// one card per linked pull request. Each updates in place from the group+/// state the Swarm already sends, so only a reader of the group sees one.+class SuperTabCards {+ const SuperTabCards._(this.task, this.pullRequests);++ factory SuperTabCards.fromJson(Object? row) {+ if (row is! Map) return const SuperTabCards._(null, []);+ return SuperTabCards._(+ row['task'] is String ? row['task'] as String : null,+ [+ for (final card in row['pullRequests'] as List? ?? const [])+ if (card is Map &&+ card['messageId'] is String &&+ card['url'] is String &&+ _pullRequest(card['url'] as String))+ SuperTabPullRequestCard(+ card['url'] as String,+ card['messageId'] as String,+ merged: card['mergedAt'] is num,+ ),+ ],+ );+ }++ final String? task;+ final List<SuperTabPullRequestCard> pullRequests;++ /// The server binds only GitHub pull request links; anything else is not a+ /// card this app can draw.+ static bool _pullRequest(String url) {+ final uri = Uri.tryParse(url);+ return uri != null &&+ uri.scheme == 'https' &&+ uri.host == 'github.com' &&+ uri.pathSegments.length == 4 &&+ uri.pathSegments[2] == 'pull';+ }++ /// The card [messageId] is, or null for a plain message.+ SuperTabCard? of(String messageId) {+ final linked = [+ for (final card in pullRequests)+ if (card.messageId == messageId) card,+ ];+ if (task != messageId && linked.isEmpty) return null;+ return (task: task == messageId, pullRequests: linked);+ }+}diff --git a/desktop/lib/super_tabs/live_card_pull_request.dart b/desktop/lib/super_tabs/live_card_pull_request.dartnew file mode 100644index 000000000..393c87703--- /dev/null+++ b/desktop/lib/super_tabs/live_card_pull_request.dart@@ -0,0 +1,118 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_svg/flutter_svg.dart';++import '../core/open_in_browser.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/theme/pull_request_icon.dart';+import '../widgets/desktop_chrome.dart';+import 'live_card_model.dart';+import 'pull_request_entry.dart';++/// What a card says of one pull request: GitHub's facts as this computer read+/// them, else the Swarm's own (its link, and a merge it recorded).+class SuperTabCardPullRequest {+ const SuperTabCardPullRequest(this.card, this.entry);+ final SuperTabPullRequestCard card;+ final SuperTabPullRequestEntry? entry;++ Uri get url => Uri.parse(card.url);+ String get name => '${url.pathSegments[1]} · PR #${url.pathSegments[3]}';++ /// A merge the Swarm recorded wins over what this computer last read.+ String get state => card.merged ? 'Merged' : entry?.state ?? '';++ /// Words beside the state: checks while it is open, and what blocks it.+ List<String> get details {+ final entry = this.entry;+ if (card.merged || entry == null || entry.finalState) return const [];+ return [+ if (entry.kind+ case PullRequestKind.conflicts ||+ PullRequestKind.changes ||+ PullRequestKind.behind)+ entry.label,+ if (entry.total > 0) entry.checksLabel,+ ];+ }+}++/// One pull request on a card: its mark and title, then where it stands.+/// Opens on GitHub.+class SuperTabCardPullRequestRow extends StatelessWidget {+ const SuperTabCardPullRequestRow(this.pull, {super.key});+ final SuperTabCardPullRequest pull;++ @override+ Widget build(BuildContext context) {+ final brightness = Theme.of(context).brightness;+ final title = pull.entry?.title ?? '';+ final bits = [+ if (title.isNotEmpty) pull.name,+ if (pull.state.isNotEmpty) pull.state,+ ...pull.details,+ ];+ return Semantics(+ link: true,+ child: InkWell(+ key: ValueKey('super-card-pr-${pull.card.url}'),+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),+ onTap: () => unawaited(openInBrowser(pull.url)),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ vertical: DesktopChrome.controlGap / 2,+ ),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SvgPicture.asset(+ pullRequestIconAsset(pull.state),+ width: grid.AppDesktop.iconSize,+ height: grid.AppDesktop.iconSize,+ colorFilter: ColorFilter.mode(+ pullRequestIconColor(+ pull.state,+ null,+ brightness: brightness,+ ),+ BlendMode.srcIn,+ ),+ ),+ const SizedBox(width: DesktopChrome.controlGap),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ title.isNotEmpty ? title : pull.name,+ style: DesktopChrome.control(medium: true),+ ),+ if (bits.isNotEmpty) SuperTabCardLine(bits),+ ],+ ),+ ),+ ],+ ),+ ),+ ),+ );+ }+}++/// A card's quiet line: its parts in metadata type, a dot between them.+class SuperTabCardLine extends StatelessWidget {+ const SuperTabCardLine(this.parts, {super.key});+ final List<String> parts;++ @override+ Widget build(BuildContext context) => Wrap(+ spacing: DesktopChrome.controlGap / 2,+ children: [+ for (final (i, part) in parts.indexed) ...[+ if (i > 0) Text('·', style: DesktopChrome.metadata()),+ Text(part, style: DesktopChrome.metadata()),+ ],+ ],+ );+}diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex d940213d5..238a6a6b5 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -1541,8 +1541,17 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {);String available(double used) =>resourcePercent((100 - used).clamp(0, 100));- // Each engine with a known, unexpired allowance, Claude first. Offline or out of reach, an allowance is an- // old reading and no chip shows it as now.+ // Engines the server suspended here after failed starts, with why (backend superTabs/engineHealth.ts), on the Mac+ // or its Harness Team account.+ final suspended = <String, String>{+ for (final pool in [shared, team])+ if (pool?['suspendedEngines'] case final Map raw)+ for (final entry in raw.entries)+ if (entry.key is String && entry.value is String)+ entry.key as String: entry.value as String,+ };+ // Each engine with a known, unexpired allowance, Claude first; a suspended one also with its allowance unknown.+ // Offline or out of reach, an allowance is an old reading and no chip shows it as now.final allowances = dim? const <_Allowance>[]: [@@ -1566,6 +1575,11 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {0,100,),+ struck:+ suspended[engine] ??+ ((row['remainingPercent'] as num) <= 0+ ? _noQuotaLeft+ : null),note: superMachineAllowanceNote(switch (row['details']) {final List lines => lines.whereType<String>(),_ => const <String>[],@@ -1578,6 +1592,19 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {_ => ['${account.figure} remaining'],},].join('\n'),+ )+ else if (suspended[engine] case final reason?)+ // Named and figured as a card with a reading is ("Claude Code", "—" when unknown).+ for (final account in WorkspaceSubscriptionUsage.fromRows([+ {'engine': engine, 'accountKey': 'machine:$id:$engine'},+ ]).accounts.take(1))+ _Allowance(+ engine: engine,+ name: account.name,+ figure: account.figure,+ left: null,+ detail: '',+ struck: reason,),];// The models this machine offers the Swarm, from the same reading: an API's by its model, without the@@ -2654,6 +2681,7 @@ class _Allowance {required this.left,required this.detail,this.note,+ this.struck,});final String engine, name, figure, detail;@@ -2661,20 +2689,30 @@ class _Allowance {/// The window that stops work first and when it resets (`5-hour limit · resets in 2h 10m`), under the figure.final String? note;- /// The share left, 0–100.- final double left;+ /// The share left, 0–100; null when unknown (a suspended engine whose allowance could not be read).+ final double? left;++ /// Why new work does not go to this engine here (out of quota, or suspended after failed starts), shown on hover+ /// with its name struck through; null when it takes work.+ final String? struck;/// Amber below 20%, red below 10%, otherwise the reading's own ink.Color get ink => statusLineInkOnSurface(- left < 10+ left == null+ ? DesktopChrome.foreground+ : left! < 10? grid.AppPalette.usageCritical- : left < 20+ : left! < 20? grid.AppPalette.usageLow: DesktopChrome.foreground,DesktopChrome.surface,);}+/// What hovering an engine with no quota left on a machine says (the route leaves it out the same way).+const _noQuotaLeft =+ 'Not used for new work here: no quota left until it resets.';+/// The same leading icon/name and trailing status column as projects.class _MachineLine extends StatelessWidget {const _MachineLine({required this.view, this.onSetUpTeam});@@ -3054,15 +3092,23 @@ class _MachineReadings extends StatelessWidget {}Widget _allowance(_Allowance allowance) {- final tone = allowance.left < 10+ final left = allowance.left;+ final tone = left == null+ ? null+ : left < 10? grid.AppPalette.usageCritical- : allowance.left < 20+ : left < 20? grid.AppPalette.usageLow: null;+ final struck = allowance.struck;return Tooltip(- message: allowance.detail,+ message: [+ ?struck,+ if (allowance.detail.isNotEmpty) allowance.detail,+ ].join('\n\n'),child: Semantics(- label: '${allowance.name} ${allowance.figure} remaining',+ label:+ '${allowance.name} ${allowance.figure} remaining${struck == null ? '' : '. $struck'}',excludeSemantics: true,child: Container(key: ValueKey(@@ -3085,7 +3131,11 @@ class _MachineReadings extends StatelessWidget {allowance.name,maxLines: 1,overflow: TextOverflow.ellipsis,- style: DesktopChrome.text(size: 12, height: 1.3),+ style: DesktopChrome.text(size: 12, height: 1.3).copyWith(+ decoration: struck == null+ ? null+ : TextDecoration.lineThrough,+ ),),),const SizedBox(width: 6),@@ -3109,7 +3159,7 @@ class _MachineReadings extends StatelessWidget {),const SizedBox(height: 6),// The bar is what is left, as the figure is.- _Meter(share: allowance.left / 100, tone: tone),+ _Meter(share: (left ?? 0) / 100, tone: tone),if (allowance.note case final note?) ...[const SizedBox(height: 5),Text(diff --git a/desktop/lib/super_tabs/message_receipt.dart b/desktop/lib/super_tabs/message_receipt.dartindex fc94886a3..ecda57464 100644--- a/desktop/lib/super_tabs/message_receipt.dart+++ b/desktop/lib/super_tabs/message_receipt.dart@@ -6,14 +6,14 @@ import '../core/models.dart';import '../shared/theme/app_icons.dart';import '../shared/theme/app_theme.dart' as grid;import '../state/app_state.dart';-import '../state/harness_activity.dart';import '../widgets/desktop_chrome.dart';import 'controller.dart';import 'machine_status.dart';import 'model.dart';-/// The approved receipt line, scoped by the chat to its newest own message.-/// No new transport is inferred: missing native activity simply reads Delivered.+/// The line under the chat's newest own message, shown only while it sends,+/// when it was not sent, or when its delivery needs a hand; a message that+/// arrived carries none, as in Slack.class SuperTabMessageReceipt extends StatefulWidget {const SuperTabMessageReceipt({super.key,@@ -93,16 +93,6 @@ class _SuperTabMessageReceiptState extends State<SuperTabMessageReceipt>super.dispose();}- String _clockText(Duration value) {- final seconds = value.inSeconds.clamp(0, 1 << 31);- return '${seconds ~/ 60}:${(seconds % 60).toString().padLeft(2, '0')}';- }-- String _replyDuration(Duration value) {- final seconds = value.inSeconds.clamp(0, 1 << 31);- return seconds < 60 ? '${seconds}s' : '${seconds ~/ 60}m ${seconds % 60}s';- }-@overrideWidget build(BuildContext context) {final message = widget.message, c = widget.controller;@@ -135,28 +125,22 @@ class _SuperTabMessageReceiptState extends State<SuperTabMessageReceipt>: now.difference(readingAt),) ==SuperTabMachineStatus.offline);- final working =- delivery?.delivered == true &&- agent != null &&- widget.app != null &&- harnessActivity(widget.app!, agent.machineId, agent.harnessId) ==- HarnessActivity.working;final fresh =delivery?.pending == true &&message.createdAt != null &&now.difference(message.createdAt!) < const Duration(seconds: 3);- var color = DesktopChrome.muted;- var icon = AppIcons.check;- String title = 'Sent';- String? detail, note, elapsed;+ final error = Theme.of(context).colorScheme.error;+ var color = error;+ var icon = AppIcons.triangleAlert;+ // Like Slack, a message that went where it was sent carries no line: only+ // sending, not sending and what needs a hand show (Dee, 10-29).+ String? title, note;bool sending = false;final actions = <(String, VoidCallback?)>[];final canResolve = c.canWrite && !c.saving && delivery?.id != null;if (delivery?.status == 'uncertain') {title = "Couldn't confirm delivery";- icon = AppIcons.triangleAlert;- color = Theme.of(context).colorScheme.error;note ="$name's computer may have typed this into the terminal without confirming. Check the terminal before sending again, or it could run twice.";for (final (label, resolution) in [@@ -171,27 +155,6 @@ class _SuperTabMessageReceiptState extends State<SuperTabMessageReceipt>: null,));}- } else if (delivery?.status == 'answered') {- title = 'Replied';- icon = AppIcons.checkCheck;- final answer = delivery?.answeredAt ?? delivery?.updatedAt;- final start = delivery?.deliveredAt ?? message.createdAt;- if (answer != null && start != null) {- title += ' · ${_replyDuration(answer.difference(start))}';- }- } else if (delivery?.delivered == true) {- icon = AppIcons.checkCheck;- final at = (delivery!.deliveredAt ?? delivery.updatedAt)?.toLocal();- title = at == null- ? 'Delivered'- : 'Delivered ${at.hour.toString().padLeft(2, '0')}:${at.minute.toString().padLeft(2, '0')}';- if (working) {- color = DesktopChrome.accent;- detail = '$name is working';- if (delivery.deliveredAt != null) {- elapsed = _clockText(now.difference(delivery.deliveredAt!));- }- }} else if (delivery == null &&c.selected?.leadId == null &&// Every person reads the Product Managers' conversation; a post there@@ -200,70 +163,32 @@ class _SuperTabMessageReceiptState extends State<SuperTabMessageReceipt>// A Buddy chat has no Lead: its Buddy takes the message.c.selected?.isBuddyChat != true) {title = 'Not sent · this chat has no Lead';- icon = AppIcons.triangleAlert;- color = Theme.of(context).colorScheme.error;actions.add(('Add a Lead', c.canWrite ? widget.onAddLead : null));} else if (delivery?.status == 'cancelled') {title = 'Not sent';- icon = AppIcons.triangleAlert;- color = Theme.of(context).colorScheme.error;} else if (delivery?.pending == true && offline) {color = grid.AppPalette.warn;- detail = "$name's computer is offline";+ icon = AppIcons.cloudOff;+ title = "$name's computer is offline";final host =machine?['name'] as String? ?? widget.machineName(agent!.machineId);note = readingAt == null? "$host is offline. Your message goes in when it's back online.": "$host was last seen ${superTabAgo(now.difference(readingAt))}. Your message goes in when it's back online.";} else if (fresh) {+ color = DesktopChrome.muted;title = 'Sending…';sending = true;}- _clock(fresh || working || (delivery?.pending == true && offline));+ _clock(fresh || (delivery?.pending == true && offline));+ if (title == null) return const SizedBox.shrink();final style = superTabReceiptStyle(color);- final motion = !MediaQuery.disableAnimationsOf(context);final parts = <Widget>[- if (sending && motion)- SizedBox(- width: 12,- height: 12,- child: CircularProgressIndicator(strokeWidth: 1.5, color: color),- )+ if (sending)+ _sendingMark(context, color)else- Icon(sending ? AppIcons.loaderCircle : icon, size: 14, color: color),+ Icon(icon, size: 14, color: color),Text(title, style: style),- if (detail != null) ...[- Text('·', style: style),- Text(detail, style: style),- ],- if (working) ...[- ExcludeSemantics(- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- for (var i = 0; i < 3; i++)- Padding(- padding: const EdgeInsets.symmetric(horizontal: 1.5),- child: Opacity(- opacity:- !motion || (now.millisecondsSinceEpoch ~/ 500) % 3 == i- ? 1- : .25,- child: Container(- width: 4,- height: 4,- decoration: BoxDecoration(- color: color,- shape: BoxShape.circle,- ),- ),- ),- ),- ],- ),- ),- if (elapsed != null) Text(elapsed, style: style),- ],for (final (label, action) in actions) ...[Text('·', style: style),_receiptAction(label, action, style),@@ -297,6 +222,16 @@ class _SuperTabMessageReceiptState extends State<SuperTabMessageReceipt>}}+/// Sending's mark: a small spinner, or a still loader when motion is off.+Widget _sendingMark(BuildContext context, Color color) =>+ MediaQuery.disableAnimationsOf(context)+ ? Icon(AppIcons.loaderCircle, size: 14, color: color)+ : SizedBox(+ width: 12,+ height: 12,+ child: CircularProgressIndicator(strokeWidth: 1.5, color: color),+ );+/// A receipt line's text: small metadata in [color], with figures that keep/// their width as a clock counts.TextStyle superTabReceiptStyle(Color color) => DesktopChrome.metadata(@@ -381,17 +316,7 @@ class SuperTabOutgoingReceipt extends StatelessWidget {if (message.state == SuperTabOutgoingState.sending) {final style = superTabReceiptStyle(DesktopChrome.muted);return _receiptLine([- if (MediaQuery.disableAnimationsOf(context))- Icon(AppIcons.loaderCircle, size: 14, color: DesktopChrome.muted)- else- SizedBox(- width: 12,- height: 12,- child: CircularProgressIndicator(- strokeWidth: 1.5,- color: DesktopChrome.muted,- ),- ),+ _sendingMark(context, DesktopChrome.muted),Text('Sending…', style: style),]);}diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex 923f36b12..4bc07440d 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -27,6 +27,7 @@ class SuperTabMessageRow extends StatefulWidget {required this.message,required this.author,required this.onReturnToComposer,+ this.card,required this.receipts,this.agent,this.person,@@ -55,6 +56,10 @@ class SuperTabMessageRow extends StatefulWidget {final SuperTabMessage message;+ /// The live card [message] is (live_card.dart), drawn in place of its pull+ /// request links; null for a plain message.+ final Widget? card;+/// The thread [message] is the root of, once it has a reply.final SuperTabThread? thread;final bool threadUnread;@@ -453,11 +458,12 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {padding: EdgeInsets.only(top: message.text.isEmpty ? 0 : 8,),- child: SuperTabAttachmentChips(+ child: SuperTabAttachments(message.attachments,),),- SuperTabPullRequestLinks(message.text),+ widget.card ??+ SuperTabPullRequestLinks(message.text),if (widget.linkTarget case final resolve?)if (widget.onOpenLink case final open?)SuperTabMessageLinkPreviews(diff --git a/desktop/lib/super_tabs/message_text.dart b/desktop/lib/super_tabs/message_text.dartindex e48454464..e7117a937 100644--- a/desktop/lib/super_tabs/message_text.dart+++ b/desktop/lib/super_tabs/message_text.dart@@ -6,6 +6,7 @@ import '../core/open_in_browser.dart';import '../shared/theme/app_theme.dart' as grid;import '../widgets/desktop_chrome.dart';import '../widgets/markdown_style.dart';+import 'code_block.dart';/// Shared content is selectable, never executable. Markdown images are labels,/// not automatic network requests or reads from a collaborator's local disk.@@ -51,7 +52,7 @@ class SuperTabMessageText extends StatelessWidget {_WorkgroupReference(references),if (mentions.isNotEmpty) _Mention(mentions),],- builders: {'pre': _WrappedCode(), 'mention': _MentionName()},+ builders: {'pre': _CodeBlock(), 'mention': _MentionName()},paddingBuilders: {'a': _CompactLinkLabel()},styleSheet: desktopMarkdownStyleSheet(context),onTapLink: (_, href, _) {@@ -191,14 +192,20 @@ class _MentionName extends MarkdownElementBuilder {);}-class _WrappedCode extends MarkdownElementBuilder {+/// A fenced block as [SuperTabCodeBlock], named by its info string.+class _CodeBlock extends MarkdownElementBuilder {@override- Widget? visitText(md.Text text, TextStyle? preferredStyle) => Padding(- padding: const EdgeInsets.all(12),- child: Text(- text.text,- softWrap: true,- style: grid.AppType.mono(color: DesktopChrome.foreground, height: 1.5),- ),- );+ Widget? visitElementAfterWithContext(+ BuildContext context,+ md.Element element,+ TextStyle? preferredStyle,+ TextStyle? parentStyle,+ ) {+ final code = element.children?.firstOrNull;+ final info = code is md.Element ? code.attributes['class'] : null;+ return SuperTabCodeBlock(+ code: element.textContent.replaceFirst(RegExp(r'\n$'), ''),+ language: info?.replaceFirst('language-', ''),+ );+ }}diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex b91c3baaa..e39cf6406 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -1,4 +1,5 @@import 'identity.dart' show superTabPersonName;+import 'live_card_model.dart';import 'profile_model.dart';export 'profile_model.dart';@@ -220,6 +221,8 @@ class SuperTabConversation {(row['pullRequestUrls'] as List?)?.whereType<String>() ??const <String>[],),+ cards = SuperTabCards.fromJson(row['cards']),+ reviewOf = row['reviewOf'] as String?,brief = _text(row, 'brief'),task = row['task'] is Map? SuperTabTask.fromJson(superTabMap(row['task']))@@ -265,6 +268,13 @@ class SuperTabConversation {/// Persisted links may be absent on older backends; loaded messages still supply links.final List<String> pullRequestUrls;++ /// Its messages drawn as live cards (live_card.dart); none from an older+ /// backend.+ final SuperTabCards cards;++ /// A review group's reviewed group; null for any other conversation.+ final String? reviewOf;final int lastMessageSequence;/// Its newest message in the main stream: a reply only in its threaddiff --git a/desktop/lib/super_tabs/pull_request_facts.dart b/desktop/lib/super_tabs/pull_request_facts.dartnew file mode 100644index 000000000..9c039c330--- /dev/null+++ b/desktop/lib/super_tabs/pull_request_facts.dart@@ -0,0 +1,139 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import 'pull_request_entry.dart';++/// Reads pull requests' status on this computer, as the PR pane does+/// (`AppNotifier.readPullRequestsStatus`).+typedef SuperTabPullRequestRead = Future<Map<String, dynamic>> Function(+ List<String> urls,+);++/// What this computer's GitHub says about the pull requests live cards show:+/// title, state and checks. Read with the viewer's own sign-in, so a card shows+/// only what the viewer could read on GitHub. Nothing to read (no reader, no+/// sign-in, no access) leaves a card with the Swarm's facts alone, quietly.+/// Every watched pull request is read again [every], merged and closed ones+/// too: a sign-out or another GitHub account must not leave their private+/// titles behind. This computer's reader answers a final state from its own+/// cache, kept per GitHub account (cli lib/pullRequestsStatus.ts). Each+/// answer names the account it was read as: a change forgets every fact+/// before the answer is taken, failed reads included, and an answer that+/// cannot say shows nothing private.+class SuperTabPullRequestFacts extends ChangeNotifier {+ SuperTabPullRequestFacts(this._read);++ static const every = Duration(seconds: 60);+ static const _batch = 50;+ static const _signedOut = {'GH_MISSING', 'GH_SIGNED_OUT'};++ final SuperTabPullRequestRead? _read;+ final _entries = <String, SuperTabPullRequestEntry>{};+ final _watchers = <String, int>{};++ /// The account [_entries] were read as; null when none can be told.+ String? _account;+ Timer? _timer;+ bool _reading = false, _disposed = false;++ SuperTabPullRequestEntry? of(String url) => _entries[url];++ /// A card shows [urls]: read the ones not read yet, then keep them fresh+ /// until [unwatch].+ void watch(Iterable<String> urls) {+ final unread = [+ for (final url in urls)+ if ((_watchers[url] = (_watchers[url] ?? 0) + 1) == 1 &&+ !_entries.containsKey(url))+ url,+ ];+ if (unread.isNotEmpty) unawaited(_refresh(unread));+ _schedule();+ }++ void unwatch(Iterable<String> urls) {+ for (final url in urls) {+ final count = (_watchers[url] ?? 0) - 1;+ if (count > 0) {+ _watchers[url] = count;+ } else {+ _watchers.remove(url);+ }+ }+ _schedule();+ }++ void _schedule() {+ if (_read == null || _watchers.isEmpty) {+ _timer?.cancel();+ _timer = null;+ return;+ }+ _timer ??= Timer.periodic(+ every,+ (_) => unawaited(_refresh(_watchers.keys.toList())),+ );+ }++ Future<void> _refresh(List<String> urls) async {+ final read = _read;+ if (read == null || _reading || urls.isEmpty) return;+ _reading = true;+ try {+ for (var i = 0; i < urls.length; i += _batch) {+ final answer = await read(urls.skip(i).take(_batch).toList());+ if (_disposed) return;+ if (!_readAs(answer['account'])) break;+ if (_signedOut.contains(answer['error'])) {+ // Another account's private titles never stay under a changed login.+ _entries.clear();+ break;+ }+ _take(answer['rows'], urls);+ }+ } catch (_) {+ // Which account an unreachable computer reads as is unknown.+ _readAs(null);+ } finally {+ _reading = false;+ }+ if (_disposed) return;+ _schedule();+ notifyListeners();+ }++ /// Whether [account] is the one the facts were read as. Another account,+ /// or none to tell, forgets them all first.+ bool _readAs(Object? account) {+ if (account is String && account == _account) return true;+ _entries.clear();+ _account = account is String ? account : null;+ return _account != null;+ }++ void _take(Object? rows, List<String> asked) {+ for (final raw in rows is List ? rows : const []) {+ if (raw is! Map) continue;+ final entry = SuperTabPullRequestEntry.fromJson(+ Map<String, dynamic>.from(raw),+ );+ final url = entry?.url.toString();+ if (entry == null || !asked.contains(url)) continue;+ // An account that cannot read it forgets it; a failed read keeps the+ // last answer.+ if (entry.status == 'found') {+ _entries[url!] = entry;+ } else if (entry.status == 'no_access') {+ _entries.remove(url);+ }+ }+ }++ @override+ void dispose() {+ _disposed = true;+ _timer?.cancel();+ super.dispose();+ }+}diff --git a/desktop/lib/super_tabs/roles_editor.dart b/desktop/lib/super_tabs/roles_editor.dartindex 235f3068a..f26eba417 100644--- a/desktop/lib/super_tabs/roles_editor.dart+++ b/desktop/lib/super_tabs/roles_editor.dart@@ -82,6 +82,7 @@ When the project owner asks in chat to switch this project's skills (Default or## 7. Keep people informed- At the project's cadence, post a scored table: one row per group, 0 to 1, its owner and what it waits on. Only merged and tried scores 1.0. If nothing changed, post nothing.- Answer each scheduled project update request as soon as it arrives: project.report through the revisions it names, with text null when nothing changed. An unanswered request blocks the later ones and keeps finished groups from archiving.+- Each task and each pull request linked in its chat is one card there that updates itself: status, checks passed, CI, review verdict and merge. Post a pull request's link once, and never a line that only repeats what a card shows (opened, CI running or green, reviewed, merged); people and agents read the card and the Swarm's status instead.- Answer questions, blockers and completions at once.- Every post carries a result, a decision asked for with your recommendation, a question, or a fault; never an acknowledgement alone.- Write like a colleague: short, in their language, no commands or internal ids. Call the roles Product Manager, Engineer and Reviewer.@@ -120,6 +121,7 @@ You finish one group's work completely, inside its brief, as if nobody will come- Name a known flaky test instead of letting it block you.- Have something to show at least every 20 minutes: a push or a short progress line.- Push your work branch at least every 30 minutes, and set your work status to working with a one-line note of what is done and what is next, so another agent can continue if you stop.+- Your task and each pull request you link are cards in the group chat that update themselves: status, checks, CI, review verdict and merge. Post a pull request's link once, in the main chat; never post a line that only repeats what a card shows (opened, CI running or green, merged). Progress lines carry what a card does not: the step, the commit, the test result, a ruling or a blocker.- When an answer is unclear, take its narrowest safe reading and say so. Keep working on whatever doesn't depend on a question, and don't ask twice.- To split the work or take more, ask the Lead. You may propose new work; the Lead decides.@@ -179,6 +181,7 @@ Start within 30 minutes of being asked; oldest ready work first. If you cannot,- Findings P1 (must fix), P2 (fix before accepting), P3 (later), each with file:line, what is wrong and the fix.- Verdict: "No finding on <rev>", or "Hold — <rev>" with the findings. A re-review covers only the new changes.- Pass or fail the independent check with the revision and verdict.+- The task's card in the group chat shows your verdict, CI and merge as they change. Post the verdict once, with its findings; never a line that only repeats what the card shows.- Tell the Lead at once about privacy, interface breaks, default-on changes to safety or updates, and device behaviour nobody could show.- Keep posts short, in the people's language, without commands or internal ids. Call the roles Product Manager, Engineer and Reviewer.diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex eaed5600a..835522f59 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -25,6 +25,8 @@ import 'unread_line.dart';import 'roster.dart';import 'recording_notice.dart';import 'profile_actions.dart';+import 'live_card.dart';+import 'pull_request_facts.dart';import 'pull_requests.dart';import 'composer_newline.dart';import 'controller.dart';@@ -175,6 +177,11 @@ class _SuperTabViewState extends State<SuperTabView>/// and the left sidebar's Models, so both show one week.late SuperTabProjectBoard _board = SuperTabProjectBoard(c);+ /// What this computer's GitHub says of the pull requests on live cards.+ late SuperTabPullRequestFacts _facts = SuperTabPullRequestFacts(+ widget.app?.readPullRequestsStatus,+ );+/// A device with a Lead of this Swarm open scrolls the chat on screen.late final _dial = DialListScroll(() => _scroll[c.selectedId]);VoidCallback? _unregisterDial;@@ -244,6 +251,8 @@ class _SuperTabViewState extends State<SuperTabView>if (oldWidget.controller != c || oldWidget.app != widget.app) {_dial.cancel();_registerDial();+ _facts.dispose();+ _facts = SuperTabPullRequestFacts(widget.app?.readPullRequestsStatus);}if (oldWidget.controller != c) {_board.dispose();@@ -567,6 +576,7 @@ class _SuperTabViewState extends State<SuperTabView>void dispose() {WidgetsBinding.instance.removeObserver(this);_board.dispose();+ _facts.dispose();c.removeListener(_changed);for (final source in _linkSources) {source.removeListener(_linkSourceChanged);@@ -2308,11 +2318,23 @@ class _SuperTabViewState extends State<SuperTabView>final thread = inThread || root != message.id? null: c.thread(message.conversationId, message.id);+ final group = inThread+ ? null+ : c.snapshot?.conversation(message.conversationId);+ final card = group?.cards.of(message.id);return SuperTabMessageRow(key: ValueKey('${inThread ? 'super-thread-message' : 'super-message'}-${message.id}',),message: message,+ card: card == null+ ? null+ : SuperTabLiveCard(+ group: group!,+ card: card,+ controller: c,+ facts: _facts,+ ),author: _shownAuthor(c, message),proposalOwner: _proposalOwner(message),// A person is named by their username, as they are tagged.diff --git a/desktop/test/super_tab_attachment_image_test.dart b/desktop/test/super_tab_attachment_image_test.dartnew file mode 100644index 000000000..39e35affd--- /dev/null+++ b/desktop/test/super_tab_attachment_image_test.dart@@ -0,0 +1,91 @@+// The chat's picture loader against a real server: it draws the picture the+// attachments host serves, and refuses a redirect, so nothing from another+// host is ever fetched or drawn.+import 'dart:async';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/painting.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/attachment_viewer.dart';++/// A real 1×1 PNG.+const _png = <int>[+ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, //+ 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,+ 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00,+ 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0xDA, 0x63, 0x64, 0x60, 0xF8, 0x5F,+ 0x0F, 0x00, 0x02, 0x87, 0x01, 0x80, 0xEB, 0x47, 0xBA, 0x92, 0x00, 0x00,+ 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,+];++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ late HttpServer server, elsewhere;+ late int elsewhereHits;+ late Future<void> Function(HttpResponse) answer;++ Uri link(String path) => Uri.parse('http://127.0.0.1:${server.port}$path');++ setUp(() async {+ elsewhereHits = 0;+ elsewhere = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ elsewhere.listen((request) {+ elsewhereHits++;+ request.response+ ..headers.contentType = ContentType('image', 'png')+ ..add(_png)+ ..close();+ });+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ server.listen((request) => answer(request.response));+ });+ tearDown(() async {+ await server.close(force: true);+ await elsewhere.close(force: true);+ imageCache.clear();+ });++ /// What [url]'s picture comes to: its image, or the error it ends in.+ Future<Object> load(Uri url) {+ final done = Completer<Object>();+ attachmentPicture(url)+ .resolve(ImageConfiguration.empty)+ .addListener(+ ImageStreamListener(+ (image, _) => done.complete(image.image),+ onError: (error, _) => done.complete(error),+ ),+ );+ return done.future;+ }++ test('draws the picture the attachments host serves', () async {+ answer = (response) => (response..add(_png)).close();++ final image = await load(link('/a.png'));+ expect(image, isA<ui.Image>());+ expect((image as ui.Image).width, 1);+ });++ for (final status in [+ HttpStatus.movedPermanently,+ HttpStatus.found,+ HttpStatus.temporaryRedirect,+ ]) {+ test('refuses a $status redirect: nothing from the other host', () async {+ answer = (response) {+ response+ ..statusCode = status+ ..headers.set(+ HttpHeaders.locationHeader,+ 'http://127.0.0.1:${elsewhere.port}/b.png',+ );+ return response.close();+ };++ expect(await load(link('/a.png')), isNot(isA<ui.Image>()));+ expect(elsewhereHits, 0);+ });+ }+}diff --git a/desktop/test/super_tab_attachments_test.dart b/desktop/test/super_tab_attachments_test.dartindex 45f6ce361..64ad7b56d 100644--- a/desktop/test/super_tab_attachments_test.dart+++ b/desktop/test/super_tab_attachments_test.dart@@ -1,6 +1,7 @@// Files in a Swarm conversation: the composer takes pasted, dropped and picked// files and uploads them before the message, and a message shows its files as-// chips that load nothing until clicked.+// chips that load nothing until clicked (pictures, shown in place, are in+// super_tab_message_media_test.dart).import 'dart:async';import 'dart:convert';import 'dart:io';@@ -288,8 +289,13 @@ void main() {expect(command['text'], 'See these');expect(command['attachmentIds'], ['attachment-1', 'attachment-2']);expect(controller.attachments('lead').isEmpty, isTrue);+ // The picture shows in place, the text file as a chip.expect(- find.byKey(const ValueKey('super-attachment:attachment-1')),+ find.byKey(const ValueKey('super-attachment-inline:attachment-1')),+ findsOneWidget,+ );+ expect(+ find.byKey(const ValueKey('super-attachment:attachment-2')),findsOneWidget,);await close(tester, controller);@@ -623,18 +629,13 @@ void main() {});group('messages', () {- testWidgets('show chips and load nothing until a click', (tester) async {+ testWidgets('a file shows as a chip and loads nothing until a click', (+ tester,+ ) async {final server = ConversationServer()..append('Here',attachments: [- {- 'id': 'a1',- 'name': 'shot.png',- 'mime': 'image/png',- 'size': 2048,- 'url': 'https://cdn.harness.autonomous.ai/a1/shot.png',- },{'id': 'a2','name': 'report.pdf',@@ -655,21 +656,9 @@ void main() {};addTearDown(() => browserOpener = original);- expect(find.text('shot.png'), findsOneWidget);- expect(find.text('2 KB'), findsOneWidget);expect(find.text('report.pdf'), findsOneWidget);expect(find.text('3.0 MB'), findsOneWidget);- expect(find.byType(Image), findsNothing);-- await tester.tap(find.byKey(const ValueKey('super-attachment:a1')));- await tester.pumpAndSettle();- expect(- find.byKey(const ValueKey('super-attachment-image:a1')),- findsOneWidget,- );expect(opened, isEmpty);- await tester.tap(find.text('Close'));- await tester.pumpAndSettle();await tester.tap(find.byKey(const ValueKey('super-attachment:a2')));await tester.pumpAndSettle();@@ -927,24 +916,6 @@ void main() {await close(tester, controller);});- testWidgets('the picture viewer offers Download', (tester) async {- final (controller, _, _) = await showFiles(tester, [- row('a1', 'shot.png', 'image/png', 2048),- ]);-- await tester.tap(find.byKey(const ValueKey('super-attachment:a1')));- await tester.pumpAndSettle();- expect(- find.byKey(const ValueKey('super-attachment-image:a1')),- findsOneWidget,- );- expect(find.text('Download'), findsOneWidget);- expect(find.text('Open in browser'), findsOneWidget);- await tester.tap(find.text('Close'));- await tester.pumpAndSettle();- await close(tester, controller);- });-testWidgets('a text file off the attachments host is never fetched', (tester,) async {diff --git a/desktop/test/super_tab_live_card_shots_test.dart b/desktop/test/super_tab_live_card_shots_test.dartnew file mode 100644index 000000000..3d178f3eb--- /dev/null+++ b/desktop/test/super_tab_live_card_shots_test.dart@@ -0,0 +1,154 @@+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/live_card.dart';+import 'package:harness/super_tabs/message_row.dart';+import 'package:harness/super_tabs/pull_request_facts.dart';+import 'package:harness/super_tabs/view.dart';++import 'super_tab_live_card_test.dart' show cardServer, found, other, pr;+import 'support/capture.dart';+import 'support/super_tab_fixture.dart';++/// Set to a folder to write the live-card PR's screenshots there: the real+/// chat rows over the in-memory Swarm and a fake GitHub, never a backend.+final shots = Platform.environment['SUPER_TAB_CARD_SHOTS'];++/// The workgroup with a second, merged pull request on a card of its own.+ConversationServer server() {+ final server = cardServer();+ final work = (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((g) => g['id'] == 'work');+ server.append('Phone follow-up: $other', conversationId: 'work');+ // Its Lead wrote the brief, as the Swarm writes a brief in the Lead's name.+ (server.state['agents'] as List).add({+ 'id': 'river',+ 'name': 'River',+ 'machineId': 'm',+ 'harnessId': 'river',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'claude'},+ });+ work['leadId'] = 'river';+ work['agentIds'] = ['river', ...work['agentIds'] as List];+ server.messages.first['author'] = {+ 'kind': 'agent',+ 'id': 'river',+ 'name': 'River',+ };+ final kai = {'kind': 'agent', 'id': 'kai', 'name': 'Kai'};+ for (final m in server.messages) {+ if (const {'message-2', 'message-4', 'message-5'}.contains(m['id'])) {+ m['author'] = kai;+ }+ }+ work['pullRequestUrls'] = [pr, other];+ (work['cards'] as Map)['pullRequests'] = [+ {'url': pr, 'messageId': 'message-2'},+ {'url': other, 'messageId': 'message-5', 'mergedAt': 5},+ ];+ return server;+}++SuperTabPullRequestFacts github() => SuperTabPullRequestFacts(+ (_) async => {+ 'account': 'ada',+ 'rows': [+ found(pr, passed: 8, pending: 4),+ {...found(other, state: 'Merged'), 'title': 'Avatars on the phone'},+ ],+ },+);++Future<void> theme(WidgetTester tester, Brightness brightness) async {+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.dark);+}++/// The chat's rows as the conversation draws them, each card under its+/// message.+Future<void> showRows(WidgetTester tester, Brightness brightness) async {+ await tester.binding.setSurfaceSize(const Size(900, 760));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await theme(tester, brightness);+ final c = server().controller();+ addTearDown(c.dispose);+ await c.refresh();+ await c.loadMessages('work');+ final facts = github();+ addTearDown(facts.dispose);+ final group = c.snapshot!.conversation('work')!;+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: ListView(+ children: [+ for (final message in c.messages('work'))+ SuperTabMessageRow(+ message: message,+ author: message.fromAgent+ ? c.snapshot!.agentName(message.authorId)+ : 'River',+ onReturnToComposer: () {},+ receipts: const [],+ card: switch (group.cards.of(message.id)) {+ final card? => SuperTabLiveCard(+ group: group,+ card: card,+ controller: c,+ facts: facts,+ ),+ null => null,+ },+ ),+ ],+ ),+ ),+ ),+ );+ await tester.pump();+ // The app animates a change of theme; the picture is of where it lands.+ await tester.pump(const Duration(milliseconds: 400));+}++void main() {+ setUpAll(() => loadCaptureFonts(shots));++ testWidgets('screenshots for review', (tester) async {+ for (final brightness in Brightness.values) {+ await showRows(tester, brightness);+ await captureWindow(tester, shots, 'cards-${brightness.name}');+ }+ // The whole conversation on a computer with no GitHub sign-in: the cards+ // keep what the Swarm knows and leave CI out.+ await tester.binding.setSurfaceSize(const Size(1280, 860));+ await theme(tester, Brightness.dark);+ final c = server().controller();+ addTearDown(c.dispose);+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'MacBookPro2021',+ ),+ ),+ ),+ );+ await c.select('work');+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, 'conversation-no-github-dark');+ await tester.pump(const Duration(milliseconds: 250));+ }, skip: shots == null);+}diff --git a/desktop/test/super_tab_live_card_test.dart b/desktop/test/super_tab_live_card_test.dartnew file mode 100644index 000000000..c108de138--- /dev/null+++ b/desktop/test/super_tab_live_card_test.dart@@ -0,0 +1,387 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/live_card.dart';+import 'package:harness/super_tabs/live_card_model.dart';+import 'package:harness/super_tabs/pull_request_facts.dart';++import 'super_tab_mentions_test.dart' show showView;+import 'support/super_tab_fixture.dart';++const pr = 'https://github.com/example/app/pull/7';+const other = 'https://github.com/example/app/pull/8';++Map<String, dynamic> found(+ String url, {+ String state = 'Open',+ int passed = 12,+ int pending = 0,+ int total = 12,+}) => {+ 'url': url,+ 'status': 'found',+ 'title': 'Round avatars',+ 'state': state,+ 'checks': {'passed': passed, 'failed': 0, 'pending': pending, 'total': total},+};++/// A workgroup with a builder, a reviewer whose verdict is in the chat, and the+/// two cards the backend names: its brief is the task card, its first link of+/// [pr] the PR card.+ConversationServer cardServer({int? mergedAt}) {+ final server = ConversationServer();+ server.state['agents'] = [+ for (final (id, name, role) in [+ ('kai', 'Kai', null),+ ('ivy', 'Ivy', 'reviewer'),+ ])+ {+ 'id': id,+ 'name': name,+ 'machineId': 'm',+ 'harnessId': id,+ 'contributorId': 'owner',+ 'configuration': {'engine': 'claude'},+ 'role': ?role,+ },+ ];+ (server.state['conversations'] as List).add({+ ...conversationFixture('work', 'Avatars'),+ 'number': 12,+ 'agentIds': ['kai', 'ivy'],+ 'brief': 'Add avatars.',+ 'checks': [+ {'id': 'a', 'description': 'Tests pass', 'evidence': 'ok'},+ {'id': 'b', 'description': 'Screens', 'evidence': null},+ ],+ 'assignment': {'id': 'w', 'agentId': 'kai', 'status': 'working'},+ 'pullRequestUrls': [pr],+ 'cards': {+ 'task': 'message-1',+ 'pullRequests': [+ {'url': pr, 'messageId': 'message-2', 'mergedAt': ?mergedAt},+ ],+ },+ });+ server.append('Add avatars.', conversationId: 'work');+ server.append('Opened $pr', conversationId: 'work');+ server.append('Ready: yes on 1a2b3c4d5', conversationId: 'work');+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'ivy',+ 'name': 'Ivy',+ };+ server.append('CI is running on $pr', conversationId: 'work');+ return server;+}++Future<SuperTabController> show(+ WidgetTester tester,+ ConversationServer server,+ SuperTabPullRequestFacts facts,+ String messageId,+) async {+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ await c.loadMessages('work');+ final group = c.snapshot!.conversation('work')!;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabLiveCard(+ group: group,+ card: group.cards.of(messageId)!,+ controller: c,+ facts: facts,+ ),+ ),+ ),+ );+ await tester.pump();+ return c;+}++SuperTabPullRequestFacts reading(+ List<Map<String, dynamic>> Function() answer, {+ void Function(List<String>)? onRead,+}) => SuperTabPullRequestFacts((urls) async {+ onRead?.call(urls);+ return {'account': 'ada', 'rows': answer()};+});++void main() {+ test('a group names which of its messages are cards', () {+ final cards = SuperTabCards.fromJson({+ 'task': 'm1',+ 'pullRequests': [+ {'url': pr, 'messageId': 'm2'},+ {'url': other, 'messageId': 'm2', 'mergedAt': 5},+ {'url': 'https://example.com/x', 'messageId': 'm3'},+ ],+ });+ expect(cards.of('m1')!.task, isTrue);+ expect(cards.of('m1')!.pullRequests, isEmpty);+ expect(cards.of('m2')!.task, isFalse);+ expect(cards.of('m2')!.pullRequests.map((p) => p.url), [pr, other]);+ expect(cards.of('m2')!.pullRequests.last.merged, isTrue);+ expect(cards.of('m3'), isNull);+ expect(SuperTabCards.fromJson(null).of('m1'), isNull);+ });++ testWidgets('a PR card shows its title, state, checks and the verdict', (+ tester,+ ) async {+ final facts = reading(() => [found(pr)]);+ addTearDown(facts.dispose);+ await show(tester, cardServer(), facts, 'message-2');+ expect(find.text('Round avatars'), findsOneWidget);+ expect(find.text('app · PR #7'), findsOneWidget);+ expect(find.text('Open'), findsOneWidget);+ expect(find.text('12 checks passed'), findsOneWidget);+ expect(+ find.text('Reviewer: Ivy · Ready: yes on 1a2b3c4d5'),+ findsOneWidget,+ );+ });++ testWidgets('without GitHub on this computer, CI is left out quietly', (+ tester,+ ) async {+ final facts = SuperTabPullRequestFacts(+ (_) async => {'error': 'GH_SIGNED_OUT'},+ );+ addTearDown(facts.dispose);+ await show(tester, cardServer(mergedAt: 5), facts, 'message-2');+ expect(find.text('app · PR #7'), findsOneWidget);+ expect(find.text('Merged'), findsOneWidget);+ expect(find.textContaining('check'), findsNothing);+ expect(find.textContaining('GitHub'), findsNothing);+ });++ testWidgets('a card with no reader at all shows what the Swarm knows', (+ tester,+ ) async {+ final facts = SuperTabPullRequestFacts(null);+ addTearDown(facts.dispose);+ await show(tester, cardServer(), facts, 'message-2');+ expect(find.text('app · PR #7'), findsOneWidget);+ expect(find.textContaining('check'), findsNothing);+ });++ testWidgets('a task card shows its title, status, checks and its PRs', (+ tester,+ ) async {+ final facts = reading(() => [found(pr)]);+ addTearDown(facts.dispose);+ await show(tester, cardServer(), facts, 'message-1');+ expect(find.text('#12 Avatars'), findsOneWidget);+ expect(find.text('Working'), findsOneWidget);+ expect(find.text('1 of 2 checks passed'), findsOneWidget);+ expect(find.text('Round avatars'), findsOneWidget);+ expect(+ find.text('Reviewer: Ivy · Ready: yes on 1a2b3c4d5'),+ findsOneWidget,+ );+ });++ testWidgets('the card updates in place as the PR changes', (tester) async {+ var answer = found(pr, passed: 3, pending: 9);+ final facts = reading(() => [answer]);+ addTearDown(facts.dispose);+ await show(tester, cardServer(), facts, 'message-2');+ expect(find.text('3 of 12 checks done'), findsOneWidget);+ answer = found(pr, state: 'Merged');+ await tester.pump(SuperTabPullRequestFacts.every);+ await tester.pump();+ expect(find.text('Merged'), findsOneWidget);+ expect(find.text('3 of 12 checks done'), findsNothing);+ });++ testWidgets(+ 'a sign-out or another GitHub account clears a card, even one whose PRs are all merged',+ (tester) async {+ Map<String, dynamic> answer = {+ 'account': 'ada',+ 'rows': [found(pr, state: 'Merged')],+ };+ final facts = SuperTabPullRequestFacts((_) async => answer);+ addTearDown(facts.dispose);+ await show(tester, cardServer(), facts, 'message-2');+ expect(find.text('Round avatars'), findsOneWidget);+ answer = {'account': 'none', 'error': 'GH_SIGNED_OUT'};+ await tester.pump(SuperTabPullRequestFacts.every);+ await tester.pump();+ expect(find.text('Round avatars'), findsNothing);+ answer = {+ 'account': 'ada',+ 'rows': [found(pr, state: 'Merged')],+ };+ await tester.pump(SuperTabPullRequestFacts.every);+ await tester.pump();+ expect(find.text('Round avatars'), findsOneWidget);+ // Another account, which cannot read that repository.+ answer = {+ 'account': 'grace',+ 'rows': [+ {'url': pr, 'status': 'no_access'},+ ],+ };+ await tester.pump(SuperTabPullRequestFacts.every);+ await tester.pump();+ expect(find.text('Round avatars'), findsNothing);+ expect(find.text('app · PR #7'), findsOneWidget);+ },+ );++ testWidgets(+ 'a switch to another GitHub account clears a card at once, even while its reads fail',+ (tester) async {+ Map<String, dynamic> answer = {+ 'account': 'ada',+ 'rows': [found(pr)],+ };+ final facts = SuperTabPullRequestFacts((_) async => answer);+ addTearDown(facts.dispose);+ await show(tester, cardServer(), facts, 'message-2');+ expect(find.text('Round avatars'), findsOneWidget);+ expect(find.text('12 checks passed'), findsOneWidget);+ for (final error in ['TIMEOUT', 'RATE_LIMITED']) {+ answer = {+ 'account': 'grace-$error',+ 'error': error,+ 'rows': [+ {'url': pr, 'status': 'unavailable', 'error': error},+ ],+ };+ await tester.pump(SuperTabPullRequestFacts.every);+ await tester.pump();+ expect(find.text('Round avatars'), findsNothing, reason: error);+ expect(find.text('12 checks passed'), findsNothing, reason: error);+ expect(find.text('app · PR #7'), findsOneWidget, reason: error);+ }+ },+ );++ testWidgets('an answer that names no account shows no private details', (+ tester,+ ) async {+ final facts = SuperTabPullRequestFacts(+ (_) async => {+ 'rows': [found(pr)],+ },+ );+ addTearDown(facts.dispose);+ await show(tester, cardServer(), facts, 'message-2');+ expect(find.text('Round avatars'), findsNothing);+ expect(find.textContaining('check'), findsNothing);+ expect(find.text('app · PR #7'), findsOneWidget);+ });++ testWidgets(+ 'a merge the Swarm recorded wins over an open read, even while GitHub fails',+ (tester) async {+ Map<String, dynamic> answer = {+ 'account': 'ada',+ 'rows': [found(pr, passed: 3, pending: 9)],+ };+ final facts = SuperTabPullRequestFacts((_) async => answer);+ addTearDown(facts.dispose);+ await show(tester, cardServer(), facts, 'message-2');+ expect(find.text('Open'), findsOneWidget);+ answer = {'account': 'ada', 'error': 'RATE_LIMITED'};+ final c = cardServer(mergedAt: 5).controller();+ addTearDown(c.dispose);+ await c.refresh();+ final group = c.snapshot!.conversation('work')!;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabLiveCard(+ group: group,+ card: group.cards.of('message-2')!,+ controller: c,+ facts: facts,+ ),+ ),+ ),+ );+ await tester.pump(SuperTabPullRequestFacts.every);+ await tester.pump();+ expect(find.text('Merged'), findsOneWidget);+ expect(find.text('Open'), findsNothing);+ expect(find.text('3 of 12 checks done'), findsNothing);+ },+ );++ testWidgets(+ 'the verdict comes from the review chat, for the revision it reviewed',+ (tester) async {+ final server = cardServer();+ server.messages.removeWhere((m) => '${m['text']}'.startsWith('Ready:'));+ final groups = (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>();+ groups.firstWhere((g) => g['id'] == 'work')['agentIds'] = ['kai'];+ groups.add({+ ...conversationFixture('review', 'Review: Avatars'),+ 'number': 13,+ 'reviewOf': 'work',+ 'agentIds': ['ivy'],+ 'assignment': {+ 'id': 'r',+ 'agentId': 'ivy',+ 'status': 'done',+ 'result': 'Ready: no — revision 050bab807. Two findings.',+ },+ });+ final facts = SuperTabPullRequestFacts(null);+ addTearDown(facts.dispose);+ await show(tester, server, facts, 'message-1');+ expect(+ find.text('Reviewer: Ivy · Ready: no on 050bab807'),+ findsOneWidget,+ );+ },+ );++ testWidgets('rebuilding a card often never stops its refresh', (+ tester,+ ) async {+ final reads = <List<String>>[];+ final facts = reading(+ () => [found(pr, passed: 3, pending: 9)],+ onRead: reads.add,+ );+ addTearDown(facts.dispose);+ final c = await show(tester, cardServer(), facts, 'message-2');+ final group = c.snapshot!.conversation('work')!;+ for (var i = 0; i < 7; i++) {+ await tester.pump(const Duration(seconds: 10));+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabLiveCard(+ group: group,+ card: group.cards.of('message-2')!,+ controller: c,+ facts: facts,+ ),+ ),+ ),+ );+ }+ expect(reads, hasLength(2));+ });++ testWidgets('the conversation draws a card message as one card', (+ tester,+ ) async {+ final c = await showView(tester, cardServer());+ await c.select('work');+ await tester.pumpAndSettle();+ expect(find.byType(SuperTabLiveCard), findsNWidgets(2));+ expect(find.text('CI is running on $pr'), findsOneWidget);+ // The read mark it just made is saved a moment later.+ await tester.pump(const Duration(milliseconds: 250));+ });+}diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dartindex 7bdae2dfb..9882f225b 100644--- a/desktop/test/super_tab_machines_test.dart+++ b/desktop/test/super_tab_machines_test.dart@@ -3635,6 +3635,139 @@ void main() {await tester.pump();},);++ // Ken, 2026-10-28: work kept landing on engines that could not run on a machine. The only visible change: an engine that+ // is out of quota or suspended there has its name struck through in the machine's Subscriptions, with why on hover.+ testWidgets(+ 'strikes through an engine out of quota or suspended on a machine, with why on hover',+ (tester) async {+ await tester.binding.setSurfaceSize(const Size(900, 1400));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final server = ConversationServer();+ const suspended =+ 'Claude Code is suspended on this machine for new work: its last 2 starts there failed. It is offered again within 6 hours, or once its owner resumes it.';+ server.state['machines'] = [+ {+ 'machineId': 'm',+ 'name': 'Studio',+ 'contributorId': 'owner',+ 'suspendedEngines': {'claude': suspended},+ 'observation': {+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,+ 'resources': {'cpuPercent': 10},+ 'quotas': [+ {'engine': 'claude', 'known': false, 'windows': []},+ {+ 'engine': 'codex',+ 'known': true,+ 'windows': [+ {'name': 'weekly', 'usedPercent': 100},+ ],+ },+ ],+ },+ },+ ];+ final c = server.controller();+ await c.refresh();+ c.toggleMachineExpanded('m');+ await tester.pumpWidget(+ MaterialApp(+ // As the sidebar does: the section is rebuilt whenever the Swarm changes.+ home: Scaffold(+ body: ListenableBuilder(+ listenable: c,+ builder: (context, _) => SuperTabMachines(+ controller: c,+ embedded: true,+ onAddAgent: (_) {},+ onOpenAgent: (_) {},+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ TextDecoration? decoration(String engine, String name) => tester+ .widget<Text>(+ find.descendant(+ of: find.byKey(ValueKey('super-machine-allowance-m-$engine')),+ matching: find.text(name),+ ),+ )+ .style+ ?.decoration;+ String tip(String engine) => tester+ .widget<Tooltip>(+ find+ .ancestor(+ of: find.byKey(ValueKey('super-machine-allowance-m-$engine')),+ matching: find.byType(Tooltip),+ )+ .first,+ )+ .message!;+ // Suspended with its allowance unknown: a card all the same, with a dash for the figure.+ expect(decoration('claude', 'Claude Code'), TextDecoration.lineThrough);+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('super-machine-allowance-m-claude')),+ matching: find.text('—'),+ ),+ findsOneWidget,+ );+ expect(tip('claude'), startsWith(suspended));+ // Out of quota: struck, its figure kept.+ expect(decoration('codex', 'Codex'), TextDecoration.lineThrough);+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('super-machine-allowance-m-codex')),+ matching: find.text('0%'),+ ),+ findsOneWidget,+ );+ expect(+ tip('codex'),+ startsWith(+ 'Not used for new work here: no quota left until it resets.',+ ),+ );+ expect(tester.takeException(), isNull);++ // Once neither holds, nothing is struck.+ server.state['machines'] = [+ {+ 'machineId': 'm',+ 'name': 'Studio',+ 'contributorId': 'owner',+ 'observation': {+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,+ 'resources': {'cpuPercent': 10},+ 'quotas': [+ for (final engine in ['claude', 'codex'])+ {+ 'engine': engine,+ 'known': true,+ 'windows': [+ {'name': 'weekly', 'usedPercent': 40},+ ],+ },+ ],+ },+ },+ ];+ await c.refresh();+ await tester.pumpAndSettle();+ expect(+ decoration('claude', 'Claude Code'),+ isNot(TextDecoration.lineThrough),+ );+ expect(decoration('codex', 'Codex'), isNot(TextDecoration.lineThrough));+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ },+ );}/// A hardware reading's value in a machine's expanded readings.diff --git a/desktop/test/super_tab_message_media_test.dart b/desktop/test/super_tab_message_media_test.dartnew file mode 100644index 000000000..f13e78403--- /dev/null+++ b/desktop/test/super_tab_message_media_test.dart@@ -0,0 +1,309 @@+// What a chat message shows besides its words, as Slack does: pictures in+// the row, up to 360 px with their shape kept, that open full screen; code+// in a block with Copy; every other file one compact chip (Dee, 10-29).+import 'dart:ui' as ui;++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/attachment_viewer.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';++/// A [width]×[height] PNG, drawn for real so a picture has a shape to keep.+Future<Uint8List> _png(WidgetTester tester, int width, int height) async =>+ (await tester.runAsync(() async {+ final recorder = ui.PictureRecorder();+ Canvas(recorder).drawRect(+ Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()),+ Paint()..color = const Color(0xFF3060A0),+ );+ final image = await recorder.endRecording().toImage(width, height);+ final data = await image.toByteData(format: ui.ImageByteFormat.png);+ return data!.buffer.asUint8List();+ }))!;++Map<String, dynamic> _file(+ String id,+ String name,+ String mime, {+ String? url,+}) => {+ 'id': id,+ 'name': name,+ 'mime': mime,+ 'size': 120 * 1024,+ 'url': url ?? 'https://cdn.harness.autonomous.ai/$id/$name',+};++void main() {+ late List<Uri> loaded;+ late Map<String, Uint8List> pictures;+ late ImageProvider Function(Uri) original;++ setUp(() {+ loaded = [];+ pictures = {};+ original = attachmentImage;+ attachmentImage = (url) {+ loaded.add(url);+ return MemoryImage(pictures[url.pathSegments.last]!);+ };+ });+ tearDown(() => attachmentImage = original);++ /// A conversation whose one message says [text] and carries [files].+ Future<SuperTabController> show(+ WidgetTester tester, {+ String text = 'Here',+ List<Map<String, dynamic>> files = const [],+ }) async {+ final server = ConversationServer()..append(text, attachments: files);+ final controller = server.controller();+ await controller.refresh();+ await tester.binding.setSurfaceSize(const Size(1100, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabView(+ controller: controller,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Test Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ // Decoding happens off the fake clock.+ await tester.runAsync(() => Future<void>.delayed(Durations.short2));+ await tester.pumpAndSettle();+ return controller;+ }++ Future<void> close(WidgetTester tester, SuperTabController c) async {+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ }++ group('pictures', () {+ for (final (width, height, shown) in [+ (720, 360, const Size(360, 180)),+ (200, 800, const Size(90, 360)),+ (120, 80, const Size(120, 80)),+ ]) {+ testWidgets('a ${width}x$height picture shows in the message at $shown', (+ tester,+ ) async {+ pictures['shot.png'] = await _png(tester, width, height);+ final c = await show(+ tester,+ files: [_file('a1', 'shot.png', 'image/png')],+ );++ final picture = find.byKey(+ const ValueKey('super-attachment-inline:a1'),+ );+ expect(picture, findsOneWidget);+ expect(tester.getSize(picture), shown);+ // Only the message's own link, however often the row rebuilds.+ expect(loaded.toSet(), {+ Uri.parse('https://cdn.harness.autonomous.ai/a1/shot.png'),+ });+ // The picture is the file: no chip besides it.+ expect(find.byKey(const ValueKey('super-attachment:a1')), findsNothing);+ await close(tester, c);+ });+ }++ testWidgets('a click opens the picture full screen, with Download', (+ tester,+ ) async {+ pictures['shot.png'] = await _png(tester, 720, 360);+ final c = await show(+ tester,+ files: [_file('a1', 'shot.png', 'image/png')],+ );++ await tester.tap(+ find.byKey(const ValueKey('super-attachment-inline:a1')),+ );+ await tester.pumpAndSettle();+ final viewer = find.byKey(const ValueKey('super-attachment-viewer:a1'));+ expect(viewer, findsOneWidget);+ expect(tester.getSize(viewer), const Size(1100, 800));+ expect(+ find.byKey(const ValueKey('super-attachment-image:a1')),+ findsOneWidget,+ );+ expect(find.text('Download'), findsOneWidget);+ expect(find.text('Open in browser'), findsOneWidget);+ await tester.tap(find.text('Close'));+ await tester.pumpAndSettle();+ expect(viewer, findsNothing);+ await close(tester, c);+ });++ testWidgets('a picture off the attachments host stays a chip, unloaded', (+ tester,+ ) async {+ final c = await show(+ tester,+ files: [+ _file(+ 'a1',+ 'shot.png',+ 'image/png',+ url: 'https://evil.example/a1/shot.png',+ ),+ _file(+ 'a2',+ 'plain.png',+ 'image/png',+ url: 'http://cdn.harness.autonomous.ai/a2/plain.png',+ ),+ // A look-alike host: the name must match exactly.+ _file(+ 'a3',+ 'near.png',+ 'image/png',+ url: 'https://cdn.harness.autonomous.ai.evil.example/a3/near.png',+ ),+ ],+ );++ expect(find.byKey(const ValueKey('super-attachment:a1')), findsOneWidget);+ expect(find.byKey(const ValueKey('super-attachment:a2')), findsOneWidget);+ expect(find.byKey(const ValueKey('super-attachment:a3')), findsOneWidget);+ expect(find.byType(Image), findsNothing);+ expect(loaded, isEmpty);+ await close(tester, c);+ });++ testWidgets('a picture that fails to load says so in its place', (+ tester,+ ) async {+ pictures['shot.png'] = Uint8List.fromList([1, 2, 3]);+ final c = await show(+ tester,+ files: [_file('a1', 'shot.png', 'image/png')],+ );++ expect(find.text('shot.png can’t be shown here.'), findsOneWidget);+ await close(tester, c);+ });+ });++ testWidgets('other files are one compact chip each: name · size', (+ tester,+ ) async {+ pictures['shot.png'] = await _png(tester, 720, 360);+ final c = await show(+ tester,+ files: [+ _file('a1', 'shot.png', 'image/png'),+ _file('a2', 'report.pdf', 'application/pdf'),+ ],+ );++ final chip = find.byKey(const ValueKey('super-attachment:a2'));+ expect(chip, findsOneWidget);+ for (final part in ['report.pdf', '·', '120 KB']) {+ expect(+ find.descendant(of: chip, matching: find.text(part)),+ findsOneWidget,+ );+ }+ await close(tester, c);+ });++ group('code', () {+ late List<String> copied;+ setUp(() {+ copied = [];+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, (call) async {+ if (call.method == 'Clipboard.setData') {+ copied.add((call.arguments as Map)['text'] as String);+ }+ return null;+ });+ });+ tearDown(+ () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, null),+ );++ testWidgets('a code block is monospace, named, and Copy copies it', (+ tester,+ ) async {+ final c = await show(+ tester,+ text: 'Try this:\n\n```main.dart\nfinal x = 1;\nprint(x);\n```',+ );++ final code = find.text('final x = 1;\nprint(x);');+ expect(code, findsOneWidget);+ expect(+ tester.widget<Text>(code).style?.fontFamily,+ grid.AppType.mono().fontFamily,+ );+ expect(find.text('main.dart'), findsOneWidget);+ await tester.tap(find.text('Copy'));+ await tester.pump();+ expect(copied, ['final x = 1;\nprint(x);']);+ expect(find.text('Code copied'), findsOneWidget);+ await tester.pumpAndSettle(const Duration(seconds: 3));+ await close(tester, c);+ });++ testWidgets('a block with no language still has Copy', (tester) async {+ final c = await show(tester, text: '```\nls -la\n```');++ expect(find.text('ls -la'), findsOneWidget);+ await tester.tap(find.text('Copy'));+ await tester.pump();+ expect(copied, ['ls -la']);+ await tester.pumpAndSettle(const Duration(seconds: 3));+ await close(tester, c);+ });++ testWidgets('a long block folds with Show more, and Copy takes it all', (+ tester,+ ) async {+ final lines = [for (var i = 1; i <= 30; i++) 'line $i'];+ final c = await show(tester, text: '```\n${lines.join('\n')}\n```');++ expect(find.text(lines.take(12).join('\n')), findsOneWidget);+ expect(find.textContaining('line 13'), findsNothing);+ await tester.tap(find.text('Show more'));+ await tester.pump();+ expect(find.text(lines.join('\n')), findsOneWidget);+ await tester.tap(find.text('Show less'));+ await tester.pump();+ expect(find.textContaining('line 13'), findsNothing);++ await tester.tap(find.text('Copy'));+ await tester.pump();+ expect(copied, [lines.join('\n')]);+ await tester.pumpAndSettle(const Duration(seconds: 3));+ await close(tester, c);+ });++ testWidgets('a short block has no Show more', (tester) async {+ final lines = [for (var i = 1; i <= 12; i++) 'line $i'];+ final c = await show(tester, text: '```\n${lines.join('\n')}\n```');++ expect(find.text(lines.join('\n')), findsOneWidget);+ expect(find.text('Show more'), findsNothing);+ await close(tester, c);+ });+ });+}diff --git a/desktop/test/super_tab_message_rows_shots_test.dart b/desktop/test/super_tab_message_rows_shots_test.dartnew file mode 100644index 000000000..75a078486--- /dev/null+++ b/desktop/test/super_tab_message_rows_shots_test.dart@@ -0,0 +1,199 @@+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/attachment_viewer.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_ROW_SHOTS'];++/// A 1440×900 stand-in for a pasted screenshot: a window with a sidebar.+Future<ui.Image> _screenshot() async {+ final recorder = ui.PictureRecorder();+ final canvas = Canvas(recorder);+ canvas+ ..drawRect(+ const Rect.fromLTWH(0, 0, 1440, 900),+ Paint()..color = const Color(0xFFF2F4F8),+ )+ ..drawRect(+ const Rect.fromLTWH(0, 0, 320, 900),+ Paint()..color = const Color(0xFF2B3442),+ );+ for (var i = 0; i < 6; i++) {+ canvas.drawRRect(+ RRect.fromLTRBR(+ 400,+ 80.0 + i * 120,+ 1360,+ 160.0 + i * 120,+ const Radius.circular(16),+ ),+ Paint()..color = const Color(0xFFDCE3EE),+ );+ }+ return recorder.endRecording().toImage(1440, 900);+}++/// Message rows as the PR shows them (Dee, 10-29): a picture in place, a+/// code block with Copy, a file chip, the thread line, and a message that+/// was not sent, in both appearances.+void main() {+ setUpAll(() async {+ if (shots != null) await loadPreviewFonts();+ });++ for (final brightness in Brightness.values) {+ testWidgets('screenshots for review (${brightness.name})', (tester) async {+ final png = (await tester.runAsync(() async {+ final image = await _screenshot();+ final data = await image.toByteData(format: ui.ImageByteFormat.png);+ return data!.buffer.asUint8List();+ }))!;+ final original = attachmentImage;+ attachmentImage = (_) => MemoryImage(png);+ addTearDown(() => attachmentImage = original);++ final picture = GlobalKey();+ final server = ConversationServer()..threads = true;+ (server.state['people'] as List).add({+ 'id': 'dee',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ const pm = {+ 'kind': 'agent',+ 'id': 'pm',+ 'name': 'Lead',+ 'displayName': 'River',+ };+ const dee = {'kind': 'person', 'id': 'dee', 'name': '[email protected]'};+ final now = DateTime.now().toUtc();+ void say(+ String text,+ Map<String, Object> author, {+ String? thread,+ List<Map<String, Object>> files = const [],+ int secondsAgo = 0,+ }) {+ server.append(text, attachments: files);+ server.messages.last+ ..['author'] = author+ ..['createdAt'] = now+ .subtract(Duration(seconds: secondsAgo))+ .toIso8601String();+ if (thread != null) {+ server.messages.last+ ..['thread'] = thread+ ..['replyTo'] = thread;+ }+ }++ say(+ 'this is so confusing. how do i create a new project now?',+ dee,+ secondsAgo: 300,+ files: [+ {+ 'id': 'a1',+ 'name': 'projects.png',+ 'mime': 'image/png',+ 'size': 182 * 1024,+ 'url': 'https://cdn.harness.autonomous.ai/a1/projects.png',+ },+ ],+ );+ say(+ 'New Project is in the sidebar now. The setting it reads:\n\n'+ '```main.dart\nfinal project = Project.create(name: name);\n'+ 'await sidebar.select(project);\n```',+ pm,+ secondsAgo: 240,+ files: [+ {+ 'id': 'a2',+ 'name': 'report.pdf',+ 'mime': 'application/pdf',+ 'size': 120 * 1024,+ 'url': 'https://cdn.harness.autonomous.ai/a2/report.pdf',+ },+ ],+ );+ say('Found it, thanks!', dee, thread: 'message-2', secondsAgo: 12);+ ((server.state['conversations'] as List)[0] as Map)['leadId'] = 'pm';+ final c = server.controller(account: 'dee');+ addTearDown(c.dispose);+ await c.refresh();+ server.loseReply = true;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ await tester.binding.setSurfaceSize(const Size(1280, 860));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) =>+ RepaintBoundary(key: picture, child: child),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ final composer = find.byKey(const ValueKey('super-message-composer'));+ await tester.tap(composer);+ await tester.enterText(composer, 'Can it be the default?');+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ await tester.runAsync(() => Future<void>.delayed(Durations.short2));+ await tester.pumpAndSettle();+ expect(find.text('Not sent'), findsOneWidget);+ expect(find.textContaining('Delivered'), findsNothing);++ Future<void> shot(String name) => tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/rows-$name-${brightness.name}.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });++ await shot('chat');+ await tester.tap(+ find.byKey(const ValueKey('super-attachment-inline:a1')),+ );+ await tester.pumpAndSettle();+ await tester.runAsync(() => Future<void>.delayed(Durations.short2));+ await tester.pumpAndSettle();+ await shot('picture');+ await tester.tap(find.text('Close'));+ await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const ValueKey('super-thread-line-message-2')),+ );+ await tester.pumpAndSettle();+ await shot('thread');+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, skip: shots == null);+ }+}diff --git a/desktop/test/super_tab_phone_targets_test.dart b/desktop/test/super_tab_phone_targets_test.dartindex 6cba3941b..fba3b489d 100644--- a/desktop/test/super_tab_phone_targets_test.dart+++ b/desktop/test/super_tab_phone_targets_test.dart@@ -30,10 +30,11 @@ void _agentMessages(ConversationServer server) {attachments: [{'id': 'a1',- 'name': 'fixture-375.png',- 'mime': 'image/png',+ // A file that stays a chip: a picture shows in place.+ 'name': 'fixture-375.pdf',+ 'mime': 'application/pdf','size': 2048,- 'url': 'https://cdn.harness.autonomous.ai/a1/fixture-375.png',+ 'url': 'https://cdn.harness.autonomous.ai/a1/fixture-375.pdf',},],);diff --git a/desktop/test/super_tab_receipt_test.dart b/desktop/test/super_tab_receipt_test.dartindex 27b0fa441..2bf8c6a42 100644--- a/desktop/test/super_tab_receipt_test.dart+++ b/desktop/test/super_tab_receipt_test.dart@@ -84,6 +84,19 @@ class ReceiptFixture {await tester.pump(const Duration(milliseconds: 100));}+ /// Nothing under the newest own message: no Sent, Delivered, Replied or+ /// working line, and the line takes no room (Slack's rows, Dee 10-29).+ void expectQuiet() {+ for (final text in ['Sent', 'Sending…', 'Not sent']) {+ expect(find.text(text), findsNothing);+ }+ for (final text in ['Delivered', 'Replied', 'is working', 'offline']) {+ expect(find.textContaining(text), findsNothing);+ }+ final line = find.byKey(ValueKey('super-message-receipt-${message['id']}'));+ expect(tester.getSize(line).height, 0);+ }+Future<void> close() async {expect(find.text('Queued'), findsNothing);expect(find.textContaining('Check delivery'), findsNothing);@@ -110,7 +123,7 @@ void main() {);for (final status in ['queued', 'claimed']) {testWidgets(- 'receipt: fresh $status reads Sending then an older message reads Sent',+ 'receipt: fresh $status reads Sending then an older message shows nothing',(tester) async {final f = ReceiptFixture(tester, status: status);await f.show(@@ -123,35 +136,27 @@ void main() {.toIso8601String();await f.controller.refresh();await tester.pump();- expect(find.text('Sent'), findsOneWidget);- expect(find.text('Sending…'), findsNothing);+ f.expectQuiet();await f.close();},);}- for (final status in ['delivered', 'confirmed']) {- testWidgets(- 'receipt: $status uses the recorded delivery time without inventing remote activity',- (tester) async {- final f = ReceiptFixture(tester, status: status);- await f.show();- final at = DateTime.parse(f.delivery['deliveredAt'] as String)- .toLocal();- expect(- find.text(- 'Delivered ${at.hour.toString().padLeft(2, '0')}:${at.minute.toString().padLeft(2, '0')}',- ),- findsOneWidget,- );- expect(find.textContaining('is working'), findsNothing);- await f.close();- },- );+ for (final status in ['delivered', 'confirmed', 'answered']) {+ testWidgets('receipt: $status shows nothing under the message', (+ tester,+ ) async {+ final f = ReceiptFixture(tester, status: status);+ await f.show(+ prepare: () => f.delivery['answeredAt'] = f.now.toIso8601String(),+ );+ f.expectQuiet();+ await f.close();+ });}testWidgets(- 'receipt: known working activity appears and clears without a new message',+ 'receipt: a delivered message stays quiet while its Lead works and after',(tester) async {final app = createApp(connected: true);addTearDown(app.dispose);@@ -162,15 +167,13 @@ void main() {'agentId': 'a0',});await tester.pump();- expect(find.text('Lead is working'), findsOneWidget);- expect(find.textContaining(RegExp(r'^0:4[2-5]$')), findsOneWidget);+ f.expectQuiet();await app.handleEventForTest('m', {'type': 'turn_ended','agentId': 'a0',});await tester.pump(const Duration(milliseconds: 100));- expect(find.text('Lead is working'), findsNothing);- expect(find.textContaining('Delivered '), findsOneWidget);+ f.expectQuiet();await f.close();},);@@ -182,9 +185,7 @@ void main() {('team_waiting_control', "Lead can't take messages right now"),('team_waiting_unavailable', "Lead can't take messages right now"),]) {- testWidgets('receipt: $reason held message reads only Sent', (- tester,- ) async {+ testWidgets('receipt: $reason held message shows nothing', (tester) async {final f = ReceiptFixture(tester);await f.show(prepare: () {@@ -194,7 +195,7 @@ void main() {.toIso8601String();},);- expect(find.text('Sent'), findsOneWidget);+ f.expectQuiet();expect(find.textContaining(label), findsNothing);expect(find.textContaining('waiting'), findsNothing);expect(find.textContaining('by itself'), findsNothing);@@ -225,12 +226,9 @@ void main() {},);- for (final (direct, shown) in [- (true, 'Sent'),- (false, "Lead's computer is offline"),- ]) {+ for (final direct in [true, false]) {testWidgets(- 'receipt: a held message to a computer with no Swarm reading ${direct ? 'connected directly reads Sent' : 'read through the Swarm says offline'}',+ 'receipt: a held message to a computer with no Swarm reading ${direct ? 'connected directly shows nothing' : 'read through the Swarm says offline'}',(tester) async {final app = createApp(connected: true);addTearDown(app.dispose);@@ -244,12 +242,12 @@ void main() {f.delivery['holdReason'] = 'team_waiting_idle';},);- expect(find.textContaining(shown), findsOneWidget);expect(find.textContaining('busy'), findsNothing);- expect(- find.textContaining('offline'),- direct ? findsNothing : findsWidgets,- );+ if (direct) {+ f.expectQuiet();+ } else {+ expect(find.text("Lead's computer is offline"), findsOneWidget);+ }await f.close();},);@@ -306,22 +304,6 @@ void main() {await f.close();});- testWidgets('receipt: answered shows its fixed delivery-to-answer duration', (- tester,- ) async {- final f = ReceiptFixture(tester, status: 'answered');- await f.show(- prepare: () {- f.delivery['answeredAt'] = f.now.toIso8601String();- f.delivery['deliveredAt'] = f.now- .subtract(const Duration(seconds: 72))- .toIso8601String();- },- );- expect(find.text('Replied · 1m 12s'), findsOneWidget);- await f.close();- });-testWidgets('receipt: only latest own message carries a receipt, even after another person speaks',(tester) async {@@ -343,16 +325,14 @@ void main() {];},);- expect(find.text('Sent'), findsOneWidget);expect(find.text("Couldn't confirm delivery"), findsNothing);f.server.append('My next question.');f.message['deliveries'] = [- {'id': 'new-delivery', 'agentId': 'lead-agent', 'status': 'delivered'},+ {'id': 'new-delivery', 'agentId': 'lead-agent', 'status': 'uncertain'},];await f.controller.refresh();await tester.pump(const Duration(milliseconds: 100));- expect(find.text('Sent'), findsNothing);- expect(find.text('Delivered'), findsOneWidget);+ expect(find.text("Couldn't confirm delivery"), findsOneWidget);await f.close();},);diff --git a/desktop/test/web/attachment_viewer_web_test.dart b/desktop/test/web/attachment_viewer_web_test.dartindex c4db969ea..5402e6501 100644--- a/desktop/test/web/attachment_viewer_web_test.dart+++ b/desktop/test/web/attachment_viewer_web_test.dart@@ -3,8 +3,8 @@ library;// In a browser a chat file is the browser's: a text file opens in a new tab// rather than being fetched into a popup (a page cannot refuse a redirect or-// stop a download part way), and a viewer offers no Download, since a page-// cannot write a chosen path.+// stop a download part way), a picture stays a chip for the same reason, and+// a viewer offers no Download, since a page cannot write a chosen path.import 'dart:typed_data';import 'package:flutter/material.dart';@@ -41,7 +41,7 @@ void main() {'url': 'https://cdn.harness.autonomous.ai/a1/spec.md',});await tester.pumpWidget(- MaterialApp(home: Scaffold(body: SuperTabAttachmentChips([file]))),+ MaterialApp(home: Scaffold(body: SuperTabAttachments([file]))),);await tester.tap(find.byKey(const ValueKey('super-attachment:a1')));@@ -70,4 +70,22 @@ void main() {expect(find.text('Open in browser'), findsOneWidget);expect(find.text('Download'), findsNothing);});++ testWidgets('a picture stays a chip: a browser cannot refuse a redirect', (+ tester,+ ) async {+ final file = SuperTabAttachment.fromJson({+ 'id': 'a1',+ 'name': 'shot.png',+ 'mime': 'image/png',+ 'size': 5,+ 'url': 'https://cdn.harness.autonomous.ai/a1/shot.png',+ });+ await tester.pumpWidget(+ MaterialApp(home: Scaffold(body: SuperTabAttachments([file]))),+ );++ expect(find.byKey(const ValueKey('super-attachment:a1')), findsOneWidget);+ expect(find.byType(Image), findsNothing);+ });}diff --git a/scripts/ui-style-allowlist/desktop.json b/scripts/ui-style-allowlist/desktop.jsonindex 1a0e4c94d..1f561008e 100644--- a/scripts/ui-style-allowlist/desktop.json+++ b/scripts/ui-style-allowlist/desktop.json@@ -6,7 +6,7 @@"edge-insets": 2},"desktop/lib/super_tabs/attachment_chips.dart": {- "edge-insets": 2,+ "edge-insets": 1,"border-radius": 2},"desktop/lib/super_tabs/attachment_text_viewer.dart": {@@ -32,15 +32,12 @@},"desktop/lib/super_tabs/message_receipt.dart": {"font-size": 2,- "edge-insets": 5,+ "edge-insets": 4,"border-radius": 1},"desktop/lib/super_tabs/message_row.dart": {"edge-insets": 5},- "desktop/lib/super_tabs/message_text.dart": {- "edge-insets": 1- },"desktop/lib/super_tabs/notifications.dart": {"edge-insets": 8},