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 11-05 i2010: #3168 #3160 #3171 (#3184)
0xken15dc9bf48d749c
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 8ad63761f..f1e7365b2 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -1154,7 +1154,7 @@ describe('Super Tabs on a real Mongo replica set', () => {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)+ await run(tab, { type: 'machine.contribute', machineId: 'health-host', name: 'Health laptop', cwd: '/project', engines: ['codex', 'claude'], maxAgents: 2 }, host)const generation = (await poolRows(store, team.session, 'health-host'))[0]!.machine.generationconst 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: [],@@ -1167,18 +1167,24 @@ describe('Super Tabs on a real Mongo replica set', () => {const request = { permissionMode: 'full', conversationId: task, 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')+ // Preparation failures remain failed starts, but do not disable either engine.+ for (let i = 0; i < 2; i++) {+ const startId = (await run(tab, { type: 'agent.start', request })).result.startId as string+ await hostRun({ type: 'agent.startFailed', startId, error: 'The Harness server answered without a GitHub token for this project.' })+ }+ expect((await pool()).suspendedEngines).toBeUndefined()for (let i = 0; i < 2; i++) {const startId = (await run(tab, { type: 'agent.start', request })).result.startId as stringawait hostRun({ type: 'agent.startDispatch', startId })- await hostRun({ type: 'agent.startFailed', startId, error: 'Codex could not launch.' })+ await hostRun({ type: 'agent.startFailed', startId, error: 'Codex sign-in failed.' })}expect((await pool()).suspendedEngines).toEqual({ codex: expect.stringContaining('Codex is suspended on this machine for new work') })const notices = (await store.messages(owner, tab, task, {})).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.+ // Signed in, even with unknown quota: a sign-in suspension ends.await store.observeMachine(team.session, tab, 'health-host', { ...observation, quotaReasons: undefined,- quotas: [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 10, resetsAt: null }] }],+ quotas: [{ engine: 'codex', known: false, windows: [] }],readiness: { engines: [{ engine: 'codex', installed: true, signedIn: true }] } })expect((await pool()).suspendedEngines).toBeUndefined()// Suspended again, and resumed by its owner.@@ -1191,6 +1197,23 @@ describe('Super Tabs on a real Mongo replica set', () => {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()+ // Timeouts of different engines share one machine cooldown, persisted across reports and reads.+ for (const engine of ['codex', 'claude']) {+ const startId = (await run(tab, { type: 'agent.start', request: { ...request, engine } })).result.startId as string+ await hostRun({ type: 'agent.startDispatch', startId })+ await hostRun({ type: 'agent.startFailed', startId, error: 'Health laptop did not start it within 3 minutes' })+ }+ await store.observeMachine(team.session, tab, 'health-host', observation)+ expect(await pool()).toMatchObject({ machineSuspended: expect.stringContaining('This machine is suspended'),+ suspendedEngines: { codex: expect.stringContaining('This machine is suspended'), claude: expect.stringContaining('This machine is suspended') } })+ for (const engine of ['codex', 'claude']) {+ await expect(run(tab, { type: 'agent.start', request: { ...request, engine } })).rejects.toMatchObject({ code: 'MACHINE_UNAVAILABLE' })+ }+ 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()).machineSuspended).toBeUndefined()+ expect((await pool()).suspendedEngines).toBeUndefined()+ expect((await run(tab, { type: 'agent.start', request })).result.startId).toBeTruthy()})it('resolves a reply beyond recent history without crossing conversation or membership boundaries', async () => {diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex f31b23694..af4123ede 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -1763,6 +1763,8 @@ describe('saving a machine again', () => {lent: [{ week, busyMs: 18_000_000 }],lentDays: [{ day: week, projectId: 'lead', busyMs: 18_000_000 }],engineFailures: { codex: 1 },+ engineBackoff: { codex: { level: 3, cause: 'engine' } },+ machineFailures: 1, machineBackoff: 2, machineSuspension: { at: NOW, durationMs: 3_600_000 },engineSuspensions: { claude: { at: NOW, fine: false } },observation: { receivedAt: NOW, runningHarnessIds: ['h1'], stoppedHarnessIds: [] } as never,}@@ -5230,8 +5232,9 @@ describe('an engine that cannot run on a contributed machine', () => {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'])+ // A different engine failure is only its first; the timeout counted against the machine.+ expect(fail('s2').mentions).toBeUndefined()+ expect(fail('s3').mentions).toEqual(['owner'])})// Quota is information, not a gate (project instructions, phase 4).@@ -5249,6 +5252,33 @@ describe('an engine that cannot run on a contributed machine', () => {expect(setup().begin().result.startId).toBeTruthy()})+ it('refuses every engine and grid starts while the machine is suspended', () => {+ const { f, begin } = setup({ localModels: [{ grid, model: 'qwen3', kind: 'local' }] })+ f.state.localModels = { grid, enabled: true }+ f.state.machines![0]!.engines = ['codex', 'claude']+ for (const startId of ['s1', 's2']) f.run({ type: 'agent.startFailed', startId,+ error: 'Mac did not start it within 3 minutes' }, owner)+ for (const extra of [{}, { engine: 'claude' }, { gridModel: 'qwen3', gridName: grid }]) {+ expect(() => begin(extra)).toThrow('This machine is suspended')+ }+ })++ it.each(['owner', 'lead'])('admits starts after the %s resumes a machine cooldown with the owner\'s authority', (who) => {+ const { f, lead, begin } = setup()+ for (const startId of ['s1', 's2']) f.run({ type: 'agent.startFailed', startId,+ error: 'Mac did not start it within 3 minutes' }, owner)+ const resume = { type: 'machine.engineResume', machineId: 'mac', engine: 'codex' } as Command+ const leadActor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }+ f.invite()+ expect(() => f.run(resume, peer)).toThrow('Only the machine\'s owner')+ expect(() => f.run(resume, leadActor)).toThrow('Only the machine\'s owner')+ expect(() => begin()).toThrow('This machine is suspended')+ if (who === 'owner') f.run(resume, owner)+ else f.run({ ...resume, askedIn: { conversationId: 'lead', messageId: 'm-owner' } } as Command, leadActor,+ { askedIn: { author: { kind: 'person', id: 'owner' } as never, source: false, createdAt: 1000 } })+ expect(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')diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex c413c2376..940c064db 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -2006,6 +2006,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// failures and suspensions and the last reading (#3043). A machine not listed yet, or Buddy-only, starts clean....(previous?.lent ? { lent: previous.lent } : {}), ...(previous?.lentDays ? { lentDays: previous.lentDays } : {}),...(previous?.engineFailures ? { engineFailures: previous.engineFailures } : {}),+ ...(previous?.engineBackoff ? { engineBackoff: previous.engineBackoff } : {}),+ ...(previous?.machineFailures ? { machineFailures: previous.machineFailures } : {}),+ ...(previous?.machineBackoff ? { machineBackoff: previous.machineBackoff } : {}),+ ...(previous?.machineSuspension ? { machineSuspension: previous.machineSuspension } : {}),...(previous?.engineSuspensions ? { engineSuspensions: previous.engineSuspensions } : {}),...(previous?.observation ? { observation: previous.observation } : {}) })// A Mac given other slots or a new name gives its team account the same, and its pause; its own folder, engines and grant stay.diff --git a/backend/src/superTabs/engineHealth.test.ts b/backend/src/superTabs/engineHealth.test.tsindex 1b4344af9..187ec1ec5 100644--- a/backend/src/superTabs/engineHealth.test.ts+++ b/backend/src/superTabs/engineHealth.test.ts@@ -2,7 +2,7 @@ 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'+import { engineUnusable, noteStartFailed, noteStartSucceeded, readingClearsSuspensions, resumeEngine, suspendedEngines } from './engineHealth.js'const NOW = 10_000_000const fine = { quotas: [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 40, resetsAt: null }] }],@@ -20,6 +20,47 @@ const start = (extra: Partial<AgentStart['request']> = {}, error = 'Codex couldrequest: { conversationId: 'g1', machineId: 'm1', engine: 'codex', name: 'Builder', cwd: '/x', ...extra } }) as unknown as AgentStartdescribe('an engine whose starts fail on a machine', () => {+ it.each([+ 'The Harness server answered without a GitHub token for this project.',+ 'This start has no authorized project.',+ 'This project repository is unavailable.',+ 'The project folder does not exist.',+ 'Cannot create a worktree: the repository has no commits.',+ 'Required tool gh is not installed.',+ 'spawn gh ENOENT',+ "This machine's ChatGPT account (plus) does not offer gpt-6-astra; choose another model.",+ "This machine held the agent's launch for 3 minutes and stopped it: Waiting to confirm the selected executable’s permission flags.",+ 'This agent does not support that permission mode.',+ 'Its machine is signed in to another account now.',+ 'Request refused by this account.',+ 'Authentication failed while fetching the project.',+ 'Unknown native preparation failure.',+ ])('does not penalize an engine for setup or an unclassified failure: %s', error => {+ const pool = machine(), state = stateWith(pool)+ noteStartFailed(state, start({}, error), NOW)+ expect(noteStartFailed(state, start({}, error), NOW)).toBeNull()+ expect(engineUnusable(pool, 'codex', NOW)).toBeNull()+ // Ignoring setup failures must not erase a real engine failure already counted.+ noteStartFailed(state, start(), NOW)+ noteStartFailed(state, start({}, error), NOW)+ expect(noteStartFailed(state, start(), NOW)).not.toBeNull()+ })++ it.each([+ 'Codex could not launch.',+ 'codex exited before its engine process became ready. See the terminal output for details.',+ 'Its engine stopped on a question that nobody here can answer.',+ 'Its engine stopped on a sign-in screen that nobody here can answer.',+ 'Codex sign-in failed.',+ 'Codex is installed but cannot run: it exited with status 1',+ 'The agent was created and has since stopped. Create a new start request to continue.',+ ])('counts the engine’s own failure: %s', error => {+ const pool = machine(), state = stateWith(pool)+ expect(noteStartFailed(state, start({}, error), NOW)).toBeNull()+ expect(noteStartFailed(state, start({}, error), NOW)).toContain('Codex is suspended')+ expect(engineUnusable(pool, 'claude', NOW)).toBeNull()+ })+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()@@ -77,32 +118,87 @@ describe('an engine whose starts fail on a machine', () => {expect(suspendedEngines(pool, NOW)).toEqual({})})- it('ends after 6 hours', () => {+ it('backs off 30m, 1h, 2h, 4h, 8h and at most 12h, retaining the level after expiry', () => {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()+ let now = NOW+ for (const minutes of [30, 60, 120, 240, 480, 720, 720]) {+ expect(noteStartFailed(state, start(), now)).toBeNull()+ expect(noteStartFailed(state, start(), now)).toContain('suspended')+ expect(engineUnusable(pool, 'codex', now + minutes * 60_000 - 1)).not.toBeNull()+ expect(engineUnusable(pool, 'codex', now + minutes * 60_000)).toBeNull()+ now += minutes * 60_000+ readingClearsSuspensions(pool, now)+ }+ noteStartSucceeded(state, start({}, ''))+ noteStartFailed(state, start(), now)+ noteStartFailed(state, start(), now)+ expect(engineUnusable(pool, 'codex', now + 30 * 60_000)).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)+ it('a successful start clears an active cooldown and resets its engine alone', () => {+ const pool = machine(), state = stateWith(pool)+ for (const engine of ['codex', 'claude']) {+ noteStartFailed(state, start({ engine }), NOW)+ noteStartFailed(state, start({ engine }), NOW)+ }+ noteStartSucceeded(state, start({}, ''))+ expect(engineUnusable(pool, 'codex', NOW)).toBeNull()+ expect(engineUnusable(pool, 'claude', NOW)).not.toBeNull()+ noteStartFailed(state, start(), NOW)+ noteStartFailed(state, start(), NOW)+ expect(engineUnusable(pool, 'codex', NOW + 30 * 60_000)).toBeNull()+ })++ it('clears a sign-in suspension on a signed-in reading with unknown quota, but not unknown sign-in', () => {+ const pool = machine(), state = stateWith(pool)+ const failed = () => start({}, 'Its engine stopped on a sign-in screen that nobody here can answer.')+ noteStartFailed(state, failed(), NOW); noteStartFailed(state, failed(), NOW)+ Object.assign(pool.observation!, { quotas: [{ engine: 'codex', known: false, windows: [] }],+ readiness: { engines: [{ engine: 'codex', installed: true, signedIn: null }] } })readingClearsSuspensions(pool, NOW + 1)expect(suspendedEngines(pool, NOW + 1)).toHaveProperty('codex')- Object.assign(pool.observation!, fine)+ pool.observation!.readiness!.engines![0]!.signedIn = truereadingClearsSuspensions(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')+ it.each([+ ['Codex could not launch.', 'Codex could not launch.'],+ ['Codex could not launch.', 'Codex sign-in failed.'],+ ['Codex sign-in failed.', 'Codex could not launch.'],+ ])('does not clear a launch failure merely because a reading says signed in: %s then %s', (first, second) => {+ const pool = machine(), state = stateWith(pool)+ noteStartFailed(state, start({}, first), NOW); noteStartFailed(state, start({}, second), NOW)+ Object.assign(pool.observation!, fine)readingClearsSuspensions(pool, NOW + 1)expect(suspendedEngines(pool, NOW + 1)).toHaveProperty('codex')+ expect(suspendedEngines(pool, NOW + 1).codex).toContain('30 minutes')+ })++ it('keeps legacy six-hour expiry and reading recovery when no cause or duration was stored', () => {+ const pool = machine()+ pool.engineSuspensions = { codex: { at: NOW, fine: false }, claude: { at: NOW, fine: true } }+ expect(engineUnusable(pool, 'claude', NOW + 6 * 3_600_000 - 1)).not.toBeNull()+ expect(engineUnusable(pool, 'claude', NOW + 6 * 3_600_000)).toBeNull()+ Object.assign(pool.observation!, fine)+ readingClearsSuspensions(pool, NOW + 1)+ expect(suspendedEngines(pool, NOW + 1)).not.toHaveProperty('codex')+ expect(suspendedEngines(pool, NOW + 1)).toHaveProperty('claude')+ })++ it('does not combine an unclassified legacy failure counter with a new engine failure', () => {+ const pool = machine(), state = stateWith(pool)+ pool.engineFailures = { codex: 1 }+ expect(noteStartFailed(state, start(), NOW)).toBeNull()+ expect(engineUnusable(pool, 'codex', NOW)).toBeNull()+ expect(noteStartFailed(state, start(), NOW)).toContain('Codex is suspended')+ })++ it('does not let a successful grid start reset the subscription engine cooldown', () => {+ const pool = machine(), state = stateWith(pool)+ noteStartFailed(state, start(), NOW); noteStartFailed(state, start(), NOW)+ noteStartSucceeded(state, start({ gridModel: 'qwen3' }, ''))+ expect(engineUnusable(pool, 'codex', NOW)).not.toBeNull()})it('ends when its owner resumes it', () => {@@ -138,3 +234,60 @@ describe('an engine a machine cannot run', () => {expect(engineUnusable(none, 'codex', NOW)).toBeNull()})})+++describe('a machine that does not pick up starts', () => {+ const timeout = (engine: string) => start({ engine }, 'Worker Mac did not start it within 3 minutes')+ it('combines timeouts across engines, blocks all engines and never penalizes either engine', () => {+ const pool = machine(), state = stateWith(pool)+ expect(noteStartFailed(state, timeout('codex'), NOW)).toBeNull()+ expect(noteStartFailed(state, timeout('claude'), NOW)).toContain('This machine is suspended')+ expect(pool.engineFailures ?? {}).toEqual({})+ expect(pool.engineSuspensions ?? {}).toEqual({})+ for (const engine of ['codex', 'claude']) expect(engineUnusable(pool, engine, NOW)).toContain('This machine is suspended')+ expect(suspendedEngines(pool, NOW)).toEqual({ codex: expect.stringContaining('This machine is suspended'), claude: expect.stringContaining('This machine is suspended') })+ expect(noteStartFailed(state, timeout('codex'), NOW + 1)).toBeNull()+ })++ it('backs off the machine across readings and resets after a successful grid start', () => {+ const pool = machine(fine), state = stateWith(pool)+ let now = NOW+ for (const minutes of [30, 60, 120, 240, 480, 720, 720]) {+ noteStartFailed(state, timeout('codex'), now)+ expect(noteStartFailed(state, timeout('claude'), now)).toContain('This machine is suspended')+ readingClearsSuspensions(pool, now + 1)+ expect(engineUnusable(pool, 'codex', now + minutes * 60_000 - 1)).not.toBeNull()+ now += minutes * 60_000+ expect(engineUnusable(pool, 'codex', now)).toBeNull()+ readingClearsSuspensions(pool, now)+ }+ noteStartFailed(state, timeout('codex'), now)+ noteStartFailed(state, timeout('claude'), now)+ noteStartSucceeded(state, start({ gridModel: 'qwen3' }, ''))+ expect(engineUnusable(pool, 'claude', now)).toBeNull()+ noteStartFailed(state, timeout('codex'), now)+ noteStartFailed(state, timeout('claude'), now)+ expect(engineUnusable(pool, 'claude', now + 30 * 60_000)).toBeNull()+ })++ it('lets the owner resume a machine and reset its backoff without clearing another engine suspension', () => {+ const pool = machine(), state = stateWith(pool)+ noteStartFailed(state, start({ engine: 'claude' }), NOW); noteStartFailed(state, start({ engine: 'claude' }), NOW)+ noteStartFailed(state, timeout('codex'), NOW); noteStartFailed(state, timeout('claude'), NOW)+ expect(resumeEngine(pool, 'codex')).toBe(true)+ expect(engineUnusable(pool, 'codex', NOW)).toBeNull()+ expect(engineUnusable(pool, 'claude', NOW)).toContain('Claude Code is suspended')+ expect(noteStartFailed(state, timeout('codex'), NOW)).toBeNull()+ expect(noteStartFailed(state, timeout('claude'), NOW)).toContain('This machine is suspended')+ expect(engineUnusable(pool, 'codex', NOW + 30 * 60_000)).toBeNull()+ noteStartFailed(state, timeout('codex'), NOW + 30 * 60_000)+ resumeEngine(pool, 'codex')+ expect(noteStartFailed(state, timeout('codex'), NOW + 30 * 60_000)).toBeNull()+ })++ it('counts a grid pickup timeout against the machine too', () => {+ const pool = machine(), state = stateWith(pool)+ noteStartFailed(state, start({ gridModel: 'qwen3' }, 'Worker Mac did not start it within 3 minutes'), NOW)+ expect(noteStartFailed(state, timeout('claude'), NOW)).toContain('This machine is suspended')+ })+})diff --git a/backend/src/superTabs/engineHealth.ts b/backend/src/superTabs/engineHealth.tsindex 8024ef260..7dedffbb6 100644--- a/backend/src/superTabs/engineHealth.ts+++ b/backend/src/superTabs/engineHealth.ts@@ -4,27 +4,32 @@* 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'+import { TIMED_OUT, TIMED_OUT_SUFFIX } 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 LEGACY_SUSPENSION_MS = 6 * 3_600_000+const duration = (level: number) => Math.min(30 * 60_000 * 2 ** (level - 1), 12 * 3_600_000)+const durationText = (ms: number) => ms < 3_600_000 ? `${ms / 60_000} minutes` : `${ms / 3_600_000} ${ms === 3_600_000 ? 'hour' : 'hours'}`+type EngineSuspension = NonNullable<ContributedMachine['engineSuspensions']>[string]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, it lacked memory, or it could not clone the project. 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) || CLONE_FAILED.test(error)-const MEMORY_SHORT = /^Not enough free memory: /-/** A first start whose machine could not clone the project (cli superTabs/projectFolder.ts): the network or GitHub, not the engine.- * Six starts on four machines failed this way on 2026-11-05, and each pair suspended an engine there for hours. */-const CLONE_FAILED = /could not (?:clone|access) the (?:project )?repository/i+/** Match the host's engine summaries, never arbitrary preparation errors. On 11-05, clone/token/tool/request failures+ * took six machines' Claude subscriptions out of routing. An unfamiliar failure still fails the start, but cannot prove+ * its engine is broken. Keep these aligned with CLI startScreen.ts, start.ts and native launch summaries. */+function engineFailure(error: string): 'sign-in' | 'engine' | null {+ const reason = error.replace(/^This machine held the agent's launch for \d+ minutes and stopped it: /, '')+ if (/^(?:Codex|Claude(?: Code)?|(?:Its|The) engine) (?:sign-in failed\.|could not sign in\.|is not signed in\b)/i.test(reason)+ || reason === 'Its engine stopped on a sign-in screen that nobody here can answer.') return 'sign-in'+ if (/^(?:Codex|Claude(?: Code)?|(?:Its|The) engine) (?:could not launch\.|failed to launch\.|exited\b|is installed but cannot run: )/i.test(reason)+ || /^Its engine stopped on .+ that nobody here can answer\.$/.test(reason)+ || reason === 'The agent was created and has since stopped. Create a new start request to continue.') return 'engine'+ return null+}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)+const worker = (start: AgentStart) => !!start.error && !start.request.leadFor && !start.request.buddyOf/** 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 {@@ -35,64 +40,107 @@ function readsFine(machine: ContributedMachine, engine: string): boolean {}function active(machine: ContributedMachine, engine: string, now: number) {const suspension = machine.engineSuspensions?.[engine]- return suspension && now - suspension.at < SUSPENSION_MS ? suspension : null+ return suspension && now - suspension.at < (suspension.durationMs ?? LEGACY_SUSPENSION_MS) ? suspension : null}-function suspensionReason(engine: string, fine: boolean): string {+function suspensionReason(engine: string, suspension: EngineSuspension): string {+ const after = durationText(suspension.durationMs ?? LEGACY_SUSPENSION_MS)+ const reading = suspension.cause === 'sign-in' ? 'once a reading shows it signed in, '+ : !suspension.cause && !suspension.fine ? 'once a reading shows it signed in with quota left, ' : ''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.')+ + `It is offered again ${reading}after ${after}, or once its owner resumes it.`+}++/** A pickup timeout says nothing about any one engine. Keep its cooldown apart, and expose it to old clients through+ * suspendedEngines too; admission still enforces it for clients that do not yet know machineSuspended. */+export function machineSuspensionReason(machine: ContributedMachine, now: number): string | null {+ const s = machine.machineSuspension+ return s && now - s.at < s.durationMs+ ? `This machine is suspended for new work: its last ${SUSPEND_AFTER} starts timed out. It is offered again after ${durationText(s.durationMs)}, or once its owner resumes it.` : null}-/** 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. */+/** Count the first failure receipt only (the caller owns deduplication). Return a notice once per cooldown. */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 }+ if (!machine || !worker(start)) return null+ if (start.error === TIMED_OUT || start.error!.endsWith(TIMED_OUT_SUFFIX)) {+ if (machineSuspensionReason(machine, now)) return null+ machine.machineFailures = (machine.machineFailures ?? 0) + 1+ if (machine.machineFailures < SUSPEND_AFTER) return null+ delete machine.machineFailures+ machine.machineBackoff = Math.min((machine.machineBackoff ?? 0) + 1, 6)+ machine.machineSuspension = { at: now, durationMs: duration(machine.machineBackoff) }+ return machineSuspensionReason(machine, now)+ }+ if (start.request.gridModel || !engineFailure(start.error!) || active(machine, engine, now)) return null+ const previous = machine.engineBackoff?.[engine]+ // A counter from before failure attribution may be a clone/token failure; only the new record proves its cause.+ const failures = (previous ? machine.engineFailures?.[engine] ?? 0 : 0) + 1+ const cause = engineFailure(start.error!) === 'engine' || (failures > 1 && previous?.cause !== 'sign-in') ? 'engine' : 'sign-in'+ if (failures < SUSPEND_AFTER) {+ machine.engineFailures = { ...machine.engineFailures, [engine]: failures }+ machine.engineBackoff = { ...machine.engineBackoff, [engine]: { level: previous?.level ?? 0, cause } }+ 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)+ const level = Math.min((previous?.level ?? 0) + 1, 6)+ machine.engineBackoff = { ...machine.engineBackoff, [engine]: { level, cause } }+ const suspension = { at: now, fine: cause === 'engine', durationMs: duration(level), cause } as const+ machine.engineSuspensions = { ...machine.engineSuspensions, [engine]: suspension }+ return suspensionReason(engine, suspension)}/** 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+ if (!machine) return+ delete machine.machineFailures+ delete machine.machineBackoff+ delete machine.machineSuspension+ if (!start.request.gridModel) resumeEngine(machine, start.request.engine)}-/** 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. */+/** Readings clear sign-in failures only; a quota reading cannot prove a launch works. Legacy causes remain unknown.+ * Expiry drops active cooldowns, keeping the bounded repeat level until a start succeeds. */export function readingClearsSuspensions(machine: ContributedMachine, now: number): void {+ if (machine.machineSuspension && !machineSuspensionReason(machine, now)) delete machine.machineSuspensionif (!machine.engineSuspensions) return- const kept = Object.entries(machine.engineSuspensions).filter(([engine, s]) => now - s.at < SUSPENSION_MS && (s.fine || !readsFine(machine, engine)))+ const kept = Object.entries(machine.engineSuspensions).filter(([engine, s]) => {+ if (!active(machine, engine, now)) return false+ if (s.cause === 'sign-in') return machine.observation?.readiness?.engines?.find(e => e.engine === engine)?.signedIn !== true+ return !!s.cause || s.fine || !readsFine(machine, engine)+ })machine.engineSuspensions = Object.fromEntries(kept)}-/** The machine owner's resume: true when there was a suspension to end. */+/** The owner's resume must lift the machine cooldown too, so the selected engine can take a start again. */export function resumeEngine(machine: ContributedMachine, engine: string): boolean {- const had = !!machine.engineSuspensions?.[engine]+ const had = !!machine.engineSuspensions?.[engine] || !!machine.machineSuspension+ delete machine.machineFailures+ delete machine.machineBackoff+ delete machine.machineSuspensionif (machine.engineSuspensions) { const { [engine]: _ended, ...others } = machine.engineSuspensions; machine.engineSuspensions = others }if (machine.engineFailures) { const { [engine]: _reset, ...others } = machine.engineFailures; machine.engineFailures = others }+ if (machine.engineBackoff) { const { [engine]: _reset, ...others } = machine.engineBackoff; machine.engineBackoff = 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> {+ const machineReason = machineSuspensionReason(machine, now)+ if (machineReason) return Object.fromEntries(machine.engines.map(engine => [engine, machineReason]))return Object.fromEntries(Object.entries(machine.engineSuspensions ?? {}).filter(([engine]) => active(machine, engine, now))- .map(([engine, s]) => [engine, suspensionReason(engine, s.fine)]))+ .map(([engine, s]) => [engine, suspensionReason(engine, s)]))}/** Why a new start of [engine] on the machine is refused, or null: signed out in its reading, or suspended. Quota is* information, not a gate (project instructions, phase 4): a used-up window refuses nothing. What the reading does not say* stays usable. */export function engineUnusable(machine: ContributedMachine, engine: string, now: number): string | null {+ const machineReason = machineSuspensionReason(machine, now)+ if (machineReason) return machineReasonconst reading = machine.observationif (reading?.readiness?.engines?.find(e => e.engine === engine)?.signedIn === false) return `${named(engine)} is not signed in to a subscription on this machine.`const suspension = active(machine, engine, now)- return suspension ? suspensionReason(engine, suspension.fine) : null+ return suspension ? suspensionReason(engine, suspension) : null}diff --git a/backend/src/superTabs/liveness.test.ts b/backend/src/superTabs/liveness.test.tsindex 890c76a67..ef0128809 100644--- a/backend/src/superTabs/liveness.test.ts+++ b/backend/src/superTabs/liveness.test.ts@@ -331,16 +331,16 @@ 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', () => {+ // Pickup timeouts describe the machine, regardless of the engine requested.+ it('suspends the machine with the second timeout, saying so once and tagging the machine owner', () => {const at = LAUNCHED + 3 * MINUTE + 1const 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.+ // All three time out in this one sweep: the second suspends the machine, 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[1]!.text).toContain('This machine is suspended for new work: its last 2 starts timed out.')expect(told[2]!.text).not.toContain('suspended')})diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.tsindex 0e4f01c1a..3fd2be5a4 100644--- a/backend/src/superTabs/liveness.ts+++ b/backend/src/superTabs/liveness.ts@@ -599,7 +599,7 @@ 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.+ // Counted as a host's failure is (commands.ts agent.startFailed); a pickup timeout suspends the machine, not its engine.return failedStartNotices(state, start, now, noteStartFailed(state, start, now))})}diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex e5378172e..ca369a643 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -1,7 +1,7 @@import { accessRefusal, sharedOwnAccess, taskAccess } from './machineAccess.js'import { createHash } from 'node:crypto'import { z } from 'zod'-import { engineUnusable } from './engineHealth.js'+import { engineUnusable, machineSuspensionReason } 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'@@ -75,8 +75,16 @@ export interface ContributedMachine {access?: import('./machineAccess.js').AccessEntry[]/** 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 }>+ /** Bounded repeat level (0–6) and cause of the current failure streak. Kept across expiry, removed by success/resume+ * or with the machine. A launch failure anywhere in the streak prevents sign-in-only recovery. */+ engineBackoff?: Record<string, { level: number; cause: 'engine' | 'sign-in' }>+ /** `fine` keeps the old reader's contract. Records before 11-05 lack duration/cause and retain their six-hour policy. */+ engineSuspensions?: Record<string, { at: number; fine: boolean; durationMs?: number; cause?: 'engine' | 'sign-in' }>+ /** Pickup timeouts across all engines. One bounded counter/level/cooldown per machine, removed by any successful start+ * or with its contribution. Expiry removes the cooldown only, preserving backoff (0–6) until recovery is proven. */+ machineFailures?: number+ machineBackoff?: number+ machineSuspension?: { at: number; durationMs: number }}/** 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. */@@ -910,6 +918,8 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque// A Buddy-only machine is recorded with its Buddy's start, before its host ever read the Swarm: the start waits for it.if (machineOffline(pool, now) && !(pool.buddyOnly && !pool.observation)) fail('MACHINE_OFFLINE', 'Wait for a fresh reading from the contributed machine.')if (!start) admitByRoom(state, pool, slots(pool), request.requirements.memoryBytes)+ const machineReason = !start ? machineSuspensionReason(pool, now) : null+ if (machineReason) fail('MACHINE_UNAVAILABLE', machineReason)// 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) : nullif (unusable) fail('ENGINE_UNAVAILABLE', unusable)diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex 6a0cf3c04..5ef68189b 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -68,6 +68,8 @@ export interface Derived {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>+ /** Pickup timeout cooldown: applies to every new start, including grid models. */+ machineSuspended?: string/** A person reading a teammate's machine: where New Project's Product Manager would run there by engine, the machine* (its Team account or itself), or why it cannot now (leadStart.ts leadChoices). Absent for their own machines. */lead?: Record<string, { machineId: string } | { refused: string }> }>diff --git a/backend/src/superTabs/read/views.test.ts b/backend/src/superTabs/read/views.test.tsindex 79e0ba2e3..c5b999793 100644--- a/backend/src/superTabs/read/views.test.ts+++ b/backend/src/superTabs/read/views.test.ts@@ -146,6 +146,19 @@ describe('reader view of the parts (design 4.1, 4.3)', () => {expect(view.derived.machines.mac!.suspendedEngines).toEqual({ codex: expect.stringContaining('Codex is suspended on this machine for new work') })})+ it('exposes a machine cooldown to new and older routing clients, then drops it at expiry', () => {+ const s = richSwarm()+ s.contribute('mac', 'swarm')+ s.edit(state => { Object.assign(state.machines![0]!, { machineSuspension: { at: NOW, durationMs: 30 * MINUTE } }) })+ const parts = store.split(s.state, { tabId: 'tab', version: R, now: NOW })+ const current = readerView(parts, peer, NOW, { teamMachines: [] }).derived.machines.mac!+ expect(current).toMatchObject({ machineSuspended: expect.stringContaining('This machine is suspended'),+ suspendedEngines: { codex: expect.stringContaining('This machine is suspended') } })+ const expired = readerView(parts, peer, NOW + 30 * MINUTE, { teamMachines: [] }).derived.machines.mac!+ expect(expired).not.toHaveProperty('machineSuspended')+ expect(expired).not.toHaveProperty('suspendedEngines')+ })+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 c7a526feb..2f72180af 100644--- a/backend/src/superTabs/read/views.ts+++ b/backend/src/superTabs/read/views.ts@@ -3,7 +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 { machineSuspensionReason, suspendedEngines } from '../engineHealth.js'import { leadChoices } from '../leadStart.js'import { isBuddyChat, isBuddyReader } from '../buddies.js'import { agentForBuddy, agentWithoutMachine, groupForBuddy, machineHiddenFrom, seenMachineIds, visibleState, withSeenRequirement, type Actor, type Agent, type Conversation, type SuperTabState } from '../model.js'@@ -139,9 +139,10 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:const refusal = machineTeamWork(state, stored, now, extras.teamMachines, extras.otherWorkspaceMachines ?? [], extras.joiningTeams ?? [])const version = extras.machineVersions?.[pool.machineId]const suspended = suspendedEngines(stored, now)+ const machineSuspended = machineSuspensionReason(stored, now)return [pool.machineId, { availableSlots: availableSlots(state, stored, slots(stored)),teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const }, ...(version ? { clientVersion: version } : {}),- ...(Object.keys(suspended).length ? { suspendedEngines: suspended } : {}), ...(leads[pool.machineId] ? { lead: leads[pool.machineId] } : {}) }] as const+ ...(Object.keys(suspended).length ? { suspendedEngines: suspended } : {}), ...(machineSuspended ? { machineSuspended } : {}), ...(leads[pool.machineId] ? { lead: leads[pool.machineId] } : {}) }] 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/store.ts b/backend/src/superTabs/store.tsindex 6b05433ac..2ef4d7ace 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -5,7 +5,7 @@ import type { PhoneNotice } from '../push/sender.js'import { joiningTeamMacs, type TeamMachineRow, accountMachineName, availableSlots, expireRemovals, followAccountName, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, slotCounter, machineTeamWork, preparableStart, readingOnly, refusableStart, recordAgentPresence, renamedBy, removalPreview, startPreparing, storedObservation, swarmGridRow, teamAccountRequired, teamWorkRefusal, ownAccountWork, ownAccountNote, type MachineObservation } from './machines.js'import { expireAccess } from './machineAccess.js'import { authorForAgent, lazyUsernames, namesPerson, rowForAgent, shownNameOf } from './personNames.js'-import { readingClearsSuspensions, suspendedEngines } from './engineHealth.js'+import { machineSuspensionReason, readingClearsSuspensions, suspendedEngines } from './engineHealth.js'import { BUDDY_OWN_MACHINE_REFUSAL } from './buddyContract.js'import { createHash } from 'node:crypto'import { isDeepStrictEqual } from 'node:util'@@ -1365,13 +1365,14 @@ export class SuperTabStore {// out for, and what Desktop can show on the machine.const refusal = machineTeamWork(state, stored, now, teamMachines, otherWorkspace, joining)const suspended = suspendedEngines(stored, now)+ const machineSuspended = machineSuspensionReason(stored, now)return { ...pool, availableSlots: availableSlots(state, stored, slots(stored)),teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const,// Its owner lets teammates' work run in their own account (machines.ts ownAccountWork): the route says so....(ownAccountWork(stored) ? { ownAccount: ownAccountNote(stored, shownNameOf(state, stored.contributorId)) } : {}) },...(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 } : {}) }+ ...(Object.keys(suspended).length ? { suspendedEngines: suspended } : {}), ...(machineSuspended ? { machineSuspended } : {}) }}) } }}@@ -3589,9 +3590,9 @@ export class SuperTabStore {if (!readingOnly(mine.observation, reading)) return nulladdLent(mine, now, record.lentCount, record.lentProjects)mine.observation = reading- const suspended = JSON.stringify(mine.engineSuspensions)+ const suspended = JSON.stringify([mine.engineSuspensions, mine.machineSuspension])readingClearsSuspensions(mine, now)- if (JSON.stringify(mine.engineSuspensions) !== suspended) return null+ if (JSON.stringify([mine.engineSuspensions, mine.machineSuspension]) !== suspended) return null// Its sweep due: the full report runs it, with the slot this reading, which passed the checks, just took.if (await this.reports.sweepDue(tabId, now)) return { sweep: true }const stamp = clock.next()diff --git a/cli/src/superTabs/route.ts b/cli/src/superTabs/route.tsindex c21e70101..b3c7ff254 100644--- a/cli/src/superTabs/route.ts+++ b/cli/src/superTabs/route.ts@@ -84,6 +84,26 @@ export interface Probe {}export interface Attempt { agent: string; outcome: string; result?: string }export interface RecentRoute { title: string; via?: string; outcome: string | null }+/** The latest start is already in the route's authorized snapshot. Say what kind of setup failed, never copy its reason:+ * the coordinator may read paths/account details there that the route log's other readers must not learn. */+export function recentStartNotes(starts: Json[], machineId: string, engine: string, now: number): string[] {+ for (let i = starts.length - 1; i >= 0; i--) {+ const start = starts[i]!, request = object(start.request)+ if (request.machineId !== machineId || request.engine !== engine) continue+ const at = finite(start.dispatchedAt) ? start.dispatchedAt : start.requestedAt+ if (start.harnessId || typeof start.error !== 'string' || !finite(at) || now - at >= 30 * 60_000) return []+ const reason = start.error+ const category = /GitHub.*token|token.*GitHub/i.test(reason) ? 'GitHub access'+ : /clone|repository.*(?:unavailable|access)|access.*repository/i.test(reason) ? 'the repository'+ : /no commits?|commit.*(?:missing|not found|unknown)/i.test(reason) ? 'a missing commit'+ : /folder|directory|checkout/i.test(reason) ? 'the project folder'+ : /permission.*(?:flag|mode)/i.test(reason) ? 'permission flags'+ : /does not offer|model.*(?:unavailable|not supported)/i.test(reason) ? 'the requested model'+ : /(?:tool|spawn |command not found|not installed)/i.test(reason) ? 'a missing tool' : null+ return category ? [`Its last start failed while preparing ${category}. The start has the details; this does not suspend the engine.`] : []+ }+ return []+}type Window = '5-hour' | 'weekly'/** How a candidate's account would carry the task, as the decision log keeps it. */export interface Fit { status: 'fits' | 'unknown' | 'short'; coverage: number | null; effectiveCost: number; expiring: number; spend: Record<Window, number>; account: string }diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.tsindex 0dfc97f92..e2c25c128 100644--- a/cli/src/superTabs/routeCommand.spec.ts+++ b/cli/src/superTabs/routeCommand.spec.ts@@ -1408,6 +1408,50 @@ describe('routing contributed capacity', () => {expect(JSON.stringify(reasons(both.answer))).not.toMatch(/suspended|Suspended/)})+ it('leaves out all new starts, including grid models, during a machine cooldown', async () => {+ const grid = 'swarm-0123456789ab', pool = swarm()+ pool.machineSuspended = 'This machine is suspended for new work: its last 2 starts timed out. It is offered again after 30 minutes.'+ pool.observation.localModels = [{ grid, model: 'qwen3' }]+ const { answer } = await runPool(pool, false, {}, project, { state: { localModels: { grid, enabled: true } }, kind: 'tests' })+ expect(answer).toMatchObject({ error: 'NO_CANDIDATE' })+ expect(reasons(answer).some(row => row.reason.includes('This machine is suspended'))).toBe(true)+ delete pool.machineSuspended+ expect((await runPool(pool, false, {}, project)).answer.ok).toBe(true)+ })++ it.each([+ ['Could not clone the repository at /private/project.', 'repository'],+ ['The Harness server answered without a GitHub token for this project.', 'GitHub'],+ ['The project folder does not exist: /private/project.', 'folder'],+ ['The repository has no commits.', 'commit'],+ ['Required tool gh is not installed.', 'tool'],+ ["This machine's ChatGPT account (private-account) does not offer gpt-6-astra; choose another model.", 'model'],+ ["This machine held the agent's launch for 3 minutes and stopped it: Waiting to confirm the selected executable’s permission flags.", 'permission'],+ ])('notes setup failures while keeping the engine available: %s', async (error, category) => {+ const { answer, s } = await runPool(swarm(), false, {}, project, { state: { starts: [+ { id: 'failed', requestedAt: Date.now(), error, request: { machineId: 'm1', engine: 'claude', conversationId: 'group' } },+ ] } })+ expect(answer.ok).toBe(true)+ const candidates = answer.candidates as Array<{ notes: string[] }>+ expect(candidates.some(row => (row.notes ?? []).some(note => note.includes(category)))).toBe(true)+ const recordedText = JSON.stringify(recorded(s).command.decision)+ expect(recordedText).not.toContain('/private/project')+ expect(recordedText).not.toContain('private-account')+ })++ it('drops setup notes after a later success or 30 minutes, without noting another engine', async () => {+ const failed = { requestedAt: Date.now(), error: 'The project folder does not exist.', request: { machineId: 'm1', engine: 'claude' } }+ for (const starts of [+ [{ ...failed, requestedAt: Date.now() - 30 * 60_000 }],+ [failed, { ...failed, harnessId: 'created', error: null }],+ [{ ...failed, request: { machineId: 'm1', engine: 'codex' } }],+ ]) {+ const { answer } = await runPool(swarm(), false, {}, project, { state: { starts } })+ expect(answer.ok).toBe(true)+ expect(JSON.stringify(answer.candidates)).not.toContain('Its last start failed while preparing')+ }+ })+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 71e58197a..cd9114ad7 100644--- a/cli/src/superTabs/routeCommand.ts+++ b/cli/src/superTabs/routeCommand.ts@@ -10,7 +10,7 @@ import { START_DEADLINE_MS, START_WINDOW_MS } from './reservations.js'import { inspectCapacity, type ScopedRequest } from './start.js'import { ENDED_WORK, object, within } from './wire.js'import { withPmAccounts } from './pmAccounts.js'-import { accountOf, API_BUILDERS, bytes, machineBrief, catalogFrom, catalogRow, choose, decide, gridStrength, parseAssessment, OLD_RECORD_MAX, quotaBrief, quotaOf2, recordOf, repoMatch, repositoryKey, type Assessment, type Catalog, type CatalogModel, type RecordShape, type Commitment, type Excluded, type Shown, type HeldModel, type MemberFrame, type Probe, type TaskFolder } from './route.js'+import { accountOf, API_BUILDERS, bytes, machineBrief, catalogFrom, catalogRow, choose, decide, gridStrength, parseAssessment, OLD_RECORD_MAX, quotaBrief, quotaOf2, recentStartNotes, recordOf, repoMatch, repositoryKey, type Assessment, type Catalog, type CatalogModel, type RecordShape, type Commitment, type Excluded, type Shown, type HeldModel, type MemberFrame, type Probe, type TaskFolder } from './route.js'import { makePlugins, ROUTE_PLUGIN_MAKERS, type PluginMaker } from './routePlugins.js'import { CI_HOLD_OPENING, CI_RETRY_MINUTES, heavyOfStart, MACHINE_FIT_MAKER } from './machineFit.js'import { stat } from 'node:fs/promises'@@ -194,6 +194,7 @@ export function unreadyPool(pool: Json, project: Json | undefined, projectId: stconst 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) : nullconst all = [+ ...(typeof pool.machineSuspended === 'string' ? [pool.machineSuspended] : []),...(NO_SWARM_AGENTS_ON.includes(String(object(observed.resources).os)) ? [`Swarm agents do not run on ${String(object(observed.resources).os)} yet.`] : []),...(checkout?.git === false ? ['The project folder on this machine is not a git checkout. Its owner can remove it, and the next start clones the project.'] : []),...(checkout?.git === true && wanted && typeof checkout.repository === 'string' && checkout.repository !== wanted@@ -499,6 +500,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;...probes.filter(p => p.machineId === failedOn && p.engine === failedEngine && !p.gridModel).map(accountOf)] : [])for (const [i, p] of probes.entries()) {const notes = [...(outside(p.machineId) ? [ELSEWHERE] : []), ...(p.kind === 'member' && !checked(p.agentId) ? [UNCHECKED_DEVICE] : []),+ ...(p.kind === 'new' ? recentStartNotes(list(state.starts), p.machineId, p.engine, Date.now()) : []),...(avoid.has(accountOf(p)) ? [AVOIDED] : [])]if (notes.length) probes[i] = { ...p, notes: [...p.notes, ...notes] }}diff --git a/desktop/lib/super_tabs/buddies.dart b/desktop/lib/super_tabs/buddies.dartindex 96e17b514..2181f326f 100644--- a/desktop/lib/super_tabs/buddies.dart+++ b/desktop/lib/super_tabs/buddies.dart@@ -572,6 +572,92 @@ class SuperTabBuddyBar extends StatelessWidget {);}+ /// The words the Buddy's machine reports for a switch the Buddy guard held+ /// (cli superTabs/buddyModel.ts refusal(), task #3256), as the backend's+ /// line in the Buddy chat begins (backend superTabs/buddyModel.ts).+ static const _heldSwitch =+ "Couldn't switch your Buddy: Start your Buddy again to switch its model";++ /// How far back the bar looks for that line: one page of the chat. The read+ /// runs on every build, so it is bounded (ENGINEERING.md 4); a refusal under+ /// more newer messages than this offers nothing, and nothing is removed.+ static const _heldSwitchReach = 100;++ /// Whether [agent]'s last switch failed because it must be started again:+ /// its newest system line in this chat says so, and no switch is under way.+ /// Its machine writes that line as the Buddy itself, so a later line (a+ /// switch that landed, another failure) settles it, and a Buddy started+ /// again, a new agent, never inherits it. Scholes, 11-05: the line alone+ /// told him to start his Buddy again, with no way to do it while it ran.+ ///+ /// Only from the chat's newest messages (Guide's review of #3171): a window+ /// opened at an older read mark holds an older page, and the line that+ /// settled the switch may be among the newer ones it has not read. The+ /// cheap checks come first, and the held rows are read from the end without+ /// a copy ([SuperTabController.newestFirst]), so the scan stops at this+ /// Buddy's newest system line.+ bool _mustStartAgain(SuperTabController c, SuperTabAgent agent) {+ if (!chat.isSwarmBuddyChat || agent.modelRequest != null) return false;+ final conversation = c.snapshot?.conversation(chat.id);+ if (conversation == null ||+ c.hasNewer(chat.id) ||+ c.awaitsNewest(chat.id)) {+ return false;+ }+ final held = c.newestFirst(chat.id);+ final newest =+ conversation.lastMainSequence ?? conversation.lastMessageSequence;+ if ((held.firstOrNull?.sequence ?? -1) < newest) return false;+ for (final m in held.take(_heldSwitchReach)) {+ if (m.source['kind'] == 'system' && m.author['id'] == agent.id) {+ return m.text.startsWith(_heldSwitch);+ }+ }+ return false;+ }++ /// Why Start again cannot run now, in words, or null when it can: new work+ /// paused in the Swarm, or [agent]'s machine paused or offline there.+ String? _restartHeld(+ SuperTabController c,+ SuperTabAgent agent,+ String machine,+ ) {+ if (c.snapshot!.paused) {+ return 'New work is paused. Start your Buddy again once it resumes.';+ }+ final target = buddyMachines(+ c,+ app: app,+ ).where((m) => m.id == agent.machineId).firstOrNull;+ final block = target == null ? null : buddyMachineBlock(target);+ return block == null+ ? null+ : "$machine is $block. Start your Buddy again once it's back.";+ }++ /// A running Buddy refuses a second start (backend BUDDY_EXISTS): it is+ /// removed, then started on the same machine and engine. Its chat and its+ /// name stay. Unlike a down Buddy's Start again, which the server replaces+ /// in one command, these are two: the machine and engine are kept first+ /// ([_restartTargets]), so a start refused after the removal, or a removal+ /// whose answer was lost, leaves the Start bar on them, one click away.+ Future<void> _startAgain(SuperTabController c, SuperTabAgent agent) async {+ final projectId = chat.projectId;+ (_restartTargets[c] ??= {})[projectId] = (+ machineId: agent.machineId,+ engine: agent.engine,+ );+ if (!await c.removeBuddy(projectId)) return;+ if (await c.addBuddy(+ projectId: projectId,+ machineId: agent.machineId,+ engine: agent.engine,+ )) {+ _restartTargets[c]?.remove(projectId);+ }+ }+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);@@ -594,6 +680,8 @@ class SuperTabBuddyBar extends StatelessWidget {access,].join(' · ');final busy = !c.canWrite || c.saving || c.hasPendingAction;+ final offer = agent.downSince == null && _mustStartAgain(c, agent);+ final held = offer ? _restartHeld(c, agent, machine) : null;return Padding(key: const ValueKey('super-buddy-bar'),padding: _padding,@@ -633,6 +721,27 @@ class SuperTabBuddyBar extends StatelessWidget {)elseText(where, style: DesktopChrome.metadata()),+ if (offer)+ Row(+ key: const ValueKey('super-buddy-start-again'),+ children: [+ Expanded(+ child: Text(+ held ?? 'Start your Buddy again to switch its model.',+ style: DesktopChrome.control(),+ ),+ ),+ // The server refuses a start while new work is paused, in the+ // Swarm or on the Buddy's machine: the Buddy is not removed+ // for a start that cannot follow (reviews of #3171).+ TextButton(+ onPressed: busy || held != null+ ? null+ : () => unawaited(_startAgain(c, agent)),+ child: const Text('Start again'),+ ),+ ],+ ),if (agent.downSince != null)Row(children: [@@ -662,6 +771,15 @@ class SuperTabBuddyBar extends StatelessWidget {}}+/// The machine and engine of a Buddy removed to start again (the Buddy bar's+/// Start again), by its project key, until a start of it is accepted: per+/// controller, so another account's never shows. In memory only: it serves+/// the restart under way in this window.+final _restartTargets =+ Expando<Map<String, ({String machineId, String engine})>>(+ 'buddy restart targets',+ );+/// A Buddy chat with no Buddy: one click starts one, on the reader's own/// machine and with Claude unless they pick otherwise (mockup A, Lead 10-29)./// A viewer, who adds nothing, sees no bar.@@ -689,6 +807,22 @@ class _BuddyStartState extends State<_BuddyStart> {String _engine = 'claude';bool _adding = false;+ /// [_machine] is a restart's target, kept while it cannot be used, until+ /// the reader chooses another (Guide's second review of #3171).+ bool _keepTarget = false;++ @override+ void initState() {+ super.initState();+ // A Buddy removed to start again whose start did not follow: back on the+ // machine and engine it ran on.+ if (_restartTargets[c]?[widget.projectId] case final target?) {+ _machine = target.machineId;+ _engine = target.engine;+ _keepTarget = true;+ }+ }+/// Starts the Buddy on [machine], first preparing it when it is one of the/// reader's machines outside the Swarm. A failed setup says why and starts/// nothing. The Buddy is for the project whose chat was clicked: once the@@ -720,6 +854,7 @@ class _BuddyStartState extends State<_BuddyStart> {setup: setup,).then((added) {+ if (added) _restartTargets[c]?.remove(projectId);// Its host reads the Swarm now rather than on its next pass.if (added && setup != null) unawaited(app?.wakeSuperTabHost(id));}),@@ -730,7 +865,11 @@ class _BuddyStartState extends State<_BuddyStart> {Widget build(BuildContext context) {if (!c.canWrite) return const SizedBox.shrink();final machines = buddyMachines(c, app: widget.app);- final machine = pickedBuddyMachine(machines, _machine);+ final kept = _keepTarget+ ? machines.where((m) => m.id == _machine).firstOrNull+ : null;+ final keptBlock = kept == null ? null : buddyMachineBlock(kept);+ final machine = kept ?? pickedBuddyMachine(machines, _machine);final busy = c.saving || c.hasPendingAction || _adding;return Padding(key: const ValueKey('super-buddy-start'),@@ -756,7 +895,11 @@ class _BuddyStartState extends State<_BuddyStart> {busy: busy,fitNames: true,onChanged: (value) {- if (!busy) setState(() => _machine = value);+ if (busy) return;+ setState(() {+ _machine = value;+ _keepTarget = false;+ });},),const SizedBox(width: 8),@@ -779,13 +922,21 @@ class _BuddyStartState extends State<_BuddyStart> {),const SizedBox(width: 8),FilledButton(- onPressed: busy || machine == null+ onPressed: busy || machine == null || keptBlock != null? null: () => unawaited(_start(machine)),child: const Text('Start'),),],),+ if (keptBlock != null) ...[+ const SizedBox(height: 4),+ Text(+ '${kept!.name} is $keptBlock. Your Buddy starts there once '+ "it's back, or choose another machine.",+ style: DesktopChrome.control(),+ ),+ ],if (machines.isNotEmpty && machine == null) ...[const SizedBox(height: 4),BuddyNoMachine(machines: machines),diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex eedabf51b..1da3c4133 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -2073,6 +2073,14 @@ class SuperTabController extends ChangeNotifier {(_messages[id] ?? const <SuperTabMessage>[]).where(_listed),);+ /// What [messages] lists, newest first, read lazily from what is held: no+ /// copy, so a caller that stops at the first it needs reads only that far.+ /// For a read on every build (the Buddy bar's Start again, task #3256): a+ /// copy of a long held history there made each rebuild slower. Read it+ /// before the next change to what is held, as within one build.+ Iterable<SuperTabMessage> newestFirst(String id) =>+ (_messages[id] ?? const <SuperTabMessage>[]).reversed.where(_listed);+static bool _listed(SuperTabMessage m) =>m.source['kind'] != 'update-request' &&!m.terminalPrompt &&diff --git a/desktop/test/benchmarks/buddy_bar_benchmark.dart b/desktop/test/benchmarks/buddy_bar_benchmark.dartnew file mode 100644index 000000000..242611dc5--- /dev/null+++ b/desktop/test/benchmarks/buddy_bar_benchmark.dart@@ -0,0 +1,90 @@+// Run explicitly: flutter test test/benchmarks/buddy_bar_benchmark.dart --reporter expanded+// Headless CPU measurements of the Swarm Buddy bar's rebuild, not display latency.+//+// Task #3256 (review of #3171): the bar reads its chat's held messages for the+// Start again offer on every build. This rebuilds the bar alone over a chat+// holding [sizes] messages, all of them read back page by page, with the held+// switch refusal last (the offer shows) and with no line by the Buddy at all+// (the scan reads every held row and finds nothing), and prints the median and+// p95 of a rebuild in microseconds.+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/buddies.dart';++import '../support/buddy_fixture.dart';++const sizes = [100, 2000, 10000];+const rebuilds = 300;++void main() {+ for (final size in sizes) {+ for (final refusalLast in [true, false]) {+ final label = refusalLast ? 'refusal last' : 'no Buddy line';+ testWidgets('Buddy bar rebuild, $size held, $label', (tester) async {+ final server = oneBuddySwarm();+ giveSwarmBuddy(server);+ for (var i = 0; i < size - 1; i++) {+ server.append('message $i', conversationId: 'swarm-buddy-peer');+ server.messages.last['author'] = {+ 'kind': 'person',+ 'id': 'peer',+ 'name': '[email protected]',+ };+ }+ server.append(+ refusalLast+ ? "Couldn't switch your Buddy: Start your Buddy again to switch "+ 'its model. It is still on your subscription.'+ : 'the last message',+ conversationId: 'swarm-buddy-peer',+ );+ server.messages.last+ ..['author'] = refusalLast+ ? {'kind': 'agent', 'id': 'wren', 'name': 'Wren'}+ : {'kind': 'person', 'id': 'peer', 'name': '[email protected]'}+ ..['source'] = refusalLast ? {'kind': 'system'} : <String, dynamic>{};+ final c = server.controller(account: 'peer');+ await c.refresh();+ await c.select('swarm-buddy-peer');+ while (c.hasOlder('swarm-buddy-peer')) {+ await c.loadMessages('swarm-buddy-peer', older: true);+ }+ expect(c.messages('swarm-buddy-peer'), hasLength(size));+ final chat = c.snapshot!.conversation('swarm-buddy-peer')!;+ late StateSetter rebuild;+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: StatefulBuilder(+ builder: (context, setState) {+ rebuild = setState;+ return SuperTabBuddyBar(controller: c, chat: chat);+ },+ ),+ ),+ ),+ );+ await tester.pump();+ final times = <int>[];+ for (var i = 0; i < rebuilds; i++) {+ rebuild(() {});+ final watch = Stopwatch()..start();+ await tester.pump();+ times.add(watch.elapsedMicroseconds);+ }+ times.sort();+ // ignore: avoid_print+ print(+ 'buddy-bar size=$size $label '+ 'median=${times[times.length ~/ 2]}us '+ 'p95=${times[(times.length * 0.95).floor()]}us',+ );+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ });+ }+ }+}diff --git a/desktop/test/super_tab_buddies_shots_test.dart b/desktop/test/super_tab_buddies_shots_test.dartindex 98410aeea..f7112b005 100644--- a/desktop/test/super_tab_buddies_shots_test.dart+++ b/desktop/test/super_tab_buddies_shots_test.dart@@ -185,6 +185,107 @@ void main() {}}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));+ // Task #3256: after a switch the Buddy guard held, the bar offers Start+ // again (Scholes approved the mockup, 11-05).+ // The UI checklist's states (review of #3171): the line at 100% and 200%+ // text, while paused (Start again disabled), and the Start bar a start+ // refused after the removal leaves, on the Buddy's machine and engine.+ for (final (state, scale) in [+ ('', 1.0),+ ('-200', 2.0),+ ('-paused', 1.0),+ ('-refused', 1.0),+ ('-machine-paused', 1.0),+ ('-kept', 1.0),+ ]) {+ testWidgets(+ 'Buddy Start again$state after a held switch in ${brightness.name}',+ (tester) async {+ if (shots == null) return;+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ tester.view.devicePixelRatio = 2;+ tester.view.physicalSize = const Size(2400, 1400);+ addTearDown(tester.view.reset);+ final server = sharedModels();+ if (state == '-paused') server.state['paused'] = true;+ Map ownMac() => (server.state['machines'] as List)+ .cast<Map>()+ .firstWhere((m) => m['machineId'] == 'ken-mac');+ if (state == '-machine-paused') ownMac()['paused'] = true;+ if (state == '-refused' || state == '-kept') {+ (server.state['agents'] as List).cast<Map>().firstWhere(+ (a) => a['id'] == 'wren',+ )['configuration'] = {+ 'engine': 'codex',+ 'model': 'default',+ };+ server.unknownCommand = (command) =>+ command['type'] == 'buddy.create';+ }+ server.append(+ "Couldn't switch your Buddy: Start your Buddy again to switch its "+ 'model. It is still on your subscription.',+ conversationId: 'swarm-buddy-peer',+ );+ server.messages.last+ ..['author'] = {'kind': 'agent', 'id': 'wren', 'name': 'Wren'}+ ..['source'] = {'kind': 'system'};+ final c = server.controller(account: 'peer');+ await c.refresh();+ await c.select('swarm-buddy-peer');+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(scale)),+ child: child!,+ ),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(+ find.byKey(const ValueKey('super-buddy-start-again')),+ findsOneWidget,+ );+ if (state == '-refused' || state == '-kept') {+ await tester.tap(find.widgetWithText(TextButton, 'Start again'));+ await tester.pumpAndSettle();+ if (state == '-kept') {+ ownMac()['paused'] = true;+ await c.refresh();+ await tester.pumpAndSettle();+ }+ expect(+ find.byKey(const ValueKey('super-buddy-start')),+ findsOneWidget,+ );+ }+ await captureWindow(+ tester,+ shots,+ 'buddy-start-again$state-${brightness.name}',+ );+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ },+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),+ );+ }+testWidgets('Buddies in ${brightness.name}', (tester) async {if (shots == null) return;final previous = grid.AppTheme.brightness.value;diff --git a/desktop/test/super_tab_buddy_model_test.dart b/desktop/test/super_tab_buddy_model_test.dartindex 4d0dd4c80..a8a8257b4 100644--- a/desktop/test/super_tab_buddy_model_test.dart+++ b/desktop/test/super_tab_buddy_model_test.dart@@ -485,4 +485,316 @@ void main() {await close(tester, c);});});++ // Task #3256: a switch the Buddy guard holds (a Buddy started before its+ // owner was recorded) comes back as this line from the Buddy's machine+ // (cli superTabs/buddyModel.ts refusal(), backend buddyModel.ts). Until the+ // Buddy is started again, the bar offers that in one click.+ group('after a switch its Buddy must be started again for', () {+ const held =+ "Couldn't switch your Buddy: Start your Buddy again to switch its "+ 'model. It is still on your subscription.';+ const offer = 'Start your Buddy again to switch its model.';+ final startAgain = find.widgetWithText(TextButton, 'Start again');++ /// The Buddy's machine's line in its chat, as the backend writes a+ /// switch's result: a system line by the Buddy agent [by].+ void line(ConversationServer server, String text, {String by = 'wren'}) {+ server.append(text, conversationId: 'swarm-buddy-peer');+ server.messages.last+ ..['author'] = {'kind': 'agent', 'id': by, 'name': 'Wren'}+ ..['source'] = {'kind': 'system'};+ }++ testWidgets('the bar offers Start again, which starts a fresh Buddy on '+ 'the same machine and engine', (tester) async {+ final server = swarm();+ line(server, held);+ final c = await show(tester, server);+ expect(find.text(offer), findsOneWidget);+ // The picker stays: the line is what was learnt, not a lock.+ expect(picker, findsOneWidget);++ await tester.tap(startAgain);+ await tester.pumpAndSettle();+ // A running Buddy refuses a second start (backend BUDDY_EXISTS): it is+ // removed, then started, as a down one is replaced.+ expect(commands(server, 'buddy.remove').single, {'type': 'buddy.remove'});+ expect(commands(server, 'buddy.create').single, {+ 'type': 'buddy.create',+ 'machineId': 'ken-mac',+ 'engine': 'claude',+ });+ expect(c.operationError, isNull);+ // The new Buddy did not write that line: the offer is gone.+ expect(c.buddy(SuperTabController.kSwarmBuddyKey)!.id, isNot('wren'));+ expect(find.text(offer), findsNothing);+ await close(tester, c);+ });++ testWidgets('it is not offered for another reason, once a later line '+ 'settles it, while a switch is under way, or for an earlier Buddy', (+ tester,+ ) async {+ Future<void> none(ConversationServer server) async {+ final c = await show(tester, server);+ expect(find.text(offer), findsNothing);+ expect(startAgain, findsNothing);+ await close(tester, c);+ }++ await none(+ swarm()..append('Start your Buddy again', conversationId: 'lead'),+ );+ final other = swarm();+ line(+ other,+ "Couldn't switch your Buddy: Your Buddy is answering. Try again when "+ 'it has finished. It is still on your subscription.',+ );+ await none(other);+ final later = swarm();+ line(later, held);+ line(+ later,+ "Peer's Buddy now runs on Kimi K3, which your machine serves.",+ );+ await none(later);+ final moving = swarm(+ modelRequest: {'id': 'req2', 'gridModel': 'kimi-k3', 'name': 'Kimi K3'},+ );+ line(moving, held);+ await none(moving);+ final earlier = swarm();+ line(earlier, held, by: 'old-wren');+ await none(earlier);+ });++ // Review of #3171 (Guide): the messages held can be an older page, read+ // back to the reader's mark, with the result that settled the switch+ // among the newer ones not read yet.+ testWidgets('it is not offered while the chat holds an older page than '+ 'its newest message', (tester) async {+ final server = swarm();+ line(server, held);+ // Newer messages are in the chat that this window has not read.+ final chat = (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((g) => g['id'] == 'swarm-buddy-peer');+ chat['lastMessageSequence'] = (chat['lastMessageSequence'] as int) + 5;+ chat['lastMainSequence'] = chat['lastMessageSequence'];+ final c = await show(tester, server);+ expect(find.text(offer), findsNothing);+ await close(tester, c);+ });++ // Review of #3171: the bar reads its chat on every build, so the read is+ // bounded: a refusal under more than a page of newer messages is not+ // offered (its person has moved on), and nothing is removed for it.+ testWidgets('a refusal more than a page back is not offered', (+ tester,+ ) async {+ final server = swarm();+ line(server, held);+ for (var i = 0; i < 100; i++) {+ server.append('later $i', conversationId: 'swarm-buddy-peer');+ server.messages.last['author'] = {+ 'kind': 'person',+ 'id': 'peer',+ 'name': '[email protected]',+ };+ }+ final c = await show(tester, server);+ while (c.hasOlder('swarm-buddy-peer')) {+ await c.loadMessages('swarm-buddy-peer', older: true);+ }+ await tester.pumpAndSettle();+ expect(c.messages('swarm-buddy-peer'), hasLength(101));+ expect(find.text(offer), findsNothing);+ await close(tester, c);+ });++ // Review of #3171: a Buddy is removed before it starts again, so nothing+ // that would refuse the start may be known when it is removed.+ testWidgets('while new work is paused, Start again removes nothing', (+ tester,+ ) async {+ final server = swarm();+ server.state['paused'] = true;+ line(server, held);+ final c = await show(tester, server);+ // Words say why, not the disabled button alone (UI checklist).+ expect(+ find.text(+ 'New work is paused. Start your Buddy again once it resumes.',+ ),+ findsOneWidget,+ );+ expect(tester.widget<TextButton>(startAgain).onPressed, isNull);+ expect(commands(server, 'buddy.remove'), isEmpty);+ await close(tester, c);+ });++ // Review of #3171: a start refused once its Buddy is removed leaves the+ // Start bar on the machine and engine it ran on, one click from them.+ testWidgets('a start refused after the removal keeps its machine and '+ 'engine in the Start bar', (tester) async {+ final server = swarm();+ final wren = (server.state['agents'] as List).cast<Map>().firstWhere(+ (a) => a['id'] == 'wren',+ );+ wren['configuration'] = {'engine': 'codex', 'model': 'default'};+ line(server, held);+ server.unknownCommand = (command) => command['type'] == 'buddy.create';+ final c = await show(tester, server);+ await tester.tap(startAgain);+ await tester.pumpAndSettle();+ expect(commands(server, 'buddy.remove'), hasLength(1));+ expect(c.buddy(SuperTabController.kSwarmBuddyKey), isNull);+ final engine = find.byKey(const ValueKey('super-buddy-start-engine'));+ expect(+ find.descendant(of: engine, matching: find.text('Codex')),+ findsOneWidget,+ );++ server.unknownCommand = null;+ await tester.tap(find.widgetWithText(FilledButton, 'Start'));+ await tester.pumpAndSettle();+ expect(commands(server, 'buddy.create').last, {+ 'type': 'buddy.create',+ 'machineId': 'ken-mac',+ 'engine': 'codex',+ });+ await close(tester, c);+ });++ // Second review of #3171 (Guide): the reader's two machines, with Ken's+ // other Mac listed first, so a Start bar that lost the Buddy's machine+ // would pick it.+ ConversationServer twoMachines({String engine = 'codex'}) {+ final server = swarm();+ final machines = server.state['machines'] as List;+ machines.insert(+ 0,+ machine('peer-mini', 'Kens-Mac-mini.local', 'peer', []),+ );+ (server.state['agents'] as List).cast<Map>().firstWhere(+ (a) => a['id'] == 'wren',+ )['configuration'] = {+ 'engine': engine,+ 'model': 'default',+ };+ line(server, held);+ return server;+ }++ void pause(ConversationServer server, String machineId) =>+ (server.state['machines'] as List).cast<Map>().firstWhere(+ (m) => m['machineId'] == machineId,+ )['paused'] = true;++ final startMachine = find.byKey(+ const ValueKey('super-buddy-start-machine'),+ );+ Finder inStart(Finder f) => find.descendant(+ of: find.byKey(const ValueKey('super-buddy-start')),+ matching: f,+ );++ testWidgets('on a paused machine, Start again removes nothing and says '+ 'why', (tester) async {+ final server = twoMachines();+ pause(server, 'ken-mac');+ final c = await show(tester, server);+ expect(+ find.text(+ "Kens-MacBook is paused. Start your Buddy again once it's "+ 'back.',+ ),+ findsOneWidget,+ );+ expect(tester.widget<TextButton>(startAgain).onPressed, isNull);+ expect(commands(server, 'buddy.remove'), isEmpty);+ await close(tester, c);+ });++ testWidgets('a Start bar left by a refused start keeps its machine while '+ 'it cannot be used, until another is chosen', (tester) async {+ final server = twoMachines();+ server.unknownCommand = (command) => command['type'] == 'buddy.create';+ final c = await show(tester, server);+ await tester.tap(startAgain);+ await tester.pumpAndSettle();+ expect(c.buddy(SuperTabController.kSwarmBuddyKey), isNull);+ // Its machine is paused since: it stays chosen, and says so.+ server.unknownCommand = null;+ pause(server, 'ken-mac');+ await c.refresh();+ await tester.pumpAndSettle();+ expect(+ find.descendant(of: startMachine, matching: find.text('Kens-MacBook')),+ findsOneWidget,+ );+ expect(+ inStart(+ find.text(+ "Kens-MacBook is paused. Your Buddy starts there "+ 'once it\'s back, or choose another machine.',+ ),+ ),+ findsOneWidget,+ );+ expect(+ tester+ .widget<FilledButton>(+ inStart(find.widgetWithText(FilledButton, 'Start')),+ )+ .onPressed,+ isNull,+ );+ // Another machine, chosen by hand, starts it there.+ await tester.tap(startMachine);+ await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const ValueKey('super-buddy-machine-option-peer-mini')),+ );+ await tester.pumpAndSettle();+ await tester.tap(inStart(find.widgetWithText(FilledButton, 'Start')));+ await tester.pumpAndSettle();+ expect(commands(server, 'buddy.create').last, {+ 'type': 'buddy.create',+ 'machineId': 'peer-mini',+ 'engine': 'codex',+ });+ await close(tester, c);+ });++ testWidgets('a removal whose answer was lost leaves the Start bar on its '+ 'machine and engine', (tester) async {+ final server = twoMachines();+ server.loseReply = true;+ final c = await show(tester, server);+ await tester.tap(startAgain);+ await tester.pumpAndSettle();+ // The removal went through; its answer did not come back, so no start+ // was sent after it.+ expect(commands(server, 'buddy.remove'), hasLength(1));+ expect(commands(server, 'buddy.create'), isEmpty);+ await c.refresh();+ await tester.pumpAndSettle();+ expect(c.buddy(SuperTabController.kSwarmBuddyKey), isNull);+ expect(+ find.descendant(of: startMachine, matching: find.text('Kens-MacBook')),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('super-buddy-start-engine')),+ matching: find.text('Codex'),+ ),+ findsOneWidget,+ );+ await close(tester, c);+ });+ });}diff --git a/desktop/test/super_tab_controller_test.dart b/desktop/test/super_tab_controller_test.dartindex cb5ed81d8..be20a4933 100644--- a/desktop/test/super_tab_controller_test.dart+++ b/desktop/test/super_tab_controller_test.dart@@ -479,4 +479,21 @@ void main() {expect(controller.messages('lead'), isEmpty);expect(controller.canWrite, isFalse);});++ // Task #3256 (review of #3171): the Buddy bar reads its chat from the end+ // on every build; [newestFirst] does so without copying what is held.+ test('newestFirst reads what messages lists, newest first', () async {+ final server = ConversationServer()+ ..append('first')+ ..append('a notice nobody reads')+ ..append('last');+ server.messages[1]['source'] = {'kind': 'update-request'};+ final c = server.controller();+ await c.refresh();+ await c.select('lead');+ expect(c.newestFirst('lead').map((m) => m.text), ['last', 'first']);+ expect(c.newestFirst('lead'), c.messages('lead').reversed);+ expect(c.newestFirst('nothing held'), isEmpty);+ c.dispose();+ });}diff --git a/docs/plans/2026-11-05-buddy-switch-start-again-plan.md b/docs/plans/2026-11-05-buddy-switch-start-again-plan.mdindex c8cee3e9b..4f8d8377c 100644--- a/docs/plans/2026-11-05-buddy-switch-start-again-plan.md+++ b/docs/plans/2026-11-05-buddy-switch-start-again-plan.md@@ -2,7 +2,7 @@**Goal:** When a Buddy's model switch is refused by the Buddy guard, its owner reads why in plain words ("Start your Buddyagain to switch its model") instead of `its computer could not switch it (SWARM_SKILL_FAILED)`, and Desktop offers a-one-click Start again.+one-click Start again once a switch has failed for that reason.**Architecture:** The switch relaunches the Buddy through the daemon's `agent_retarget`; the relaunch's launch overrides(cli/src/lib/launchOverrides.ts) run `prepareBuddyFolder` (cli/src/lib/swarmSkills.ts), whose guard throws one of two fixedsentences, and return `SWARM_SKILL_FAILED` with that sentence as the detail. `refusal()` in cli/src/superTabs/buddyModel.ts@@ -34,10 +34,18 @@ with no execution handoff.- [ ] Watch it fail, commit.- [ ] `refusal()` reads the detail of a `SWARM_SKILL_FAILED` answer for the two sentences. Test passes, commit.-### 2. Desktop offers Start again before a switch (after Scholes's yes)-**Files:** desktop/lib/super_tabs/buddies.dart, desktop/test/-- [ ] Failing widget test: a Swarm Buddy bar whose Buddy's owner isn't recorded shows "Start your Buddy again to switch its- model." with a Start again button that calls `addBuddy` for its machine and engine, and no model picker.+### 2. Desktop offers Start again after a failed switch (Scholes approved the mockup; PM's scope ruling, 11-05)+**Files:** desktop/lib/super_tabs/buddies.dart, desktop/test/super_tab_buddy_model_test.dart+**Scope:** the Desktop files only. The machine does not report a missing owner record before a switch: Desktop shows the+offer once a switch has failed for that reason (River: it only affects Buddies started before 0.5.40, which isn't worth+more surface).+**Signal:** the newest system line by the current Buddy agent in its Swarm Buddy chat is the backend's+"Couldn't switch your Buddy: Start your Buddy again to switch its model…" (task 1's words), and no switch is under way.+A later line by that agent (a success, another failure) settles it, and a Buddy started again is a new agent, so a line+written by an earlier Buddy never shows the offer.+**Start again:** a running Buddy refuses a second start (backend BUDDY_EXISTS), so it is removed and then started on the+same machine and engine, which is the replacement a down Buddy's Start again already does. Its chat and its name stay.+- [ ] Failing widget test: the bar shows "Start your Buddy again to switch its model." with Start again, which sends+ buddy.remove then buddy.create for its machine and engine; the offer is gone for the new Buddy. Not shown for+ another reason, after a later line, while a switch is under way, or for a line by an earlier Buddy.- [ ] Watch it fail, commit; build the row; test passes, commit.-- The signal Desktop reads for "owner not recorded" is decided with the PM in the task (it needs the Buddy's machine to- report it, outside this task's files today).diff --git a/docs/plans/2026-11-05-engine-suspension-plan.md b/docs/plans/2026-11-05-engine-suspension-plan.mdnew file mode 100644index 000000000..a42a9e06d--- /dev/null+++ b/docs/plans/2026-11-05-engine-suspension-plan.md@@ -0,0 +1,74 @@+# Engine and machine suspension implementation plan++> The Engineer implements this plan sequentially, test first, with one independent review of the complete pull request. Commit each failing test before its implementation.++**Goal:** Keep usable engines available while backing off repeated engine failures and unresponsive machines.++**Architecture:** Classify only known engine failures from existing start receipts; unknown/setup failures remain failed starts without engine penalties. Retain bounded backoff state on the existing machine part, with separate engine and machine cooldowns. Admission and both read projections expose the same cooldown decision; CLI routing explains setup failures without excluding otherwise usable engines.++**Tech Stack:** TypeScript, Vitest, existing MongoDB machine parts and guarded transactions.++**Spec:** Swarm task #3293, “Engine suspension counts only the engine's own failures, and backs off instead of a flat 6 hours,” requested by Ken on 2026-11-05. Requirements: only engine launch/exit/question/sign-in failures count against an engine; clone/token/folder/commit/tool/model/permission-flag failures do not. Three-minute pickup failures count against the machine across engines. Two failures suspend; cooldowns progress 30m, 1h, 2h, 4h, 8h, 12h (cap), reset by success. A signed-in reading clears a sign-in suspension even when quota is unknown. Owner resume remains available.++## Global Constraints++- Scope: backend Super Tabs and CLI routing notes; no Swarm logic in `cli/src/core`.+- Preserve raw failure audience rules; route notes contain fixed categories, never raw paths, tokens or terminal text.+- No real CLI sign-out, no production writes, no new runtime dependencies or timers.+- Keep current two-failure threshold; ignored failures neither increment nor reset it. An active suspension produces one notice and does not accumulate another penalty.+- Backend unit suite and focused engine-health integrations before Ready, as explicitly requested in the task. Full Super Tab integration suite runs in PR CI only.+- One independent review. Integrator owns batched merge and release, outside 09:00–10:00 VN and within the release window.+- PR body starts: Requested by 0xKen15 through Harness.++## Design++1. **Growth:** At most one counter, capped backoff level and active suspension per supported engine, plus one set for the machine. Success removes its state; owner resume clears its selected engine and machine state, preserving other engine suspensions; expiry removes active suspensions but retains bounded backoff levels until success/removal. Machine removal/account replacement deletes all health state. Saving settings preserves it.+2. **Concurrency:** Existing guarded machine-part writes serialize failure receipts, successes, sweeps and readings. Commands count the first failure only; a late host report cannot count a server timeout twice. Fast readings fall back to the full transaction whenever a suspension changes.+3. **Read cost:** No new query, scan, history load or polling. Existing machine reads carry bounded counters; derived reads return fixed suspension sentences. CLI uses the starts it already reads.+4. **Scale:** Cost remains linear in listed machines and constant per engine, even after arbitrarily many failures. Measure a fixed machine-health workload before/after; track existing start failure notices and machine-part byte size. No growing failure history is added.+5. **Compatibility:** Extend existing suspension records with optional duration/cause and add optional backoff/machine state. Legacy `{at,fine}` records retain their six-hour expiry and old recovery rule because their cause is unknown. Both `store.ts` and `read/views.ts` expose machine cooldowns and existing per-engine refusal strings; old clients still see all engines suspended. New CLI tolerates old servers with no machine field. Review seats use the same suspension projection. Legacy pending failure counters without attribution are ignored on the next engine failure. No native launch contract changes.+6. **Migration/rollback:** Backend first, CLI second; no schema/index migration or production data rewrite. Old backend ignores additive machine/backoff fields and treats engine entries with its existing six-hour semantics; rollback therefore restores the old policy, not data loss. Re-contribution on an old backend can discard new optional fields; document this operational limitation. Fixture rows cover legacy shape.+7. **Audience:** Existing machine visibility and failure-reason predicates remain authoritative. New derived messages reveal only cooldown scope/duration. No copied raw failure reasons.+8. **Identity:** All actions keep existing authenticated host/owner checks. No sign-in, credential, account or execution identity changes.+9. **Failure:** Start failures retain their original reason and recipients. Suspension notices occur once and routing/admission agree. Ignored failures remain visible as route notes; unknown text is conservatively uncounted.+10. **Platforms:** Backend on Linux; pure CLI routing on macOS/Linux/Windows. No process spawning or platform-specific behavior changes.++## Review Focus++- Real setup errors contain words like “token,” “launch” and “sign in”; only known engine-specific summaries count (task 1).+- Repeated expired cooldowns retain escalation through machine readings and settings saves, and success resets only the appropriate engine plus machine (tasks 2–3).+- Timeouts of different engines combine at machine level; grid starts cannot bypass a machine cooldown (task 3).+- A healthy reading clears sign-in failures only, not a different launch/question failure; legacy records remain readable (task 2).+- A timeout followed by its host's failure is counted once; owner resume permissions and public reason redaction remain intact (task 3). Owner resume lifts the machine cooldown so admission can recover, without clearing unrelated engine suspensions.++### Task 1: Attribute failures to engines precisely++**Files:** `backend/src/superTabs/engineHealth.ts`, `engineHealth.test.ts`.++**Interfaces:** Keep `noteStartFailed(state, start, now): string | null`; add a private classification of known engine launch/exit/question/sign-in failures, leaving unknown/setup errors uncounted.++- [x] Add table-driven negative cases for clone, GitHub token, missing folder/commit/tool, unavailable model, permission flags, removed/moved machines and unknown request/account failures; positive cases use real native exit and hidden-screen summaries.+- [x] Commit tests; run `npm test -- src/superTabs/engineHealth.test.ts --maxWorkers=2` and retain failing evidence.+- [x] Implement conservative classification; run the same test plus direct command/liveness callers; commit and push.++### Task 2: Back off engine failures and recover by cause++**Files:** `backend/src/superTabs/engineHealth.ts`, `machines.ts`, `commands.ts`, `engineHealth.test.ts`, `commands.test.ts`, `backend/integration/superTabs.test.ts`.++**Interfaces:** Extend `engineSuspensions` with optional `durationMs` and `cause`; retain bounded `engineBackoff` per engine. Existing `readingClearsSuspensions`, `noteStartSucceeded`, `resumeEngine`, `engineUnusable`, `suspendedEngines` remain entry points.++- [x] Test literal durations 30m/1h/2h/4h/8h/12h/12h across expiry and readings; test success reset, owner resume, settings preservation and legacy records.+- [x] Test signed-in plus unknown quota clears sign-in cause only; mixed failures must not clear a launch failure.+- [x] Commit failing tests and capture red; implement duration/cause/reset semantics and settings preservation, run focused tests, commit and push green.++### Task 3: Machine timeouts and route explanations++**Files:** `backend/src/superTabs/{engineHealth,machines,commands,store}.ts`, `backend/src/superTabs/read/{views,contract}.ts`, their existing tests, `backend/integration/superTabs.test.ts`, `cli/src/superTabs/{route,routeCommand}.ts`, corresponding specs.++**Interfaces:** Add bounded machine timeout counters/backoff/suspension and `machineSuspensionReason(machine, now): string | null`. Server exposes optional `machineSuspended` plus per-engine reasons for older clients. CLI `unreadyPool` treats the machine reason as an all-engine refusal; route notes use fixed descriptions of recent setup failures.++- [x] Test alternating-engine timeouts, one notice, double-report suppression, successful start reset, expiry/backoff, grid admission and preservation across re-contribution.+- [x] Test both read projections and persisted host readings; test route all-engine refusal and safe setup notes while candidates stay available.+- [x] Commit failing tests and capture red; implement through existing command/read paths, run affected tests and commit/push green.+- [x] Run backend unit suite, focused Super Tab engine-health integrations, CLI routing specs and both typechecks with bounded workers/timeouts. Full integration and CLI suites remain automatic PR CI.+- [ ] Record red/green evidence and timings in a PR comment, mark Ready, request the Integrator's independent review, and resolve findings.diff --git a/docs/plans/2026-11-05-phone-project-rows-unread-plan.md b/docs/plans/2026-11-05-phone-project-rows-unread-plan.mdnew file mode 100644index 000000000..af276f50f--- /dev/null+++ b/docs/plans/2026-11-05-phone-project-rows-unread-plan.md@@ -0,0 +1,64 @@+# Phone project rows read as Desktop's Implementation Plan++**Goal:** A project row on the phone's Home stops being bold (and loses its dot) once the person has read the project's+chat, on the phone or on Desktop, as Desktop's sidebar row does (task #3268, Dee 11-05).++**Architecture:** The phone's `swarmProjectNews` (mobile/lib/swarm/swarm_unread.dart) bolds a project while its project+chat or any open task has any message past the read mark, agents' progress and system rows included. Desktop's row+(desktop/lib/super_tabs/project_sidebar.dart `_row`, since #2427 and #2638) is bold only for the project's own chat: a+person's message past the mark (`unreadForPeople`, the chat's `lastPersonSequence`) or a tag of the reader there. Busy+projects always have a task with a fresh agent post, so the phone's row never clears. The phone takes Desktop's rule;+tags and decisions in tasks still keep the project under Home's Unread and Mentions filters (`hasWaitingTag`), as+Desktop's `_hasUnread` keeps a project with tags in its work.++**Tech Stack:** Flutter (mobile/), flutter_test with the Swarm fixture (mobile/test/swarm/swarm_fixture.dart).++**Spec:** task #3268 brief; Desktop's rule in project_sidebar.dart `_row` and controller.dart `unreadForPeople`.++## Global Constraints++- Phone only: the server already sends `lastPersonSequence` and read marks in first loads and in polls (light groups+ leave them out, and the phone keeps a group's last whole copy), and Desktop already reads by this rule.+- Read marks from another device arrive in a poll's `readMarks`; the tests drive both the first load and a poll.+- A chat's own row inside the project (`swarmChatNews`) is unchanged, as Desktop's chat rows are.++## Review Focus++- The project row reads its own chat only, by `lastPersonSequence` against the higher of the server's and the phone's+ marks; muted never bold.+- Tags and decisions in tasks no longer bold the row, but `hasWaitingTag` still lists the project under the filters.++## Task 1: The project row reads as Desktop's++**Files:** mobile/lib/swarm/swarm_unread.dart, mobile/lib/swarm/swarm_read_marks.dart,+mobile/test/swarm/swarm_unread_test.dart, mobile/test/swarm/swarm_project_rows_read_test.dart (new), mobile/lib/swarm/swarm_home_list.dart,+mobile/test/swarm/swarm_home_read_sync_test.dart (new), existing Home and notification tests++**Interfaces:** `SwarmReadMarks.unreadForPeople(SuperTabConversation)`; `swarmProjectNews` keeps its type.++- [x] Failing tests: a project whose open task has agent posts past the mark is not bold; a project chat read on+ Desktop (a poll carrying the server's moved mark) clears the row; a project chat read on the phone clears it and sends+ the mark Desktop reads; an agent-only post in the project chat does not bold it, a person's does; tags in the project+ chat still bold it with its count; tags in a task leave the row quiet but `hasWaitingTag` set.+- [x] Run them; watch them fail.+- [x] `unreadForPeople` and the new `swarmProjectNews`; update the old tests that wrote down the old rule.+- [x] Run swarm_unread_test.dart, the new test and the Home tests that read project news.+++## Completed validation and review notes++- The visible change follows the approved rule: after reading, `#openharness •` (bold) becomes+ `#openharness` (normal weight); an unread person message in `#design •` remains bold.+- Home widget tests exercise Desktop marks arriving alongside whole changed groups, and tapping the phone's+ project chat then returning to Home. Both run in light and dark using a fake account, in-memory read marks+ and an in-memory backend. Read-boundary, first-load, older server-mark, thread-only and mute cases have+ focused reader tests. Desktop's existing remote-mark/sidebar tests pass with the same rule.+- Task tags no longer bold the project. They still keep it in the filters and out of Other projects; the folding+ condition now uses the same news predicate as the filters. The existing tests of the previous bolding policy+ were updated with explicit person-message counters where an unread project is intended.+- Screenshot evidence is in `assets/phone-project-unread/`: before and after the production fix for each+ device's read flow in both themes. These are offscreen Flutter renders at 390 × 844 points, not simulator+ captures: this Team Mac has no simulator runtimes. This uses the project's Team-account fallback;+ a simulator run would additionally cover the native renderer/navigation environment.+- No storage, server, wire-format or migration change. iOS and Android share the changed Dart code.+ Rollback is reverting the client change; Desktop and the backend need no rollout changes.diff --git a/docs/plans/assets/phone-project-unread/after-home-Desktop-dark.png b/docs/plans/assets/phone-project-unread/after-home-Desktop-dark.pngnew file mode 100644index 000000000..09e2f7e78Binary files /dev/null and b/docs/plans/assets/phone-project-unread/after-home-Desktop-dark.png differdiff --git a/docs/plans/assets/phone-project-unread/after-home-Desktop-light.png b/docs/plans/assets/phone-project-unread/after-home-Desktop-light.pngnew file mode 100644index 000000000..28a79a117Binary files /dev/null and b/docs/plans/assets/phone-project-unread/after-home-Desktop-light.png differdiff --git a/docs/plans/assets/phone-project-unread/after-home-phone-dark.png b/docs/plans/assets/phone-project-unread/after-home-phone-dark.pngnew file mode 100644index 000000000..0532e8b58Binary files /dev/null and b/docs/plans/assets/phone-project-unread/after-home-phone-dark.png differdiff --git a/docs/plans/assets/phone-project-unread/after-home-phone-light.png b/docs/plans/assets/phone-project-unread/after-home-phone-light.pngnew file mode 100644index 000000000..8051e5717Binary files /dev/null and b/docs/plans/assets/phone-project-unread/after-home-phone-light.png differdiff --git a/docs/plans/assets/phone-project-unread/before-home-Desktop-dark.png b/docs/plans/assets/phone-project-unread/before-home-Desktop-dark.pngnew file mode 100644index 000000000..8b9985bb4Binary files /dev/null and b/docs/plans/assets/phone-project-unread/before-home-Desktop-dark.png differdiff --git a/docs/plans/assets/phone-project-unread/before-home-Desktop-light.png b/docs/plans/assets/phone-project-unread/before-home-Desktop-light.pngnew file mode 100644index 000000000..27fbe39e5Binary files /dev/null and b/docs/plans/assets/phone-project-unread/before-home-Desktop-light.png differdiff --git a/docs/plans/assets/phone-project-unread/before-home-phone-dark.png b/docs/plans/assets/phone-project-unread/before-home-phone-dark.pngnew file mode 100644index 000000000..8b9985bb4Binary files /dev/null and b/docs/plans/assets/phone-project-unread/before-home-phone-dark.png differdiff --git a/docs/plans/assets/phone-project-unread/before-home-phone-light.png b/docs/plans/assets/phone-project-unread/before-home-phone-light.pngnew file mode 100644index 000000000..27fbe39e5Binary files /dev/null and b/docs/plans/assets/phone-project-unread/before-home-phone-light.png differdiff --git a/mobile/lib/swarm/swarm_home_list.dart b/mobile/lib/swarm/swarm_home_list.dartindex 34ede7fb9..abd7e5bdf 100644--- a/mobile/lib/swarm/swarm_home_list.dart+++ b/mobile/lib/swarm/swarm_home_list.dart@@ -70,8 +70,7 @@ SwarmHomeLists swarmHomeLists(} else if (sort == SwarmHomeSort.sections &&active != null &&now.difference(active) > swarmQuietAfter &&- !project.news.bold &&- project.news.tags == 0) {+ !_hasNews(project)) {quiet.add(project);} else {recent.add(project);diff --git a/mobile/lib/swarm/swarm_read_marks.dart b/mobile/lib/swarm/swarm_read_marks.dartindex abec80e02..8fbe35867 100644--- a/mobile/lib/swarm/swarm_read_marks.dart+++ b/mobile/lib/swarm/swarm_read_marks.dart@@ -193,6 +193,14 @@ class SwarmReadMarks extends ChangeNotifier {max(server, max(_marks[group.id] ?? 0, _held[group.id] ?? 0));}+ /// The desktop's project-row rule: only a person's main-stream message+ /// past the read mark, never agents' progress or system notices.+ bool unreadForPeople(SuperTabConversation group) =>+ _loaded &&+ _started &&+ !swarmMuted(reader, group) &&+ group.lastPersonSequence > (readThrough(group.id) ?? 0);+/// How far the person has read [conversationId]: the higher of the/// server's mark and this phone's; null until the phone's are read back,/// and once access is lost.diff --git a/mobile/lib/swarm/swarm_unread.dart b/mobile/lib/swarm/swarm_unread.dartindex 1fe53d71b..b5fa6a3cf 100644--- a/mobile/lib/swarm/swarm_unread.dart+++ b/mobile/lib/swarm/swarm_unread.dart@@ -88,14 +88,13 @@ const _unknown = 1 << 52;bool swarmUnreadShown(SwarmReader reader, SuperTabConversation group) =>!swarmMuted(reader, group) && (reader.readMarks?.unread(group) ?? false);-/// Each project's row with something new, by project id: bold while its-/// project chat or any of its open work shows unread, as the desktop's-/// sidebar reads a collapsed project — never for closed work, a private chat-/// or the person's Buddy chat, which has a row of its own — or while tags-/// count there. Its number counts only its project chat's tags, which opening-/// the project reads; decisions asked there are on that chat's own row-/// ([swarmChatCount]) and in Activity (#2927). Task tags stay on their own rows and in-/// Activity. A tag counts only in a listed chat under its own project.+/// Each project's row with something new, by project id: bold only for a+/// person's message or a tag in its own chat, as the desktop's sidebar+/// (#2427, #2638). Agents' progress and system notices never keep it bold.+/// Its number counts only that chat's tags, which opening the project reads.+/// Decisions and open task tags keep it under Home's filters, without+/// bolding it; their counts stay on their own rows and in Activity (#2927).+/// Closed work, private chats and Buddy chats never contribute./// One pass over the Swarm's chats for every project.Map<String, SwarmProjectNews> swarmProjectNews(SwarmReader reader,@@ -114,6 +113,10 @@ Map<String, SwarmProjectNews> swarmProjectNews(final unread = <String>{};final tags = <String, int>{};final hasWaitingTag = <String>{};+ final projectChats = {+ for (final project in snapshot.projects)+ project.id: project.leadConversationId,+ };for (final group in snapshot.conversations) {if (group.closed ||group.audience != null ||@@ -121,9 +124,13 @@ Map<String, SwarmProjectNews> swarmProjectNews(continue;}final projectId = group.projectId;- if (!unread.contains(projectId) && swarmUnreadShown(reader, group)) {+ final ownChat = group.id == projectChats[projectId];+ if (ownChat && (reader.readMarks?.unreadForPeople(group) ?? false)) {unread.add(projectId);}+ // Most task updates are agents' progress, with no tags or decisions.+ if (!waiting.containsKey(group.id) && !asked.containsKey(group.id))+ continue;final count = _countIn(reader,group,@@ -131,9 +138,8 @@ Map<String, SwarmProjectNews> swarmProjectNews(asked[group.id] ?? 0,);if (count > 0) {- unread.add(projectId);hasWaitingTag.add(projectId);- if (group.id == snapshot.projectById(projectId)?.leadConversationId) {+ if (ownChat) {// Its chat's tags alone (#2927): decisions are in Activity and on// the chat's own row.tags[projectId] = _countIn(@@ -142,13 +148,14 @@ Map<String, SwarmProjectNews> swarmProjectNews(waiting[group.id] ?? const [],0,);+ if (tags[projectId]! > 0) unread.add(projectId);}}}return {- for (final id in {...unread, ...tags.keys})+ for (final id in {...unread, ...hasWaitingTag})id: (- bold: true,+ bold: unread.contains(id),tags: tags[id] ?? 0,hasWaitingTag: hasWaitingTag.contains(id),),diff --git a/mobile/test/swarm/swarm_chat_notify_test.dart b/mobile/test/swarm/swarm_chat_notify_test.dartindex 694ab0195..3659db2dc 100644--- a/mobile/test/swarm/swarm_chat_notify_test.dart+++ b/mobile/test/swarm/swarm_chat_notify_test.dart@@ -319,7 +319,7 @@ void main() {final r = await unreadAndTagged();expect(news(r), (bold: true, tags: 1));expect(swarmProjectNews(r.reader, r.asks), {- project: (bold: true, tags: 0, hasWaitingTag: true),+ project: (bold: false, tags: 0, hasWaitingTag: true),});final held = hold(r.swarm);diff --git a/mobile/test/swarm/swarm_home_list_test.dart b/mobile/test/swarm/swarm_home_list_test.dartindex 62d84d645..b07da3ac9 100644--- a/mobile/test/swarm/swarm_home_list_test.dart+++ b/mobile/test/swarm/swarm_home_list_test.dart@@ -291,12 +291,17 @@ void main() {news: (bold: true, tags: 0, hasWaitingTag: false),),project('d', minutes: 60 * 32),+ project(+ 'task-tag',+ minutes: 60 * 33,+ news: (bold: false, tags: 0, hasWaitingTag: true),+ ),],pins: const {},now: now,);- expect(ids(lists.recent), ['a', 'b', 'c']);+ expect(ids(lists.recent), ['a', 'b', 'c', 'task-tag']);expect(ids(lists.quiet), ['d']);});diff --git a/mobile/test/swarm/swarm_home_read_sync_test.dart b/mobile/test/swarm/swarm_home_read_sync_test.dartnew file mode 100644index 000000000..1e52564fe--- /dev/null+++ b/mobile/test/swarm/swarm_home_read_sync_test.dart@@ -0,0 +1,274 @@+import 'dart:convert';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++// These tests drive Home, the real reader, and the project chat against an+// in-memory backend. Optional screenshots use the same data and assertions+// before and after the fix; no account or machine is contacted.+final shots = Platform.environment['SWARM_READ_SYNC_SHOTS'];++void main() {+ setUpAll(() async {+ if (shots == null || !Platform.isMacOS) return;+ final sf = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),+ );+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {+ await (FontLoader(family)..addFont(Future.value(sf))).load();+ }+ final mono = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),+ );+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {+ await (FontLoader(family)..addFont(Future.value(mono))).load();+ }+ final manifest =+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;+ for (final entry in manifest.cast<Map<String, dynamic>>()) {+ final loader = FontLoader(entry['family'] as String);+ for (final font in (entry['fonts'] as List).cast<Map>()) {+ loader.addFont(rootBundle.load(font['asset'] as String));+ }+ await loader.load();+ }+ });++ const names = [+ 'openharness',+ 'radio',+ 'computer',+ 'harness-gtm',+ 'pod',+ 'lamp',+ 'pcb',+ 'design',+ ];+ final now = DateTime.utc(2026, 11, 5, 10);++ Map<String, dynamic> chat(String name, {int personSequence = 4}) => {+ ...groupData('chat-$name', title: name, lastMessageSequence: 9),+ 'projectId': name,+ 'lastMainSequence': 9,+ 'lastPersonSequence': personSequence,+ };++ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Design crew', 'ownerId': me},+ ],+ 'next': null,+ };+ final load = firstLoad(+ head: headData(+ projects: [+ for (final name in names)+ {+ 'id': name,+ 'name': name,+ 'ownerId': me,+ 'leadConversationId': 'chat-$name',+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ ),+ groups: [+ for (final name in names) ...[+ chat(name),+ {+ ...groupData('task-$name', lastMessageSequence: 12),+ 'projectId': name,+ 'lastMainSequence': 12,+ 'lastPersonSequence': 0,+ },+ ],+ ],+ derived: {+ 'readMarks': {for (final name in names) 'chat-$name': 1},+ },+ );+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...load,+ 'groups': [+ for (final group in load['groups'] as List)+ {...group as Map, 'changedAt': now.millisecondsSinceEpoch},+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/conversations/chat-openharness/read'] = (+ body,+ ) => {'sequence': body!['sequence']};+ fake.routes['/api/super-tabs/$tab/conversations/chat-openharness/messages'] =+ (_) => {+ 'messages': [+ {+ 'id': 'person-message',+ 'conversationId': 'chat-openharness',+ 'sequence': 4,+ 'author': {'kind': 'person', 'id': me, 'name': 'Dee'},+ 'text': 'Please check the phone project rows.',+ 'createdAt': now.toIso8601String(),+ },+ {+ 'id': 'agent-message',+ 'conversationId': 'chat-openharness',+ 'sequence': 9,+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},+ 'text': 'The tests are ready for review.',+ 'createdAt': now.toIso8601String(),+ },+ ],+ 'next': null,+ };+ return fake;+ }++ Finder row(String name) => find.byKey(ValueKey('swarm-project-$tab-$name'));+ Finder inside(String name, String key) =>+ find.descendant(of: row(name), matching: find.byKey(ValueKey(key)));++ void expectRead(WidgetTester tester, String name) {+ expect(row(name), findsOneWidget);+ expect(inside(name, 'swarm-project-unread'), findsNothing);+ expect(+ tester.widget<Text>(inside(name, 'swarm-project-name')).style!.fontWeight,+ isNot(FontWeight.w600),+ );+ }++ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {+ for (final device in ['Desktop', 'phone']) {+ testWidgets('Home clears after reading on $device (${palette.name})', (+ tester,+ ) async {+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ tester.view.padding = const FakeViewPadding(top: 141, bottom: 102);+ addTearDown(tester.view.reset);+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = palette.brightness;+ addTearDown(() {+ AppTheme.palette.value = HarnessPalette.graphite;+ AppTheme.brightness.value = Brightness.dark;+ });+ final fake = backend();+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => me,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ addTearDown(host.dispose);+ addTearDown(account.dispose);+ final boundary = GlobalKey();+ final navigator = GlobalKey<NavigatorState>();+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ navigatorKey: navigator,+ debugShowCheckedModeBanner: false,+ theme: buildAppTheme(brightness: palette.brightness),+ builder: (_, child) => SwarmScope(notifier: host, child: child!),+ home: SwarmPage(now: () => now),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(inside('openharness', 'swarm-project-unread'), findsOneWidget);++ if (device == 'Desktop') {+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ // A poll carries whole changed groups and the remote marks.+ groups: [+ for (final name in names)+ {+ ...part('chat-$name', 40, chat(name)),+ 'changedAt': now.millisecondsSinceEpoch,+ },+ ],+ derived: {+ 'readMarks': {+ for (final name in names.where((n) => n != 'design'))+ 'chat-$name': 4,+ },+ },+ );+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();+ } else {+ await tester.tap(row('openharness'));+ await tester.pumpAndSettle();+ expect(+ find.text('Please check the phone project rows.'),+ findsOneWidget,+ );+ expect(+ fake.calls.where(+ (c) =>+ c.method == 'POST' &&+ c.path.endsWith('/chat-openharness/read') &&+ (c.body?['sequence'] as int? ?? 0) >= 4,+ ),+ isNotEmpty,+ );+ navigator.currentState!.pop();+ await tester.pumpAndSettle();+ }++ // Capture before asserting so the failing baseline shows the bug.+ if (shots != null) {+ await tester.runAsync(() async {+ final image =+ await (boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/home-$device-${palette.brightness.name}.png')+ .writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ }+ expectRead(tester, 'openharness');+ if (device == 'Desktop') {+ for (final name in names.skip(1).where((n) => n != 'design')) {+ expectRead(tester, name);+ }+ }+ // A genuinely unread person's message still stands out.+ expect(inside('design', 'swarm-project-unread'), findsOneWidget);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ });+ }+ }+}diff --git a/mobile/test/swarm/swarm_home_test.dart b/mobile/test/swarm/swarm_home_test.dartindex b22ea40a0..39db24a25 100644--- a/mobile/test/swarm/swarm_home_test.dart+++ b/mobile/test/swarm/swarm_home_test.dart@@ -904,7 +904,7 @@ void main() {);});- testWidgets('a project with a task-chat tag stays bold without a number; '+ testWidgets('a project with a task-chat tag stays quiet without a number; ''the rest are quiet; each on one line, with no people and no time', (tester,) async {@@ -913,7 +913,7 @@ void main() {const mobileRow = 'swarm-project-$tab-$project';const webRow = 'swarm-project-$tab-$web';- expect(weightOf(tester, mobileRow, 'Mobile'), AppFont.semibold);+ expect(weightOf(tester, mobileRow, 'Mobile'), isNot(AppFont.semibold));expect(inside(mobileRow, find.byType(SwarmTags)), findsNothing);expect(find.bySemanticsLabel(RegExp('1 mention')), findsNothing);expect(weightOf(tester, webRow, 'Web'), isNot(AppFont.semibold));@@ -940,31 +940,35 @@ void main() {semantics.dispose();});- testWidgets('a project with a chat read since is bold, with a dot and no '- 'count', (tester) async {- final fake = backend();- final host = await pump(tester, fake);- moveOn(fake, {- webLead: {- ...groupData(- webLead,- title: 'Web',- agentIds: ['agent-cleo'],- leadId: 'agent-cleo',- lastMessageSequence: 1,- ),- 'projectId': web,- },- });- await host.session!.inbox.refresh();- await tester.pumpAndSettle();+ testWidgets(+ 'a person writing in the project chat makes it bold, with a dot and no '+ 'count',+ (tester) async {+ final fake = backend();+ final host = await pump(tester, fake);+ moveOn(fake, {+ webLead: {+ ...groupData(+ webLead,+ title: 'Web',+ agentIds: ['agent-cleo'],+ leadId: 'agent-cleo',+ lastMessageSequence: 1,+ ),+ 'projectId': web,+ 'lastPersonSequence': 1,+ },+ });+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();- const webRow = 'swarm-project-$tab-$web';- expect(weightOf(tester, webRow, 'Web'), AppFont.semibold);- expect(inside(webRow, key('swarm-project-unread')), findsOneWidget);- expect(inside(webRow, find.textContaining('@')), findsNothing);- expect(inside(webRow, find.byType(SwarmTags)), findsNothing);- });+ const webRow = 'swarm-project-$tab-$web';+ expect(weightOf(tester, webRow, 'Web'), AppFont.semibold);+ expect(inside(webRow, key('swarm-project-unread')), findsOneWidget);+ expect(inside(webRow, find.textContaining('@')), findsNothing);+ expect(inside(webRow, find.byType(SwarmTags)), findsNothing);+ },+ );testWidgets('projects newest first, the time off the row', (tester) async {final now = DateTime.utc(2026, 10, 29, 10);@@ -1313,8 +1317,8 @@ void main() {);expect(weightOf(tester, 'swarm-project-$tab-$project', 'Mobile'),- AppFont.semibold,- reason: 'the tag waiting on the person makes it bold',+ isNot(AppFont.semibold),+ reason: 'a task tag keeps it listed without bolding its project chat',);});diff --git a/mobile/test/swarm/swarm_home_view_test.dart b/mobile/test/swarm/swarm_home_view_test.dartindex 81464c205..abcfa390b 100644--- a/mobile/test/swarm/swarm_home_view_test.dart+++ b/mobile/test/swarm/swarm_home_view_test.dart@@ -315,7 +315,7 @@ void main() {group('Home', () {final mobileAt = now.subtract(const Duration(hours: 2));- /// One Swarm: Mobile, with g1 unread; and Web, read and quiet for+ /// One Swarm: Mobile, with its project chat unread; and Web, read and quiet for/// [webAgo], with what waits in [mentions].FakeSwarm backend({Duration webAgo = const Duration(hours: 1),@@ -355,6 +355,10 @@ void main() {],),groups: [+ {+ ...groupData(leadChat, title: 'Mobile', lastMessageSequence: 5),+ 'lastPersonSequence': 5,+ },groupData('g1', title: 'Fix login', lastMessageSequence: 5),{...groupData(webLead, title: 'Web', lastMessageSequence: 1),diff --git a/mobile/test/swarm/swarm_mark_all_test.dart b/mobile/test/swarm/swarm_mark_all_test.dartindex 600482eba..b34ae125c 100644--- a/mobile/test/swarm/swarm_mark_all_test.dart+++ b/mobile/test/swarm/swarm_mark_all_test.dart@@ -516,38 +516,49 @@ void main() {return on;}- testWidgets('Mark all read tells how many with Undo; Undo puts the bold '- 'back and sends nothing, and with nothing unread it is greyed', (- tester,- ) async {- final fake = backend();- await pump(tester, fake);- expect(bold(tester, project), isTrue);- expect(await markable(tester), isTrue);-- await markAll(tester);- await tester.pump();- await tester.pump(const Duration(milliseconds: 500));+ testWidgets(+ 'Mark all read tells how many with Undo; task reads are restored '+ 'without bolding the read project, and nothing unread greys the action',+ (tester) async {+ final fake = backend();+ final host = await pump(tester, fake);+ final reader = host.session!.inbox.reader(tab)!;+ bool taskUnread() =>+ reader.readMarks!.unread(reader.snapshot!.conversation('g1')!);+ // Only the tasks are unread; the project's own chat is already read.+ expect(taskUnread(), isTrue);+ expect(bold(tester, project), isFalse);+ expect(await markable(tester), isTrue);++ await markAll(tester);+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 500));- expect(find.text('Marked 2 chats read'), findsOneWidget);- expect(bold(tester, project), isFalse);- expect(await markable(tester), isFalse);+ expect(find.text('Marked 2 chats read'), findsOneWidget);+ expect(taskUnread(), isFalse);+ expect(bold(tester, project), isFalse);+ expect(await markable(tester), isFalse);- await tester.tap(find.text('Undo'));- await tester.pump();- await tester.pump(const Duration(seconds: 7));- await tester.pumpAndSettle();+ await tester.tap(find.text('Undo'));+ await tester.pump();+ await tester.pump(const Duration(seconds: 7));+ await tester.pumpAndSettle();- expect(marksSent(fake), isEmpty);- expect(bold(tester, project), isTrue);+ expect(marksSent(fake), isEmpty);+ expect(taskUnread(), isTrue);+ expect(bold(tester, project), isFalse);+ expect(await markable(tester), isTrue);- await markAll(tester);- await tester.pump();- await tester.pump(const Duration(seconds: 7));- await tester.pumpAndSettle();- expect(marksSent(fake), [('g1', 5), ('g2', 4)]);- expect(await markable(tester), isFalse);- });+ await markAll(tester);+ await tester.pump();+ await tester.pump(const Duration(seconds: 7));+ await tester.pumpAndSettle();+ expect(marksSent(fake), [('g1', 5), ('g2', 4)]);+ expect(taskUnread(), isFalse);+ expect(bold(tester, project), isFalse);+ expect(await markable(tester), isFalse);+ },+ );testWidgets('a chat muted on this phone a moment ago is not marked: the ''toast counts the rest, and with all muted the button greys', (diff --git a/mobile/test/swarm/swarm_project_rows_read_test.dart b/mobile/test/swarm/swarm_project_rows_read_test.dartnew file mode 100644index 000000000..118333442--- /dev/null+++ b/mobile/test/swarm/swarm_project_rows_read_test.dart@@ -0,0 +1,279 @@+import 'package:flutter_test/flutter_test.dart';++import 'package:harness_mobile/swarm/swarm_asks.dart';+import 'package:harness_mobile/swarm/swarm_read_marks.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_unread.dart';++import 'swarm_fixture.dart';++/// A project's row on Home reads as the desktop's sidebar row+/// (project_sidebar.dart `_row`, #2427, #2638): bold only for its own chat, a+/// person's message there past the reader's mark or a tag of theirs there.+/// Agents' progress in its tasks or its chat never keeps it bold, so a+/// project read on any device stops showing as unread (Dee, 11-05, #3268).+void main() {+ /// The project chat with its newest main-stream message at [main], the+ /// newest of them a person wrote at [person].+ Map<String, dynamic> lead({required int main, int person = 0}) => {+ ...groupData(+ leadChat,+ title: 'Mobile',+ agentIds: ['agent-lead'],+ leadId: 'agent-lead',+ lastMessageSequence: main,+ ),+ 'lastMainSequence': main,+ 'lastPersonSequence': person,+ };++ /// A task whose agents posted through [main], no person among them.+ Map<String, dynamic> busyTask(String id, {required int main}) => {+ ...groupData(id, title: 'Fix login', lastMessageSequence: main),+ 'lastMainSequence': main,+ };++ Map<String, dynamic> tag(String id, String conversationId, int sequence) => {+ 'id': id,+ 'messageSequence': sequence,+ 'projectId': project,+ 'projectName': 'Mobile',+ 'conversationId': conversationId,+ 'conversationTitle': 'Mobile',+ 'messageId': 'msg-$id',+ 'leadName': 'River',+ 'text': 'Look',+ 'createdAt': '2026-11-05T01:00:00.000Z',+ };++ /// The phone reading a Swarm whose first load holds [groups] and the+ /// server's [readMarks] from every device of the reader.+ Future<({FakeSwarm swarm, SwarmReader reader, SwarmAsks asks})> rig({+ List<Map<String, dynamic>> groups = const [],+ Map<String, int> readMarks = const {},+ List<Map<String, dynamic>> tags = const [],+ }) async {+ final swarm = FakeSwarm();+ final derived = {+ 'mentionsWaiting': tags.length,+ 'decisionsWaiting': 0,+ 'readMarks': readMarks,+ };+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: groups, derived: derived);+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: {'mentionsWaiting': tags.length});+ swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': tags,+ };+ swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ swarm.routes['/api/super-tabs/$tab/conversations/'] = (body) => {+ 'sequence': body!['sequence'],+ };+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: swarm.request,+ );+ final marks = reader.readMarks = SwarmReadMarks(reader, store: null);+ final asks = SwarmAsks(reader);+ addTearDown(() {+ asks.dispose();+ marks.dispose();+ reader.dispose();+ });+ await reader.refresh();+ await settle();+ return (swarm: swarm, reader: reader, asks: asks);+ }++ /// A poll in which [groups] moved and the server's marks [readMarks] moved.+ Future<void> poll(+ ({FakeSwarm swarm, SwarmReader reader, SwarmAsks asks}) r, {+ required int version,+ List<Map<String, dynamic>> groups = const [],+ Map<String, int> readMarks = const {},+ }) async {+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c$version',+ derived: {if (readMarks.isNotEmpty) 'readMarks': readMarks},+ groups: [for (final g in groups) part(g['id'] as String, version, g)],+ );+ await r.reader.refresh();+ await settle();+ }++ SwarmProjectNews? row(+ ({FakeSwarm swarm, SwarmReader reader, SwarmAsks asks}) r,+ ) => swarmProjectNews(r.reader, r.asks)[project];++ bool bold(({FakeSwarm swarm, SwarmReader reader, SwarmAsks asks}) r) =>+ row(r)?.bold ?? false;++ test('reading a project on Desktop clears its row on the phone after the '+ 'next poll, while its tasks keep getting agent posts', () async {+ final r = await rig(+ groups: [busyTask('g1', main: 2)],+ readMarks: {leadChat: 1, 'g1': 2},+ );+ // A person wrote in the project chat; an agent posts in its task.+ await poll(+ r,+ version: 20,+ groups: [lead(main: 4, person: 4), busyTask('g1', main: 6)],+ );+ expect(bold(r), isTrue, reason: "Dee hasn't read the person's message");++ // Desktop read the project chat: the server's mark comes in a poll.+ await poll(r, version: 21, readMarks: {leadChat: 4});++ expect(bold(r), isFalse);+ expect(row(r)?.tags ?? 0, 0);+ });++ test(+ 'a project read on Desktop before the phone opens is not bold on its '+ 'first load, though its tasks and its chat have agent posts since',+ () async {+ final r = await rig(+ groups: [lead(main: 9, person: 4), busyTask('g1', main: 7)],+ readMarks: {leadChat: 4, 'g1': 2},+ );++ expect(bold(r), isFalse);+ },+ );++ test('reading it on the phone clears it there and sends the mark Desktop '+ 'reads', () async {+ final r = await rig(+ groups: [busyTask('g1', main: 2)],+ readMarks: {leadChat: 1, 'g1': 2},+ );+ await poll(+ r,+ version: 20,+ groups: [lead(main: 5, person: 4), busyTask('g1', main: 6)],+ );+ expect(bold(r), isTrue);++ r.reader.readMarks!.markRead(leadChat, 5);+ await settle();++ expect(bold(r), isFalse);+ expect(+ r.swarm.calls.where(+ (c) =>+ c.method == 'POST' &&+ c.path == '/api/super-tabs/$tab/conversations/$leadChat/read' &&+ c.body?['sequence'] == 5,+ ),+ hasLength(1),+ reason: "the server's mark, which Desktop's row reads",+ );++ // A whole changed group and an older server mark must not undo the+ // phone's read while that write is still reaching other devices.+ await poll(+ r,+ version: 21,+ groups: [lead(main: 9, person: 4)],+ readMarks: {leadChat: 4},+ );+ expect(bold(r), isFalse);+ });++ test(+ 'whole changed groups retain the person counter after a remote read',+ () async {+ final r = await rig(readMarks: {leadChat: 4});+ await poll(r, version: 20, groups: [lead(main: 9, person: 7)]);+ expect(bold(r), isTrue);++ // The server returns changed groups whole, including the latest agent+ // message, together with Desktop's read through the person's message.+ await poll(+ r,+ version: 21,+ groups: [lead(main: 10, person: 7)],+ readMarks: {leadChat: 7},+ );+ expect(bold(r), isFalse);++ // Opening that same point sends nothing: it is already read on the+ // server. The row must already be quiet (#2950).+ r.reader.readMarks!.markRead(leadChat, 7);+ await settle();+ expect(bold(r), isFalse);+ expect(r.swarm.calls.where((c) => c.method == 'POST'), isEmpty);+ },+ );++ test(+ 'thread-only replies and tags do not make the project chat unread',+ () async {+ final r = await rig(+ groups: [+ {...lead(main: 4, person: 4), 'lastMessageSequence': 12},+ ],+ readMarks: {leadChat: 4},+ tags: [+ {...tag('thread-tag', leadChat, 12), 'threadId': 'thread-root'},+ ],+ );+ expect(bold(r), isFalse);+ expect(row(r)?.tags ?? 0, 0);+ },+ );++ test("an agent's post in the project chat does not bold it; a person's "+ 'does', () async {+ final r = await rig(readMarks: {leadChat: 1});+ await poll(r, version: 20, groups: [lead(main: 6, person: 1)]);+ expect(bold(r), isFalse);++ await poll(r, version: 21, groups: [lead(main: 7, person: 7)]);+ expect(bold(r), isTrue);+ });++ test('a muted project chat is never bold', () async {+ final r = await rig(readMarks: {leadChat: 1});+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c20',+ groups: [part(leadChat, 20, lead(main: 7, person: 7))],+ derived: {+ 'chatSettings': {leadChat: 'muted'},+ },+ );+ await r.reader.refresh();+ await settle();++ expect(bold(r), isFalse);+ });++ test(+ 'a tag of hers in the project chat keeps it bold with its count',+ () async {+ final r = await rig(+ groups: [lead(main: 5, person: 1)],+ readMarks: {leadChat: 4},+ tags: [tag('t1', leadChat, 5)],+ );++ expect(row(r), (bold: true, tags: 1, hasWaitingTag: true));+ },+ );++ test('a tag in a task leaves the row quiet but listed under Unread and '+ 'Mentions', () async {+ final r = await rig(+ groups: [busyTask('g1', main: 5)],+ readMarks: {leadChat: 0, 'g1': 4},+ tags: [tag('t1', 'g1', 5)],+ );++ expect(row(r), (bold: false, tags: 0, hasWaitingTag: true));+ });+}diff --git a/mobile/test/swarm/swarm_unread_test.dart b/mobile/test/swarm/swarm_unread_test.dartindex 72e415da2..040004dda 100644--- a/mobile/test/swarm/swarm_unread_test.dart+++ b/mobile/test/swarm/swarm_unread_test.dart@@ -169,7 +169,7 @@ void main() {});test('a reply only in a thread leaves a read chat and its project as they '- 'were; a message in the main stream still makes them bold', () async {+ 'were; a main-stream task message makes only its chat bold', () async {final r = await rig();await moveOn(r, {'g1': {@@ -189,9 +189,7 @@ void main() {});expect(chat(r, 'g1'), (bold: true, tags: 0));- expect(swarmProjectNews(r.reader, r.asks), {- project: (bold: true, tags: 0, hasWaitingTag: false),- });+ expect(swarmProjectNews(r.reader, r.asks), isEmpty);});test("a chat the Lead tagged the person in is bold with the count of the "@@ -227,7 +225,7 @@ void main() {r.reader.readMarks!.markRead(leadChat, 4);await settle();expect(swarmProjectNews(r.reader, r.asks)[project], (- bold: true,+ bold: false,tags: 0,hasWaitingTag: true,));@@ -239,25 +237,23 @@ void main() {);});- test('a project is bold while its project chat or open work is unread, '- 'without counting tags in task chats', () async {+ test('a project is bold for people in its own chat, while task tags '+ 'only keep it under the filters', () async {final r = await rig(tags: [mentionRow('t1'), mentionRow('t2')]);expect(swarmProjectNews(r.reader, r.asks), {- project: (bold: true, tags: 0, hasWaitingTag: true),+ project: (bold: false, tags: 0, hasWaitingTag: true),});final quiet = await rig();await moveOn(quiet, {- leadChat: groupData(- leadChat,- title: 'Mobile',- agentIds: ['agent-lead'],- leadId: 'agent-lead',- lastMessageSequence: 5,- ),+ leadChat: {+ ...groupData(leadChat, title: 'Mobile', lastMessageSequence: 5),+ 'lastPersonSequence': 5,+ },'web-lead': {...groupData('web-lead', title: 'Web', lastMessageSequence: 2),+ 'lastPersonSequence': 2,'projectId': other,},});@@ -320,7 +316,7 @@ void main() {expect(chat(r, 'g1'), (bold: true, tags: 1));expect(swarmProjectNews(r.reader, r.asks), {- project: (bold: true, tags: 0, hasWaitingTag: true),+ project: (bold: false, tags: 0, hasWaitingTag: true),});r.reader.readMarks!.markRead('g1', 4);@@ -336,7 +332,7 @@ void main() {expect(chat(r, 'g1'), (bold: true, tags: 1));expect(swarmProjectNews(r.reader, r.asks), {- project: (bold: true, tags: 0, hasWaitingTag: true),+ project: (bold: false, tags: 0, hasWaitingTag: true),});// The person reads the chat as far as the first read had marked it.@@ -433,7 +429,7 @@ void main() {expect(chat(r, 'g1'), (bold: true, tags: 1));expect(swarmProjectNews(r.reader, r.asks), {- project: (bold: true, tags: 0, hasWaitingTag: true),+ project: (bold: false, tags: 0, hasWaitingTag: true),});});@@ -453,7 +449,7 @@ void main() {expect(chat(r, 'g1'), (bold: false, tags: 0));expect(chat(r, 'g2'), (bold: true, tags: 1));expect(swarmProjectNews(r.reader, r.asks), {- project: (bold: true, tags: 0, hasWaitingTag: true),+ project: (bold: false, tags: 0, hasWaitingTag: true),});expect(r.asks.mentions, hasLength(2));});@@ -527,7 +523,7 @@ void main() {expect(chat(r, 'g1'), (bold: true, tags: 1));expect(swarmProjectNews(r.reader, r.asks), {- project: (bold: true, tags: 0, hasWaitingTag: true),+ project: (bold: false, tags: 0, hasWaitingTag: true),});},);@@ -536,13 +532,19 @@ void main() {// in Activity and on the chat's own row.test('a decision asked in the project chat raises its chat row, not the '"project's number, even while the chat is unread", () async {- final r = await rig(decisions: [decisionRow('d1', conversationId: leadChat)]);+ final r = await rig(+ decisions: [decisionRow('d1', conversationId: leadChat)],+ );await moveOn(r, {leadChat: groupData(leadChat, title: 'Mobile', lastMessageSequence: 4),});expect(chat(r, leadChat), (bold: true, tags: 1));- expect(swarmProjectNews(r.reader, r.asks)[project]?.tags, 0);+ expect(swarmProjectNews(r.reader, r.asks)[project], (+ bold: false,+ tags: 0,+ hasWaitingTag: true,+ ));expect(r.asks.decisions, hasLength(1), reason: 'Activity keeps it');});@@ -568,9 +570,7 @@ void main() {await settle();expect(chat(r, 'g1'), (bold: true, tags: 0));- expect(swarmProjectNews(r.reader, r.asks), {- project: (bold: true, tags: 0, hasWaitingTag: false),- });+ expect(swarmProjectNews(r.reader, r.asks), isEmpty);expect(r.swarm.paths.where((p) => p.endsWith('/parts')),hasLength(loads),