Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Merge batch 11-02 b2200: #2616 #2618 #2601 #2619 (#2624)

0xken15568842dbf0c3
diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.ts
index 1c34ad9fb..c3d62b0f1 100644
--- a/backend/integration/superTabLiveness.test.ts
+++ b/backend/integration/superTabLiveness.test.ts
@@ -2217,3 +2217,209 @@ describe('an agent closed on its machine', () => {
expect(await closing(f)).toEqual([])
})
})
+
+// Huy, 2026-11-02 (task #2131, after #2569): once a closed agent left the list, reopening its session left it outside the Swarm until
+// someone added it from Desktop. The removal keeps a record in its machine's part, and that machine's own report brings it back.
+describe('a session reopened after its agent was removed', () => {
+ const state = async (f: Awaited<ReturnType<typeof swarm>>) => (await f.timed.read(owner, f.tab)).state
+ const machinePart = async (f: { tab: string }, machineId: string) => (await db.swarmMachine.findFirstOrThrow({ where: { tabId: f.tab, key: machineId } })).data as { removedSessions?: Array<Record<string, any>> }
+ /** A Swarm with an idle agent of a role, in the task's group, that its machine's report just removed. */
+ async function removed(over: Record<string, unknown> = {}) {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ const idle = await f.add(f.group, 'test-host', f.harness.other, 'Idle one')
+ const row = await db.swarmAgent.findFirstOrThrow({ where: { tabId: f.tab, key: idle } })
+ await db.swarmAgent.update({ where: { id: row.id }, data: { data: { ...row.data as object, roleName: 'Reviewer', ...over } } })
+ // A session listed stopped leaves once it has stayed so, by a machine that keeps reporting (closedAgents.ts STOPPED_REMOVE_MS).
+ for (let seconds = 0; seconds < 35; seconds += 5) {
+ f.clock.now += 5_000
+ await f.observe('lead-host', [f.harness.lead])
+ await f.observe('test-host', [f.harness.worker], { stoppedHarnessIds: [f.harness.other] })
+ }
+ expect((await state(f)).agents.map(a => a.id)).not.toContain(idle)
+ return { ...f, idle }
+ }
+ const resume = (f: Awaited<ReturnType<typeof removed>>) => { f.clock.now += MINUTE; return f.observe('test-host', [f.harness.worker, f.harness.other]) }
+ const patchRecord = async (f: Awaited<ReturnType<typeof removed>>, change: (record: Record<string, any>) => void) => {
+ const row = await db.swarmMachine.findFirstOrThrow({ where: { tabId: f.tab, key: 'test-host' } })
+ const data = structuredClone(row.data) as { removedSessions: Array<Record<string, any>> }
+ change(data.removedSessions[0]!)
+ await db.swarmMachine.update({ where: { id: row.id }, data: { data: data as object } })
+ }
+
+ it('is listed again with its group, role and configuration, once, and its record goes', async () => {
+ const f = await removed()
+ await resume(f)
+ const read = await state(f), back = read.agents.find(a => a.id === f.idle)!
+ expect(back).toMatchObject({ harnessId: f.harness.other, machineId: 'test-host', name: 'Idle one', roleName: 'Reviewer', configuration: config })
+ expect(back.downSince).toBeUndefined()
+ expect(read.conversations.find(c => c.id === f.group)!.agentIds).toContain(f.idle)
+ expect((await machinePart(f, 'test-host')).removedSessions ?? []).toEqual([])
+ await resume(f)
+ expect((await state(f)).agents.filter(a => a.id === f.idle)).toHaveLength(1)
+ })
+
+ it('stays out while the report does not list it running', async () => {
+ const f = await removed()
+ f.clock.now += MINUTE
+ await f.observe('test-host', [f.harness.worker])
+ expect((await state(f)).agents.map(a => a.id)).not.toContain(f.idle)
+ expect((await machinePart(f, 'test-host')).removedSessions).toHaveLength(1)
+ })
+
+ it('comes back only from its own machine: another machine\'s report leaves it out, and a stranger\'s is refused', async () => {
+ const f = await removed()
+ f.clock.now += MINUTE
+ await f.observe('lead-host', [f.harness.lead, f.harness.other])
+ expect((await state(f)).agents.map(a => a.id)).not.toContain(f.idle)
+ expect((await machinePart(f, 'test-host')).removedSessions).toHaveLength(1)
+ const generation = (await poolRows(f.timed, host, 'test-host')).find(p => p.tabId === f.tab)!.machine.generation
+ await expect(f.timed.observeMachine(owner, f.tab, 'test-host', { generation, tools: [], quotas: [], resources: {} as never,
+ runningHarnessIds: [f.harness.other], stoppedHarnessIds: [] } as never)).rejects.toBeTruthy()
+ expect((await state(f)).agents.map(a => a.id)).not.toContain(f.idle)
+ expect((await machinePart(f, 'test-host')).removedSessions).toHaveLength(1)
+ })
+
+ it('no command brings it back: nothing a person or an agent sends names the record', async () => {
+ const f = await removed()
+ await expect(f.execute({ type: 'agent.rejoin', machineId: 'test-host', harnessId: f.harness.other } as unknown as Command)).rejects.toBeTruthy()
+ expect((await state(f)).agents.map(a => a.id)).not.toContain(f.idle)
+ })
+
+ it('is told only to its own machine\'s host, and is in no person\'s read', async () => {
+ const f = await removed()
+ expect((await poolRows(f.timed, host, 'test-host')).find(p => p.tabId === f.tab)).toMatchObject({ removedHarnessIds: [f.harness.other] })
+ expect((await poolRows(f.timed, host, 'lead-host')).find(p => p.tabId === f.tab)!.removedHarnessIds ?? []).toEqual([])
+ expect(JSON.stringify(await state(f))).not.toContain('removedSessions')
+ expect(JSON.stringify(await f.timed.read(host, f.tab))).not.toContain('removedSessions')
+ })
+
+ it('keeps no record of an agent someone asked to stop, or a confidential one', async () => {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ const stop = await f.add(f.group, 'test-host', f.harness.other, 'Stop one')
+ await f.execute({ type: 'agent.release', agentId: stop, decision: 'stop' })
+ f.clock.now += MINUTE
+ await f.observe('lead-host', [f.harness.lead])
+ await f.observe('test-host', [f.harness.worker], { stoppedHarnessIds: [f.harness.other] })
+ expect((await machinePart(f, 'test-host')).removedSessions ?? []).toEqual([])
+ const secret = await removed({ confidential: true })
+ expect((await machinePart(secret, 'test-host')).removedSessions ?? []).toEqual([])
+ })
+
+ it('keeps no record of a session that reads a private chat, though nothing marked it confidential', async () => {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ const idle = await f.add(f.group, 'test-host', f.harness.other, 'Idle one')
+ const group = await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.group } })
+ await db.swarmGroup.update({ where: { id: group.id }, data: { data: { ...group.data as object, audience: { kind: 'people', people: [{ id: owner.sub }] } } } })
+ for (let seconds = 0; seconds < 35; seconds += 5) {
+ f.clock.now += 5_000
+ await f.observe('lead-host', [f.harness.lead])
+ await f.observe('test-host', [f.harness.worker], { stoppedHarnessIds: [f.harness.other] })
+ }
+ expect((await state(f)).agents.map(a => a.id)).not.toContain(idle)
+ expect((await machinePart(f, 'test-host')).removedSessions ?? []).toEqual([])
+ })
+
+ it.each([
+ ['a machine owner who is not the report\'s', (r: Record<string, any>) => { r.agent.machineOwnerId = 'someone-else' }],
+ ['a contributor no longer in the Swarm', (r: Record<string, any>) => { r.agent.contributorId = 'someone-else' }],
+ ['its contributor left and came back', (r: Record<string, any>) => { r.agent.membershipGeneration = 'an-older-one' }],
+ ['its project gone', (r: Record<string, any>) => { r.agent.projectId = 'no-such-project' }],
+ ['a share grant that changed', (r: Record<string, any>) => { r.agent.hostGrant = 'revoked' }],
+ ['a harness that does not match', (r: Record<string, any>) => { r.agent.harnessId = 'other-session' }],
+ ])('is not restored with %s, and its record goes', async (_, change) => {
+ const f = await removed()
+ await patchRecord(f, change)
+ await resume(f)
+ expect((await state(f)).agents.map(a => a.id)).not.toContain(f.idle)
+ expect((await machinePart(f, 'test-host')).removedSessions ?? []).toEqual([])
+ })
+
+ it('does not come back into an archived group, a private chat, or one that is gone; it is listed all the same', async () => {
+ const f = await removed()
+ const open = String((await f.execute({ type: 'conversation.create', title: 'Open one', brief: 'b', checks: [] })).result.conversationId)
+ await patchRecord(f, r => { r.groupIds = [f.group, open, 'no-such-group'] })
+ await f.execute({ type: 'conversation.archive', conversationId: open, archived: true })
+ const group = await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.group } })
+ await db.swarmGroup.update({ where: { id: group.id }, data: { data: { ...group.data as object, audience: { people: [] } } } })
+ await resume(f)
+ const read = await db.swarmGroup.findMany({ where: { tabId: f.tab, key: { in: [f.group, open] } } })
+ for (const row of read) expect((row.data as { agentIds: string[] }).agentIds).not.toContain(f.idle)
+ expect((await state(f)).agents.map(a => a.id)).toContain(f.idle)
+ })
+
+ it('leaves one added by hand meanwhile as it is, and one registered in another Swarm out', async () => {
+ const f = await removed()
+ const again = await f.add(f.group, 'test-host', f.harness.other, 'Added by hand')
+ expect(again).toBe(f.idle)
+ await resume(f)
+ expect((await state(f)).agents.find(a => a.id === f.idle)!.name).toBe('Added by hand')
+ expect((await machinePart(f, 'test-host')).removedSessions ?? []).toEqual([])
+
+ const moved = await removed()
+ const elsewhere = await swarm()
+ await elsewhere.add(elsewhere.group, 'test-host', moved.harness.other, 'Elsewhere now')
+ await resume(moved)
+ expect((await state(moved)).agents.map(a => a.id)).not.toContain(moved.idle)
+ expect((await machinePart(moved, 'test-host')).removedSessions ?? []).toEqual([])
+ })
+
+ // Rowan's review of #2569: the removal now also orders its host to close the session.
+ it('stays open when it comes back before its host closed it: the close order goes with the record', async () => {
+ const f = await removed()
+ expect((await poolRows(f.timed, host, 'test-host')).length).toBeGreaterThan(0)
+ const closing = () => db.swarmMachine.findFirstOrThrow({ where: { tabId: f.tab, key: 'test-host' } }).then(row => (row.data as { closingSessions: Array<{ harnessId: string }> }).closingSessions)
+ expect((await closing()).map(c => c.harnessId)).toContain(f.harness.other)
+ await resume(f)
+ expect((await state(f)).agents.map(a => a.id)).toContain(f.idle)
+ expect((await closing()).map(c => c.harnessId)).not.toContain(f.harness.other)
+ })
+
+ it('rejoins after its host closed it, once the session is opened again', async () => {
+ const f = await removed()
+ const row = await db.swarmMachine.findFirstOrThrow({ where: { tabId: f.tab, key: 'test-host' } })
+ await db.swarmMachine.update({ where: { id: row.id }, data: { data: { ...row.data as object, closingSessions: [] } } })
+ await resume(f)
+ expect((await state(f)).agents.map(a => a.id)).toContain(f.idle)
+ })
+
+ it('never past a hold: a session its Team account is held for stays out, and the hold stands', async () => {
+ const f = await removed()
+ const row = await db.swarmMachine.findFirstOrThrow({ where: { tabId: f.tab, key: 'test-host' } })
+ const data = structuredClone(row.data) as { closingSessions: Array<Record<string, unknown>> }
+ for (const close of data.closingSessions) if (close.harnessId === f.harness.other) Object.assign(close, { heldFor: 'lead', since: f.clock.now })
+ await db.swarmMachine.update({ where: { id: row.id }, data: { data: data as object } })
+ await resume(f)
+ expect((await state(f)).agents.map(a => a.id)).not.toContain(f.idle)
+ const after = (await db.swarmMachine.findFirstOrThrow({ where: { tabId: f.tab, key: 'test-host' } })).data as { closingSessions: Array<Record<string, unknown>>; removedSessions?: unknown[] }
+ expect(after.closingSessions.find(c => c.harnessId === f.harness.other)).toMatchObject({ heldFor: 'lead' })
+ expect(after.removedSessions ?? []).toEqual([])
+ })
+
+ // Security review 1 of #2601: the record every Swarm registering this session writes (sessionScope.ts bindSession).
+ it.each([
+ ['withdrawn from this Swarm', (tab: string) => ({ releasedTabIds: [tab] })],
+ ['being stopped', () => ({ stopReleaseId: 'release-1' })],
+ ['tied to another private project', () => ({ privateScope: 'another-scope' })],
+ ])('stays out of a session %s, and its record goes', async (_, fields) => {
+ const f = await removed()
+ const row = await db.superTab.findUniqueOrThrow({ where: { id: f.tab }, select: { autonomousEnv: true } })
+ const scope = stableId('swarm-session', row.autonomousEnv, host.sub, f.idle)
+ await db.superTabSessionScope.upsert({ where: { id: scope }, create: { id: scope, scopeIds: [], ...fields(f.tab) }, update: fields(f.tab) })
+ await resume(f)
+ expect((await state(f)).agents.map(a => a.id)).not.toContain(f.idle)
+ expect((await machinePart(f, 'test-host')).removedSessions ?? []).toEqual([])
+ })
+
+ it('goes after 30 days, and with its machine', async () => {
+ const f = await removed()
+ f.clock.now += 31 * 24 * 60 * MINUTE
+ await f.observe('test-host', [f.harness.worker])
+ expect((await machinePart(f, 'test-host')).removedSessions ?? []).toEqual([])
+ const g = await removed()
+ await g.execute({ type: 'machine.remove', machineId: 'test-host' }, host)
+ expect((await machinePart(g, 'test-host')).removedSessions ?? []).toEqual([])
+ })
+})
diff --git a/backend/src/superTabs/closedAgents.test.ts b/backend/src/superTabs/closedAgents.test.ts
index 6cee91179..f23a3b87d 100644
--- a/backend/src/superTabs/closedAgents.test.ts
+++ b/backend/src/superTabs/closedAgents.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from 'vitest'
import { applyCommand } from './commands.js'
-import { closedAgents, DOWN_REMOVE_MS, removeClosedAgents, STOPPED_REMOVE_MS } from './closedAgents.js'
+import { closedAgents, DOWN_REMOVE_MS, REMOVED_KEEP_MS, REMOVED_KEPT, removeClosedAgents, reopened, restoreRefusal, restoreSessions, STOPPED_REMOVE_MS } from './closedAgents.js'
import { MACHINE_FRESH_MS } from './machines.js'
-import { createSuperTab, type Actor, type Agent, type SuperTabState } from './model.js'
+import { createSuperTab, type Actor, type Agent, type Conversation, type RemovedSession, type SuperTabState } from './model.js'
import { projectsOf } from './projects.js'
const config = { engine: 'codex', model: 'm', effort: 'high', contextWindow: null, engineVersion: null }
@@ -108,3 +108,107 @@ describe('removeClosedAgents: what a removal leaves for the host', () => {
expect(f.state.closingSessions).toBeUndefined()
})
})
+
+// A person's choice stands over an older record (security review 1 of #2601).
+describe('a person\'s add or remove of the session', () => {
+ const recordOf = (target: Agent) => ({ machineId: 'mac', harnessId: target.harnessId, agent: target, groupIds: ['lead'], leadOf: [], removedAt: NOW })
+
+ it('takes its record with it when they add it back', () => {
+ const f = fixture()
+ // No machine listed, as a person may add a session on any machine of theirs.
+ const state = { ...f.state, machines: undefined, agents: f.state.agents.filter(a => a.id !== f.worker.id), removedSessions: [recordOf(f.worker)] }
+ const added = applyCommand(state, person, { type: 'agent.add', conversationId: 'lead', machineId: 'mac', harnessId: 'worker', name: 'worker', lead: false, configuration: config },
+ { now: NOW, operationId: 'add-again', contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).state
+ expect(added.removedSessions ?? []).toEqual([])
+ })
+
+ it('takes its record with it when they remove it, so a reopen does not undo that', () => {
+ const f = fixture()
+ f.worker.workDecision = 'stop'
+ const state = { ...f.state, removedSessions: [recordOf(f.worker), { ...recordOf(f.worker), harnessId: 'another' }] }
+ const removed = applyCommand(state, person, { type: 'agent.remove', agentId: f.worker.id }, { now: NOW, operationId: 'remove-it' }).state
+ expect(removed.agents.map(a => a.id)).not.toContain(f.worker.id)
+ expect((removed.removedSessions ?? []).map(r => r.harnessId)).toEqual(['another'])
+ })
+
+ it('an expired record is not reopened, so it writes no session record', () => {
+ const f = fixture()
+ const state = { ...f.state, removedSessions: [{ ...recordOf(f.worker), removedAt: NOW - REMOVED_KEEP_MS }] }
+ expect(reopened(state, 'mac', ['worker'], NOW)).toEqual([])
+ expect(reopened(state, 'mac', ['worker'], NOW - 1)).toHaveLength(1)
+ })
+})
+
+// What a removal keeps, and a reopened session coming back from it (task #2131).
+const AT = Date.parse('2026-11-02T08:00:00.000Z')
+const removedAgent = (patch: Partial<Agent> = {}): Agent => ({ id: 'a1', machineId: 'mac', harnessId: 'h1', projectId: 'p', machineOwnerId: 'owner', contributorId: 'owner',
+ membershipGeneration: 'g1', hostGrant: null, name: 'Agent', configuration: { engine: 'codex', model: 'm', effort: 'high', contextWindow: null, engineVersion: null },
+ configurationVersion: 'v1', ...patch }) as Agent
+const removedGroup = (patch: Partial<Conversation> = {}): Conversation => ({ id: 'g1', title: 'Task', projectId: 'p', leadId: null, agentIds: [], archived: false, ...patch }) as Conversation
+const record = (patch: Partial<RemovedSession> = {}): RemovedSession => ({ machineId: 'mac', harnessId: 'h1', agent: removedAgent(), groupIds: ['g1'], leadOf: [], removedAt: AT - 60_000, ...patch })
+function restoring(patch: Partial<SuperTabState> = {}, pool: Record<string, unknown> = {}): SuperTabState {
+ return { id: 'tab', environment: 'prod', people: [{ id: 'owner', email: 'o@x', role: 'owner', generation: 'g1' }, { id: 'mate', email: 'm@x', role: 'collaborator', generation: 'g2' }],
+ agents: [], conversations: [removedGroup()], projects: [{ id: 'p', name: 'P', ownerId: 'owner', leadConversationId: 'lead-p', visibility: 'public', members: [] }, { id: 'other', name: 'O', ownerId: 'owner', leadConversationId: 'lead-o', visibility: 'public', members: [] }],
+ machines: [{ machineId: 'mac', contributorId: 'owner', name: 'Mac', generation: 'gen', ...pool }], removedSessions: [record()], ...patch } as unknown as SuperTabState
+}
+const facts = { elsewhere: new Set<string>(), teamMachines: [] as string[], otherWorkspaceMachines: [] as string[] }
+
+// Security review 1 of #2601: a restore takes the rules a person's add takes (commands.ts agent.add).
+describe('what may come back', () => {
+ it('comes back on an ordinary machine', () => {
+ expect(restoreRefusal(restoring(), record(), 'owner', AT, facts)).toBeNull()
+ })
+
+ it('never onto a Team account that serves another project', () => {
+ const team = { hostMachineId: 'host-mac', teamAccountOnly: true }
+ const onTeam = record({ agent: removedAgent({ teamAccount: true }) })
+ const held = [{ agentId: 'b', machineId: 'mac', harnessId: 'b', machineOwnerId: 'owner', heldFor: 'other', since: AT }]
+ expect(restoreRefusal(restoring({ closingSessions: held } as Partial<SuperTabState>, team), onTeam, 'owner', AT, { ...facts, teamMachines: ['mac'] })).toBe('team-other-project')
+ const mine = [{ agentId: 'b', machineId: 'mac', harnessId: 'b', machineOwnerId: 'owner', heldFor: 'p', since: AT }]
+ expect(restoreRefusal(restoring({ closingSessions: mine } as Partial<SuperTabState>, team), onTeam, 'owner', AT, { ...facts, teamMachines: ['mac'] })).toBeNull()
+ })
+
+ it('never a teammate\'s project on a machine that can no longer take it', () => {
+ // The Team account was removed: its owner's own project may come back there, and nobody else's.
+ expect(restoreRefusal(restoring({}, { hostMachineId: 'host-mac' }), record(), 'owner', AT, facts)).toBeNull()
+ const theirs = restoring({ projects: [{ id: 'p', name: 'P', ownerId: 'mate', leadConversationId: 'lead-p', visibility: 'public', members: [] }] } as unknown as Partial<SuperTabState>, { hostMachineId: 'host-mac' })
+ expect(restoreRefusal(theirs, record(), 'owner', AT, facts)).toBe('team-work')
+ })
+
+ it('leaves out a task marked Team-written while it was away, and keeps the rest', () => {
+ const state = restoring({ conversations: [removedGroup({ teamWritten: true }), removedGroup({ id: 'g2' })], removedSessions: [record({ groupIds: ['g1', 'g2'] })] })
+ restoreSessions(state, 'mac', ['h1'], AT, new Set(['h1']), () => {})
+ expect(state.conversations.find(c => c.id === 'g1')!.agentIds).toEqual([])
+ expect(state.conversations.find(c => c.id === 'g2')!.agentIds).toEqual(['a1'])
+ })
+})
+
+describe('what a removal keeps', () => {
+ const removal = (target: Agent, patch: Partial<SuperTabState> = {}) => {
+ const state = restoring({ agents: [target], conversations: [removedGroup({ agentIds: [target.id] })], removedSessions: [], ...patch })
+ removeClosedAgents(state, [target], AT)
+ return state
+ }
+
+ it('keeps no pending switch or alert of the session it was', () => {
+ const kept = removal(removedAgent({ switchRequest: { id: 's' }, switchLanded: { id: 's', requestedBy: 'x' }, alerting: ['prompt'] } as unknown as Partial<Agent>)).removedSessions![0]!.agent
+ expect(kept).not.toHaveProperty('switchRequest')
+ expect(kept).not.toHaveProperty('switchLanded')
+ expect(kept).not.toHaveProperty('alerting')
+ })
+
+ it('a later removal that keeps no record takes the older one with it', () => {
+ const state = removal(removedAgent({ confidential: true }), { removedSessions: [record()] })
+ expect(state.removedSessions ?? []).toEqual([])
+ })
+
+ it('keeps at most REMOVED_KEPT for a machine, the oldest going first, and leaves another machine\'s', () => {
+ const old = Array.from({ length: REMOVED_KEPT }, (_, i) => record({ harnessId: `h-${i}`, removedAt: AT - 1000 + i, agent: removedAgent({ id: `x-${i}`, harnessId: `h-${i}` }) }))
+ const other = record({ machineId: 'other-mac', harnessId: 'o' })
+ const left = removal(removedAgent(), { removedSessions: [...old, other] }).removedSessions!
+ expect(left.filter(r => r.machineId === 'mac')).toHaveLength(REMOVED_KEPT)
+ expect(left.some(r => r.harnessId === 'h-0')).toBe(false)
+ expect(left.some(r => r.harnessId === 'h1')).toBe(true)
+ expect(left).toContainEqual(other)
+ })
+})
diff --git a/backend/src/superTabs/closedAgents.ts b/backend/src/superTabs/closedAgents.ts
index 737f0f697..1028c4f7c 100644
--- a/backend/src/superTabs/closedAgents.ts
+++ b/backend/src/superTabs/closedAgents.ts
@@ -1,7 +1,8 @@
import { isBuddy } from './buddies.js'
-import { MACHINE_FRESH_MS, type MachineObservation } from './machines.js'
-import { activeWork, type Agent, type SuperTabState } from './model.js'
-import { agentProjectId, isConfidential, ledProject, onTeamAccount } from './projects.js'
+import { MACHINE_FRESH_MS, productManagerOn, teamAccountPool, teamWorkCheck, type MachineObservation } from './machines.js'
+import { activeWork, type Agent, type RemovedSession, type SuperTabState } from './model.js'
+import { agentProjectId, canReadProject, isConfidential, ledProject, onTeamAccount, projectsOf } from './projects.js'
+import { barredFromTeamWritten } from './teamWritten.js'
// Huy, 2026-11-02: four agents closed on their machine sat under Idle for hours, each in the machine's stopped list, because
// only an agent's own host removed it, and only after a stop was asked for. A session closed by hand never asked. Now the
@@ -9,6 +10,9 @@ import { agentProjectId, isConfidential, ledProject, onTeamAccount } from './pro
/** How long an agent not listed running stays before its machine, still reporting, removes it without a stopped list. */
export const DOWN_REMOVE_MS = 15 * 60_000
+/** The most records of removed agents one machine keeps, the oldest going first, and how long one lasts. */
+export const REMOVED_KEPT = 50
+export const REMOVED_KEEP_MS = 30 * 24 * 60 * 60_000
/** How long an agent whose session is listed stopped stays first: a host mid-restart, or an agent changing its session, lists
* one stopped for a moment before it is back (security reviews of #2569). */
export const STOPPED_REMOVE_MS = 30_000
@@ -68,6 +72,7 @@ export function removeClosedAgents(state: SuperTabState, closed: Agent[], now: n
if (!removed.length) return []
for (const target of removed) recordClosing(state, target, now)
const gone = new Set(removed.map(target => target.id))
+ for (const target of removed) keepRecord(state, target, now)
state.agents = state.agents.filter(target => !gone.has(target.id))
for (const group of state.conversations) {
group.agentIds = group.agentIds.filter(id => !gone.has(id))
@@ -76,6 +81,93 @@ export function removeClosedAgents(state: SuperTabState, closed: Agent[], now: n
return removed
}
+/** What a removal restores from if the session reopens (task #2131), unless the agent is meant to stay gone: someone asked it to stop,
+ * or its session held private chats, which purge deletes. Only what it was, not how it was doing: down, stopping, lost, noticed. */
+function keepRecord(state: SuperTabState, target: Agent, now: number): void {
+ const others = (state.removedSessions ?? []).filter(r => r.machineId !== target.machineId || r.harnessId !== target.harnessId)
+ // An older record of this session goes either way: it would undo the stop or the purge this removal stands for.
+ if (target.workDecision === 'stop' || target.confidential || isConfidential(state, target)) {
+ if (state.removedSessions) state.removedSessions = others
+ return
+ }
+ const { downSince: _down, lostTask: _lost, releaseId: _release, idleStop: _idle, idleNoticedAt: _noticed, workDecision: _decision,
+ switchRequest: _switch, switchLanded: _landed, alerting: _alerting, ...agent } = target
+ const mine = others.filter(r => r.machineId === target.machineId)
+ const over = mine.length + 1 - REMOVED_KEPT
+ const dropped = new Set(over > 0 ? [...mine].sort((a, b) => a.removedAt - b.removedAt).slice(0, over) : [])
+ state.removedSessions = [...others.filter(r => !dropped.has(r)), { machineId: target.machineId, harnessId: target.harnessId, agent,
+ groupIds: state.conversations.filter(group => group.agentIds.includes(target.id)).map(group => group.id),
+ leadOf: state.conversations.filter(group => group.leadId === target.id).map(group => group.id), removedAt: now }]
+}
+
+/** This machine's unexpired records of sessions [running] lists again, for the report to read their groups before restoring them. */
+export const reopened = (state: SuperTabState, machineId: string, running: readonly string[], now: number): RemovedSession[] =>
+ (state.removedSessions ?? []).filter(r => r.machineId === machineId && running.includes(r.harnessId) && now - r.removedAt < REMOVED_KEEP_MS)
+
+/** What a restore's rules read outside the Swarm's state: sessions registered in another Swarm by now, and the machines
+ * commands.ts agent.add's team rules read (store.ts teamMachines, otherWorkspaceMachines). */
+export interface RestoreFacts { elsewhere: ReadonlySet<string>; teamMachines: readonly string[]; otherWorkspaceMachines: readonly string[] }
+
+/**
+ * Why [record] may not come back as it was, by a fixed word, or null. The rules a person's add takes (commands.ts agent.add, whose
+ * session record and share the caller checks after this), each read from the state this write loaded, as any of it may have
+ * changed since: its machine's Team account may serve another project now, and that machine may no longer take a teammate's.
+ */
+export function restoreRefusal(state: SuperTabState, record: RemovedSession, machineOwnerId: string, now: number, facts: RestoreFacts): string | null {
+ const { agent } = record
+ // The record names its own session; a machine reports only its own, and a report is the only way here.
+ if (agent.machineId !== record.machineId || agent.harnessId !== record.harnessId || agent.machineOwnerId !== machineOwnerId) return 'not-this-machine'
+ if (state.agents.some(a => a.id === agent.id || (a.machineId === record.machineId && a.harnessId === record.harnessId))) return 'already-listed'
+ if (facts.elsewhere.has(record.harnessId)) return 'in-another-swarm'
+ if (state.closingSessions?.some(c => c.machineId === record.machineId && c.harnessId === record.harnessId && c.heldFor)) return 'team-held'
+ // Its contributor may be another person, on a machine shared with them: they must still be here, and the share must hold.
+ const contributor = state.people.find(p => p.id === agent.contributorId)
+ if (!contributor || contributor.generation !== agent.membershipGeneration || contributor.role === 'viewer') return 'contributor-changed'
+ const project = projectsOf(state).find(p => p.id === agentProjectId(state, agent))
+ if (!project || !canReadProject(state, { kind: 'person', userId: contributor.id, email: contributor.email }, project)) return 'project-ended'
+ if (teamAccountPool(state.machines?.find(m => m.machineId === record.machineId))) {
+ const held = productManagerOn(state, record.machineId)
+ if (held && held !== project.id) return 'team-other-project'
+ }
+ return teamWorkCheck(state, record.machineId, agent.contributorId, project, now, facts.teamMachines, facts.otherWorkspaceMachines) ? 'team-work' : null
+}
+
+/**
+ * Brings back the agents of [machineId] whose sessions [running] lists again and the caller [allowed], from the records their
+ * removal kept, and drops the records that came due or were refused. Called only with a report already proved to be this machine's;
+ * no command reaches it. An agent comes back only to the open groups of its own project it was in: never a private chat, since who
+ * may read there is not its to decide again, nor a task marked Team-written while it was away, unless it runs in a Team account.
+ * The restored agents.
+ */
+export function restoreSessions(state: SuperTabState, machineId: string, running: readonly string[], now: number,
+ allowed: ReadonlySet<string>, reserve: (harnessId: string) => void): Agent[] {
+ const records = state.removedSessions
+ if (!records?.length) return []
+ const restored: Agent[] = []
+ const left = records.filter(record => {
+ if (record.machineId !== machineId) return true
+ if (now - record.removedAt >= REMOVED_KEEP_MS) return false
+ if (!running.includes(record.harnessId)) return true
+ if (!allowed.has(record.harnessId)) return false
+ state.agents.push(record.agent)
+ reserve(record.harnessId)
+ // Back before its host closed it: the session stays open, as when a person adds it back (commands.ts agent.add). A close held for
+ // a Team account was refused: that account stays held until its host confirms (restoreRefusal, `team-held`).
+ state.closingSessions = state.closingSessions?.filter(c => c.machineId !== record.machineId || c.harnessId !== record.harnessId)
+ if (!state.closingSessions?.length) delete state.closingSessions
+ for (const group of state.conversations) {
+ if (group.archived || group.dormant || group.kind || group.audience || (state.projects && group.projectId !== record.agent.projectId)) continue
+ if (barredFromTeamWritten(state, group, record.agent)) continue
+ if (record.groupIds.includes(group.id) && !group.agentIds.includes(record.agent.id)) group.agentIds.push(record.agent.id)
+ if (record.leadOf.includes(group.id) && !group.leadId) group.leadId = record.agent.id
+ }
+ restored.push(record.agent)
+ return false
+ })
+ if (left.length !== records.length) state.removedSessions = left
+ return restored
+}
+
/** The next time a report of [machineId] could remove an agent, after those it just judged: its reports skip the full load
* until then (machineReports.ts), so a stopped list that stays the same still removes its agent when its wait ends. */
export function nextRemovalAt(state: SuperTabState, machineId: string, now: number): number | undefined {
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 1fe76348c..503063646 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -569,6 +569,11 @@ function releaseHarness(state: SuperTabState, machineId: string, harnessId: stri
}
}
+function dropRemovedRecord(state: SuperTabState, machineId: string, harnessId: string): void {
+ state.removedSessions = state.removedSessions?.filter(r => r.machineId !== machineId || r.harnessId !== harnessId)
+ if (!state.removedSessions?.length) delete state.removedSessions
+}
+
function dropClosing(state: SuperTabState, keep: (request: NonNullable<SuperTabState['closingSessions']>[number]) => boolean): void {
state.closingSessions = state.closingSessions?.filter(keep)
if (!state.closingSessions?.length) delete state.closingSessions
@@ -1210,6 +1215,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
/** Deleting its project is the only removal that takes a Lead. `close: false` when its host already closed the session. */
const removeAgent = (target: Agent, { lead = false, close = true } = {}) => {
+ // A person's removal stands: a record of this session must not bring it back when it reopens (closedAgents.ts).
+ dropRemovedRecord(state, target.machineId, target.harnessId)
// A Buddy chat's record of its sessions (buddySessions.ts): a session leaves it, and a main Buddy takes its sessions with it.
for (const chat of state.conversations.filter(c => isBuddyChat(c) && c.agentIds.includes(target.id))) {
if (target.buddySession) setSessions(chat, (chat.buddySessions ?? []).filter(e => e.agentId !== target.id))
@@ -1284,6 +1291,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// Its capacity left with it: no slot there is held for anyone now.
state.harnessReservations = state.harnessReservations?.filter(r => r.machineId !== machineId)
state.releasedHarnesses = state.releasedHarnesses?.filter(r => r.machineId !== machineId)
+ state.removedSessions = state.removedSessions?.filter(r => r.machineId !== machineId)
const machine = pool?.name ?? 'a machine'
// Routing lives in each project's instructions (project instructions), but reads still serve the old rules, older CLIs
// still route by them and a rollback would enforce them: for this release a machines rule still loses the machine, and
@@ -1968,6 +1976,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
fail('TEAM_ACCOUNT_HELD', 'This session held people\'s private chats and is being deleted from this machine\'s Harness Team account, so it cannot be added back.', 403)
}
if (!existing) reserveHarnessSlot(state, command.machineId, command.harnessId, operationId)
+ // Added back by hand: what they chose now stands over what its removal kept.
+ dropRemovedRecord(state, command.machineId, command.harnessId)
// Added back before its host closed it: the session stays open.
if (!existing) dropClosing(state, c => c.machineId !== command.machineId || c.harnessId !== command.harnessId)
if (!existing) state.agents.push({ id: agentId, machineId: command.machineId, harnessId: command.harnessId,
@@ -3191,7 +3201,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
/** A contribution owns capacity independently of membership. Reuse invalidates every prior stop proof. */
export { swarmGridName } from './model.js'
-function reserveHarnessSlot(state: SuperTabState, machineId: string, harnessId: string, generation: string) {
+export function reserveHarnessSlot(state: SuperTabState, machineId: string, harnessId: string, generation: string) {
const observation = state.machines?.find(m => m.machineId === machineId)?.observation
const renewed = !!(state.harnessReservations?.some(r => r.machineId === machineId && r.harnessId === harnessId)
|| state.releasedHarnesses?.some(r => r.machineId === machineId && r.harnessId === harnessId)
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 59ca70c5a..0a62c2a1c 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -503,6 +503,7 @@ export function dropIdleBuddyMachines(state: SuperTabState, now: number): void {
machineOwnerId: pool.contributorId, requestedAt: new Date(now).toISOString(), buddyOnly: true })
state.harnessReservations = state.harnessReservations?.filter(r => r.machineId !== pool.machineId)
state.releasedHarnesses = state.releasedHarnesses?.filter(r => r.machineId !== pool.machineId)
+ state.removedSessions = state.removedSessions?.filter(r => r.machineId !== pool.machineId)
}
}
diff --git a/backend/src/superTabs/migration/verify.ts b/backend/src/superTabs/migration/verify.ts
index d84ed0436..4c1d47117 100644
--- a/backend/src/superTabs/migration/verify.ts
+++ b/backend/src/superTabs/migration/verify.ts
@@ -2,10 +2,10 @@
import type { SuperTabState } from '../model.js'
/** Lists the parts store keeps only when they have entries: absent and empty are the same list. */
-const OPTIONAL_LISTS = ['starts', 'machines', 'harnessReservations', 'releasedHarnesses', 'closingSessions', 'machineCleanups',
+const OPTIONAL_LISTS = ['starts', 'machines', 'harnessReservations', 'releasedHarnesses', 'closingSessions', 'removedSessions', 'machineCleanups',
'parkedConversations', 'overlapAlerts'] as const
/** Lists whose order carries no meaning; machine parts regroup them by machine. */
-const UNORDERED = ['harnessReservations', 'releasedHarnesses', 'closingSessions', 'machineCleanups', 'overlapAlerts'] as const
+const UNORDERED = ['harnessReservations', 'releasedHarnesses', 'closingSessions', 'removedSessions', 'machineCleanups', 'overlapAlerts'] as const
/** The state as stored JSON sees it (no undefined), unordered lists sorted, empty optional lists removed. */
function canonical(state: SuperTabState): Record<string, unknown> {
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 7b9cff793..c0049f4fa 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -391,6 +391,16 @@ export interface Invitation {
conversationId: string
expiresAt: number
}
+/** An agent a machine's report removed as closed: as it was, and where it was (closedAgents.ts). */
+export interface RemovedSession {
+ machineId: string
+ harnessId: string
+ agent: Agent
+ groupIds: string[]
+ leadOf: string[]
+ removedAt: number
+}
+
export interface SuperTabState {
version: 1
id: string
@@ -441,6 +451,9 @@ export interface SuperTabState {
* host confirms the close, which it does once its saved session there is deleted (machines.ts productManagerOn); `since`
* when it was removed, and `noticed` once the Swarm said it lasts (liveness.ts). */
/** `buddyOnly`: a Buddy's session on a Buddy-only machine, kept from every reader as its machine is (read/changes.ts). */
+ /** What a report's removal of a closed agent must restore if its session reopens (closedAgents.ts): only its machine's host hears
+ * of it (read/hostRows.ts), and no reader gets it, as it names private chats. */
+ removedSessions?: RemovedSession[]
closingSessions?: Array<{ agentId: string; machineId: string; harnessId: string; machineOwnerId: string; heldFor?: string; since?: number; noticed?: true
buddyOnly?: true }>
/** Removed machines whose host still has to clean up (machines.ts expireRemovals), listed only to that host. */
@@ -787,7 +800,7 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
// not every member's), and overlap alerts. Nor a dormant conversation: it is read on demand, never in a whole-Swarm read
// (spec, Archive); a command may still load one.
const { sharing: _sharing, harnessReservations: _reservations, releasedHarnesses: _released, overlapAlerts: _alerts, closingSessions: _closing,
- ...kept } = state
+ removedSessions: _removed, ...kept } = state
const visible = cloneData({ ...kept, conversations: state.conversations.filter(c => !c.dormant) })
// A Buddy-only machine is no machine of the Swarm to anyone, its own person included (machines.ts buddyOnly): their Buddy
// shows as a Buddy, and their machine stays theirs. Machines, status and the leaderboard's lent hours all read this.
diff --git a/backend/src/superTabs/parts/shape.test.ts b/backend/src/superTabs/parts/shape.test.ts
index 0de9387cd..b6dc6894c 100644
--- a/backend/src/superTabs/parts/shape.test.ts
+++ b/backend/src/superTabs/parts/shape.test.ts
@@ -48,6 +48,17 @@ describe('splitting a Swarm into parts', () => {
expect([parts.head, ...parts.members, ...parts.groups].every(p => p.version === 500 && p.changedAt === 1000)).toBe(true)
})
+ // Task #2131: what a removal restores from. A new list here that shape does not copy vanishes on load.
+ it('keeps a removal\'s record on its machine, there and back, and writes no empty list for one with none', () => {
+ const record = { machineId: 'mac', harnessId: 'h-gone', agent: { id: 'gone', name: 'Gone' } as never, groupIds: ['g1'], leadOf: [], removedAt: 5 }
+ const state = { ...legacy(), removedSessions: [record] }
+ const parts = split(state, { tabId: 'tab1', version: 500, now: 1000 })
+ expect(parts.machines.find(p => p.key === 'mac')!.data!.removedSessions).toEqual([{ harnessId: 'h-gone', agent: record.agent, groupIds: ['g1'], leadOf: [], removedAt: 5 }])
+ expect(parts.machines.find(p => p.key === 'other')!.data).not.toHaveProperty('removedSessions')
+ expect(reassemble(parts).removedSessions).toEqual([record])
+ expect(reassemble(split(legacy(), { tabId: 'tab1', version: 500, now: 1000 }))).not.toHaveProperty('removedSessions')
+ })
+
it('keeps a slot ledger for every machine the Swarm references, contributed or not', () => {
const machines = split(legacy(), { tabId: 'tab1', version: 500, now: 1000 }).machines
expect(machines.map(p => p.key)).toEqual(['mac', 'other', 'third', 'removed'])
diff --git a/backend/src/superTabs/parts/shape.ts b/backend/src/superTabs/parts/shape.ts
index b64a17dde..a078dfc87 100644
--- a/backend/src/superTabs/parts/shape.ts
+++ b/backend/src/superTabs/parts/shape.ts
@@ -11,9 +11,9 @@ interface LegacyProgress { dirtyRevision: number; summarizedRevision: number; re
export { knownKind }
const PART_ONLY_GROUP_FIELDS = ['messageSeq', 'reportSeq', 'dormant', 'lastActivityAt'] as const
/** Optional lists of `SuperTab.state` an empty one of which differs from an absent one (`[]` after the last machine left). */
-const LISTS = ['parkedConversations', 'starts', 'machines', 'harnessReservations', 'releasedHarnesses', 'closingSessions', 'machineCleanups'] as const
+const LISTS = ['parkedConversations', 'starts', 'machines', 'harnessReservations', 'releasedHarnesses', 'closingSessions', 'removedSessions', 'machineCleanups'] as const
const STATE_ONLY = ['people', 'agents', 'conversations', 'parkedConversations', 'starts', 'machines', 'harnessReservations',
- 'releasedHarnesses', 'closingSessions', 'machineCleanups', 'otherProjectsWork', 'groupCounter', 'sequenceBase'] as const
+ 'releasedHarnesses', 'closingSessions', 'removedSessions', 'machineCleanups', 'otherProjectsWork', 'groupCounter', 'sequenceBase'] as const
const isLegacyProgress = (progress: unknown): progress is LegacyProgress =>
!!progress && typeof progress === 'object' && 'dirtyRevision' in progress
@@ -39,6 +39,7 @@ function machineParts(state: SuperTabState): Map<string, MachineData> {
// With its Team account hold (`heldFor`, `since`, `noticed`): dropped here, the account was free on the next read (review of #2142).
for (const { machineId, ...closing } of state.closingSessions ?? []) of(machineId).closingSessions.push(closing)
for (const { machineId, ...cleanup } of state.machineCleanups ?? []) of(machineId).cleanups.push(cleanup)
+ for (const { machineId, ...removed } of state.removedSessions ?? []) (of(machineId).removedSessions ??= []).push(removed)
return machines
}
@@ -122,6 +123,7 @@ export function reassemble(parts: SwarmParts, { share = false }: { share?: boole
const released = flat(m => m.released.map(harnessId => ({ machineId: m.machineId, harnessId })))
const closing = flat(m => m.closingSessions.map(c => ({ ...c, machineId: m.machineId })))
const cleanups: MachineCleanup[] = flat(m => m.cleanups.map(c => ({ machineId: m.machineId, ...c })))
+ const removed = flat(m => (m.removedSessions ?? []).map(r => ({ machineId: m.machineId, ...r })))
const list = <K extends typeof LISTS[number]>(key: K, items: NonNullable<SuperTabState[K]>) => {
if (items.length || present.has(key)) state[key] = copy(items)
}
@@ -131,6 +133,7 @@ export function reassemble(parts: SwarmParts, { share = false }: { share?: boole
list('harnessReservations', reservations)
list('releasedHarnesses', released)
list('closingSessions', closing)
+ list('removedSessions', removed)
list('machineCleanups', cleanups)
return state
}
diff --git a/backend/src/superTabs/parts/types.ts b/backend/src/superTabs/parts/types.ts
index aaa6711cf..b33781dc6 100644
--- a/backend/src/superTabs/parts/types.ts
+++ b/backend/src/superTabs/parts/types.ts
@@ -27,7 +27,7 @@ export type HeadProject = Omit<SwarmProject, 'progress'>
/** The head: everything in `SuperTabState` that is not one of the other parts. */
export type HeadData = Omit<SuperTabState, 'people' | 'agents' | 'conversations' | 'parkedConversations' | 'starts' | 'machines'
- | 'harnessReservations' | 'releasedHarnesses' | 'closingSessions' | 'machineCleanups' | 'otherProjectsWork' | 'projects'
+ | 'harnessReservations' | 'releasedHarnesses' | 'closingSessions' | 'removedSessions' | 'machineCleanups' | 'otherProjectsWork' | 'projects'
| 'groupCounter' | 'sequenceBase'> & { projects?: HeadProject[]
/** Which optional lists the state had, so an empty one comes back as `[]` and an absent one stays absent. */
presentLists?: string[] }
@@ -47,6 +47,8 @@ export interface MachineData {
released: string[]
closingSessions: Array<Omit<NonNullable<SuperTabState['closingSessions']>[number], 'machineId'>>
cleanups: Array<{ removalId: string; machineOwnerId: string; requestedAt?: string; buddyOnly?: true }>
+ /** Absent on a part with none, as on every part from before it. */
+ removedSessions?: Array<Omit<NonNullable<SuperTabState['removedSessions']>[number], 'machineId'>>
}
/** One project's report watermark (section 3.6). Group sequences are per group; floors carry pre-split tab revisions. */
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index ebfb648d0..87568b01d 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -280,6 +280,7 @@ export interface HostPool {
localGrid?: string
reservations: Array<{ harnessId: string; generation: string }>
harnessIds: string[]
+ removedHarnessIds?: string[]
githubApp?: true
/** The host may say what it launches beyond workers in its readings (leadStart.ts). */
capabilitiesWanted?: true
diff --git a/backend/src/superTabs/read/hostRows.ts b/backend/src/superTabs/read/hostRows.ts
index a9abcf714..c278c86d0 100644
--- a/backend/src/superTabs/read/hostRows.ts
+++ b/backend/src/superTabs/read/hostRows.ts
@@ -116,6 +116,7 @@ function pool(tabId: string, state: SuperTabState, machineId: string, user: Auth
const leadStarts = pending.filter(s => s.request.leadFor)
const buddyChats = new Set(buddyStarts.map(s => s.request.conversationId))
const reservations = (state.harnessReservations ?? []).filter(r => r.machineId === machineId)
+ const removedHere = (state.removedSessions ?? []).filter(r => r.machineId === machineId).map(r => r.harnessId)
return { tabId, paused: state.paused, machine: contribution, starts, ...(buddyStarts.length ? { buddyStarts } : {}), ...(leadStarts.length ? { leadStarts } : {}),
...(contribution.scope === 'swarm' ? { projects: projectsOf(state).filter(p => pending.some(s => startProject(state, s.request)?.id === p.id))
.map(p => ({ id: p.id, leadConversationId: p.leadConversationId, repository: p.repository,
@@ -125,6 +126,9 @@ function pool(tabId: string, state: SuperTabState, machineId: string, user: Auth
// A Buddy-only machine never joins the Swarm's grid: it serves nobody's models (machines.ts buddyOnly).
...(contribution.buddyOnly ? {} : hostLocalGrid(state)),
reservations: reservations.map(({ harnessId, generation }) => ({ harnessId, generation })),
+ // Sessions whose agents left as closed, which this host lists again if they reopen (closedAgents.ts restoreSessions). Ids only,
+ // and only to the machine's own host. Absent when there are none.
+ ...(removedHere.length ? { removedHarnessIds: removedHere } : {}),
harnessIds: [...new Set([...state.agents.filter(a => a.machineId === machineId).map(a => a.harnessId), ...reservations.map(r => r.harnessId),
...(state.starts ?? []).filter(s => s.request.machineId === machineId && s.harnessId).map(s => s.harnessId!)])],
...(githubApp ? { githubApp: true as const } : {}),
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index b482d95d1..1c8200730 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -13,7 +13,7 @@ import { isTeamSession, teamMachine, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE
import { machineShareGrant, sharedVia } from '../lib/machineSharePolicy.js'
import { machineBillingAllowsDataPlane } from '../lib/billingState.js'
import { DELETED_SWARM_COMMANDS, DELETION_COMMANDS, notThere } from './deletion.js'
-import { applyCommand, authorizeCommandAccess, IGNORED_NOTE, LOOP_NOTICE_AT, mayResumeStart, operationSchema, PAIR_CHAIN_LIMIT, postable, ruleProject, type Command, type CommandContext } from './commands.js'
+import { applyCommand, authorizeCommandAccess, IGNORED_NOTE, LOOP_NOTICE_AT, mayResumeStart, operationSchema, PAIR_CHAIN_LIMIT, postable, reserveHarnessSlot, ruleProject, type Command, type CommandContext } from './commands.js'
import { redactCredentials } from './credentials.js'
import type { AvatarUpload } from './profile.js'
import { reactionCounts, type ReactionTarget } from './reactions.js'
@@ -30,7 +30,7 @@ import { logger } from '../utils/logger.js'
import { retryTransient } from './retry.js'
import { recordReload } from './retryStats.js'
import { buddyChatId, swarmBuddyChatId, type ChosenBuddyName } from './buddies.js'
-import { accountOf, wordsOf, buddyPerson, canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, onTeamAccount, projectOf, projectsOf, agentProjectId, readConversation, readProject, skillModeOf, startProject, type ProjectVisibility } from './projects.js'
+import { accountOf, wordsOf, buddyPerson, canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, onTeamAccount, projectOf, projectsOf, agentProjectId, readConversation, readProject, skillModeOf, startProject, type ProjectVisibility, sessionKey } from './projects.js'
import { bindSession, makeProjectPrivate } from './sessionScope.js'
import { SESSION_ENDED_KIND, sessionContext, sessionReadsRow, type ContextRow } from './buddySessions.js'
import { isBuddy, isBuddyChat, isBuddyReader, refuseBuddyRouting, routingRow } from './buddies.js'
@@ -43,7 +43,7 @@ import { confidentialSessions, otherRegistrations, recordConfidential } from './
import { answersRequest, dirtyGroups, noteWorkChanges, projectUpdateRequest, UNANSWERED_REQUEST_MS } from './projectUpdates.js'
import { cloneData } from './cloneData.js'
import { digestDue, digestMessageId, digestOf, digestRequest, digestSince } from './digest.js'
-import { closedAgents, nextRemovalAt, removeClosedAgents } from './closedAgents.js'
+import { closedAgents, nextRemovalAt, removeClosedAgents, reopened, restoreRefusal, restoreSessions } from './closedAgents.js'
import { judgedMachines, loseTasks, nextLossAt, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'
import { archivable, archiveLine, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests } from './tidy.js'
import { clock, insertParts, loadActive, loadGroups, loadLightGroups, loadMachineParts, loadObserved, reassemble, split, type GroupData, type HeadData, type MachineData, type Part, type SwarmParts } from './parts/index.js'
@@ -2932,8 +2932,11 @@ export class SuperTabStore {
let loaded = loadedFrom(row, observed)
// Agents this reading shows closed leave with their groups' membership, so every group they are in is read, quiet ones too.
const closed = closedAgents(loaded.state, machineId, observation, this.now()).map(a => a.id)
- if (closed.length) {
- const more = await loadGroups(tx, tabId, 'agents', { agentIds: { $in: closed } })
+ // Sessions it shows open again come back with their groups (closedAgents.ts restoreSessions), so those are read too.
+ const back = reopened(loaded.state, machineId, observation.runningHarnessIds, this.now())
+ if (closed.length || back.length) {
+ const more = [...closed.length ? await loadGroups(tx, tabId, 'agents', { agentIds: { $in: closed } }) : [],
+ ...back.length ? await loadGroups(tx, tabId, 'key', { key: { $in: back.flatMap(r => [...r.groupIds, ...r.leadOf]) } }) : []]
loaded = loadedFrom(row, { ...observed, groups: [...new Map([...observed.groups, ...more].map(g => [g.key, g])).values()] })
}
const state = cloneData(loaded.state)
@@ -3001,6 +3004,29 @@ export class SuperTabStore {
const checked = [...loseTasks(state, now, worker => worker.machineId === machineId), ...sweep ? sweepLiveness(state, now) : []]
// Then the agents it shows closed leave, those with no active work left: the Lead is told of their tasks above (closedAgents.ts).
removedIds.push(...removeClosedAgents(state, state.agents.filter(a => closed.includes(a.id)), now).map(a => a.id))
+ // And the sessions it shows open again come back, by this report alone: it is proved this machine's contributor's above.
+ const allowed = new Set<string>()
+ if (back.length) {
+ const elsewhere = await otherRegistrations(tx, state, back.map(r => ({ machineId, harnessId: r.harnessId })))
+ const facts = { elsewhere: new Set(back.flatMap(r => { const key = sessionKey(machineId, r.harnessId); return elsewhere.registered.has(key) || elsewhere.confidential.has(key) ? [r.harnessId] : [] })),
+ teamMachines: await this.teamMachines(tx, state), otherWorkspaceMachines: await this.otherWorkspaceMachines(tx, state) }
+ for (const record of back) {
+ const refused = restoreRefusal(state, record, user.sub, now, facts)
+ if (refused) { logger.info('[swarm] a reopened session was not restored', { reason: refused }); continue }
+ // Its share, then the record every Swarm registering this session writes: withdrawn, stopping or tied to a private project.
+ try {
+ await this.agentGrant(tx, state, record.agent)
+ await bindSession(tx, state, record.agent, now)
+ allowed.add(record.harnessId)
+ } catch (error) {
+ if (!(error instanceof SuperTabError)) throw error
+ logger.info('[swarm] a reopened session was not restored', { reason: error.code })
+ }
+ }
+ }
+ const restored = restoreSessions(state, machineId, observation.runningHarnessIds, now, allowed, harnessId => reserveHarnessSlot(state, machineId, harnessId, `rejoin-${stamp}`))
+ // An agent reads its groups again from here: said, as nothing else records why (security review 2 of #2601).
+ for (const agent of restored) logger.info('[swarm] a reopened session rejoined', { tabId, agentId: agent.id, machineId, projectId: agent.projectId ?? null })
const written = await saved(checked)
// What the next reports of this machine need to skip the load, as this commit leaves the Swarm.
const mine = state.machines?.find(m => m.machineId === machineId)
diff --git a/backend/src/superTabs/teamWritten.ts b/backend/src/superTabs/teamWritten.ts
index 09a021a0e..f3a98324d 100644
--- a/backend/src/superTabs/teamWritten.ts
+++ b/backend/src/superTabs/teamWritten.ts
@@ -41,9 +41,13 @@ export function markTeamWritten(state: SuperTabState, group: Conversation, worke
/** Refuses an agent outside a Team account for Team-written code. The project's coordinator stays: it never builds or runs it. */
export function requireTeamWrittenAccount(state: SuperTabState, group: Conversation, worker: Agent): void {
- if (!coordinates(state, group, worker) && teamWrittenTask(state, group) && !onTeamAccount(state, worker)) failTeamWritten()
+ if (barredFromTeamWritten(state, group, worker)) failTeamWritten()
}
+/** Whether [worker] may not join [group]: an agent outside a Team account, in Team-written code, and not its project's coordinator. */
+export const barredFromTeamWritten = (state: SuperTabState, group: Conversation, worker: Agent): boolean =>
+ !coordinates(state, group, worker) && teamWrittenTask(state, group) && !onTeamAccount(state, worker)
+
/** Refuses a start for Team-written code on a machine outside a Team account. */
export function requireTeamWrittenMachine(state: SuperTabState, group: Conversation, machineId: string): void {
if (teamWrittenTask(state, group) && !teamAccountPool(state.machines?.find(m => m.machineId === machineId))) failTeamWritten()
diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.ts
index 088f2983f..5d47d141a 100644
--- a/cli/src/superTabs/machines.spec.ts
+++ b/cli/src/superTabs/machines.spec.ts
@@ -1430,6 +1430,23 @@ describe('contributed machine executor', () => {
const after = async (f: ReturnType<typeof fixture>, ms: number) => { f.step(ms); await f.machine.tick() }
const quiet = (f: ReturnType<typeof fixture>) => { f.pool.starts.length = 0 }
+ // Task #2131: a session whose agent left as closed comes back by this report. Only one the backend names, and only one running.
+ it('lists a recorded session that runs again, and no stopped, gone or unnamed one', async () => {
+ const f = fixture(); quiet(f)
+ Object.assign(f.pool, { removedHarnessIds: ['reopened', 'still-stopped', 'gone', 'not an id!'] })
+ vi.mocked(f.core.agents.byAgent).mockImplementation(id => ['running', 'reopened', 'still-stopped', 'unnamed'].includes(id) ? { agentId: id } as never : undefined)
+ vi.mocked(f.core.agents.stopped!).mockImplementation(async id => id === 'stopped' || id === 'still-stopped')
+ await f.machine.tick()
+ expect(lastBody(f)).toMatchObject({ runningHarnessIds: ['running', 'reopened'], stoppedHarnessIds: ['stopped'] })
+ })
+
+ it('reports nothing new from a backend that names no recorded session', async () => {
+ const f = fixture(); quiet(f)
+ vi.mocked(f.core.agents.byAgent).mockImplementation(id => ['running', 'reopened'].includes(id) ? { agentId: id } as never : undefined)
+ await f.machine.tick()
+ expect(lastBody(f).runningHarnessIds).toEqual(['running'])
+ })
+
it('publishes at once when a harness starts or stops running', async () => {
const f = fixture(); quiet(f)
await f.machine.tick()
diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.ts
index 7db7244f9..cba21b735 100644
--- a/cli/src/superTabs/machines.ts
+++ b/cli/src/superTabs/machines.ts
@@ -502,7 +502,14 @@ export class ContributedMachines {
for (const id of ids) {
if (await this.core.agents.stopped?.(id) || (!this.core.agents.byAgent(id) && await this.core.agents.gone?.(id))) stopped.push(id)
}
- const running = ids.filter(id => !!this.core.agents.byAgent(id) && !stopped.includes(id))
+ // A session whose agent left as closed, reopened here: listed running, and that report brings its agent back (backend
+ // closedAgents.ts restoreSessions). The backend names them, so nothing else on this machine is ever reported.
+ const removed = Array.isArray(row.removedHarnessIds) ? row.removedHarnessIds.filter(identifier) : []
+ const reopened: string[] = []
+ for (const id of removed) {
+ if (!ids.includes(id) && this.core.agents.byAgent(id) && !await this.core.agents.stopped?.(id)) reopened.push(id)
+ }
+ const running = [...ids.filter(id => !!this.core.agents.byAgent(id) && !stopped.includes(id)), ...reopened]
const pending = startsOf(row)
looked.push({ row, pool, pending })
const preparing = began >= this.preparingRefusedUntil ? pending.flatMap(start => this.preparing.has(String(start.id)) ? [String(start.id)] : []) : []
diff --git a/desktop/lib/super_tabs/activity.dart b/desktop/lib/super_tabs/activity.dart
index 54f989bc5..bc144753c 100644
--- a/desktop/lib/super_tabs/activity.dart
+++ b/desktop/lib/super_tabs/activity.dart
@@ -130,6 +130,15 @@ class SuperTabActivity extends ChangeNotifier {
String get _path =>
'/api/super-tabs/${Uri.encodeComponent(controller.tabId)}';
+ /// Whether the filter lists [item]. Decisions and Mentions list neither kind.
+ bool shows(SuperTabActivityItem item) => switch (filter) {
+ SuperTabActivityFilter.all => true,
+ SuperTabActivityFilter.replies => item.kind == SuperTabActivityKind.reply,
+ SuperTabActivityFilter.reactions =>
+ item.kind == SuperTabActivityKind.reaction,
+ _ => false,
+ };
+
/// Whether [item] shows bold.
bool isUnread(SuperTabActivityItem item) =>
!item.read || _newThisVisit.contains(item.id);
@@ -169,16 +178,21 @@ class SuperTabActivity extends ChangeNotifier {
unawaited(mentions.load());
}
- /// The view was left: what it showed is read on every device.
+ /// The view was left: what its list showed then is read on every device, and
+ /// the next visit starts on All unless it asks for a list (Diego, 2026-11-02).
+ /// Rows only passed by on the way to another list stay unread, which loses
+ /// nothing; marking a row nobody read would.
void closed() {
if (!_open) return;
_open = false;
_newThisVisit.clear();
+ final shown = {for (final i in items.where(shows)) i.id};
+ filter = SuperTabActivityFilter.all;
// The view is going away while this runs (its dispose): what listens is
// told after the frame's teardown, never during it.
scheduleMicrotask(() {
if (_disposed) return;
- unawaited(_markShownRead());
+ unawaited(_markShownRead(shown));
notifyListeners();
});
}
@@ -189,11 +203,23 @@ class SuperTabActivity extends ChangeNotifier {
notifyListeners();
}
- Future<void> _markShownRead() async {
- final newest = items
- .where((i) => !i.read)
- .map((i) => i.createdAt)
- .whereType<DateTime>()
+ /// The mark is by time, whatever the kind (backend activity.ts
+ /// markActivityRead): it stops before the oldest unread row [shown] lacks, or
+ /// that row would be read on every device unseen. A shown row newer than it
+ /// stays unread for now, which loses nothing.
+ Future<void> _markShownRead(Set<String> shown) async {
+ final unread = items.where((i) => !i.read && i.createdAt != null).toList();
+ final unseen = unread
+ .where((i) => !shown.contains(i.id))
+ .map((i) => i.createdAt!)
+ .fold<DateTime?>(null, (a, b) => a == null || b.isBefore(a) ? b : a);
+ final newest = unread
+ .where(
+ (i) =>
+ shown.contains(i.id) &&
+ (unseen == null || i.createdAt!.isBefore(unseen)),
+ )
+ .map((i) => i.createdAt!)
.fold<DateTime?>(null, (a, b) => a == null || b.isAfter(a) ? b : a);
if (newest == null || !supported || controller.accessRevoked) return;
final epoch = controller.visibilityEpoch;
diff --git a/desktop/lib/super_tabs/activity_view.dart b/desktop/lib/super_tabs/activity_view.dart
index 14ab4ab7d..08f788d81 100644
--- a/desktop/lib/super_tabs/activity_view.dart
+++ b/desktop/lib/super_tabs/activity_view.dart
@@ -80,20 +80,13 @@ class _SuperTabActivityViewState extends State<SuperTabActivityView> {
final mentions =
filter == SuperTabActivityFilter.all ||
filter == SuperTabActivityFilter.mentions;
- bool kind(SuperTabActivityItem i) => switch (filter) {
- SuperTabActivityFilter.all => true,
- SuperTabActivityFilter.replies => i.kind == SuperTabActivityKind.reply,
- SuperTabActivityFilter.reactions =>
- i.kind == SuperTabActivityKind.reaction,
- _ => false,
- };
final epoch = DateTime.fromMillisecondsSinceEpoch(0);
return [
if (mentions)
for (final m in [...a.mentions.waiting, ...a.mentions.earlier])
(at: m.createdAt ?? epoch, mention: m, item: null),
for (final i in a.items)
- if (kind(i)) (at: i.createdAt ?? epoch, mention: null, item: i),
+ if (a.shows(i)) (at: i.createdAt ?? epoch, mention: null, item: i),
]..sort((x, y) => y.at.compareTo(x.at));
}
diff --git a/desktop/lib/super_tabs/add_computers.dart b/desktop/lib/super_tabs/add_computers.dart
index 28b7882b8..ef92bd6ad 100644
--- a/desktop/lib/super_tabs/add_computers.dart
+++ b/desktop/lib/super_tabs/add_computers.dart
@@ -488,7 +488,7 @@ class _AddComputersState extends State<_AddComputers> {
@override
Widget build(BuildContext context) => ListenableBuilder(
- listenable: Listenable.merge([app, c]),
+ listenable: Listenable.merge([app, c, c.machinesChanged]),
builder: (context, _) {
// Another account signed in: nothing of this one's stays on screen.
if (!_sameAccount) {
diff --git a/desktop/lib/super_tabs/agent_details.dart b/desktop/lib/super_tabs/agent_details.dart
index 51c544f40..523139db4 100644
--- a/desktop/lib/super_tabs/agent_details.dart
+++ b/desktop/lib/super_tabs/agent_details.dart
@@ -270,7 +270,11 @@ Future<void> showSuperTabAgentDetails(
return showAppDialog<void>(
context: context,
builder: (context) => ListenableBuilder(
- listenable: Listenable.merge([controller, ?app]),
+ listenable: Listenable.merge([
+ controller,
+ controller.machinesChanged,
+ ?app,
+ ]),
builder: (context, _) {
final current = controller.snapshot?.agent(agent.id) ?? agent;
// The same words the Agents list's hover says: the Swarm's state first.
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 397186cf6..6f6356af3 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -14,6 +14,7 @@ import 'attachment_upload.dart';
import 'avatar_upload.dart';
import 'message_link.dart';
import 'identity.dart' show superTabMachineName;
+import 'machine_status.dart' show kSuperTabMachineOfflineAfter;
import 'model.dart';
import 'buddy_chat.dart';
import 'catch_up.dart';
@@ -332,6 +333,12 @@ class SuperTabController extends ChangeNotifier {
/// What the tab says once [updateRequired] (docs/naming-system.md).
static const updateMessage = 'Update Harness to keep using this Swarm.';
+ /// Told when only what machines report moved (a heartbeat): the controller's
+ /// own listeners hear nothing of it. Whatever shows a machine's readings
+ /// listens to this too.
+ Listenable get machinesChanged => _machinesChanged;
+ final _machinesChanged = ValueNotifier<int>(0);
+
/// The Swarm's parts as last read: what the next read asks changes for, and what [snapshot] is built from.
SuperTabParts? _parts;
@@ -455,6 +462,11 @@ class SuperTabController extends ChangeNotifier {
if (_toldTimes.length > _kToldTimes) _toldTimes.remove(_toldTimes.first);
}
if (main) {
+ // A wait for a machine's report may be the slow one: this one is not.
+ if (!_toldMain) {
+ _toldRead?.cancel();
+ _toldRead = null;
+ }
_toldMain = true;
} else {
_toldMachine = true;
@@ -474,7 +486,7 @@ class SuperTabController extends ChangeNotifier {
final last = _lastFullRead;
final wait = last == null
? Duration.zero
- : _readGap - clock.now().difference(last);
+ : _toldGap - clock.now().difference(last);
if (wait <= Duration.zero) {
unawaited(refresh());
return;
@@ -511,9 +523,14 @@ class SuperTabController extends ChangeNotifier {
return pollInterval;
}
+ /// How long what the reader was told waits since the last read. A change
+ /// to the Swarm: [_readGap], on screen or off. A machine's report alone says
+ /// nothing a Swarm not on screen shows: its slow pace ([_every]).
+ Duration get _toldGap => _toldMain || _every < _readGap ? _readGap : _every;
+
bool get _gapPassed {
final last = _lastFullRead;
- return last == null || clock.now().difference(last) >= _readGap;
+ return last == null || clock.now().difference(last) >= _toldGap;
}
/// Whether this poll reads. Always, unless the server pushes: then only when
@@ -583,6 +600,8 @@ class SuperTabController extends ChangeNotifier {
set away(bool value) {
if (_away == value) return;
_away = value;
+ // The machines list's clock runs only while it shows.
+ if (!_disposed) _machinesChanged.value++;
if (_startedAt == null || _disposed) return;
if (!_policy.pausesAway) {
// Going away slows the poll; coming back reads at once unless a poll
@@ -3136,16 +3155,20 @@ class SuperTabController extends ChangeNotifier {
Future<void> _read() async {
// An adapting read that changes nothing redraws nothing: on a phone each
// redraw of the whole tab is a long frame, every poll.
- final quiet = _policy.adapts && snapshot != null;
+ // So does a read for a machine's report alone (a heartbeat every 15 s per
+ // machine): if it brings more, the state moving says so below.
+ final beat = _toldMachine && !_toldMain;
+ final quiet = (_policy.adapts || beat) && snapshot != null;
final serial = ++_readSerial;
- final before = _shown;
+ var before = _shown;
var stateChanged = false;
loading = snapshot == null;
if (!quiet) _changed();
_lastFullRead = clock.now();
// Taken as the read starts: a push heard while it is out reads once more,
// on the next allowed read, unless it repeats a time already told.
- final told = _toldMain || _toldMachine;
+ // A machine's report says nothing of any conversation: no messages for it.
+ final told = _toldMain;
_toldMain = _toldMachine = false;
final took = Stopwatch()..start();
// The open conversation's messages, asked for beside the state
@@ -3189,7 +3212,16 @@ class SuperTabController extends ChangeNotifier {
// A part or a value worked out at read time (an agent seen down, a
// limit that ran out) changed: the snapshot is built again. The first
// read over a saved view wins, whatever it saved.
- final moved = read.changed || _showingSaved || snapshot == null;
+ // Only what a machine reports moved: the machines are new and nothing
+ // else is, so only what shows them hears of it.
+ final machinesOnly =
+ read.machinesOnly && !_showingSaved && snapshot != null;
+ final moved =
+ !machinesOnly && (read.changed || _showingSaved || snapshot == null);
+ if (machinesOnly) {
+ snapshot!.replaceMachines(parts.machines);
+ _machinesChanged.value++;
+ }
if (moved) {
// A closed group named by the saved selection is read by id: a first
// load has only the active groups.
@@ -3198,6 +3230,7 @@ class SuperTabController extends ChangeNotifier {
if (_disposed || accessRevoked) return;
}
final raw = parts.state;
+ if (beat) stateChanged = true;
if (_policy.adapts) {
stateChanged = true;
// A read mark moving is the page around the view: no new copy kept.
@@ -3267,8 +3300,24 @@ class SuperTabController extends ChangeNotifier {
}
// A first open draws its sidebar now, not once its chat answers.
if (stateReads == 1) _changed();
+ _watchMachineSilence();
final sidebarMs = took.elapsedMilliseconds;
+ final changedAtBefore = lastChangedAt;
lastChangedAt = parts.lastChangedAt;
+ // A machine's report moves the newest change, and no conversation or
+ // anything else that is shown.
+ if (machinesOnly) {
+ _messagesAt.updateAll(
+ (_, at) => at == changedAtBefore ? lastChangedAt : at,
+ );
+ before = (
+ lastChangedAt: lastChangedAt,
+ error: before.error,
+ failing: before.failing,
+ revoked: before.revoked,
+ loading: before.loading,
+ );
+ }
// Every state read, a quiet one too: a count a failed read left open is
// finished; one that is known reads nothing.
_dropLeft();
@@ -3280,7 +3329,7 @@ class SuperTabController extends ChangeNotifier {
if (early != null ||
!_messagesCurrent(selectedId) ||
read.full ||
- read.changed) {
+ (read.changed && !machinesOnly)) {
await (selectedId == earlyId && messagesRead != null
? messagesRead
: _readMessages(
@@ -3330,10 +3379,53 @@ class SuperTabController extends ChangeNotifier {
}
}
+ /// The machines whose last report is too old to call them online, as last
+ /// worked out. A machine going silent sends nothing, and another's heartbeat
+ /// no longer redraws: everything that reads a machine's age (agent marks,
+ /// the terminal's notice) redraws when this set changes, which is rare.
+ Set<String>? _silentMachines;
+ Timer? _silenceWatch;
+
+ void _watchMachineSilence() {
+ _silenceWatch?.cancel();
+ final rows = snapshot?.machines;
+ if (_disposed || rows == null || _startedAt == null) return;
+ final now = clock.now();
+ final silent = <String>{};
+ DateTime? next;
+ for (final m in rows) {
+ final observation = m['observation'];
+ final at = observation is Map ? observation['receivedAt'] : null;
+ final passes = at is num
+ ? DateTime.fromMillisecondsSinceEpoch(at.toInt())
+ .add(kSuperTabMachineOfflineAfter)
+ : null;
+ if (passes == null || !passes.isAfter(now)) {
+ silent.add(m['machineId'] as String);
+ } else if (next == null || passes.isBefore(next)) {
+ next = passes;
+ }
+ }
+ final before = _silentMachines;
+ _silentMachines = silent;
+ if (before != null && !setEquals(before, silent)) _changed();
+ if (next != null) {
+ _silenceWatch = Timer(next.difference(now), _watchMachineSilence);
+ }
+ }
+
/// One read of the Swarm's parts: changes since the cursor once a first load
/// is held, else a first load. A reload answer, or a change read refused (the
/// Swarm or the reader's access moved), reads in full at once.
- Future<({bool full, bool changed, bool marksOnly, Set<String> removed})>
+ Future<
+ ({
+ bool full,
+ bool changed,
+ bool machinesOnly,
+ bool marksOnly,
+ Set<String> removed,
+ })
+ >
_readParts() async {
final held = _parts;
if (held != null) {
@@ -3355,6 +3447,7 @@ class SuperTabController extends ChangeNotifier {
return (
full: false,
changed: change.changed || refreshed,
+ machinesOnly: change.machinesOnly && !refreshed,
marksOnly: change.readMarksOnly && !refreshed,
removed: change.removedGroups,
);
@@ -3372,6 +3465,7 @@ class SuperTabController extends ChangeNotifier {
return (
full: true,
changed: true,
+ machinesOnly: false,
marksOnly: false,
removed: const <String>{},
);
@@ -4569,6 +4663,8 @@ class SuperTabController extends ChangeNotifier {
// Closing the Swarm is no Undo: the held marks go before anything stops.
_markAll?._commit();
_disposed = true;
+ _machinesChanged.dispose();
+ _silenceWatch?.cancel();
for (final then in _onDispose) {
then();
}
diff --git a/desktop/lib/super_tabs/local_models.dart b/desktop/lib/super_tabs/local_models.dart
index 022dfa73b..3474790d4 100644
--- a/desktop/lib/super_tabs/local_models.dart
+++ b/desktop/lib/super_tabs/local_models.dart
@@ -137,7 +137,7 @@ class _SwarmModelsWindowState extends State<_SwarmModelsWindow> {
final c = widget.controller, app = widget.app;
final size = MediaQuery.sizeOf(context);
return ListenableBuilder(
- listenable: c,
+ listenable: Listenable.merge([c, c.machinesChanged]),
builder: (context, _) {
final local = c.snapshot?.localModels;
final on = local?.enabled == true;
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index 13ee58130..680bc53af 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -1,7 +1,9 @@
import 'dart:async';
import 'package:clock/clock.dart';
+import 'package:flutter/foundation.dart' show listEquals;
import 'package:flutter/material.dart';
+import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import '../core/machine_resources.dart';
@@ -88,11 +90,16 @@ class SuperTabMachines extends StatefulWidget {
this.collapsed = false,
this.onToggleCollapsed,
this.onOpenAgent,
+ this.ticks,
});
final SuperTabController controller;
final AppNotifier? app;
final bool embedded;
+ /// Runs the one-second clock; by default everywhere but under `flutter test`.
+ @visibleForTesting
+ final bool? ticks;
+
/// Whether the body below the heading is hidden. The heading itself, and
/// its Add machine action, remain visible so the group stays reachable.
final bool collapsed;
@@ -784,8 +791,15 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
/// reporting through it are refreshing until one more is. Null: the app has not been away.
int? _swarmReadsAtReturn;
- /// Once a second, so that ages, states and the heading's count follow the clock between the Swarm's reads.
+ /// Once a second while the list shows ([_syncTick]), so that ages and states
+ /// follow the clock between the Swarm's reads.
Timer? _tick;
+
+ /// What each row last drew, and their order: a tick or a machine's report
+ /// redraws only a row whose words moved, and the list only when rows move.
+ final _rowsDrawn = <String, Object>{};
+ List<String> _orderDrawn = const [];
+ final _rowBeats = <String, ValueNotifier<int>>{};
final _tips = <String, GlobalKey<TooltipState>>{};
/// One per Swarm menu open now, each keeping the browser's menu off.
@@ -817,9 +831,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
@override
void initState() {
super.initState();
- if (!kUnderTest) {
- _tick = Timer.periodic(const Duration(seconds: 1), (_) => _changed());
- }
+ c.machinesChanged.addListener(_machinesMoved);
unawaited(_readTeamSetup());
if ((!kUnderTest || widget.readLocal != null) && widget.app != null) {
_updateUsage();
@@ -832,6 +844,88 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
if (mounted) setState(() {});
}
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ _syncTick();
+ }
+
+ @override
+ void didUpdateWidget(SuperTabMachines old) {
+ super.didUpdateWidget(old);
+ if (!identical(old.controller, c)) {
+ old.controller.machinesChanged.removeListener(_machinesMoved);
+ c.machinesChanged.addListener(_machinesMoved);
+ }
+ _syncTick();
+ }
+
+ /// The clock runs only while something it moves shows: not for a Swarm not
+ /// on screen, a window at the back, or a collapsed group, whose heading shows
+ /// an age only while the Swarm can't be read.
+ void _syncTick() {
+ final wanted =
+ (widget.ticks ?? !kUnderTest) &&
+ !c.away &&
+ TickerMode.valuesOf(context).enabled &&
+ widget.app?.foreground.value != false &&
+ (!widget.collapsed || c.backendUnreachable);
+ if (!wanted) {
+ _tick?.cancel();
+ _tick = null;
+ } else {
+ _tick ??= Timer.periodic(
+ const Duration(seconds: 1),
+ (_) => _redrawMoved(),
+ );
+ }
+ }
+
+ /// A machine reported, or the Swarm came on screen or left it. Told outside
+ /// a build but for that last, which may come from one.
+ void _machinesMoved() {
+ if (!mounted) return;
+ if (SchedulerBinding.instance.schedulerPhase ==
+ SchedulerPhase.persistentCallbacks) {
+ SchedulerBinding.instance.addPostFrameCallback((_) => _machinesMoved());
+ return;
+ }
+ _syncTick();
+ _redrawMoved();
+ }
+
+ /// Redraws what no longer says what it drew, and nothing else.
+ void _redrawMoved() {
+ if (!mounted || c.snapshot == null || c.accessRevoked) return;
+ final views = _sortedViews();
+ if (c.backendUnreachable ||
+ !listEquals(_orderDrawn, [for (final v in views) v.id])) {
+ _changed();
+ return;
+ }
+ for (final view in views) {
+ if (_rowsDrawn[view.id] != _rowWords(view)) {
+ _rowBeats[view.id]?.value++;
+ }
+ }
+ }
+
+ /// Everything a row's look goes by, but for what a rebuild of the list says.
+ Object _rowWords(_MachineView view) => Object.hashAll([
+ view.name,
+ view.status,
+ view.readingAt,
+ view.arrived,
+ view.paused,
+ view.cleaning,
+ view.dim,
+ view.details,
+ view.tip,
+ view.problem,
+ view.subscriptionsAside,
+ view.agents.length,
+ ]);
+
/// Reads why this Mac has no Harness Team account, only while its person's
/// own row offers Set up: asked of this Mac's daemon, never of another's.
Future<void> _readTeamSetup() async {
@@ -872,6 +966,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
}
void _foreground() {
+ _syncTick();
_updateUsage();
_revision++;
_timer?.cancel();
@@ -929,6 +1024,10 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
_revision++;
_timer?.cancel();
_tick?.cancel();
+ c.machinesChanged.removeListener(_machinesMoved);
+ for (final beat in _rowBeats.values) {
+ beat.dispose();
+ }
widget.app?.foreground.removeListener(_foreground);
_usage?.removeListener(_changed);
_usage?.dispose();
@@ -2215,7 +2314,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
}
/// Keep offline machines in the same list and on the same columns.
- List<Widget> _machines() {
+ List<_MachineView> _sortedViews() {
final views = [for (final id in _rowIds) _view(id)];
String key(_MachineView view) =>
superTabMachineName(view.name).toLowerCase();
@@ -2231,7 +2330,30 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
? key(a).compareTo(key(b))
: a.id.compareTo(b.id),
);
- return [for (final view in views) _machine(view)];
+ return views;
+ }
+
+ /// One row each, redrawn on its own ([_redrawMoved]).
+ List<Widget> _machines() {
+ final views = _sortedViews();
+ _orderDrawn = [for (final v in views) v.id];
+ _rowBeats.removeWhere((id, beat) {
+ if (_orderDrawn.contains(id)) return false;
+ beat.dispose();
+ return true;
+ });
+ return [
+ for (final id in _orderDrawn)
+ ValueListenableBuilder<int>(
+ key: ValueKey('super-machine-row-$id'),
+ valueListenable: _rowBeats.putIfAbsent(id, () => ValueNotifier(0)),
+ builder: (context, _, _) {
+ final view = _view(id);
+ _rowsDrawn[id] = _rowWords(view);
+ return _machine(view);
+ },
+ ),
+ ];
}
@override
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index f406738cb..200ab2cee 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -512,10 +512,7 @@ class SuperTabSnapshot {
: Map.unmodifiable(superTabMap(row['project'])),
people = superTabUsernames(_list(row['people'], SuperTabPerson.fromJson)),
agents = _list(row['agents'], SuperTabAgent.fromJson),
- machines = _list(
- row['machines'] ?? const [],
- (m) => Map<String, dynamic>.unmodifiable(m),
- ),
+ _machines = _machineRows(row['machines'] ?? const []),
// The Product Managers chat is gone (Dee, 2026-10-31): an older server
// still sends it, by its kind or the id the head names, and no screen
// may list or open it.
@@ -610,7 +607,17 @@ class SuperTabSnapshot {
late final List<SuperTabAgent> teamAgents = List.unmodifiable(
agents.where((a) => !a.isBuddy),
);
- final List<Map<String, dynamic>> machines;
+ List<Map<String, dynamic>> get machines => _machines;
+ List<Map<String, dynamic>> _machines;
+
+ static List<Map<String, dynamic>> _machineRows(Object? rows) =>
+ _list(rows, (m) => Map<String, dynamic>.unmodifiable(m));
+
+ /// A machine's report arrived and nothing else moved: only the machines are
+ /// new, so nothing worked out from the rest of the Swarm is done again
+ /// (`SuperTabController.machinesChanged` says so).
+ void replaceMachines(List<Map<String, dynamic>> rows) =>
+ _machines = _machineRows(rows);
final List<SuperTabConversation> conversations;
late final List<SuperTabProject> projects;
final List<Map<String, dynamic>> invitations;
diff --git a/desktop/lib/super_tabs/parts.dart b/desktop/lib/super_tabs/parts.dart
index 85b325878..e29c12d95 100644
--- a/desktop/lib/super_tabs/parts.dart
+++ b/desktop/lib/super_tabs/parts.dart
@@ -24,6 +24,7 @@ class SuperTabPartsChange {
this.removedGroups = const {},
this.dormantGroups = const {},
this.readMarksOnly = false,
+ this.machinesOnly = false,
});
/// Some part or a derived value is new: what the screens draw may differ.
@@ -37,6 +38,10 @@ class SuperTabPartsChange {
/// Only the reader's read marks moved: the page around the view, not what a saved view holds.
final bool readMarksOnly;
+
+ /// Only what a machine reports moved (its reading, its Lent, its worked-out
+ /// values): what shows machines may differ, nothing else.
+ final bool machinesOnly;
}
/// The parts of one Swarm as this reader last saw them (section 5.1): every part by kind and key at the newest
@@ -224,12 +229,14 @@ class SuperTabParts {
/// the group out of the active ones, `derived` is replaced, and the cursor moves. A reload answer is the caller's.
SuperTabPartsChange apply(Map<String, dynamic> changes) {
var changed = false;
+ // Anything but a machine's own report moved.
+ var beyondMachines = false;
final removed = <String>{}, dormant = <String>{};
if (changes['head'] != null) {
final head = _envelope(changes['head'], live: true);
if (_newer('head', head)) {
_head = head;
- changed = true;
+ changed = beyondMachines = true;
}
}
for (final kind in _lists) {
@@ -239,6 +246,9 @@ class SuperTabParts {
final key = part['key'] as String;
if (!_newer('$kind:$key', part)) continue;
changed = true;
+ if (kind != 'machines' || !_reportOnly(held[key], part)) {
+ beyondMachines = true;
+ }
if (part['deleted'] == true) {
held.remove(key);
if (kind == 'groups') {
@@ -281,6 +291,7 @@ class SuperTabParts {
_takeChatSettings(derived.remove('chatSettings')) |
readMarksMoved;
if (!const DeepCollectionEquality().equals(derived, _derived)) {
+ if (!_sameBeyondMachines(derived, _derived)) beyondMachines = true;
_derived = derived;
changed = true;
}
@@ -292,9 +303,45 @@ class SuperTabParts {
removedGroups: removed,
dormantGroups: dormant,
readMarksOnly: marksMoved && !changed,
+ machinesOnly: changed && !beyondMachines && !marksMoved,
);
}
+ /// Whether [next] says of a held machine only what its reports write: a
+ /// heartbeat. A new machine, a removed one, or one renamed or paused is news
+ /// to more than the machines list.
+ static bool _reportOnly(
+ Map<String, dynamic>? held,
+ Map<String, dynamic> next,
+ ) {
+ if (held == null || next['deleted'] == true || next['data'] == null) {
+ return false;
+ }
+ Map<String, dynamic> rest(Map<String, dynamic> part) =>
+ Map.of(superTabMap(part['data']))
+ ..remove('observation')
+ ..remove('lent')
+ ..remove('lentDays');
+ return const DeepCollectionEquality().equals(rest(held), rest(next));
+ }
+
+ static bool _sameBeyondMachines(
+ Map<String, dynamic> a,
+ Map<String, dynamic> b,
+ ) => const DeepCollectionEquality().equals(
+ Map.of(a)..remove('machines'),
+ Map.of(b)..remove('machines'),
+ );
+
+ /// The machines as [state] lists them, with what the server worked out.
+ List<Map<String, dynamic>> get machines {
+ final worked = _derivedMap('machines');
+ return [
+ for (final machine in _data('machines'))
+ _overlay(machine, worked[machine['machineId']]),
+ ];
+ }
+
/// Takes dormant groups read on demand (section 4.5): a page of the dormant list, or one group by id. Each is kept
/// unless this reader already holds a newer version of it; one that is active here at a lower version moves out.
SuperTabPartsChange addDormant(List groups) {
@@ -323,7 +370,6 @@ class SuperTabParts {
/// groups come first in the order they were read, then the dormant groups held.
Map<String, dynamic> get state {
final agentsDerived = _derivedMap('agents');
- final machinesDerived = _derivedMap('machines');
final avatars = _derivedMap('avatars');
final state = <String, dynamic>{
...superTabMap(_head['data']),
@@ -347,10 +393,7 @@ class SuperTabParts {
..._data('groups'),
for (final part in _dormant.values) superTabMap(part['data']),
],
- 'machines': [
- for (final machine in _data('machines'))
- _overlay(machine, machinesDerived[machine['machineId']]),
- ],
+ 'machines': machines,
'starts': [for (final start in _data('starts')) start],
'githubApp': githubApp,
};
diff --git a/desktop/lib/super_tabs/personal_projects.dart b/desktop/lib/super_tabs/personal_projects.dart
index ce334d242..bcb1da4fe 100644
--- a/desktop/lib/super_tabs/personal_projects.dart
+++ b/desktop/lib/super_tabs/personal_projects.dart
@@ -31,13 +31,25 @@ import 'swarm_switcher.dart' show PersonalSwarm;
const kScratchRepo = 'scratch';
const kScratchProjectName = 'scratch';
+/// The form an agent reports its project's remote in: `host[:port]/owner/repo`
+/// with no scheme, user or `.git` (the CLI's `canonicalRepository`, and
+/// `canonicalGitRemote` for this computer's own reading). Every real remote
+/// arrives so; a host needs a dot and a letter-only last label, which a folder
+/// path (`/srv/api`, `./api`, `C:\api`) never has.
+final _canonicalRemote = RegExp(
+ r'^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}(?::\d+)?/\S+$',
+ caseSensitive: false,
+);
+
/// A pane's repo as one string for every computer: the remote's host and path,
/// lower case, without scheme, user, password, port or `.git`, so
-/// `[email protected]:Owner/Api.git` and `https://github.com/owner/api` are one.
+/// `[email protected]:Owner/Api.git`, `https://github.com/owner/api` and the
+/// `github.com/owner/api` an agent reports are one.
/// Null for no remote, or one only this computer can reach (a folder).
String? normalizedRemote(String? remote) {
var text = remote?.trim() ?? '';
if (text.isEmpty) return null;
+ if (_canonicalRemote.hasMatch(text)) text = 'https://$text';
String? host, path;
final url = RegExp(
r'^([a-z][a-z0-9+.-]*)://(.*)$',
diff --git a/desktop/lib/super_tabs/switch_pm.dart b/desktop/lib/super_tabs/switch_pm.dart
index 6b300cb50..1d559ff88 100644
--- a/desktop/lib/super_tabs/switch_pm.dart
+++ b/desktop/lib/super_tabs/switch_pm.dart
@@ -45,7 +45,7 @@ Future<void> showSwitchPm(
requireWrite: true,
child: StatefulBuilder(
builder: (context, update) => ListenableBuilder(
- listenable: c,
+ listenable: Listenable.merge([c, c.machinesChanged]),
builder: (context, _) {
final snapshot = c.snapshot;
final lead = snapshot?.leadOf(projectId);
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 034130990..de6985b73 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -1661,7 +1661,8 @@ class _SuperTabViewState extends State<SuperTabView>
SuperTabController? from,
}) {
if (!mounted || (from != null && from != c)) return;
- if (filter != null) SuperTabActivity.of(c).setFilter(filter);
+ // Its row asks for no list: All, whichever one was showing.
+ SuperTabActivity.of(c).setFilter(filter ?? SuperTabActivityFilter.all);
_closeSidebar();
setState(() {
_showNotifications = true;
diff --git a/desktop/test/super_tab_activity_test.dart b/desktop/test/super_tab_activity_test.dart
index c65addc2d..5ef542269 100644
--- a/desktop/test/super_tab_activity_test.dart
+++ b/desktop/test/super_tab_activity_test.dart
@@ -689,6 +689,197 @@ void main() {
});
});
+ group('leaving Activity marks read only what the visit showed (Diego)', () {
+ Future<void> visit(
+ WidgetTester tester,
+ SuperTabActivity activity, {
+ List<SuperTabActivityFilter> filters = const [],
+ Future<void> Function()? during,
+ }) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabActivityView(
+ activity: activity,
+ onOpenMention: (_) {},
+ onOpenMessage: (_, _) {},
+ now: () => DateTime.utc(2026, 10, 31, 6),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ for (final filter in filters) {
+ await tester.tap(
+ find.byKey(ValueKey('super-activity-filter-${filter.name}')),
+ );
+ await tester.pumpAndSettle();
+ }
+ await during?.call();
+ await tester.pumpWidget(const SizedBox());
+ await tester.runAsync(settle);
+ }
+
+ Future<(ConversationServer, SuperTabController, SuperTabActivity)> unread(
+ WidgetTester tester,
+ List<Map<String, dynamic>> items,
+ ) async {
+ final server = projectServer();
+ server.state['activityDigest'] = 'd1';
+ server.activity = {'items': items, 'more': false};
+ final c = await openHere(server);
+ final activity = SuperTabActivity.of(c);
+ await tester.runAsync(settle);
+ return (server, c, activity);
+ }
+
+ Map<String, dynamic> at(Map<String, dynamic> item, String time) => {
+ ...item,
+ 'createdAt': '2026-10-31T$time:00.000Z',
+ };
+
+ testWidgets('a Decisions-only visit leaves replies unread', (tester) async {
+ final (server, c, activity) = await unread(tester, [reply('r1')]);
+ final count = activity.count;
+ await visit(
+ tester,
+ activity,
+ filters: [SuperTabActivityFilter.decisions],
+ );
+ expect(server.activityReadPosts, isEmpty);
+ expect(activity.items.single.read, isFalse);
+ expect(activity.count, count);
+ await close(tester, c);
+ });
+
+ testWidgets('a Mentions-only visit leaves reactions unread', (
+ tester,
+ ) async {
+ final (server, c, activity) = await unread(tester, [reaction('x1')]);
+ await visit(tester, activity, filters: [SuperTabActivityFilter.mentions]);
+ expect(server.activityReadPosts, isEmpty);
+ expect(activity.items.single.read, isFalse);
+ await close(tester, c);
+ });
+
+ testWidgets('a visit on All marks both kinds through the newest', (
+ tester,
+ ) async {
+ final (server, c, activity) = await unread(tester, [
+ at(reply('r1'), '05:00'),
+ at(reaction('x1'), '04:00'),
+ ]);
+ await visit(tester, activity);
+ expect(server.activityReadPosts, hasLength(1));
+ expect(
+ server.activityReadPosts.single['through'],
+ '2026-10-31T05:00:00.000Z',
+ );
+ expect(activity.items.every((i) => i.read), isTrue);
+ await close(tester, c);
+ });
+
+ testWidgets(
+ 'only the list showing when it is left counts: Replies, then Reactions',
+ (tester) async {
+ final (server, c, activity) = await unread(tester, [
+ at(reaction('x1'), '05:00'),
+ at(reply('r1'), '06:00'),
+ ]);
+ await visit(
+ tester,
+ activity,
+ filters: [
+ SuperTabActivityFilter.replies,
+ SuperTabActivityFilter.reactions,
+ ],
+ );
+ expect(
+ server.activityReadPosts.single['through'],
+ '2026-10-31T05:00:00.000Z',
+ );
+ expect(
+ {for (final i in activity.items) i.id: i.read},
+ {'x1': true, 'r1': false},
+ );
+ await close(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'a Replies visit stops before an unread reaction it did not show: '
+ 'the mark is by time',
+ (tester) async {
+ final (server, c, activity) = await unread(tester, [
+ at(reply('new'), '06:00'),
+ at(reaction('x1'), '05:00'),
+ at(reply('old'), '04:00'),
+ ]);
+ activity.setFilter(SuperTabActivityFilter.replies);
+ await visit(tester, activity);
+ expect(
+ server.activityReadPosts.single['through'],
+ '2026-10-31T04:00:00.000Z',
+ );
+ final read = {for (final i in activity.items) i.id: i.read};
+ expect(read, {'new': false, 'x1': false, 'old': true});
+ await close(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'an unread reaction at the same moment as a shown reply stops it too',
+ (tester) async {
+ final (server, c, activity) = await unread(tester, [
+ at(reply('r1'), '05:00'),
+ at(reaction('x1'), '05:00'),
+ ]);
+ activity.setFilter(SuperTabActivityFilter.replies);
+ await visit(tester, activity);
+ expect(server.activityReadPosts, isEmpty);
+ await close(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'a row that arrives while Replies shows is listed, and is read on leaving',
+ (tester) async {
+ final (server, c, activity) = await unread(tester, [
+ at(reply('r1'), '05:00'),
+ ]);
+ await visit(
+ tester,
+ activity,
+ filters: [SuperTabActivityFilter.replies],
+ during: () async {
+ server.activity = {
+ 'items': [at(reply('r2'), '06:00'), at(reply('r1'), '05:00')],
+ 'more': false,
+ };
+ await tester.runAsync(() => activity.load());
+ },
+ );
+ expect(
+ server.activityReadPosts.single['through'],
+ '2026-10-31T06:00:00.000Z',
+ );
+ await close(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'leaving puts the filter back on All; a filter asked for still opens on it',
+ (tester) async {
+ final (_, c, activity) = await unread(tester, [reply('r1')]);
+ activity.setFilter(SuperTabActivityFilter.decisions);
+ await visit(tester, activity);
+ expect(activity.filter, SuperTabActivityFilter.all);
+ await close(tester, c);
+ },
+ );
+ });
+
group('the one # buddy row (#2447) follows the same rules', () {
Future<SuperTabController> show(
WidgetTester tester,
diff --git a/desktop/test/super_tab_catch_up_test.dart b/desktop/test/super_tab_catch_up_test.dart
index 18b323f47..8babf88ed 100644
--- a/desktop/test/super_tab_catch_up_test.dart
+++ b/desktop/test/super_tab_catch_up_test.dart
@@ -340,6 +340,21 @@ void main() {
expect(SuperTabActivity.of(c).filter, SuperTabActivityFilter.decisions);
});
+ testWidgets(
+ 'Activity opened from the sidebar starts on All after a Decisions visit',
+ (tester) async {
+ final c = await showCounted(tester);
+ await tester.tap(find.byKey(_decisions));
+ await tester.pumpAndSettle();
+ expect(SuperTabActivity.of(c).filter, SuperTabActivityFilter.decisions);
+ // The row, with Activity still showing.
+ await tester.tap(find.byKey(const ValueKey('super-activity')));
+ await tester.pumpAndSettle();
+ expect(activityView(), findsOneWidget);
+ expect(SuperTabActivity.of(c).filter, SuperTabActivityFilter.all);
+ },
+ );
+
testWidgets("Needs you's more opens Activity on Mentions", (tester) async {
final c = await showCounted(tester);
expect(
diff --git a/desktop/test/super_tab_heartbeat_test.dart b/desktop/test/super_tab_heartbeat_test.dart
new file mode 100644
index 000000000..83a6ccf05
--- /dev/null
+++ b/desktop/test/super_tab_heartbeat_test.dart
@@ -0,0 +1,237 @@
+import 'dart:async';
+
+import 'package:clock/clock.dart';
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/reading.dart';
+
+import 'support/super_tab_fixture.dart';
+
+bool _isStateRead(String path) =>
+ path == '/api/super-tabs/tab/parts' ||
+ path.startsWith('/api/super-tabs/tab/changes?');
+
+/// A Swarm of five machines, each reporting every 15 s, as a machine's
+/// heartbeat does (cli/src/superTabs/machines.ts MACHINE_HEARTBEAT_MS). What
+/// the app heard and read is counted, and each count is printed for the PR.
+class _Rig {
+ _Rig(this.async, {bool away = false}) {
+ server.append('Hello');
+ server.state['machines'] = [
+ for (final id in _ids)
+ {
+ 'machineId': id,
+ 'name': id,
+ 'contributorId': 'owner',
+ 'maxAgents': 4,
+ 'observation': {
+ 'receivedAt': _at(),
+ 'resources': {'cpu': 1},
+ },
+ },
+ ];
+ c = SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ request: (method, path, {body}) {
+ if (method == 'GET') paths.add(path);
+ return failing ?? server.request(method, path, body: body);
+ },
+ save: server.save,
+ reading: SuperTabReading.desktop,
+ )..start();
+ async.flushMicrotasks();
+ c.pushUntil = clock.now().add(kSwarmPushLease);
+ c.away = away;
+ async.elapse(const Duration(seconds: 3));
+ c.addListener(() => told++);
+ paths.clear();
+ told = 0;
+ }
+
+ static const _ids = ['m1', 'm2', 'm3', 'm4', 'm5'];
+ static int _at() => clock.now().millisecondsSinceEpoch;
+
+ final FakeAsync async;
+ final server = ConversationServer();
+ late final SuperTabController c;
+ final paths = <String>[];
+ int told = 0;
+ Future<Map<String, dynamic>>? failing;
+
+ Map<String, dynamic> machine(String id) => (server.state['machines'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((m) => m['machineId'] == id);
+
+ /// [id] reports now, and the server says so with a machine's push.
+ void beat(String id) {
+ final m = machine(id);
+ m['observation'] = {
+ 'receivedAt': _at(),
+ 'resources': {'cpu': _at() % 97},
+ };
+ c.told(main: false, at: _at());
+ }
+
+ /// A minute of heartbeats: five machines, 15 s apart each, spread evenly.
+ void minute() {
+ for (var i = 0; i < 20; i++) {
+ beat(_ids[i % 5]);
+ async.elapse(const Duration(seconds: 3));
+ }
+ }
+
+ int get states => paths.where(_isStateRead).length;
+ int get messages => paths.where((p) => p.contains('/messages')).length;
+ void close() => c.dispose();
+}
+
+void main() {
+ group('a minute of heartbeats from five machines, on screen', () {
+ test('reads no messages and tells the controller\'s listeners nothing', () {
+ fakeAsync((async) {
+ final r = _Rig(async);
+ final before = r.c.snapshot;
+ r.minute();
+ // ignore: avoid_print
+ print(
+ 'COUNT on screen: state reads ${r.states}, messages reads '
+ '${r.messages}, controller notifications ${r.told}',
+ );
+ expect(r.states, greaterThan(0));
+ expect(r.messages, 0);
+ expect(r.told, 0);
+ expect(identical(r.c.snapshot, before), isTrue);
+ r.close();
+ });
+ });
+
+ test('its machine\'s reading is new, and those listening hear of it', () {
+ fakeAsync((async) {
+ final r = _Rig(async);
+ var heard = 0;
+ r.c.machinesChanged.addListener(() => heard++);
+ r.beat('m3');
+ final at = r.machine('m3')['observation']['receivedAt'];
+ async.elapse(const Duration(seconds: 3));
+ expect(heard, 1);
+ expect(r.c.snapshot!.pool('m3')!['observation']['receivedAt'], at);
+ r.close();
+ });
+ });
+ });
+
+ group('a read a heartbeat came with something else in', () {
+ void redraws(String what, void Function(_Rig r) change, {bool? messages}) {
+ test('$what: everything redraws, and the chat is read', () {
+ fakeAsync((async) {
+ final r = _Rig(async);
+ final before = r.c.snapshot;
+ change(r);
+ r.beat('m1');
+ async.elapse(const Duration(seconds: 3));
+ expect(r.told, greaterThan(0));
+ expect(identical(r.c.snapshot, before), isFalse);
+ expect(r.messages, greaterThan(0));
+ r.close();
+ });
+ });
+ }
+
+ redraws('a new message', (r) => r.server.append('A reply'));
+ redraws('a renamed machine', (r) => r.machine('m2')['name'] = 'Studio');
+ redraws('a paused machine', (r) => r.machine('m2')['paused'] = true);
+ redraws(
+ 'a new machine',
+ (r) => (r.server.state['machines'] as List).add({
+ 'machineId': 'm6',
+ 'name': 'm6',
+ 'contributorId': 'owner',
+ 'maxAgents': 4,
+ }),
+ );
+ redraws(
+ 'a machine gone',
+ (r) => (r.server.state['machines'] as List).removeWhere(
+ (m) => (m as Map)['machineId'] == 'm5',
+ ),
+ );
+ });
+
+ group('a Swarm not on screen', () {
+ test('keeps its slow pace through a minute of heartbeats', () {
+ fakeAsync((async) {
+ final r = _Rig(async, away: true);
+ r.minute();
+ // ignore: avoid_print
+ print(
+ 'COUNT off screen: state reads ${r.states}, messages reads '
+ '${r.messages}, controller notifications ${r.told}',
+ );
+ expect(r.states, lessThanOrEqualTo(4));
+ expect(r.messages, 0);
+ expect(r.told, 0);
+ r.close();
+ });
+ });
+
+ test('still reads a real change at the old pace, heartbeats or not', () {
+ fakeAsync((async) {
+ final r = _Rig(async, away: true);
+ r.beat('m1');
+ async.elapse(const Duration(seconds: 1));
+ r.paths.clear();
+ r.server.append('A reply');
+ r.c.told(main: true, at: clock.now().millisecondsSinceEpoch);
+ async.elapse(const Duration(seconds: 3));
+ expect(r.states, 1);
+ expect(r.c.messages('lead').last.text, 'A reply');
+ r.close();
+ });
+ });
+ });
+
+ group('a machine that goes silent', () {
+ test('redraws once as it passes the offline threshold, no push needed', () {
+ fakeAsync((async) {
+ final r = _Rig(async);
+ for (var i = 0; i < 16; i++) {
+ r.beat(_Rig._ids[i % 4]);
+ async.elapse(const Duration(seconds: 3));
+ }
+ expect(r.told, 1);
+ r.close();
+ });
+ });
+
+ test('redraws once as it comes back', () {
+ fakeAsync((async) {
+ final r = _Rig(async);
+ for (var i = 0; i < 16; i++) {
+ r.beat(_Rig._ids[i % 4]);
+ async.elapse(const Duration(seconds: 3));
+ }
+ r.told = 0;
+ r.beat('m5');
+ async.elapse(const Duration(seconds: 3));
+ expect(r.told, 1);
+ r.close();
+ });
+ });
+ });
+
+ test('a read failing during a heartbeat still says so', () {
+ fakeAsync((async) {
+ final r = _Rig(async);
+ r.failing = Future.error(
+ const SuperTabFailure('UNAVAILABLE', 'Down', statusCode: 503),
+ )..ignore();
+ r.beat('m1');
+ async.elapse(const Duration(seconds: 3));
+ expect(r.told, greaterThan(0));
+ expect(r.c.backendUnreachable, isTrue);
+ r.close();
+ });
+ });
+}
diff --git a/desktop/test/super_tab_heartbeat_widgets_test.dart b/desktop/test/super_tab_heartbeat_widgets_test.dart
new file mode 100644
index 000000000..48ddcf696
--- /dev/null
+++ b/desktop/test/super_tab_heartbeat_widgets_test.dart
@@ -0,0 +1,266 @@
+import 'package:clock/clock.dart';
+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/controller.dart';
+import 'package:harness/super_tabs/machines.dart';
+import 'package:harness/super_tabs/project_status_card.dart';
+import 'package:harness/super_tabs/reading.dart';
+import 'package:harness/super_tabs/roster.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/super_tab_fixture.dart';
+
+const _ids = ['m1', 'm2', 'm3', 'm4', 'm5'];
+
+/// The chat, the roster, the Status card and the machines list on one screen,
+/// over a Swarm of five machines, counting what each rebuilds.
+class _Screen {
+ _Screen(this.tester);
+ final WidgetTester tester;
+ final server = ConversationServer();
+ late final SuperTabController c;
+ final rebuilt = <Type, int>{};
+ final rows = <String, int>{};
+ int machineCalls = 0;
+ int rosterBuilds = 0;
+ ValueNotifier<bool>? collapsed;
+
+ static int _at() => clock.now().millisecondsSinceEpoch;
+
+ Map<String, dynamic> machine(String id) => (server.state['machines'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((m) => m['machineId'] == id);
+
+ Future<void> show({bool ticks = false, bool collapse = false}) async {
+ server.append('Hello');
+ server.state['machines'] = [
+ for (final id in _ids)
+ {
+ 'machineId': id,
+ 'name': id,
+ 'contributorId': 'owner',
+ 'maxAgents': 4,
+ 'observation': {
+ 'receivedAt': _at(),
+ 'resources': {'cpuPercent': 1},
+ },
+ },
+ ];
+ c = SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ request: server.request,
+ save: server.save,
+ reading: SuperTabReading.desktop,
+ )..start();
+ await tester.pump();
+ await tester.pump();
+ c.pushUntil = clock.now().add(kSwarmPushLease);
+ collapsed = ValueNotifier(collapse);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: Row(
+ children: [
+ Expanded(
+ child: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ SizedBox(
+ width: 300,
+ child: Column(
+ children: [
+ Expanded(
+ child: SuperTabRoster(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenAgent: (_) {},
+ onAnswer: (_) {},
+ ),
+ ),
+ SuperTabProjectStatusCard(
+ controller: c,
+ projectId: c.snapshot?.projects.firstOrNull?.id ?? 'p',
+ ),
+ Expanded(
+ child: ValueListenableBuilder(
+ valueListenable: collapsed!,
+ builder: (context, shut, _) => SuperTabMachines(
+ controller: c,
+ onAddAgent: (_) {},
+ collapsed: shut,
+ ticks: ticks,
+ now: () {
+ machineCalls++;
+ return clock.now();
+ },
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(seconds: 3));
+ // What opening the chat changed (its read mark) is read before counting.
+ c.told(main: true);
+ await tester.pump(const Duration(seconds: 3));
+ await tester.pump();
+ debugOnRebuildDirtyWidget = _count;
+ addTearDown(() => debugOnRebuildDirtyWidget = null);
+ rebuilt.clear();
+ rows.clear();
+ rosterBuilds = 0;
+ machineCalls = 0;
+ }
+
+ void _count(Element element, bool _) {
+ final key = element.widget.key;
+ if (key == const PageStorageKey('super-tab-resources-tab')) rosterBuilds++;
+ if (key is ValueKey<String> && key.value.startsWith('super-machine-row-')) {
+ rows.update(key.value.substring(18), (n) => n + 1, ifAbsent: () => 1);
+ }
+ void bump(Type type) =>
+ rebuilt.update(type, (n) => n + 1, ifAbsent: () => 1);
+ for (final type in const [
+ SuperTabView,
+ SuperTabRoster,
+ SuperTabProjectStatusCard,
+ SuperTabMachines,
+ ]) {
+ if (element.widget.runtimeType == type) bump(type);
+ }
+ element.visitAncestorElements((up) {
+ final type = up.widget.runtimeType;
+ if (type == SuperTabView ||
+ type == SuperTabRoster ||
+ type == SuperTabProjectStatusCard ||
+ type == SuperTabMachines) {
+ bump(type);
+ return false;
+ }
+ return true;
+ });
+ }
+
+ Future<void> beat(String id) async {
+ machine(id)['observation'] = {
+ 'receivedAt': _at(),
+ 'resources': {'cpuPercent': _at() % 97},
+ };
+ c.told(main: false, at: _at());
+ await tester.pump(const Duration(seconds: 3));
+ await tester.pump();
+ }
+
+ Future<void> close() async {
+ await tester.pumpWidget(const SizedBox());
+ c.dispose();
+ }
+}
+
+void main() {
+ testWidgets(
+ 'a minute of heartbeats rebuilds no chat, roster or Status card',
+ (tester) async {
+ final s = _Screen(tester);
+ await s.show();
+ for (var i = 0; i < 20; i++) {
+ await s.beat(_ids[i % 5]);
+ }
+ // ignore: avoid_print
+ print(
+ 'COUNT rebuilt elements a minute: ${s.rebuilt}, '
+ 'roster list builds ${s.rosterBuilds}',
+ );
+ expect(s.rebuilt[SuperTabView] ?? 0, 0);
+ expect(s.rebuilt[SuperTabProjectStatusCard] ?? 0, 0);
+ // Only its own 30-second clock, for ages and leases on a quiet Swarm.
+ expect(s.rosterBuilds, lessThanOrEqualTo(2));
+ await s.close();
+ },
+ );
+
+ testWidgets('a machine\'s report redraws its own row alone', (tester) async {
+ final s = _Screen(tester);
+ await s.show();
+ // The first report of a test draws what the clock moved since the screen
+ // opened (no clock runs here): each row's "just now" passing.
+ await s.beat('m1');
+ await tester.pump(const Duration(seconds: 6));
+ await s.beat('m1');
+ s.rows.clear();
+ await s.beat('m2');
+ expect(s.rows.keys, ['m2']);
+ await s.close();
+ });
+
+ group('the machines list\'s one-second timer', () {
+ testWidgets('runs while it shows, redrawing nothing if nothing changed', (
+ tester,
+ ) async {
+ final s = _Screen(tester);
+ await s.show(ticks: true);
+ await tester.pump(const Duration(seconds: 5));
+ expect(s.machineCalls, greaterThan(0));
+ expect(s.rows, isEmpty);
+ await s.close();
+ });
+
+ testWidgets('stops while the Swarm is away, and runs again on return', (
+ tester,
+ ) async {
+ final s = _Screen(tester);
+ await s.show(ticks: true);
+ s.c.away = true;
+ await tester.pump();
+ s.machineCalls = 0;
+ await tester.pump(const Duration(seconds: 5));
+ expect(s.machineCalls, 0);
+ s.c.away = false;
+ await tester.pump(const Duration(seconds: 5));
+ expect(s.machineCalls, greaterThan(0));
+ await s.close();
+ });
+
+ testWidgets('stops while its group is collapsed', (tester) async {
+ final s = _Screen(tester);
+ await s.show(ticks: true, collapse: true);
+ await tester.pump();
+ s.machineCalls = 0;
+ await tester.pump(const Duration(seconds: 5));
+ expect(s.machineCalls, 0);
+ await s.close();
+ });
+ });
+
+ testWidgets('a row says what its machine last reported', (tester) async {
+ final s = _Screen(tester);
+ await s.show();
+ s.machine('m1')['observation'] = <String, dynamic>{
+ 'receivedAt': clock.now().millisecondsSinceEpoch,
+ 'resources': {'cpuPercent': 7},
+ };
+ s.c.told(main: false, at: clock.now().millisecondsSinceEpoch);
+ await tester.pump(const Duration(seconds: 3));
+ await tester.pump();
+ expect(s.c.snapshot!.pool('m1')!['observation']['resources'], {
+ 'cpuPercent': 7,
+ });
+ expect(s.rows['m1'], greaterThan(0));
+ await s.close();
+ });
+}
diff --git a/desktop/test/super_tab_personal_projects_test.dart b/desktop/test/super_tab_personal_projects_test.dart
index 3e832f305..a4cd87099 100644
--- a/desktop/test/super_tab_personal_projects_test.dart
+++ b/desktop/test/super_tab_personal_projects_test.dart
@@ -197,6 +197,26 @@ void main() {
}
});
+ test('the daemon\'s own form, host/owner/repo, is that repo too', () {
+ // What every agent reports as its project's remote (cli agentProject.ts
+ // canonicalRepository): no scheme, no user, no .git.
+ for (final form in [
+ 'github.com/acme/api',
+ 'GitHub.com/Acme/Api',
+ 'github.com/acme/api/',
+ ]) {
+ expect(normalizedRemote(form), 'github.com/acme/api', reason: form);
+ }
+ expect(
+ normalizedRemote('example.com:2222/Org/App'),
+ 'example.com/org/app',
+ );
+ expect(
+ normalizedRemote('gitlab.com/team/sub/api'),
+ 'gitlab.com/team/sub/api',
+ );
+ });
+
test('a folder or nothing is no repo', () {
for (final form in [
null,
@@ -335,6 +355,35 @@ void main() {
},
);
+ test('panes whose agents report the daemon\'s own remote form get repo projects', () async {
+ final f = SuperTabLaunchFixture();
+ f.app.machineStates['m']!.agents = [
+ _agent('n1', remote: 'github.com/acme/api', cwd: '/w/api'),
+ _agent('n2', remote: 'github.com/acme/web', cwd: '/w/web'),
+ ];
+ _machine(f.app, 'laptop').agents = [
+ _agent('n1', remote: 'github.com/acme/api', cwd: '/x/api-copy'),
+ ];
+ _tab(f.app, 'one', [_pane('m', 'n1'), _pane('m', 'n2')]);
+ _tab(f.app, 'two', [_pane('laptop', 'n1')]);
+ expect(
+ [for (final e in personalPanes(f.app)) e.repo],
+ ['github.com/acme/api', 'github.com/acme/web', 'github.com/acme/api'],
+ );
+ final c = await _personal(f);
+ await PersonalProjects.of(f.app).sync(c);
+ expect(
+ [for (final p in _commands(f)) p['operationId']],
+ [
+ personalProjectOperation('github.com/acme/api'),
+ personalProjectOperation('github.com/acme/web'),
+ ],
+ );
+ final names = [for (final p in c.snapshot!.projects) p.name];
+ expect(names, containsAll(['api', 'web']));
+ expect(names, isNot(contains('scratch')));
+ });
+
test('nothing is sent of a pane but its project\'s name', () async {
final f = SuperTabLaunchFixture();
_desk(f);
diff --git a/docs/plans/2026-11-02-heartbeat-no-wake-plan.md b/docs/plans/2026-11-02-heartbeat-no-wake-plan.md
new file mode 100644
index 000000000..80eda8e4e
--- /dev/null
+++ b/docs/plans/2026-11-02-heartbeat-no-wake-plan.md
@@ -0,0 +1,93 @@
+# A machine's heartbeat no longer wakes a Swarm's reads and redraws Implementation Plan
+
+> **Way of working:** by this project's instructions (Engineer role), not subagent-driven-development: each failing test committed and watched fail before its code, the branch pushed after each task, one independent review of the pull request. There is no Execution Handoff.
+
+**Goal:** A machine's heartbeat changes only what shows machines: no messages read, no chat, roster or Status card rebuild, and a Swarm not on screen keeps its slow pace.
+
+**Architecture:** The server already labels a heartbeat's push `machine` alone. `SuperTabParts.apply` says when a read changed only what a machine reports; the controller then replaces the machines in the snapshot it holds, tells a new `machinesChanged` listenable, and neither reads messages nor notifies its own listeners. The machines list listens to that, and its one-second timer runs only while it shows, redrawing only rows whose words changed.
+
+**Tech Stack:** Flutter, `flutter_test`, `fake_async`, in `desktop/`.
+
+**Spec:** Task #2168 (Dee). Line numbers in its brief are from main at 08e24276a.
+
+## Global Constraints
+
+- The PR body starts with: Requested by [email protected] through Harness.
+- Desktop tests use a memory store and a fake sign-in; never a test that signs this Mac out of the real CLI.
+- Swarm code stays out of `cli/src/core`. No backend change.
+- No on/off switch: the change ships on.
+- A told `main` change still reads at `pollInterval`, on screen or off: a tag reaches an away Swarm's badge as fast as before.
+- The web build's reading (`SuperTabReading` in `web_chrome.dart`) keeps its behaviour for its messages reads.
+
+## Review Focus
+
+- A read that brings a heartbeat and a real change together (a group, an agent, `derived.agents`, a new or removed machine, a renamed or paused one) is not machine-only: everything redraws and messages are read.
+- A `main` push arriving while a machine-only read waits on the slow off-screen gap must not wait that gap.
+- A machine that goes silent sends no push: anything reading its age (agent marks, the terminal notice) must still say offline when the threshold passes, with no other machine's heartbeat to redraw it.
+- A failing read during a heartbeat still says the Swarm can't be reached: a quiet read must not swallow it.
+- An open dialog that shows a machine's readings still updates on a heartbeat.
+
+## Design
+
+- **Growth, migration, audience, identity:** N/A because nothing is stored and no read's scope changes; the same read returns the same parts.
+- **Concurrency:** N/A because the controller's reads are already one at a time (`refresh`).
+- **Read cost:** the point of this task: a heartbeat reads state changes only.
+- **Scale:** at 10x machines the on-screen state reads stay capped at one per 3 s and off screen one per 15 s. The first-open log after the Desktop release is the live check.
+- **Compatibility:** an older backend sends no push label it does not have; a read that can't be told apart redraws as today.
+- **Failure:** a failed read still notifies, by comparing the failing state before and after.
+- **Platforms:** all Desktop platforms; the web keeps reading messages as it does.
+
+---
+
+### Task 1: A machine-only read reads no messages and redraws nothing but machines
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/parts.dart` (`SuperTabPartsChange`, `apply`), `desktop/lib/super_tabs/model.dart` (`SuperTabSnapshot.machines`), `desktop/lib/super_tabs/controller.dart` (`_read`, `_readParts`)
+- Test: `desktop/test/super_tab_heartbeat_test.dart`, `desktop/test/support/super_tab_fixture.dart`
+
+**Interfaces:**
+- Produces: `SuperTabPartsChange.machinesOnly` (bool); `SuperTabController.machinesChanged` (`Listenable`); `ConversationServer.heartbeat(machineId)` in the fixture.
+
+- [ ] **Step 1: Write the failing tests:** over a minute of heartbeats from 5 machines on screen: no messages read, the controller's listeners are not told, the snapshot object stays and its machine's reading is new, `machinesChanged` fires. A read carrying a heartbeat and a group change, a renamed machine, a new machine or a changed `derived.agents` does all of today's. A read failing during a heartbeat notifies.
+- [ ] **Step 2: Run to verify they fail.** Run: `flutter test test/super_tab_heartbeat_test.dart`. Expected: FAIL.
+- [ ] **Step 3: Implement.** `apply` tracks a change to anything but a machine part whose data differs only in `observation` and `lent`/`lentDays`, or `derived.machines`. `_read` asks messages only for a told `main`, is quiet for a told `machine` alone, and on `machinesOnly` replaces the machines in place and moves `_messagesAt` along with `lastChangedAt`.
+- [ ] **Step 4: Run to verify they pass.** Same command, then `flutter test test/super_tab_pushes_test.dart test/super_tab_quiet_mode_test.dart test/super_tab_controller_test.dart`.
+- [ ] **Step 5: Commit** the test first, then the code; push.
+
+### Task 2: An off-screen Swarm keeps its pace, and a silent machine still shows offline
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/controller.dart` (`_readWhenAllowed`, `_pollDue`, `_read`)
+- Test: `desktop/test/super_tab_heartbeat_test.dart`
+
+**Interfaces:**
+- Consumes: `machinesOnly`; `kSuperTabMachineOfflineAfter`.
+
+- [ ] **Step 1: Write the failing tests:** away, a minute of heartbeats from 5 machines reads state at most once per `awayPoll` (4); a `main` push during that wait reads at `pollInterval`, not after it; a machine whose heartbeats stop tells the controller's listeners once when it passes the offline threshold, and live machines never do.
+- [ ] **Step 2: Run to verify they fail.** Same file. Expected: FAIL.
+- [ ] **Step 3: Implement.** A told machine alone waits `_every`; a told `main` cancels that wait. One timer for the next machine to pass the threshold, re-armed by each machine read, tells listeners only when the offline set changed.
+- [ ] **Step 4: Run to verify they pass.**
+- [ ] **Step 5: Commit** the test first, then the code; push.
+
+### Task 3: The machines list listens for itself, and ticks only while it shows
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/machines.dart` (`_SuperTabMachinesState`), and each open dialog that shows a machine's readings and listens to the controller
+- Test: `desktop/test/super_tab_heartbeat_widgets_test.dart`
+
+**Interfaces:**
+- Consumes: `SuperTabController.machinesChanged`, `SuperTabController.away`.
+
+- [ ] **Step 1: Write the failing tests:** with `SuperTabView`, the roster, the Status card and `SuperTabMachines` on screen, a minute of heartbeats from 5 machines: chat, roster and Status card build counts stay put; only the row of the machine that reported rebuilds. The one-second timer is not running while the Swarm is away, or the group is collapsed, and runs again when it shows.
+- [ ] **Step 2: Run to verify they fail.** Run: `flutter test test/super_tab_heartbeat_widgets_test.dart`. Expected: FAIL.
+- [ ] **Step 3: Implement.** Each row in its own listenable builder; a tick or `machinesChanged` compares each row's words and order with what it shows and redraws only what differs.
+- [ ] **Step 4: Run to verify they pass,** then `flutter test test/super_tab_machines_test.dart test/super_tab_roster_test.dart`.
+- [ ] **Step 5: Commit** the test first, then the code; push.
+
+### Task 4: Counts before and after
+
+**Files:**
+- Test: `desktop/test/super_tab_heartbeat_test.dart`, `desktop/test/super_tab_heartbeat_widgets_test.dart`
+
+- [ ] **Step 1:** Run both files at main's code (the tests' red run) and at the head; record reads and rebuilds per minute on and off screen in a PR comment.
+- [ ] **Step 2:** Run the Super Tab Desktop tests affected, by the symbols changed. Mark the PR ready and ask the Reviewer.
diff --git a/docs/plans/2026-11-02-resumed-session-rejoins-swarm-plan.md b/docs/plans/2026-11-02-resumed-session-rejoins-swarm-plan.md
new file mode 100644
index 000000000..f4d605ff1
--- /dev/null
+++ b/docs/plans/2026-11-02-resumed-session-rejoins-swarm-plan.md
@@ -0,0 +1,101 @@
+# A reopened session rejoins the Swarm Implementation Plan
+
+> **Way of working:** by this project's instructions: each failing test committed before its code, then one independent review of the pull request.
+
+**Goal:** When an agent removed because its session closed has that session reopened on its machine, it is listed again with its groups, role and configuration, by that machine's host alone.
+
+**Architecture:** The removal keeps a record in the machine's own part. Only that machine's host sees which sessions are recorded, in its roster row. It lists a recorded session that runs again in its machine report, and that report's write restores the agent. The report is already authenticated as this machine's contributor, so no person or agent has a way to send this.
+
+**Tech Stack:** TypeScript, Fastify, Prisma on MongoDB, Vitest integration tests with a real replica set.
+
+**Spec:** Task #2131, a follow-up to #2569 (`docs/plans/2026-11-02-closed-agents-leave-list-plan.md`).
+
+## Global Constraints
+
+- PR body starts with: Requested by [email protected] through Harness.
+- Two security reviews (who may add an agent): Cleo and Luna.
+- Full Super Tab integration suite before Ready.
+- Swarm code stays out of `cli/src/core`.
+- A new field in a machine part goes through `parts/shape.ts` both ways, or it vanishes on load.
+- Old hosts keep working: they send nothing new and their sessions simply don't rejoin by themselves.
+
+## Departure from the brief
+
+The brief says "a host-only command". This uses the machine report instead. A command goes through `applyCommand`, where every actor check would need an exception, and the report already proves the machine and its contributor, carries a generation, and writes that machine's part. There is less to attack, and nothing new to authorize.
+
+## What #2569's close order means here
+
+The removal also orders the host to close the session. A session reopened before that close is restored and the order dropped, as a person's add does. A session its Team account is held for is never restored, and the hold stands until its host confirms. A session that read a private chat keeps no record at all.
+
+## What security review added
+
+A restore takes the rules a person's add takes, by one check (`restoreRefusal`) and then the share and session record (`bindSession`), written in the same transaction: never onto a Team account serving another project, never a teammate's project where that machine can't take it, never into a task marked Team-written unless it runs in a Team account. A restore logs its agent, machine and project.
+
+## Review Focus
+
+- A person left the Swarm or rejoined, the machine's share was revoked, or the contribution is new: the record is dropped and nothing is restored.
+- A private chat or a dormant, archived or deleted group in the record: the agent doesn't come back into it.
+- A session someone asked to stop, or a confidential or Team-held one: no record, so it can't come back.
+- The same session added by hand, or registered in another Swarm, in the meantime: no second agent, no restore.
+- A report that lists a recorded session and is refused or retried: nothing half-restored, and a report never fails because a restore can't happen.
+
+---
+
+### Task 1: The removal keeps a record, on the machine's part
+
+**Files:**
+- Modify: `backend/src/superTabs/closedAgents.ts`, `model.ts`, `parts/types.ts`, `parts/shape.ts`, `migration/verify.ts`, `machines.ts`, `commands.ts`
+- Test: `backend/integration/superTabLiveness.test.ts`, `backend/src/superTabs/parts/shape.test.ts`
+
+**Interfaces:**
+- Produces: `SuperTabState.removedSessions?: RemovedSession[]`, with `RemovedSession = { machineId; harnessId; agent: Agent; groupIds: string[]; leadOf: string[]; removedAt: number }`, and `REMOVED_KEPT = 50` per machine, `REMOVED_KEEP_MS = 30 days`.
+
+- [ ] **Step 1: Write the failing tests:** `shape.test.ts` round-trips `removedSessions`; the record is not in any person's read of the Swarm; a stopped-by-request or confidential agent keeps none.
+- [ ] **Step 2: Run to verify they fail.** Run: `npm test -- src/superTabs/parts/shape.test.ts`. Expected: FAIL, the field vanishes.
+- [ ] **Step 3: Implement.** `removeClosedAgents` writes the record. Strip it in `model.ts`'s read copy, as `closingSessions` is. Drop a machine's records where its reservations go when it leaves.
+- [ ] **Step 4: Run to verify they pass.** Same command. Expected: PASS.
+- [ ] **Step 5: Commit.**
+
+### Task 2: A report that lists a recorded session restores it
+
+**Files:**
+- Modify: `backend/src/superTabs/closedAgents.ts`, `store.ts` (`fullReading`), `read/hostRows.ts`, `read/contract.ts`
+- Test: `backend/integration/superTabLiveness.test.ts`
+
+**Interfaces:**
+- Consumes: `RemovedSession` from Task 1.
+- Produces: `restoreSessions(state, machineId, runningHarnessIds, now, elsewhere): Agent[]`, and the host row field `removedHarnessIds: string[]`.
+
+- [ ] **Step 1: Write the failing tests:** `a removed agent whose session resumes is listed again with its group and role`; `another machine's report can't restore it`; each Review Focus refusal; `the record goes after 30 days`.
+- [ ] **Step 2: Run to verify they fail.** Run: `npx vitest run --config vitest.super-tabs.config.ts integration/superTabLiveness.test.ts`. Expected: FAIL.
+- [ ] **Step 3: Implement** `restoreSessions` and load the record's groups in `fullReading`, as the closed agents' are.
+- [ ] **Step 4: Run to verify they pass, then** `npm run test:super-tabs`. Expected: PASS.
+- [ ] **Step 5: Commit.**
+
+### Task 3: The host lists a recorded session that runs again
+
+**Files:**
+- Modify: `cli/src/superTabs/machines.ts`
+- Test: the spec beside it
+
+**Interfaces:**
+- Consumes: the row's `removedHarnessIds`.
+
+- [ ] **Step 1: Write the failing test:** `a recorded session that runs again is listed running; a stopped or gone one isn't, and neither is one the row doesn't name`.
+- [ ] **Step 2: Run to verify it fails.** Run: `npx vitest run src/superTabs/machines`. Expected: FAIL.
+- [ ] **Step 3: Implement** in the report pass, next to `running`.
+- [ ] **Step 4: Run to verify it passes.**
+- [ ] **Step 5: Commit.**
+
+## Design
+
+- **Growth:** at most 50 records per machine, oldest first. Deleted on restore, after 30 days, or when the machine leaves.
+- **Concurrency:** in the report's own transaction, on the machine part it already writes, so a retry reads the record again.
+- **Read cost:** none on a report with no recorded session running. Otherwise one read of the record's groups and one of other Swarms' registrations.
+- **Scale:** at 10x the machine part's size warns first; 50 records at about 1 KB each.
+- **Compatibility:** an old host ignores the new row field. An old backend sends none.
+- **Migration and rollback:** none. A rollback ignores the field and shape drops it.
+- **Audience:** the server restores only into open groups of the agent's own project, never a private chat; the record is left out of every person's read.
+- **Identity:** the report is authenticated as the machine's contributor, and the record must match that contributor, membership generation, machine owner and share grant.
+- **Failure:** a restore that can't happen drops the record and logs its reason by code; the report still succeeds.
+- **Platforms:** all that report machines.