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 1440: #2509 #2512 #2519 #2538 (#2543)

0xken15300f5f04a349
diff --git a/backend/integration/bench/run.ts b/backend/integration/bench/run.ts
index f02feda47..281047d6d 100644
--- a/backend/integration/bench/run.ts
+++ b/backend/integration/bench/run.ts
@@ -8,6 +8,7 @@ import { readProfile, renderProfile, startProfiling } from './profile.js'
import { renderMarkdown } from './report.js'
import { benchStamps } from './stamps.js'
import { listGroupIndexes } from '../../src/superTabs/parts/indexed.js'
+import { readDelta } from '../../src/superTabs/cachedReads.js'
/** `npm run bench:swarm-state -- [options] [--profile]` (README.md). Writes `<driver>-<time>.json` and `.md` to the results
* folder; with `--profile`, every database operation of the run goes through Mongo's profiler and the report adds what each
@@ -19,7 +20,9 @@ async function main() {
const database = await localDatabase()
// As each server does at startup (server.ts): hot reads name the indexes the database has.
await listGroupIndexes(database.db)
- const stamps = await benchStamps(cache)
+ // As the server: deltas unless SWARM_CACHE_DELTA=off (spec 2026-11-02), so one flag compares the two.
+ const stamps = await benchStamps(cache, process.env.SWARM_CACHE_DELTA === 'off' ? undefined
+ : readDelta(database.db))
try {
if (profile) await startProfiling(database.db)
const peak = profile ? peakConnections(database.db) : null
diff --git a/backend/integration/bench/stamps.ts b/backend/integration/bench/stamps.ts
index 2824ed74a..80581a2fe 100644
--- a/backend/integration/bench/stamps.ts
+++ b/backend/integration/bench/stamps.ts
@@ -1,16 +1,18 @@
import { Redis } from 'ioredis'
-import { configureSwarmStamps, redisStamps, type StampScope } from '../../src/superTabs/cache.js'
+import { configureSwarmStamps, redisStamps, type CacheOptions, type StampScope } from '../../src/superTabs/cache.js'
import { MemoryStamps } from '../../src/superTabs/cache.test-support.js'
-/** Sets up the read cache's stamps for the run (config.ts `--cache`); returns what the report names and how to close it. */
-export async function benchStamps(cache: string): Promise<{ label: string; close(): Promise<void> }> {
+/** Sets up the read cache's stamps for the run (config.ts `--cache`); returns what the report names and how to close it.
+ * `delta`: the cache patches what it holds from deltas, as a server with SWARM_CACHE_DELTA=on does (server.ts). */
+export async function benchStamps(cache: string, delta?: CacheOptions['delta']): Promise<{ label: string; close(): Promise<void> }> {
+ const patching = delta ? { delta } : {}, said = delta ? ', patched from deltas' : ''
if (cache === 'off') {
configureSwarmStamps(new MemoryStamps(), { reads: false })
return { label: 'off (SWARM_READ_CACHE=off: every read goes to MongoDB)', close: async () => configureSwarmStamps(null) }
}
if (cache === 'memory') {
- configureSwarmStamps(new MemoryStamps())
- return { label: 'on, stamps in this process', close: async () => configureSwarmStamps(null) }
+ configureSwarmStamps(new MemoryStamps(), patching)
+ return { label: `on, stamps in this process${said}`, close: async () => configureSwarmStamps(null) }
}
const pub = new Redis(cache, { maxRetriesPerRequest: 1, enableOfflineQueue: false }), sub = new Redis(cache)
await Promise.all([pub, sub].map(r => new Promise(resolve => r.once('ready', resolve))))
@@ -27,6 +29,6 @@ export async function benchStamps(cache: string): Promise<{ label: string; close
sub.on('message', heard)
return () => { sub.off('message', heard) }
},
- }))
- return { label: `on, stamps in Redis (${new URL(cache).host})`, close: async () => { configureSwarmStamps(null); await Promise.all([pub.quit(), sub.quit()]) } }
+ }), patching)
+ return { label: `on, stamps in Redis (${new URL(cache).host})${said}`, close: async () => { configureSwarmStamps(null); await Promise.all([pub.quit(), sub.quit()]) } }
}
diff --git a/backend/integration/superTabCache.test.ts b/backend/integration/superTabCache.test.ts
index ba4073370..9caac1214 100644
--- a/backend/integration/superTabCache.test.ts
+++ b/backend/integration/superTabCache.test.ts
@@ -339,6 +339,60 @@ describe('named light conversations', () => {
})
})
+describe('loadDelta', () => {
+ /** A group renamed, another removed and a machine's own reading, all after `since`. */
+ async function changes(tabId: string, web: string, removed: string) {
+ const since = Date.now()
+ await new Promise(resolve => setTimeout(resolve, 5))
+ await swarmTransaction(db, async tx => {
+ const loaded = await parts.loadActive(tx, tabId, { groupIds: [web, removed] })
+ const group = loaded.groups.find(g => g.key === web)!, gone = loaded.groups.find(g => g.key === removed)!
+ const machine = (await parts.loadMachines(tx, tabId))[0]!
+ const t = Date.now()
+ await guardedWrite(tx, tabId, { op: 'update', kind: 'group', key: web, seen: group.version, data: { ...group.data!, title: 'Web 2' } }, t)
+ await guardedWrite(tx, tabId, { op: 'remove', kind: 'group', key: removed, seen: gone.version, data: gone.data }, t)
+ await guardedWrite(tx, tabId, { op: 'update', kind: 'machine', key: machine.key, seen: machine.version, data: machine.data }, t)
+ })
+ return since
+ }
+
+ it('returns only what changed after since, tombstones and readings included', async () => {
+ const { tabId, web, done } = await privateScene()
+ const since = await changes(tabId, web, done)
+ const delta = await parts.loadDelta(db, tabId, since, parts.PART_KINDS)
+ const machine = (await parts.loadMachines(db, tabId))[0]!
+ expect(delta.parts.map(p => `${p.kind}:${p.key}`).sort()).toEqual([`group:${done}`, `group:${web}`, `machine:${machine.key}`].sort())
+ expect(delta.parts.find(p => p.key === done)!.deleted).toBe(true)
+ expect(delta.parts.find(p => p.kind === 'machine')!.readAt).toBeGreaterThan(since)
+ expect(delta.head).toBeNull()
+ expect((await parts.loadDelta(db, tabId, Date.now() + 1_000, parts.PART_KINDS)).parts).toEqual([])
+ })
+
+ it('carries the head columns when the head changed', async () => {
+ const { tabId } = await privateScene()
+ const since = Date.now()
+ await new Promise(resolve => setTimeout(resolve, 5))
+ await swarmTransaction(db, async tx => {
+ const head = (await parts.loadActive(tx, tabId)).head
+ const row = await tx.swarmHead.findUniqueOrThrow({ where: { id: `${tabId}:head` } })
+ await guardedWrite(tx, tabId, { op: 'update', kind: 'head', key: 'head', seen: head.version, data: { ...head.data!, name: 'Renamed' },
+ head: { groupCounter: row.groupCounter + 1, visibilityEpoch: row.visibilityEpoch, sequenceBase: row.sequenceBase } }, Date.now())
+ })
+ const row = await db.swarmHead.findUniqueOrThrow({ where: { id: `${tabId}:head` } })
+ const delta = await parts.loadDelta(db, tabId, since, parts.PART_KINDS)
+ expect(delta.head).toEqual({ groupCounter: row.groupCounter, visibilityEpoch: row.visibilityEpoch, sequenceBase: row.sequenceBase })
+ expect(delta.parts.find(p => p.kind === 'head')!.data).toMatchObject({ name: 'Renamed' })
+ })
+
+ it('reads only the kinds asked', async () => {
+ const { tabId, web, done } = await privateScene()
+ const since = await changes(tabId, web, done)
+ const read = await partReads(() => parts.loadDelta(db, tabId, since, ['machine']))
+ expect(Object.keys(read.byCollection)).toEqual(['SwarmMachine'])
+ expect(read.value.parts.map(p => p.kind)).toEqual(['machine'])
+ })
+})
+
describe('the change feed', () => {
it('gives what loadChanged gives for any cursor, and serves a later cursor at the same stamp from memory', async () => {
const { tabId, web } = await privateScene()
diff --git a/backend/integration/superTabCacheDelta.test.ts b/backend/integration/superTabCacheDelta.test.ts
new file mode 100644
index 000000000..066f384cb
--- /dev/null
+++ b/backend/integration/superTabCacheDelta.test.ts
@@ -0,0 +1,151 @@
+import { randomUUID } from 'node:crypto'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import { configureSwarmStamps, swarmTransaction, SwarmCache } from '../src/superTabs/cache.js'
+import { MemoryStamps } from '../src/superTabs/cache.test-support.js'
+import { cacheDigest } from '../src/superTabs/cachePatch.js'
+import * as parts from '../src/superTabs/parts/index.js'
+import { guardedWrite } from '../src/superTabs/parts/write.js'
+import { DIRECT, readDelta, readLastChangedAt, readParts, type ReadNamed } from '../src/superTabs/cachedReads.js'
+import { migrateSwarm } from '../src/superTabs/migration/migrate.js'
+import { stableId, type SuperTabState } from '../src/superTabs/model.js'
+import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'
+import { outsider as outsiderActor, owner as ownerActor, peer as peerActor, richSwarm } from '../src/superTabs/read/fixture.test-support.js'
+
+// The read cache patched from deltas (spec docs/superpowers/specs/2026-11-02-swarm-cache-delta-design.md, Phases 1-2) against
+// reads with no cache, after real writes, on a fresh loopback replica set. Setup as integration/superTabCache.test.ts.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+let stamps: MemoryStamps
+const person = (actor: { userId: string; email: string }): AuthUser => ({ sub: actor.userId, email: actor.email, autonomousEnv: 'prod', role: 'user' })
+const people = { owner: person(ownerActor), peer: person(peerActor), outsider: person(outsiderActor) }
+
+beforeAll(async () => {
+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ const uri = replica.getUri(`swarm_cache_delta_test_${randomUUID().replaceAll('-', '_')}`)
+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {
+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,
+ })
+ db = new PrismaClient({ datasources: { db: { url: uri } } })
+ for (const each of Object.values(people)) await db.user.create({ data: { id: each.sub, externalId: `fixture-${each.sub}`, email: each.email, autonomousEnv: 'prod' } })
+})
+afterAll(async () => {
+ configureSwarmStamps(null)
+ await db?.$disconnect()
+ await replica?.stop()
+})
+beforeEach(() => { stamps = new MemoryStamps(); configureSwarmStamps(stamps) })
+afterEach(() => configureSwarmStamps(null))
+
+async function scene() {
+ const s = richSwarm(Date.now())
+ const tabId = `tab-${randomUUID()}`
+ await writeLegacySwarm(db, { state: { ...structuredClone(s.state), id: tabId } as SuperTabState, revision: 10 })
+ const report = await migrateSwarm(db, tabId)
+ if (!report.ok) throw new Error(report.error)
+ return { tabId, web: s.web, secret: s.secret }
+}
+
+/** A seeded generator, so a failure replays. */
+function seeded(seed: number) {
+ let x = seed
+ return () => { x = (x * 1_103_515_245 + 12_345) % 2_147_483_648; return x / 2_147_483_648 }
+}
+
+/** One write, committed as a command commits: in a Swarm transaction, guarded by the version read in it. */
+async function write(tabId: string, pick: (all: parts.SwarmParts) => parts.PartWrite | null, stamp = Date.now()): Promise<boolean> {
+ return swarmTransaction(db, async tx => {
+ const change = pick(await parts.loadAll(tx, tabId))
+ if (!change) return false
+ await guardedWrite(tx, tabId, change, stamp)
+ return true
+ })
+}
+
+const liveOf = <T>(list: parts.Part<T>[]) => list.filter(p => !p.deleted)
+
+describe('the patched cache answers as reads with no cache do', () => {
+ it('patched entries equal fresh loads after every write', { timeout: 120_000 }, async () => {
+ const { tabId, web, secret } = await scene()
+ const delta = vi.fn(readDelta(db))
+ const cache = new SwarmCache(stamps, { delta })
+ const store = new SuperTabStore(db, Date.now, null, { readCache: cache })
+ const random = seeded(20261102)
+ const one = <T>(list: T[]): T | undefined => list[Math.floor(random() * list.length)]
+ let n = 0
+
+ const ops: Array<() => Promise<unknown>> = [
+ // A conversation renamed.
+ () => write(tabId, all => { const g = one(liveOf(all.groups)); return g ? { op: 'update', kind: 'group', key: g.key, seen: g.version, data: { ...g.data!, title: `T${++n}` } } : null }),
+ // Put to sleep, and woken.
+ () => write(tabId, all => { const g = one(liveOf(all.groups).filter(x => !x.dormant && x.key !== 'lead')); return g ? { op: 'update', kind: 'group', key: g.key, seen: g.version, data: { ...g.data!, dormant: true } } : null }),
+ () => write(tabId, all => { const g = one(liveOf(all.groups).filter(x => x.dormant)); return g ? { op: 'update', kind: 'group', key: g.key, seen: g.version, data: { ...g.data!, dormant: false } } : null }),
+ // An agent leaves a conversation (as its removal rewrites each conversation it is in).
+ () => write(tabId, all => { const g = one(liveOf(all.groups).filter(x => x.data!.agentIds.length)); return g ? { op: 'update', kind: 'group', key: g.key, seen: g.version, data: { ...g.data!, agentIds: g.data!.agentIds.slice(1) } } : null }),
+ // A start begins, finishes, and expires.
+ () => write(tabId, all => ({ op: 'insert', kind: 'start', key: `s-${++n}`, ordinal: 1_000 + n, data: { id: `s-${n}`, harnessId: null, createdAt: new Date().toISOString(),
+ request: { machineId: 'host', conversationId: web, harnessId: `h-${n}` } } })),
+ () => write(tabId, all => { const s = one(liveOf(all.starts).filter(x => !x.data!.harnessId)); return s ? { op: 'update', kind: 'start', key: s.key, seen: s.version, data: { ...s.data!, harnessId: `${s.key}-harness` } } : null }),
+ () => write(tabId, all => { const s = one(liveOf(all.starts).filter(x => !!x.data!.harnessId)); return s ? { op: 'remove', kind: 'start', key: s.key, seen: s.version, data: s.data } : null }),
+ // An agent renamed; the head renamed.
+ () => write(tabId, all => { const a = one(liveOf(all.agents)); return a ? { op: 'update', kind: 'agent', key: a.key, seen: a.version, data: { ...a.data!, name: `A${++n}` } } : null }),
+ () => write(tabId, all => ({ op: 'update', kind: 'head', key: 'head', seen: all.head.version, data: { ...all.head.data!, name: `S${++n}` } })),
+ // A machine's own reading (machine stamp only).
+ () => write(tabId, all => { const m = one(liveOf(all.machines)); return m ? { op: 'update', kind: 'machine', key: m.key, seen: m.version, data: m.data } : null }),
+ // A real command. Refused once earlier steps left the conversation with no agent to address: a refusal writes nothing.
+ () => store.execute(people.owner, tabId, { operationId: `send-${randomUUID()}`, command: { type: 'message.send', conversationId: web, text: `m${++n}`, replyTo: null, recipientIds: [] } })
+ .catch((error: { code?: string }) => { if (!error.code) throw error }),
+ ]
+
+ /** Every named form a read takes, from what the Swarm holds now. */
+ async function namedForms(): Promise<ReadNamed[]> {
+ const all = await parts.loadAll(db, tabId)
+ const agents = liveOf(all.agents).map(a => a.key)
+ const finished = liveOf(all.starts).filter(s => !!s.data!.harnessId)
+ const dormant = liveOf(all.groups).filter(g => g.dormant).map(g => g.key)
+ return [{}, { includeRecentStarts: true }, { startIds: finished.slice(0, 1).map(s => s.key) },
+ { startAgentIds: finished.slice(0, 2).map(s => stableId(s.data!.request.machineId, s.data!.harnessId!)) },
+ { agentIds: agents.slice(0, 1) }, { agentIds: agents.slice(0, 3) }, { projectIds: ['lead'] }, { projectIds: [secret, 'lead'] },
+ { allGroups: true }, { groupIds: dormant.slice(0, 2) }]
+ }
+
+ const check = async (step: string) => {
+ for (const named of await namedForms()) {
+ const cached = await readParts(db, await cache.at([tabId]), tabId, named)
+ const fresh = await readParts(db, DIRECT, tabId, named)
+ expect(cacheDigest(cached), `${step} ${JSON.stringify(named)}`).toBe(cacheDigest(fresh))
+ const active = await db.$transaction(tx => parts.loadActive(tx, tabId, named))
+ expect(cacheDigest(fresh), `loadActive ${step} ${JSON.stringify(named)}`).toBe(cacheDigest(active))
+ }
+ expect(await readLastChangedAt(db, await cache.at([tabId]), tabId)).toBe(await readLastChangedAt(db, DIRECT, tabId))
+ }
+
+ await check('start')
+ for (let i = 0; i < 60; i++) {
+ const op = Math.floor(random() * ops.length)
+ await ops[op]!()
+ await check(`step ${i} (op ${op})`)
+ }
+ // The cache patched rather than loaded again: one delta per Swarm and stamp, so about one per write that changed something.
+ expect(delta.mock.calls.length).toBeGreaterThan(30)
+ })
+
+ it('a write committed after the load but stamped 20 s earlier is in the next patch', async () => {
+ const { tabId, web } = await scene()
+ const cache = new SwarmCache(stamps, { delta: readDelta(db) })
+ await readParts(db, await cache.at([tabId]), tabId)
+ // A transaction that began 20 s ago commits now: its parts carry the time it wrote them.
+ await write(tabId, all => { const g = all.groups.find(x => x.key === web)!; return { op: 'update', kind: 'group', key: web, seen: g.version, data: { ...g.data!, title: 'Late' } } },
+ Date.now() - 20_000)
+ const read = await readParts(db, await cache.at([tabId]), tabId)
+ expect(read.groups.find(g => g.key === web)!.data!.title).toBe('Late')
+ })
+})
diff --git a/backend/src/config/env.ts b/backend/src/config/env.ts
index 1fdc90686..52204310a 100644
--- a/backend/src/config/env.ts
+++ b/backend/src/config/env.ts
@@ -39,10 +39,17 @@ const envSchema = z.object({
// What each process keeps of the Swarms it read, by their stamps in Redis (superTabs/cache.ts). 'off' is the kill switch:
// every read goes to Mongo again, while writes still bump the stamps, so processes that keep theirs on stay right.
SWARM_READ_CACHE: z.enum(['on', 'off']).default('on'),
+ // The read cache patches what it holds from the parts that changed (superTabs/cache.ts, spec 2026-11-02); off: a bump drops it.
+ SWARM_CACHE_DELTA: z.enum(['on', 'off']).default('on'),
+ // The share of patches checked against a full load in the background: the drift alarm in the `swarm cache` log.
+ SWARM_CACHE_VERIFY_RATE: z.coerce.number().min(0).max(1).default(0.01),
// A frame an adapter sends for one viewer goes to the process holding that viewer (lib/terminalRoute.ts), found by its
// record in Redis, instead of to every process with a viewer of the machine. 'off' is the kill switch: such frames go
// through the machine's channels again; a viewer on the adapter's own process is still served directly.
TERMINAL_POD_ROUTES: z.enum(['on', 'off']).default('on'),
+ // `__clients` tells each daemon it may hold a machine's live events while no app views it (lib/hub.ts). 'off' is the
+ // kill switch: the frame stops saying so, and daemons send every event again with no release of their own.
+ RELAY_UI_GATE: z.enum(['on', 'off']).default('on'),
// Its size per process, counted as the JSON size of what it holds.
SWARM_CACHE_MB: z.string().default('64').transform(Number),
// The worker's hourly move of finished deliveries older than 14 days into their messages' receipts
diff --git a/backend/src/lib/bus.ts b/backend/src/lib/bus.ts
index 587f6b9f5..48b977577 100644
--- a/backend/src/lib/bus.ts
+++ b/backend/src/lib/bus.ts
@@ -1167,6 +1167,8 @@ export async function getAgentClientTotals(machineId: string): Promise<{ ui: num
export async function getAgentClientState(machineId: string): Promise<{
totals: { ui: number; commander: number; commanderActive: number }
commanderJoinGeneration: number | undefined
+ /** The counts could not be read: the zeros stand for "unknown", never for "nobody". */
+ failed?: true
}> {
try {
const res = await pub.pipeline().hgetall(clientsKey(machineId)).get(commanderJoinGenerationKey(machineId)).exec()
@@ -1181,7 +1183,7 @@ export async function getAgentClientState(machineId: string): Promise<{
}
} catch (err) {
logger.error('[bus] getAgentClientState failed', err, { machineId })
- return { totals: { ui: 0, commander: 0, commanderActive: 0 }, commanderJoinGeneration: undefined }
+ return { totals: { ui: 0, commander: 0, commanderActive: 0 }, commanderJoinGeneration: undefined, failed: true }
}
}
diff --git a/backend/src/lib/circuitBreaker.test.ts b/backend/src/lib/circuitBreaker.test.ts
index 3f8162e80..2ce1b05b2 100644
--- a/backend/src/lib/circuitBreaker.test.ts
+++ b/backend/src/lib/circuitBreaker.test.ts
@@ -79,6 +79,34 @@ describe('circuit breaker', () => {
expect(breaker.state()).toBe('closed')
})
+ // The Redis guard counts a command it sent itself with these, so they must keep `run`'s accounting exactly.
+ it('success and failure count as a call through run would', async () => {
+ const c = clock()
+ const breaker = createCircuitBreaker({ name: 'redis', failureThreshold: 2, openMs: 1_000, now: c.now,
+ isFailure: err => !(err instanceof Error && err.message === 'answer') })
+ breaker.failure(new Error('down'))
+ breaker.success()
+ breaker.failure(new Error('down'))
+ breaker.failure(new Error('answer'))
+ breaker.failure(new Error('down'))
+ expect(breaker.state()).toBe('closed')
+ breaker.failure(new Error('down'))
+ expect(breaker.state()).toBe('open')
+ await expect(breaker.run(ok)).rejects.toBeInstanceOf(CircuitOpenError)
+ c.advance(1_000)
+ await expect(breaker.run(ok)).resolves.toBe('ok')
+ expect(breaker.state()).toBe('closed')
+ })
+
+ it('without a timeout, a call is handed one shared signal that never aborts instead of a new controller', async () => {
+ const breaker = createCircuitBreaker({ name: 'redis' })
+ const signals: AbortSignal[] = []
+ await breaker.run(async signal => { signals.push(signal) })
+ await breaker.run(async signal => { signals.push(signal) })
+ expect(signals[0]).toBe(signals[1])
+ expect(signals[0]!.aborted).toBe(false)
+ })
+
it('reports each change of state once', async () => {
const c = clock()
const changes: string[] = []
diff --git a/backend/src/lib/circuitBreaker.ts b/backend/src/lib/circuitBreaker.ts
index 7e4096fea..84c06fa68 100644
--- a/backend/src/lib/circuitBreaker.ts
+++ b/backend/src/lib/circuitBreaker.ts
@@ -39,8 +39,16 @@ export interface CircuitBreakerOptions {
export interface CircuitBreaker {
run<T>(fn: (signal: AbortSignal) => Promise<T>): Promise<T>
state(): CircuitState
+ /** Count the outcome of a call made without `run` while the circuit was closed, with the accounting `run` applies to
+ * it. The Redis guard sends each command this way, for want of an async frame per command (redisGuard.ts). */
+ success(): void
+ failure(err: unknown): void
}
+// Handed to every call when there is no timeout: nothing can abort it, so one signal serves them all, and a call costs
+// no AbortController.
+const NEVER_ABORTED = new AbortController().signal
+
export function createCircuitBreaker({
name,
failureThreshold = 5,
@@ -62,7 +70,7 @@ export function createCircuitBreaker({
}
const withTimeout = <T>(fn: (signal: AbortSignal) => Promise<T>): Promise<T> => {
- if (timeoutMs === undefined) return fn(new AbortController().signal)
+ if (timeoutMs === undefined) return fn(NEVER_ABORTED)
const controller = new AbortController()
let timer: NodeJS.Timeout | undefined
const expired = new Promise<never>((_, reject) => {
@@ -75,8 +83,26 @@ export function createCircuitBreaker({
return Promise.race([fn(controller.signal), expired]).finally(() => clearTimeout(timer))
}
+ const succeeded = (): void => {
+ failures = 0
+ move('closed')
+ }
+
+ const failed = (err: unknown, trial: boolean): void => {
+ if (!isFailure(err)) {
+ failures = 0
+ move('closed')
+ } else if (trial || ++failures >= failureThreshold) {
+ failures = 0
+ openedAt = now()
+ move('open')
+ }
+ }
+
return {
state: () => state,
+ success: succeeded,
+ failure: err => failed(err, false),
async run(fn) {
let trial = false
if (state !== 'closed') {
@@ -87,18 +113,10 @@ export function createCircuitBreaker({
}
try {
const result = await withTimeout(fn)
- failures = 0
- move('closed')
+ succeeded()
return result
} catch (err) {
- if (!isFailure(err)) {
- failures = 0
- move('closed')
- } else if (trial || ++failures >= failureThreshold) {
- failures = 0
- openedAt = now()
- move('open')
- }
+ failed(err, trial)
throw err
} finally {
if (trial) trialRunning = false
diff --git a/backend/src/lib/hub.test.ts b/backend/src/lib/hub.test.ts
index 94ef392a6..d2ae911df 100644
--- a/backend/src/lib/hub.test.ts
+++ b/backend/src/lib/hub.test.ts
@@ -16,7 +16,9 @@ vi.mock('./bus.js', () => bus)
vi.mock('./providerLink.js', () => ({ routeDown: async (_m: string, _d: unknown, fallback: () => Promise<number>) => fallback() }))
vi.mock('../utils/logger.js', () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn() } }))
-const { attachHubClient, deliverUpLocal, sendClientsControl } = await import('./hub.js')
+const { attachHubClient, deliverUpLocal, recomputeAndSendClients, sendClientsControl } = await import('./hub.js')
+const registry = await import('./registry.js')
+const { env } = await import('../config/env.js')
const { SEND_HIGH_WATER, SEND_KILL_WATER } = await import('./wsSend.js')
function socket(out: unknown[], bufferedAmount = 0): WebSocket {
@@ -113,3 +115,40 @@ describe('sendClientsControl coalescing', () => {
expect(bus.setAgentClientCount).toHaveBeenCalledTimes(2)
})
})
+
+describe('the __clients frame', () => {
+ // A daemon holds a machine's live events while no UI client views it only when the backend says it may
+ // (`uiGate`); RELAY_UI_GATE=off withdraws that without a daemon release (spec 2026-11-02-swarm-cache-delta-design, Part 4).
+ it('__clients carries uiGate, and none with RELAY_UI_GATE=off', async () => {
+ const machineId = `hub-uigate-${Date.now()}`
+ const sent: string[] = []
+ const control = socket(sent)
+ registry.bindControlSocket(machineId, control)
+ const saved = env.RELAY_UI_GATE
+ try {
+ await recomputeAndSendClients(machineId)
+ env.RELAY_UI_GATE = 'off'
+ await recomputeAndSendClients(machineId)
+ } finally {
+ env.RELAY_UI_GATE = saved
+ registry.unbindControlSocket(machineId, control)
+ }
+ const payloads = sent.map((s) => JSON.parse(s).frame.payload)
+ expect(payloads[0]).toEqual({ ui: 0, commander: 0, commanderActive: 0, uiGate: true })
+ expect(payloads[1]).toEqual({ ui: 0, commander: 0, commanderActive: 0 })
+ })
+
+ it('a count it could not read never offers the gate: a Redis blip must not tell the daemon nobody is viewing', async () => {
+ const machineId = `hub-uigate-failed-${Date.now()}`
+ const sent: string[] = []
+ const control = socket(sent)
+ registry.bindControlSocket(machineId, control)
+ vi.mocked(bus.getAgentClientState).mockResolvedValueOnce({ totals: { ui: 0, commander: 0, commanderActive: 0 }, commanderJoinGeneration: undefined, failed: true } as never)
+ try {
+ await recomputeAndSendClients(machineId)
+ } finally {
+ registry.unbindControlSocket(machineId, control)
+ }
+ expect(JSON.parse(sent[0]!).frame.payload).toEqual({ ui: 0, commander: 0, commanderActive: 0 })
+ })
+})
diff --git a/backend/src/lib/hub.ts b/backend/src/lib/hub.ts
index 0573573ee..10165c78a 100644
--- a/backend/src/lib/hub.ts
+++ b/backend/src/lib/hub.ts
@@ -28,6 +28,7 @@ import type { ClientKind } from './registry.js'
import type { Frame, UpBusMsg } from './tunnel.js'
import { routeDown } from './providerLink.js'
import { logger } from '../utils/logger.js'
+import { env } from '../config/env.js'
import { decodeTerminalHop, encodeTerminalHop, TerminalHopDirection } from './terminalBinary.js'
import { guardedSend, guardedSendJson } from './wsSend.js'
@@ -153,10 +154,17 @@ async function sendClientsControlNow(machineId: string, commanderJoined: boolean
/** B_m-only: read the cross-instance total and emit `__clients` down the local manager control socket
* (single in-order writer → the node's last frame is always the true global state). */
export async function recomputeAndSendClients(machineId: string): Promise<void> {
- const { totals: { ui, commander, commanderActive }, commanderJoinGeneration } = await getAgentClientState(machineId)
+ const { totals: { ui, commander, commanderActive }, commanderJoinGeneration, failed } = await getAgentClientState(machineId)
const frame = {
type: CLIENTS_FRAME,
- payload: { ui, commander, commanderActive, ...(commanderJoinGeneration != null ? { commanderJoinGeneration } : {}) },
+ // `uiGate` lets the daemon hold live events while `ui` is 0; without it the daemon sends everything, so
+ // RELAY_UI_GATE=off undoes the gate from here alone (spec 2026-11-02-swarm-cache-delta-design, Part 4).
+ payload: {
+ ui, commander, commanderActive,
+ ...(commanderJoinGeneration != null ? { commanderJoinGeneration } : {}),
+ // Never on a count that could not be read: its zero would tell the daemon nobody is viewing (final review, Critical 1).
+ ...(env.RELAY_UI_GATE !== 'off' && !failed ? { uiGate: true } : {}),
+ },
}
const local = registry.controlSocketFor(machineId)
if (local && local.readyState === WebSocket.OPEN) {
diff --git a/backend/src/lib/redisGuard.test.ts b/backend/src/lib/redisGuard.test.ts
index 7916bd511..88bff0b0d 100644
--- a/backend/src/lib/redisGuard.test.ts
+++ b/backend/src/lib/redisGuard.test.ts
@@ -111,6 +111,77 @@ describe('guarded Redis commands', () => {
expect(breaker.state()).toBe('closed')
})
+ // While the circuit is closed a command is sent directly and its outcome counted from its own promise: no `run`, no
+ // async frame and no AbortController per command (spec 2026-11-02-swarm-cache-delta-design, Part 4).
+ it('a closed circuit sends without run', async () => {
+ const redis = await stuckRedis()
+ const breaker = createCircuitBreaker({ name: 'redis', failureThreshold: 5, openMs: 5_000, isFailure: isRedisFailure })
+ const run = vi.spyOn(breaker, 'run')
+ guardRedisCommands(redis.client, breaker)
+ redis.answer(true)
+
+ await expect(redis.client.get('k')).resolves.toBeNull()
+ await expect(redis.client.set('k', 'v')).resolves.toBeNull()
+
+ expect(run).not.toHaveBeenCalled()
+ expect(breaker.state()).toBe('closed')
+ })
+
+ it('five failures through the fast path open it', async () => {
+ const redis = await stuckRedis()
+ const breaker = createCircuitBreaker({ name: 'redis', failureThreshold: 5, openMs: 5_000, isFailure: isRedisFailure })
+ const run = vi.spyOn(breaker, 'run')
+ guardRedisCommands(redis.client, breaker)
+
+ for (let i = 0; i < 4; i++) await expect(redis.client.get('k')).rejects.toThrow(/timed out/i)
+ expect(breaker.state()).toBe('closed')
+ await expect(redis.client.get('k')).rejects.toThrow(/timed out/i)
+
+ expect(breaker.state()).toBe('open')
+ expect(run).not.toHaveBeenCalled()
+ const sent = redis.commands()
+ await expect(redis.client.get('k')).rejects.toBeInstanceOf(CircuitOpenError)
+ expect(redis.commands()).toBe(sent)
+ })
+
+ it('open refuses, and after 5 s one trial closes it on success', async () => {
+ let now = 0
+ const redis = await stuckRedis()
+ const breaker = createCircuitBreaker({ name: 'redis', failureThreshold: 5, openMs: 5_000, isFailure: isRedisFailure, now: () => now })
+ guardRedisCommands(redis.client, breaker)
+ for (let i = 0; i < 5; i++) await expect(redis.client.get('k')).rejects.toThrow(/timed out/i)
+ redis.answer(true)
+ now += 4_999
+ await expect(redis.client.get('k')).rejects.toBeInstanceOf(CircuitOpenError)
+
+ now += 1
+ // One trial at a time: the second command, sent while the first is in flight, is still refused.
+ const trial = redis.client.get('k')
+ const other = redis.client.get('k').catch((err: unknown) => err)
+ await expect(trial).resolves.toBeNull()
+ expect(await other).toBeInstanceOf(CircuitOpenError)
+
+ expect(breaker.state()).toBe('closed')
+ await expect(redis.client.get('k')).resolves.toBeNull()
+ })
+
+ it('a reply error does not count as a failure', async () => {
+ const redis = await stuckRedis()
+ const breaker = createCircuitBreaker({ name: 'redis', failureThreshold: 2, openMs: 60_000, isFailure: isRedisFailure })
+ const run = vi.spyOn(breaker, 'run')
+ guardRedisCommands(redis.client, breaker)
+
+ await expect(redis.client.get('k')).rejects.toThrow(/timed out/i)
+ redis.answer(true, '-WRONGTYPE Operation against a key holding the wrong kind of value\r\n')
+ await expect(redis.client.get('k')).rejects.toThrow(/WRONGTYPE/)
+ redis.answer(false)
+ // The answer in between reset the count, so one more timeout is the first in a row again.
+ await expect(redis.client.get('k')).rejects.toThrow(/timed out/i)
+
+ expect(breaker.state()).toBe('closed')
+ expect(run).not.toHaveBeenCalled()
+ })
+
it('lets a connection that is not ready yet send its own setup, so it can come back while the circuit is open', async () => {
// A Redis that answers, including the INFO that ioredis' ready check sends before the connection is ready.
server = createServer(socket => {
diff --git a/backend/src/lib/redisGuard.ts b/backend/src/lib/redisGuard.ts
index 6ddbb7445..58852e29d 100644
--- a/backend/src/lib/redisGuard.ts
+++ b/backend/src/lib/redisGuard.ts
@@ -18,6 +18,13 @@ export function guardRedisCommands(redis: Redis, breaker: CircuitBreaker): void
const send = redis.sendCommand.bind(redis)
redis.sendCommand = ((command: Command, stream?: unknown, node?: unknown) => {
if (stream || redis.status !== 'ready') return (send as (c: Command, s?: unknown, n?: unknown) => unknown)(command, stream, node)
+ // Closed, as nearly always: send it and count its outcome from its own promise, which saves `run`'s async frame and
+ // promises on every command. Open or half open, `run` decides whether it may go at all.
+ if (breaker.state() === 'closed') {
+ send(command)
+ command.promise.then(() => breaker.success(), (err: unknown) => breaker.failure(err))
+ return command.promise
+ }
breaker.run(() => {
send(command)
return command.promise
diff --git a/backend/src/lib/registry.test.ts b/backend/src/lib/registry.test.ts
new file mode 100644
index 000000000..c5e6a1357
--- /dev/null
+++ b/backend/src/lib/registry.test.ts
@@ -0,0 +1,21 @@
+import { expect, it } from 'vitest'
+import type { WebSocket } from 'ws'
+import { addClient, clientCounts, removeClient } from './registry.js'
+
+// A daemon stops a machine's live events while `ui` is 0 (spec 2026-11-02-swarm-cache-delta-design, Part 4), so every
+// client that receives web-eligible frames must add to it. Desktop, the web app and the phone all attach as 'web'
+// (webWs.ts); a guest is a web client too and must keep the gate open for the frames sealed for it.
+it('ui counts web and guest web clients, never commanders', () => {
+ const machineId = `registry-ui-${Date.now()}`
+ const socket = {} as WebSocket
+ addClient({ connId: 'desktop', machineId, kind: 'web', socket })
+ addClient({ connId: 'phone', machineId, kind: 'web', socket })
+ addClient({ connId: 'guest', machineId, kind: 'web', socket, guest: true })
+ addClient({ connId: 'device', machineId, kind: 'commander', socket, active: true })
+ try {
+ expect(clientCounts(machineId)).toEqual({ ui: 3, commander: 1, commanderActive: 1 })
+ } finally {
+ for (const connId of ['desktop', 'phone', 'guest', 'device']) removeClient(machineId, connId)
+ }
+ expect(clientCounts(machineId)).toEqual({ ui: 0, commander: 0, commanderActive: 0 })
+})
diff --git a/backend/src/lib/relayStats.test.ts b/backend/src/lib/relayStats.test.ts
index 53d191465..27a960bca 100644
--- a/backend/src/lib/relayStats.test.ts
+++ b/backend/src/lib/relayStats.test.ts
@@ -13,9 +13,22 @@ it('counts local and published frames and the receivers each publish reached, pe
recordRelay('up targeted', 'published', 1)
while (!logs.length) await new Promise(resolve => setTimeout(resolve, 10))
expect(logs[0]!.kinds).toEqual({
- termup: { local: 2, published: 1, receivers: 2 },
- 'up targeted': { local: 0, published: 1, receivers: 1 },
+ termup: { local: 2, published: 1, receivers: 2, none: 0 },
+ 'up targeted': { local: 0, published: 1, receivers: 1, none: 0 },
})
await new Promise(resolve => setTimeout(resolve, 120))
expect(logs).toHaveLength(1)
})
+
+// A publish no process subscribes to is work for nobody: `none` is what tells whether the daemon's UI gate pays
+// (spec 2026-11-02-swarm-cache-delta-design, Part 4).
+it('a publish reaching no subscriber counts as none', async () => {
+ const logs: Array<Record<string, unknown>> = []
+ stop = startRelayStats({ everyMs: 50, log: (_m, c) => logs.push(c) })
+ recordRelay('up broadcast', 'published', 0)
+ recordRelay('up broadcast', 'published', 0)
+ recordRelay('up broadcast', 'published', 3)
+ recordRelay('up broadcast', 'local')
+ while (!logs.length) await new Promise(resolve => setTimeout(resolve, 10))
+ expect(logs[0]!.kinds).toEqual({ 'up broadcast': { local: 1, published: 3, receivers: 3, none: 2 } })
+})
diff --git a/backend/src/lib/relayStats.ts b/backend/src/lib/relayStats.ts
index 45b72373e..8383a9f44 100644
--- a/backend/src/lib/relayStats.ts
+++ b/backend/src/lib/relayStats.ts
@@ -6,15 +6,17 @@
import { logger } from '../utils/logger.js'
export type RelayKind = 'termup' | 'up targeted' | 'up broadcast' | 'pod hop' | 'pod json'
-interface Counts { local: number; published: number; receivers: number }
+// `none` counts the publishes that reached no subscription: work for nobody, which is what the daemon's UI gate removes
+// (spec 2026-11-02-swarm-cache-delta-design, Part 4).
+interface Counts { local: number; published: number; receivers: number; none: number }
let kinds = new Map<RelayKind, Counts>()
export function recordRelay(kind: RelayKind, path: 'local' | 'published', receivers = 0): void {
let counts = kinds.get(kind)
- if (!counts) kinds.set(kind, counts = { local: 0, published: 0, receivers: 0 })
+ if (!counts) kinds.set(kind, counts = { local: 0, published: 0, receivers: 0, none: 0 })
if (path === 'local') counts.local++
- else { counts.published++; counts.receivers += receivers }
+ else { counts.published++; counts.receivers += receivers; if (receivers === 0) counts.none++ }
}
export function startRelayStats({ everyMs = 60_000, log = (message: string, context: Record<string, unknown>) => logger.info(message, context) }:
diff --git a/backend/src/server.ts b/backend/src/server.ts
index 17ab932a0..58b9a0002 100644
--- a/backend/src/server.ts
+++ b/backend/src/server.ts
@@ -24,6 +24,8 @@ import { closeBus, pub, redisCount, redisSsoProfileStore, redisSwarmStamps } fro
import { prisma } from './lib/prisma.js'
import { backendReadinessChecks, createReadiness, drainBeforeClosing, processDrain } from './lib/readiness.js'
import { configureSwarmStamps } from './superTabs/cache.js'
+import { startCacheStats } from './superTabs/cacheStats.js'
+import { readDelta } from './superTabs/cachedReads.js'
import { watchGroupIndexes } from './superTabs/parts/indexed.js'
import { startMessageReadStats } from './superTabs/messageReadStats.js'
import { useSharedSsoProfileStore } from './lib/ssoAuth.js'
@@ -149,6 +151,8 @@ async function start(): Promise<void> {
const stopQueryStats = startQueryStats()
// Every minute, how often Swarm transactions ran again and commands loaded twice (superTabs/retryStats.ts, DB 2.1).
const stopRetryStats = startRetryStats()
+ // Every minute: how the Swarm read cache served reads (hit, patched, loaded in full and why) and what its checks found.
+ const stopCacheStats = startCacheStats()
const stopRouteLatency = startRouteLatency(registerRouteLatency(app))
// Every minute: who reads messages how, with the rows each page decoded and showed (superTabs/messageReadStats.ts).
const stopMessageReadStats = startMessageReadStats()
@@ -177,7 +181,9 @@ async function start(): Promise<void> {
startWsCounterLog()
// Each pod's machine reports a minute, stored without a Swarm load (fast) or in full (DB roadmap 2.5).
const stopMachineReportLog = startMachineReportLog()
- configureSwarmStamps(redisSwarmStamps(), { reads: env.SWARM_READ_CACHE === 'on', maxBytes: env.SWARM_CACHE_MB * 2 ** 20 })
+ configureSwarmStamps(redisSwarmStamps(), { reads: env.SWARM_READ_CACHE === 'on', maxBytes: env.SWARM_CACHE_MB * 2 ** 20,
+ ...(env.SWARM_CACHE_DELTA === 'on' ? { delta: readDelta(prisma) } : {}),
+ verifyRate: env.SWARM_CACHE_VERIFY_RATE })
// Hot Swarm reads name their indexes once the database is seen to have them (superTabs/parts/indexed.ts).
watchGroupIndexes(prisma)
@@ -237,6 +243,7 @@ async function start(): Promise<void> {
// The last partial minute of these logs, once the drain and the usage flush have run their queries.
stopQueryStats()
stopRetryStats()
+ stopCacheStats()
stopRouteLatency()
stopMachineReportLog()
stopMessageReadStats()
diff --git a/backend/src/superTabs/cache.test.ts b/backend/src/superTabs/cache.test.ts
index 2757126db..36e53d297 100644
--- a/backend/src/superTabs/cache.test.ts
+++ b/backend/src/superTabs/cache.test.ts
@@ -1,6 +1,10 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { configureSwarmStamps, noteChange, readStamps, stampOwed, swarmTransaction, SwarmCache } from './cache.js'
+import { configureSwarmStamps, freeze, noteChange, readStamps, sizeOf, stampOwed, swarmTransaction, SwarmCache } from './cache.js'
import { MemoryStamps } from './cache.test-support.js'
+import { machinesRule, type PatchRule } from './cachePatch.js'
+import { logger } from '../utils/logger.js'
+import type { MachineData, Part, PartKind } from './parts/index.js'
+import type { SwarmDelta } from './parts/load.js'
/** A loader that counts its calls and returns a fresh object each time, numbered. */
function counted<T extends object>(make: (n: number) => T) {
@@ -9,6 +13,36 @@ function counted<T extends object>(make: (n: number) => T) {
return loader
}
+describe('freeze', () => {
+ it('freezes every nested object and tells the same size as before', () => {
+ const inner = { b: 'x' }, list = [inner, new Date(0)], value = { a: list, c: 1 }
+ // 60: the JSON estimate the walk gave before it remembered sizes.
+ expect(freeze(value)).toBe(60)
+ expect([value, list, inner].every(o => Object.isFrozen(o))).toBe(true)
+ })
+
+ it('a second freeze visits no child', () => {
+ const value = { a: [{ b: 'x' }], c: { d: [1, 2] } }
+ const size = freeze(value)
+ const entries = vi.spyOn(Object, 'entries')
+ try {
+ expect(freeze(value)).toBe(size)
+ expect(entries).not.toHaveBeenCalled()
+ } finally { entries.mockRestore() }
+ })
+
+ it('sizeOf reads a frozen value without walking it', () => {
+ const value = { a: [{ b: 'x' }] }
+ const size = freeze(value)
+ const entries = vi.spyOn(Object, 'entries')
+ try {
+ expect(sizeOf(value)).toBe(size)
+ expect(entries).not.toHaveBeenCalled()
+ } finally { entries.mockRestore() }
+ expect(sizeOf('ab')).toBe(4)
+ })
+})
+
describe('SwarmCache', () => {
it('answers a read at an unchanged stamp from memory', async () => {
const cache = new SwarmCache(new MemoryStamps())
@@ -217,3 +251,342 @@ describe('the stamps a machine report reads (DB 2.5)', () => {
expect(stamps.bumps).toEqual([{ tabId: 't1', scopes: ['main'] }])
})
})
+
+describe('a stale entry is patched, not loaded again (spec 2026-11-02, Phase 1)', () => {
+ interface Held { keys: string[] }
+ const part = (key: string, version = 1, kind: PartKind = 'group'): Part => ({ kind, key, version, changedAt: version, ordinal: 1, data: {} })
+ /** Appends each changed key; a part keyed 'reload' asks for a reload. */
+ const rule = (kinds: readonly PartKind[] = ['group']): PatchRule<Held> => ({
+ kinds,
+ apply: (held, delta) => delta.parts.some(p => p.key === 'reload') ? 'reload'
+ : delta.parts.length ? { keys: [...held.keys, ...delta.parts.map(p => p.key)] } : held,
+ })
+ function setup(options: { parts?: Part[]; fail?: boolean; delta?: boolean } = {}) {
+ let now = 1_000_000
+ const stamps = new MemoryStamps()
+ const delta = vi.fn(async (_tabId: string, _since: number, _kinds: readonly PartKind[]): Promise<SwarmDelta> => {
+ if (options.fail) throw new Error('mongo down')
+ return { parts: options.parts ?? [part('g2')], head: null }
+ })
+ const cache = new SwarmCache(stamps, { now: () => now, ...(options.delta === false ? {} : { delta }) })
+ const load = vi.fn(async (): Promise<Held> => ({ keys: ['g1'] }))
+ // `null`: no rule (a default parameter would replace `undefined`).
+ const read = async (patch: PatchRule<Held> | null = rule(), scope: 'main' | 'all' = 'main', name = 'base') =>
+ (await cache.at(['t1'])).get('t1', name, scope, load, patch ?? undefined)
+ return { stamps, cache, delta, load, read, advance: (ms: number) => { now += ms } }
+ }
+
+ it('a bump patches a held entry instead of loading it', async () => {
+ const { stamps, delta, load, read } = setup()
+ await read()
+ await stamps.bump('t1', ['main'])
+ expect(await read()).toEqual({ keys: ['g1', 'g2'] })
+ expect(load).toHaveBeenCalledTimes(1)
+ expect(delta).toHaveBeenCalledTimes(1)
+ // Patched at the new stamp, it is a hit until the next bump.
+ expect(await read()).toEqual({ keys: ['g1', 'g2'] })
+ expect(delta).toHaveBeenCalledTimes(1)
+ })
+
+ it('asks for the changes since the entry was read, less the overlap', async () => {
+ const { stamps, delta, read, advance } = setup()
+ await read()
+ advance(5_000)
+ await stamps.bump('t1', ['main'])
+ await read()
+ expect(delta.mock.calls[0]![1]).toBe(1_000_000 - 30_000)
+ expect(delta.mock.calls[0]![2]).toEqual(['group'])
+ })
+
+ it('one delta per Swarm and stamp, over the kinds its stale entries need', async () => {
+ const { stamps, delta, read, advance } = setup({ parts: [part('g2')] })
+ await read(rule(['group']), 'main', 'base')
+ await read(rule(['machine']), 'all', 'machines')
+ advance(1)
+ await stamps.bump('t1', ['main'])
+ await read(rule(['group']), 'main', 'base')
+ await read(rule(['machine']), 'all', 'machines')
+ expect(delta).toHaveBeenCalledTimes(1)
+ expect([...delta.mock.calls[0]![2]].sort()).toEqual(['group', 'machine'])
+ })
+
+ describe('a same-stamp refresh never reuses a delta older than what it refreshes (review of #2519)', () => {
+ it('a change whose bump was lost is read at the next 60 s refresh, not left to the 120 s gap reload', async () => {
+ const changes = { parts: [] as Part[] }
+ const { delta, load, read, advance } = setup(changes)
+ await read(rule(), 'main', 'a')
+ await read(rule(), 'main', 'b')
+ advance(61_000)
+ await read(rule(), 'main', 'a')
+ await read(rule(), 'main', 'b')
+ expect(delta).toHaveBeenCalledTimes(1)
+ // Committed, and no pod ever heard: the stamps stand still.
+ changes.parts = [part('lost')]
+ advance(61_000)
+ expect(await read(rule(), 'main', 'a')).toEqual({ keys: ['g1', 'lost'] })
+ expect(await read(rule(), 'main', 'b')).toEqual({ keys: ['g1', 'lost'] })
+ expect(delta).toHaveBeenCalledTimes(2)
+ expect(load).toHaveBeenCalledTimes(2)
+ })
+
+ it('a machine removed before an entry loaded does not come back from an older delta', async () => {
+ const machine = (version: number, deleted = false): Part<MachineData> =>
+ ({ kind: 'machine', key: 'm1', version, changedAt: version, ordinal: 1, data: {} as MachineData, ...(deleted ? { deleted: true } : {}) })
+ let now = 1_000_000, changed: Part[] = [machine(2)], stored: Part<MachineData>[] = [machine(1)]
+ const cache = new SwarmCache(new MemoryStamps(), { now: () => now, delta: async () => ({ parts: changed, head: null }) })
+ const read = async (name: string) => (await cache.at(['t1'])).get('t1', name, 'all', async () => stored, machinesRule)
+ await read('a')
+ // A second entry of the Swarm: with one, replacing it forgets the delta and hides this.
+ await read('other')
+ now += 61_000
+ // The delta 'a' refreshes from holds the machine, live.
+ expect((await read('a')).map(p => p.key)).toEqual(['m1'])
+ // Then it is removed, its bump lost, and 'b' loads correctly without it.
+ changed = [machine(3, true)]
+ stored = []
+ now += 1
+ expect(await read('b')).toEqual([])
+ now += 60_000
+ expect(await read('b')).toEqual([])
+ })
+
+ it('a member removed before an entry loaded does not come back from an older delta', async () => {
+ const changes = { parts: [part('removed-member')] }
+ const { read, advance, load } = setup(changes)
+ await read(rule(), 'main', 'a')
+ await read(rule(), 'main', 'other')
+ advance(61_000)
+ await read(rule(), 'main', 'a')
+ changes.parts = []
+ advance(1)
+ load.mockResolvedValueOnce({ keys: ['correct'] })
+ expect(await read(rule(), 'main', 'b')).toEqual({ keys: ['correct'] })
+ advance(60_000)
+ expect(await read(rule(), 'main', 'b')).toEqual({ keys: ['correct'] })
+ })
+
+ it('the writing pod reads its own commit while its bump is owed, on every entry', async () => {
+ const changes = { parts: [] as Part[] }
+ const { cache, delta, read, advance } = setup(changes)
+ await read(rule(), 'main', 'a')
+ await read(rule(), 'main', 'b')
+ advance(61_000)
+ // 'a' refreshes from a delta; 'b', not read since, is still older than that delta.
+ await read(rule(), 'main', 'a')
+ expect(delta).toHaveBeenCalledTimes(1)
+ advance(1_000)
+ // A commit here that Redis would not take: announce() drops the Swarm, and the stamps stand still.
+ changes.parts = [part('mine')]
+ cache.drop('t1')
+ expect(await read(rule(), 'main', 'b')).toEqual({ keys: ['g1', 'mine'] })
+ expect(await read(rule(), 'main', 'a')).toEqual({ keys: ['g1', 'mine'] })
+ })
+
+ it('entries refreshed together still share one delta', async () => {
+ const { delta, load, read, advance } = setup({ parts: [] })
+ await read(rule(), 'main', 'a')
+ await read(rule(), 'main', 'b')
+ advance(61_000)
+ await read(rule(), 'main', 'a')
+ await read(rule(), 'main', 'b')
+ expect(delta).toHaveBeenCalledTimes(1)
+ expect(load).toHaveBeenCalledTimes(2)
+ })
+ })
+
+ it('an entry not read for two minutes loads in full, and never stretches another entry\'s delta', async () => {
+ const { stamps, delta, load, read, advance } = setup()
+ await read(rule(), 'main', 'old')
+ advance(150_000)
+ await read(rule(), 'main', 'hot')
+ await stamps.bump('t1', ['main'])
+ await read(rule(), 'main', 'hot')
+ expect(delta.mock.calls[0]![1]).toBe(1_000_000 + 150_000 - 30_000)
+ await read(rule(), 'main', 'old')
+ // old: loaded, hot: loaded, old: loaded again (too old to patch).
+ expect(load).toHaveBeenCalledTimes(3)
+ })
+
+ it('readers of one Swarm at one stamp share one delta', async () => {
+ const { stamps, delta, read } = setup()
+ await read()
+ await stamps.bump('t1', ['main'])
+ await Promise.all([read(), read(), read()])
+ expect(delta).toHaveBeenCalledTimes(1)
+ })
+
+ it('a machine-only bump leaves main entries alone and asks the delta for machines only', async () => {
+ const { stamps, delta, read } = setup({ parts: [part('m1', 2, 'machine')] })
+ await read(rule(['group']), 'main', 'base')
+ await read(rule(['machine']), 'all', 'machines')
+ await stamps.bump('t1', ['machine'])
+ await read(rule(['group']), 'main', 'base')
+ expect(delta).not.toHaveBeenCalled()
+ expect(await read(rule(['machine']), 'all', 'machines')).toEqual({ keys: ['g1', 'm1'] })
+ expect(delta.mock.calls.map(c => c[2])).toEqual([['machine']])
+ })
+
+ it('age patch without a bump: past 60 s an entry reads the changes it may have missed', async () => {
+ const { delta, load, read, advance } = setup()
+ await read()
+ advance(61_000)
+ expect(await read()).toEqual({ keys: ['g1', 'g2'] })
+ expect(load).toHaveBeenCalledTimes(1)
+ expect(delta).toHaveBeenCalledTimes(1)
+ })
+
+ it('past DELTA_MAX_AGE_MS it loads in full', async () => {
+ const { stamps, delta, load, read, advance } = setup()
+ await read()
+ advance(600_001)
+ await stamps.bump('t1', ['main'])
+ expect(await read()).toEqual({ keys: ['g1'] })
+ expect(load).toHaveBeenCalledTimes(2)
+ expect(delta).not.toHaveBeenCalled()
+ })
+
+ it('over DELTA_MAX_PARTS it loads in full', async () => {
+ const { stamps, load, read } = setup({ parts: Array.from({ length: 501 }, (_, i) => part(`g${i + 10}`)) })
+ await read()
+ await stamps.bump('t1', ['main'])
+ expect(await read()).toEqual({ keys: ['g1'] })
+ expect(load).toHaveBeenCalledTimes(2)
+ })
+
+ it('a delta error loads in full', async () => {
+ const { stamps, load, read } = setup({ fail: true })
+ await read()
+ await stamps.bump('t1', ['main'])
+ expect(await read()).toEqual({ keys: ['g1'] })
+ expect(load).toHaveBeenCalledTimes(2)
+ })
+
+ it('reload from the rule loads in full', async () => {
+ const { stamps, load, read } = setup({ parts: [part('reload')] })
+ await read()
+ await stamps.bump('t1', ['main'])
+ expect(await read()).toEqual({ keys: ['g1'] })
+ expect(load).toHaveBeenCalledTimes(2)
+ })
+
+ it('entries without a rule are dropped and loaded as before', async () => {
+ const { stamps, delta, load, read } = setup()
+ await read(null)
+ await stamps.bump('t1', ['main'])
+ await read(null)
+ expect(load).toHaveBeenCalledTimes(2)
+ expect(delta).not.toHaveBeenCalled()
+ })
+
+ it('without delta configured the cache loads in full as before', async () => {
+ const { stamps, load, read } = setup({ delta: false })
+ await read()
+ await stamps.bump('t1', ['main'])
+ await read()
+ expect(load).toHaveBeenCalledTimes(2)
+ })
+
+ it('a patched value is frozen', async () => {
+ const { stamps, read } = setup()
+ await read()
+ await stamps.bump('t1', ['main'])
+ const value = await read()
+ expect(Object.isFrozen(value)).toBe(true)
+ expect(Object.isFrozen(value.keys)).toBe(true)
+ })
+
+ it('stale entries are evicted first', async () => {
+ const stamps = new MemoryStamps()
+ // Each value is 19 bytes as JSON: two fit, three do not.
+ const cache = new SwarmCache(stamps, { maxBytes: 40, delta: async () => ({ parts: [], head: null }) })
+ const get = async (tabId: string) => (await cache.at([tabId])).get(tabId, 'base', 'main', async () => ({ keys: ['x'.repeat(4)] }), rule())
+ await get('old')
+ await get('fresh')
+ // 'old' is now the most recently used, so plain LRU would evict 'fresh'; once stale, 'old' goes first.
+ await get('old')
+ await stamps.bump('old', ['main'])
+ await get('third')
+ expect(cache.size.entries).toBe(2)
+ const loads = vi.fn(async () => ({ keys: ['y'] }))
+ await (await cache.at(['fresh'])).get('fresh', 'base', 'main', loads, rule())
+ expect(loads).not.toHaveBeenCalled()
+ })
+})
+
+describe('the verify sample (spec 2026-11-02, "Checking it on prod")', () => {
+ const machine = (key: string, version: number, data: unknown): Part => ({ kind: 'machine', key, version, changedAt: version, ordinal: 1, data })
+ function setup(changed: Part[], truth: () => Part[]) {
+ const stamps = new MemoryStamps()
+ const cache = new SwarmCache(stamps, { verifyRate: 1, random: () => 0, delta: async () => ({ parts: changed, head: null }) })
+ const load = vi.fn(async () => truth())
+ const read = async () => (await cache.at(['t1'])).get('t1', 'machines', 'all', load, machinesRule)
+ return { stamps, cache, load, read }
+ }
+
+ it('a sampled patch is checked against a full load', async () => {
+ let truth = [machine('m1', 1, { a: 1 })]
+ const { stamps, load, read } = setup([machine('m1', 2, { a: 2 })], () => truth)
+ await read()
+ truth = [machine('m1', 2, { a: 2 })]
+ await stamps.bump('t1', ['machine'])
+ const warn = vi.spyOn(logger, 'warn')
+ try {
+ await read()
+ await vi.waitFor(() => expect(load).toHaveBeenCalledTimes(2))
+ await new Promise(resolve => setTimeout(resolve, 10))
+ expect(warn).not.toHaveBeenCalled()
+ } finally { warn.mockRestore() }
+ })
+
+ it('a mismatch drops the entry and logs ids only', async () => {
+ let truth = [machine('m1', 1, { secret: 'stored' })]
+ const { stamps, load, read } = setup([machine('m1', 2, { secret: 'patched' })], () => truth)
+ await read()
+ truth = [machine('m1', 2, { secret: 'stored' })]
+ await stamps.bump('t1', ['machine'])
+ const warn = vi.spyOn(logger, 'warn')
+ try {
+ await read()
+ await vi.waitFor(() => expect(warn).toHaveBeenCalledWith('swarm cache verify mismatch', { entry: 'machines', tabId: 't1', kinds: ['machine'], keys: ['machine:m1'] }))
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('secret')
+ // Dropped: the next read loads again.
+ await read()
+ expect(load).toHaveBeenCalledTimes(3)
+ } finally { warn.mockRestore() }
+ })
+
+ it('a stamp move during the check counts nothing', async () => {
+ let truth = [machine('m1', 1, { a: 1 })]
+ const stamps = new MemoryStamps()
+ const cache = new SwarmCache(stamps, { verifyRate: 1, random: () => 0, delta: async () => ({ parts: [machine('m1', 2, { a: 2 })], head: null }) })
+ let calls = 0
+ const load = async () => { calls++; if (calls === 2) await stamps.bump('t1', ['machine']); return truth }
+ const read = async () => (await cache.at(['t1'])).get('t1', 'machines', 'all', load, machinesRule)
+ await read()
+ truth = [machine('m1', 9, { other: true })]
+ await stamps.bump('t1', ['machine'])
+ const warn = vi.spyOn(logger, 'warn')
+ try {
+ await read()
+ await vi.waitFor(() => expect(calls).toBe(2))
+ await new Promise(resolve => setTimeout(resolve, 10))
+ expect(warn).not.toHaveBeenCalled()
+ } finally { warn.mockRestore() }
+ })
+
+ it('one check at a time per process', async () => {
+ let release: () => void = () => {}
+ const gate = new Promise<void>(resolve => { release = resolve })
+ const stamps = new MemoryStamps()
+ const cache = new SwarmCache(stamps, { verifyRate: 1, random: () => 0, delta: async () => ({ parts: [], head: null }) })
+ let loads = 0
+ const load = async () => { loads++; if (loads > 2) await gate; return [] as Part[] }
+ const read = async (tabId: string) => (await cache.at([tabId])).get(tabId, 'machines', 'all', load, machinesRule)
+ await read('t1'); await read('t2')
+ await stamps.bump('t1', ['machine']); await stamps.bump('t2', ['machine'])
+ await read('t1'); await read('t2')
+ await new Promise(resolve => setTimeout(resolve, 10))
+ expect(loads).toBe(3)
+ release()
+ })
+})
diff --git a/backend/src/superTabs/cache.ts b/backend/src/superTabs/cache.ts
index 590d0134d..f5d284bfe 100644
--- a/backend/src/superTabs/cache.ts
+++ b/backend/src/superTabs/cache.ts
@@ -10,6 +10,11 @@
import type { Prisma, PrismaClient } from '@prisma/client'
import { logger } from '../utils/logger.js'
+import { cacheDigest, differingKeys, type PatchRule } from './cachePatch.js'
+import { recordCache, type ReloadReason } from './cacheStats.js'
+import type { PartKind } from './parts/types.js'
+import type { SwarmDelta } from './parts/load.js'
+import { OVERLAP_MS } from './read/cursor.js'
/** The stamps of one Swarm. A stamp only grows; one that never moved is 0. */
export interface Stamp { main: number; machine: number }
@@ -24,7 +29,21 @@ export interface SwarmStamps {
subscribe(listener: (tabId: string, scopes: readonly StampScope[]) => void): () => void
}
-interface Entry { tabId: string; stamp: Stamp; scope: StampScope | 'all'; at: number; bytes: number; value: unknown }
+interface Entry {
+ tabId: string
+ stamp: Stamp
+ scope: StampScope | 'all'
+ /** When the stamps it is current at were read, before its load or patch: the next patch reads changes from here, less
+ * OVERLAP_MS (the longest transaction plus clock drift between processes, as change cursors use it). */
+ at: number
+ /** When it was last loaded in full: past deltaMaxAgeMs it is loaded in full again, whatever patches it took. */
+ fullAt: number
+ bytes: number
+ value: unknown
+ /** Its Swarm moved: kept only to be patched by the next read. */
+ stale: boolean
+ patch?: PatchRule<unknown>
+}
export interface CacheOptions {
/** What the held values may take, counted as their JSON size. */
@@ -34,15 +53,38 @@ export interface CacheOptions {
/** A read that cannot learn the stamps in this time reads Mongo itself. */
stampTimeoutMs?: number
now?: () => number
+ /** The parts of a Swarm changed since a time (parts/load.ts loadDelta). With it, a bump marks entries with a patch rule
+ * stale and the next read patches them; without it (SWARM_CACHE_DELTA=off) a bump drops them, as before. */
+ delta?: (tabId: string, since: number, kinds: readonly PartKind[]) => Promise<SwarmDelta>
+ /** An entry is loaded in full again at least this often: the net for anything a delta cannot see. */
+ deltaMaxAgeMs?: number
+ /** A delta larger than this is applied by loading in full, which then costs about as much. */
+ deltaMaxParts?: number
+ /** The share of patches checked against a full load in the background (SWARM_CACHE_VERIFY_RATE): the drift alarm. */
+ verifyRate?: number
+ random?: () => number
}
export const CACHE_MAX_BYTES = 64 * 1024 * 1024
export const CACHE_MAX_AGE_MS = 60_000
export const STAMP_TIMEOUT_MS = 200
+export const DELTA_MAX_AGE_MS = 600_000
+export const DELTA_MAX_PARTS = 500
+/** An entry not refreshed for this long loads in full rather than stretch its Swarm's delta back to its last read: one
+ * forgotten entry made every delta of its Swarm read an hour of changes (final review, Important 2). Twice the age at which
+ * a read refreshes an entry, so one read every minute keeps it patched. */
+export const DELTA_MAX_GAP_MS = 120_000
+
+/** One delta read: the stamps it was read at, the kinds it holds, from when, and when it started. */
+interface Delta { stamp: string; kinds: ReadonlySet<PartKind>; since: number; at: number; read: Promise<SwarmDelta> }
const key = (tabId: string, name: string) => `${tabId}\u0000${name}`
-/** Freezes a loaded value all through and tells its size as JSON, in one pass. */
+/** Each frozen object's size, so a value held again (a patch keeps the parts that did not change) is never walked twice:
+ * the walk of every load was 4.4% of the event loop, 12.4 M calls in the 2026-11-02 profiles (spec Part 3). */
+const sizes = new WeakMap<object, number>()
+
+/** Freezes a loaded value all through and tells its size as JSON, in one pass; an object frozen here before is not walked. */
export function freeze(value: unknown): number {
if (value === null || value === undefined) return 4
switch (typeof value) {
@@ -50,32 +92,51 @@ export function freeze(value: unknown): number {
case 'number': case 'boolean': case 'bigint': return 8
case 'object': {
if (value instanceof Date) return 26
+ const known = sizes.get(value)
+ if (known !== undefined) return known
let bytes = 2
if (Array.isArray(value)) for (const item of value) bytes += freeze(item) + 1
else for (const [name, item] of Object.entries(value)) bytes += name.length + 4 + freeze(item)
Object.freeze(value)
+ sizes.set(value, bytes)
return bytes
}
default: return 8
}
}
+/** A value's size as `freeze` tells it: remembered for one already frozen, else frozen now. */
+export const sizeOf = (value: unknown): number => freeze(value)
+
export class SwarmCache {
private readonly entries = new Map<string, Entry>()
/** Each Swarm's entry names, so a bump touches only that Swarm's entries, not every Swarm's. */
private readonly bySwarm = new Map<string, Set<string>>()
private readonly loading = new Map<string, Promise<unknown>>()
+ /** Each Swarm's latest delta read: every entry of the Swarm patched at its stamps shares it, while and after it runs. */
+ private readonly deltas = new Map<string, Delta>()
private bytes = 0
private readonly maxBytes: number
private readonly maxAgeMs: number
private readonly stampTimeoutMs: number
private readonly now: () => number
+ private readonly delta: CacheOptions['delta']
+ private readonly deltaMaxAgeMs: number
+ private readonly deltaMaxParts: number
+ private readonly verifyRate: number
+ private readonly random: () => number
+ private verifying = false
constructor(private readonly stamps: SwarmStamps, options: CacheOptions = {}) {
this.maxBytes = options.maxBytes ?? CACHE_MAX_BYTES
this.maxAgeMs = options.maxAgeMs ?? CACHE_MAX_AGE_MS
this.stampTimeoutMs = options.stampTimeoutMs ?? STAMP_TIMEOUT_MS
this.now = options.now ?? Date.now
+ this.delta = options.delta
+ this.deltaMaxAgeMs = options.deltaMaxAgeMs ?? DELTA_MAX_AGE_MS
+ this.deltaMaxParts = options.deltaMaxParts ?? DELTA_MAX_PARTS
+ this.verifyRate = options.verifyRate ?? 0
+ this.random = options.random ?? Math.random
stamps.subscribe((tabId, scopes) => this.drop(tabId, scopes))
}
@@ -83,65 +144,182 @@ export class SwarmCache {
/** One read's view of these Swarms: their stamps, read once, before anything is loaded. */
async at(tabIds: readonly string[]): Promise<CacheView> {
+ const at = this.now()
let timer: NodeJS.Timeout | undefined
const late = new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), this.stampTimeoutMs) })
try {
- return new CacheView(this, await Promise.race([this.stamps.read(tabIds), late]))
+ return new CacheView(this, await Promise.race([this.stamps.read(tabIds), late]), at)
} catch {
- return new CacheView(this, null)
+ return new CacheView(this, null, at)
} finally {
clearTimeout(timer)
}
}
- /** Forgets what this process holds of a Swarm that these stamps' moves make stale; everything, by default. */
+ /** What these stamps' moves make stale of a Swarm, everything by default: an entry with a patch rule is kept to be patched,
+ * any other is forgotten. The Swarm's latest delta predates the change, so no entry refreshes from it; a bump owed by this
+ * process leaves the stamps as they were, where an entry older than that delta would otherwise reuse it. */
drop(tabId: string, scopes: readonly StampScope[] = ['main']): void {
+ this.deltas.delete(tabId)
const main = scopes.includes('main')
- for (const name of this.bySwarm.get(tabId) ?? []) {
- if (main || this.entries.get(name)!.scope !== 'main') this.drop1(name)
+ for (const name of [...this.bySwarm.get(tabId) ?? []]) {
+ const entry = this.entries.get(name)!
+ if (!main && entry.scope === 'main') continue
+ if (entry.patch && this.delta) entry.stale = true
+ else this.drop1(name)
}
}
- /** @internal CacheView's lookup. */
- held(tabId: string, name: string, stamp: Stamp): unknown {
- const entry = this.entries.get(key(tabId, name))
- if (!entry) return undefined
- const fresh = entry.stamp.main === stamp.main && (entry.scope === 'main' || entry.stamp.machine === stamp.machine) && this.now() - entry.at < this.maxAgeMs
- if (!fresh) {
- this.drop1(key(tabId, name))
- return undefined
+ /** @internal CacheView's get: held, patched, or loaded and held. */
+ async get<T>(tabId: string, name: string, scope: StampScope | 'all', stamp: Stamp, at: number, load: () => Promise<T>,
+ patch?: PatchRule<T>): Promise<T> {
+ const k = key(tabId, name), entry = this.entries.get(k)
+ if (!entry) return this.load(tabId, name, scope, stamp, at, load, patch, 'cold')
+ const current = entry.stamp.main === stamp.main && (entry.scope === 'main' || entry.stamp.machine === stamp.machine)
+ if (current && !entry.stale && this.now() - entry.at < this.maxAgeMs) {
+ // Most recently used last.
+ this.entries.delete(k)
+ this.entries.set(k, entry)
+ recordCache(name, 'hit')
+ return entry.value as T
+ }
+ if (!entry.patch || !this.delta) {
+ this.drop1(k)
+ return this.load(tabId, name, scope, stamp, at, load, patch, 'off')
}
- // Most recently used last.
- this.entries.delete(key(tabId, name))
- this.entries.set(key(tabId, name), entry)
- return entry.value
+ if (this.now() - entry.fullAt >= this.deltaMaxAgeMs) return this.load(tabId, name, scope, stamp, at, load, patch, 'age')
+ return this.patched(tabId, name, scope, stamp, entry, load, entry.patch as PatchRule<T>)
}
- /** @internal CacheView's load: one load for every reader that misses the same entry at the same stamp. */
- async load<T>(tabId: string, name: string, scope: StampScope | 'all', stamp: Stamp, load: () => Promise<T>): Promise<T> {
- const flight = `${key(tabId, name)}\u0000${stamp.main}\u0000${scope === 'main' ? '' : stamp.machine}`
+ /** One load for every reader that misses the same entry at the same stamp. */
+ private async load<T>(tabId: string, name: string, scope: StampScope | 'all', stamp: Stamp, at: number, load: () => Promise<T>,
+ patch: PatchRule<T> | undefined, reason: ReloadReason): Promise<T> {
+ const flight = this.flight(tabId, name, scope, stamp)
const running = this.loading.get(flight) as Promise<T> | undefined
if (running) return running
- const at = this.now()
const loaded = load().then(value => {
- const bytes = freeze(value)
- if (bytes <= this.maxBytes) {
- this.drop1(key(tabId, name))
- this.entries.set(key(tabId, name), { tabId, stamp, scope, at, bytes, value })
- this.bytes += bytes
- const names = this.bySwarm.get(tabId) ?? new Set<string>()
- this.bySwarm.set(tabId, names.add(key(tabId, name)))
- for (const oldest of this.entries.keys()) {
- if (this.bytes <= this.maxBytes) break
- this.drop1(oldest)
- }
- }
+ const bytes = this.keep(tabId, name, { tabId, stamp, scope, at, fullAt: at, bytes: 0, value, stale: false, patch: patch as PatchRule<unknown> | undefined })
+ recordCache(name, 'full', { bytes, reason })
return value
}).finally(() => this.loading.delete(flight))
this.loading.set(flight, loaded)
return loaded
}
+ /** The held entry with its Swarm's changes since it was read applied, or loaded in full when they cannot be. */
+ private async patched<T>(tabId: string, name: string, scope: StampScope | 'all', stamp: Stamp, entry: Entry, load: () => Promise<T>,
+ patch: PatchRule<T>): Promise<T> {
+ const flight = this.flight(tabId, name, scope, stamp)
+ const running = this.loading.get(flight) as Promise<T> | undefined
+ if (running) return running
+ const reload = (reason: ReloadReason) => { this.loading.delete(flight); return this.load(tabId, name, scope, stamp, this.now(), load, patch, reason) }
+ const patching = (async (): Promise<T> => {
+ if (this.now() - entry.at > DELTA_MAX_GAP_MS) return reload('age')
+ let read: Delta
+ try { read = this.deltaFor(tabId, stamp, patch.kinds, entry) } catch { return reload('error') }
+ let delta: SwarmDelta
+ try { delta = await read.read } catch { return reload('error') }
+ // A delta started for other entries may lack this one's kinds, or begin after this entry's changes did.
+ if (!patch.kinds.every(kind => read.kinds.has(kind)) || entry.at - OVERLAP_MS < read.since) return reload('since')
+ if (delta.parts.length > this.deltaMaxParts) return reload('parts')
+ const next = patch.apply(entry.value as T, delta)
+ if (next === 'reload') return reload('epoch')
+ this.keep(tabId, name, { tabId, stamp, scope, at: read.at, fullAt: entry.fullAt, bytes: 0, value: next, stale: false, patch: patch as PatchRule<unknown> })
+ recordCache(name, 'patch', { parts: delta.parts.length, bytes: sizeOf(delta.parts) })
+ this.verify(tabId, name, scope, stamp, load, next, patch.kinds)
+ return next
+ })()
+ this.loading.set(flight, patching)
+ return patching.finally(() => { if (this.loading.get(flight) === patching) this.loading.delete(flight) })
+ }
+
+ /** Whether an entry must be refreshed before it serves a read at these stamps. */
+ private due(entry: Entry, stamp: Stamp, now: number): boolean {
+ const current = entry.stamp.main === stamp.main && (entry.scope === 'main' || entry.stamp.machine === stamp.machine)
+ return entry.stale || !current || now - entry.at >= this.maxAgeMs
+ }
+
+ /**
+ * This Swarm's changes at these stamps, read once for every entry patched from them (the spec's one delta per Swarm and
+ * stamp: one read per kind was up to five reads of the same window per bump, final review Important 3): over the kinds
+ * of every entry of the Swarm due for a refresh, from the earliest of their reads, less OVERLAP_MS. An entry refreshed
+ * too long ago (DELTA_MAX_GAP_MS) is left out: it loads in full when read.
+ *
+ * The stamps can stand still while the Swarm changes (a bump lost, or owed by this process), so a delta is shared only with
+ * an entry read before it started: an older one could miss a change the entry's refresh exists to find, or bring back a
+ * part the entry was loaded without.
+ */
+ private deltaFor(tabId: string, stamp: Stamp, kinds: readonly PartKind[], entry: Entry): Delta {
+ const stamped = `${stamp.main}\u0000${stamp.machine}`
+ const latest = this.deltas.get(tabId)
+ if (latest && latest.stamp === stamped && kinds.every(kind => latest.kinds.has(kind)) && latest.at > entry.at && entry.at - OVERLAP_MS >= latest.since) return latest
+ const now = this.now(), union = new Set(kinds)
+ let earliest = entry.at
+ for (const name of this.bySwarm.get(tabId) ?? []) {
+ const other = this.entries.get(name)!
+ if (other === entry || !other.patch || now - other.at > DELTA_MAX_GAP_MS || now - other.fullAt >= this.deltaMaxAgeMs || !this.due(other, stamp, now)) continue
+ for (const kind of other.patch.kinds) union.add(kind)
+ earliest = Math.min(earliest, other.at)
+ }
+ const since = earliest - OVERLAP_MS
+ const started: Delta = { stamp: stamped, kinds: union, since, at: now, read: this.delta!(tabId, since, [...union]) }
+ this.deltas.set(tabId, started)
+ // A failed read is not kept for the next entry to reuse.
+ started.read.catch(() => { if (this.deltas.get(tabId) === started) this.deltas.delete(tabId) })
+ return started
+ }
+
+ /**
+ * Now and then, in the background, a patched value is compared with a full load at the same stamps: one at a time per
+ * process, off the request path. A stamp that moved meanwhile makes the check say nothing. A difference drops the entry,
+ * and is logged with the part keys that differ, never their data.
+ */
+ private verify<T>(tabId: string, name: string, scope: StampScope | 'all', stamp: Stamp, load: () => Promise<T>, patched: T,
+ kinds: readonly PartKind[]): void {
+ if (this.verifying || !(this.random() < this.verifyRate)) return
+ this.verifying = true
+ const unmoved = (now: Stamp | undefined) => !!now && now.main === stamp.main && (scope === 'main' || now.machine === stamp.machine)
+ void (async () => {
+ const before = (await this.stamps.read([tabId])).get(tabId)
+ const fresh = await load()
+ const after = (await this.stamps.read([tabId])).get(tabId)
+ if (!unmoved(before) || !unmoved(after)) return
+ recordCache(name, 'verify')
+ if (cacheDigest(fresh) === cacheDigest(patched)) return
+ const k = key(tabId, name)
+ if (this.entries.get(k)?.value === patched) this.drop1(k)
+ recordCache(name, 'mismatch')
+ logger.warn('swarm cache verify mismatch', { entry: name.split(':', 1)[0], tabId, kinds: [...kinds], keys: differingKeys(patched, fresh) })
+ })().catch(() => { /* A check that cannot run says nothing; the 10-minute full load stays the net. */ })
+ .finally(() => { this.verifying = false })
+ }
+
+ private flight(tabId: string, name: string, scope: StampScope | 'all', stamp: Stamp): string {
+ return `${key(tabId, name)}\u0000${stamp.main}\u0000${scope === 'main' ? '' : stamp.machine}`
+ }
+
+ /** Holds `entry` (frozen) in place of what was held under its name, within the byte budget: stale entries go first, then
+ * the least recently used. Returns its size. */
+ private keep(tabId: string, name: string, entry: Entry): number {
+ const bytes = freeze(entry.value)
+ if (bytes > this.maxBytes) { this.drop1(key(tabId, name)); return bytes }
+ const k = key(tabId, name)
+ this.drop1(k)
+ this.entries.set(k, { ...entry, bytes })
+ this.bytes += bytes
+ const names = this.bySwarm.get(tabId) ?? new Set<string>()
+ this.bySwarm.set(tabId, names.add(k))
+ for (const [held, each] of this.entries) {
+ if (this.bytes <= this.maxBytes) break
+ if (each.stale) this.drop1(held)
+ }
+ for (const oldest of this.entries.keys()) {
+ if (this.bytes <= this.maxBytes) break
+ this.drop1(oldest)
+ }
+ return bytes
+ }
+
private drop1(name: string) {
const entry = this.entries.get(name)
if (!entry) return
@@ -149,13 +327,17 @@ export class SwarmCache {
this.bytes -= entry.bytes
const names = this.bySwarm.get(entry.tabId)!
names.delete(name)
- if (!names.size) this.bySwarm.delete(entry.tabId)
+ if (!names.size) {
+ this.bySwarm.delete(entry.tabId)
+ this.deltas.delete(entry.tabId)
+ }
}
}
/** One read's stamps. Without them (Redis unreachable or late) every get reads Mongo, and nothing is kept. */
export class CacheView {
- constructor(private readonly cache: SwarmCache | null, private readonly stamps: Map<string, Stamp> | null) {}
+ /** `at`: when the stamps were read, before anything was loaded (SwarmCache.at). */
+ constructor(private readonly cache: SwarmCache | null, private readonly stamps: Map<string, Stamp> | null, readonly at = Date.now()) {}
get available(): boolean { return this.stamps !== null }
@@ -164,14 +346,13 @@ export class CacheView {
return this.cache ? this.stamps?.get(tabId)?.main : undefined
}
- /** The value `load` gives for this Swarm at the view's stamp: held, or loaded and held. `scope` says which stamps it
- * depends on: 'main' for what a machine's reading never changes, 'all' for anything holding machine parts. */
- async get<T>(tabId: string, name: string, scope: StampScope | 'all', load: () => Promise<T>): Promise<T> {
+ /** The value `load` gives for this Swarm at the view's stamp: held, patched by `patch` from what was held, or loaded and
+ * held. `scope` says which stamps it depends on: 'main' for what a machine's reading never changes, 'all' for anything
+ * holding machine parts. */
+ async get<T>(tabId: string, name: string, scope: StampScope | 'all', load: () => Promise<T>, patch?: PatchRule<T>): Promise<T> {
const stamp = this.stamps?.get(tabId)
if (!stamp || !this.cache) return load()
- const held = this.cache.held(tabId, name, stamp)
- if (held !== undefined) return held as T
- return this.cache.load(tabId, name, scope, stamp, load)
+ return this.cache.get(tabId, name, scope, stamp, this.at, load, patch)
}
}
diff --git a/backend/src/superTabs/cachePatch.test.ts b/backend/src/superTabs/cachePatch.test.ts
new file mode 100644
index 000000000..9b88250b9
--- /dev/null
+++ b/backend/src/superTabs/cachePatch.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it } from 'vitest'
+import { baseRule, cacheDigest, dormantAgentRule, dormantProjectRule, dormantRule, finishedStartsRule, groupRule, machinesRule } from './cachePatch.js'
+import type { Part, PartKind, SwarmParts } from './parts/index.js'
+import type { SwarmDelta } from './parts/load.js'
+
+// Part<never> fits any entry's list in these tests.
+const part = (kind: PartKind, key: string, version: number, data: unknown, extra: Partial<Part> = {}): Part<never> =>
+ ({ kind, key, version, changedAt: version * 1_000, ordinal: version, data, ...extra }) as Part<never>
+const delta = (parts: Part[], head: SwarmDelta['head'] = null): SwarmDelta => ({ parts, head })
+
+function base(): SwarmParts {
+ return {
+ tabId: 't1', head: part('head', 'head', 3, { name: 'Swarm' }),
+ members: [part('member', 'p1', 1, { id: 'p1' })], agents: [part('agent', 'a1', 2, { id: 'a1' }), part('agent', 'a2', 2, { id: 'a2' })],
+ groups: [part('group', 'g1', 4, { id: 'g1', title: 'One' }), part('group', 'g2', 4, { id: 'g2', title: 'Two' })],
+ machines: [], starts: [part('start', 's1', 1, { id: 's1' })], progress: [],
+ sequenceBase: 10, visibilityEpoch: 1, groupCounter: 2,
+ }
+}
+
+describe('baseRule', () => {
+ it('replaces a newer part by key, adds a new one, and keeps the unchanged ones as they were', () => {
+ const held = base()
+ const next = baseRule.apply(held, delta([part('group', 'g1', 5, { id: 'g1', title: 'Uno' }), part('agent', 'a3', 1, { id: 'a3' })])) as SwarmParts
+ expect(next.groups.map(g => [g.key, g.version])).toEqual([['g1', 5], ['g2', 4]])
+ expect(next.agents.map(a => a.key)).toEqual(['a1', 'a2', 'a3'])
+ expect(next.groups[1]).toBe(held.groups[1])
+ expect(next.members).toBe(held.members)
+ expect(next.agents[0]).toBe(held.agents[0])
+ })
+
+ it('an older or equal version is ignored', () => {
+ const held = base()
+ expect(baseRule.apply(held, delta([part('group', 'g1', 4, { id: 'g1', title: 'Stale' }), part('agent', 'a1', 1, { id: 'a1', old: true })]))).toBe(held)
+ })
+
+ it('a tombstone removes', () => {
+ const next = baseRule.apply(base(), delta([part('agent', 'a2', 3, { id: 'a2' }, { deleted: true })])) as SwarmParts
+ expect(next.agents.map(a => a.key)).toEqual(['a1'])
+ })
+
+ it('a group put to sleep leaves the base and joins dormant', () => {
+ const sleep = part('group', 'g2', 5, { id: 'g2', title: 'Two', dormant: true }, { dormant: true })
+ const next = baseRule.apply(base(), delta([sleep])) as SwarmParts
+ expect(next.groups.map(g => g.key)).toEqual(['g1'])
+ expect((dormantRule.apply([], delta([sleep])) as Part[]).map(g => g.key)).toEqual(['g2'])
+ })
+
+ it('a woken group leaves dormant and joins the base', () => {
+ const held = base(), dormant = [part('group', 'g9', 6, { id: 'g9', dormant: true }, { dormant: true })]
+ const woken = part('group', 'g9', 7, { id: 'g9' })
+ expect((baseRule.apply(held, delta([woken])) as SwarmParts).groups.map(g => g.key)).toEqual(['g1', 'g2', 'g9'])
+ expect(dormantRule.apply(dormant, delta([woken]))).toEqual([])
+ })
+
+ it('a start that finishes moves from the base to finished-starts', () => {
+ const done = part('start', 's1', 2, { id: 's1', harnessId: 'h1' })
+ expect((baseRule.apply(base(), delta([done])) as SwarmParts).starts).toEqual([])
+ expect((finishedStartsRule.apply([], delta([done])) as Part[]).map(s => s.key)).toEqual(['s1'])
+ // Still running: it stays in the base and never enters finished-starts.
+ const running = part('start', 's1', 2, { id: 's1', harnessId: null })
+ expect((baseRule.apply(base(), delta([running])) as SwarmParts).starts.map(s => s.version)).toEqual([2])
+ expect(finishedStartsRule.apply([], delta([running]))).toEqual([])
+ })
+
+ it('the 7-day expiry tombstone leaves finished-starts', () => {
+ const held = [part('start', 's9', 3, { id: 's9', harnessId: 'h9' })]
+ expect(finishedStartsRule.apply(held, delta([part('start', 's9', 4, { id: 's9', harnessId: 'h9' }, { deleted: true })]))).toEqual([])
+ })
+
+ it('head data and its columns are patched; machine parts are not the base\'s', () => {
+ const next = baseRule.apply(base(), delta([part('head', 'head', 4, { name: 'Renamed' }), part('machine', 'm1', 1, {})],
+ { groupCounter: 3, visibilityEpoch: 1, sequenceBase: 10 })) as SwarmParts
+ expect(next.head.data).toEqual({ name: 'Renamed' })
+ expect(next.groupCounter).toBe(3)
+ expect(next.machines).toEqual([])
+ })
+
+ it('a visibilityEpoch change asks for a reload', () => {
+ expect(baseRule.apply(base(), delta([part('head', 'head', 4, { name: 'Swarm' })], { groupCounter: 2, visibilityEpoch: 2, sequenceBase: 10 }))).toBe('reload')
+ })
+
+ it('keeps a part in the shape a load gives: no readAt', () => {
+ const next = machinesRule.apply([], delta([part('machine', 'm1', 2, { machineId: 'm1' }, { readAt: 5_000 })])) as Part[]
+ expect(next[0]).not.toHaveProperty('readAt')
+ })
+})
+
+describe('the other rules', () => {
+ it('machinesRule replaces by key and drops a tombstone', () => {
+ const held = [part('machine', 'm1', 1, { machineId: 'm1' }), part('machine', 'm2', 1, { machineId: 'm2' })]
+ const next = machinesRule.apply(held, delta([part('machine', 'm1', 2, { machineId: 'm1', x: 1 }), part('machine', 'm2', 2, {}, { deleted: true })])) as Part[]
+ expect(next.map(m => [m.key, m.version])).toEqual([['m1', 2]])
+ })
+
+ it('groupRule ignores other keys and empties on a tombstone', () => {
+ const held = [part('group', 'g1', 1, { id: 'g1' })]
+ expect(groupRule('g1').apply(held, delta([part('group', 'g2', 9, { id: 'g2' })]))).toBe(held)
+ expect(groupRule('g1').apply(held, delta([part('group', 'g1', 2, { id: 'g1' }, { deleted: true })]))).toEqual([])
+ expect(groupRule('g3').apply([], delta([part('group', 'g3', 1, { id: 'g3' })]))).toHaveLength(1)
+ })
+
+})
+
+describe('cacheDigest', () => {
+ it('ignores part order and versions but not data', () => {
+ const same = { changedAt: 1_000, ordinal: 1 }
+ const a = [part('group', 'g1', 1, { x: 1 }, same), part('group', 'g2', 1, { y: [1, 2] }, same)]
+ const b = [part('group', 'g2', 7, { y: [1, 2] }, same), part('group', 'g1', 3, { x: 1 }, same)]
+ expect(cacheDigest({ groups: a, n: 1 })).toBe(cacheDigest({ n: 1, groups: b }))
+ expect(cacheDigest(a)).not.toBe(cacheDigest([part('group', 'g1', 1, { x: 2 }, same), a[1]]))
+ expect(cacheDigest({ y: [2, 1] })).not.toBe(cacheDigest({ y: [1, 2] }))
+ })
+})
+
+describe('dormant selections', () => {
+ const asleep = (key: string, version: number, agentIds: string[], projectId?: string) =>
+ part('group', key, version, { id: key, agentIds, ...projectId ? { projectId } : {} }, { dormant: true })
+
+ it('an agent removed while its selection is held: its rewritten groups leave the selection', () => {
+ const held = [asleep('g1', 1, ['a1', 'a2']), asleep('g2', 1, ['a1'])]
+ const next = dormantAgentRule('a1').apply(held, delta([asleep('g1', 2, ['a2']), asleep('g2', 2, [])])) as Part[]
+ expect(next).toEqual([])
+ })
+
+ it('a woken group leaves every dormant selection', () => {
+ const held = [asleep('g1', 1, ['a1'], 'p1')]
+ const woken = part('group', 'g1', 2, { id: 'g1', agentIds: ['a1'], projectId: 'p1' })
+ expect(dormantAgentRule('a1').apply(held, delta([woken]))).toEqual([])
+ expect(dormantProjectRule('p1').apply(held, delta([woken]))).toEqual([])
+ })
+
+ it('a group put to sleep joins its agents\' and project\'s selections, and lead takes groups with no project', () => {
+ const sleep = asleep('g5', 3, ['a7'])
+ expect((dormantAgentRule('a7').apply([], delta([sleep])) as Part[]).map(g => g.key)).toEqual(['g5'])
+ expect((dormantProjectRule('lead').apply([], delta([sleep])) as Part[]).map(g => g.key)).toEqual(['g5'])
+ expect(dormantProjectRule('p1').apply([], delta([sleep]))).toEqual([])
+ expect(dormantAgentRule('a8').apply([], delta([sleep]))).toEqual([])
+ })
+})
diff --git a/backend/src/superTabs/cachePatch.ts b/backend/src/superTabs/cachePatch.ts
new file mode 100644
index 000000000..ed4190702
--- /dev/null
+++ b/backend/src/superTabs/cachePatch.ts
@@ -0,0 +1,149 @@
+/**
+ * How each read cache entry takes a Swarm's change instead of being loaded again (spec
+ * docs/superpowers/specs/2026-11-02-swarm-cache-delta-design.md, Phase 1). A bump used to drop everything a process held of a
+ * Swarm, and the next read loaded the whole Swarm again: ~1.4 MB for prod's busiest, 63% of the bytes read from Mongo
+ * (2026-11-02). A rule applies the parts that changed since the entry was loaded (cache.ts, parts/load.ts loadDelta).
+ *
+ * A changed part comes as its row is now, so applying one twice, or one older than what is held, does nothing: a part is
+ * applied only when its version is above the held one. A rule returns the held value itself when nothing changed, else new
+ * lists that share every part that did not change (the cache freezes what is new).
+ */
+import { createHash } from 'node:crypto'
+import { type GroupData, type MachineData, type Part, type PartKind, type SwarmParts } from './parts/index.js'
+import type { SwarmDelta } from './parts/load.js'
+import { startFinished } from './parts/write.js'
+import type { AgentStart } from './model.js'
+
+export interface PatchRule<T> {
+ /** The part kinds whose changes this entry holds: a refresh reads only those. */
+ kinds: readonly PartKind[]
+ /** The held value with the delta applied, or 'reload' when the delta cannot be applied and the entry loads again. */
+ apply(held: T, delta: SwarmDelta): T | 'reload'
+}
+
+/** A changed part as a load would have given it: a change read adds `readAt`, which no load carries. */
+function asLoaded<T>(changed: Part): Part<T> {
+ if (changed.readAt === undefined) return changed as Part<T>
+ const { readAt: _readAt, ...loaded } = changed
+ return loaded as Part<T>
+}
+
+/**
+ * `list` with the parts of `kind` among `changed` applied: a newer version replaces the held part in place, or is added at
+ * the end when not held, if `keep` says the entry holds it; else the held part is removed. The same list when nothing moved.
+ */
+function applyByKey<T>(list: readonly Part<T>[], changed: readonly Part[], kind: PartKind, keep: (part: Part) => boolean): Part<T>[] {
+ let next: Part<T>[] | null = null
+ for (const part of changed) {
+ if (part.kind !== kind) continue
+ const current = next ?? list
+ const at = current.findIndex(p => p.key === part.key)
+ if (at >= 0 && part.version <= current[at]!.version) continue
+ if (!keep(part) && at < 0) continue
+ next ??= [...list]
+ if (!keep(part)) next.splice(at, 1)
+ else if (at >= 0) next[at] = asLoaded<T>(part)
+ else next.push(asLoaded<T>(part))
+ }
+ return next ?? (list as Part<T>[])
+}
+
+const live = (part: Part) => !part.deleted
+const awake = (part: Part) => !part.deleted && !part.dormant
+const asleep = (part: Part) => !part.deleted && !!part.dormant
+const finished = (part: Part) => !!part.data && startFinished(part.data as AgentStart)
+
+/** The `parts` entry (parts/load.ts loadReadBase): head, members, agents, awake groups, unfinished starts and progress. */
+export const baseRule: PatchRule<SwarmParts> = {
+ kinds: ['head', 'member', 'agent', 'group', 'start', 'progress'],
+ apply(held, delta) {
+ // A new visibility epoch changes what every reader may see from then on: load the base again rather than patch it.
+ if (delta.head && delta.head.visibilityEpoch !== held.visibilityEpoch) return 'reload'
+ const { parts } = delta
+ const headPart = parts.find(p => p.kind === 'head' && p.version > held.head.version)
+ const next: SwarmParts = {
+ ...held,
+ head: headPart ? asLoaded(headPart) : held.head,
+ members: applyByKey(held.members, parts, 'member', live),
+ agents: applyByKey(held.agents, parts, 'agent', live),
+ groups: applyByKey(held.groups, parts, 'group', awake),
+ starts: applyByKey(held.starts, parts, 'start', p => live(p) && !finished(p)),
+ progress: applyByKey(held.progress, parts, 'progress', live),
+ ...(headPart && delta.head ? delta.head : {}),
+ }
+ const same = (Object.keys(next) as Array<keyof SwarmParts>).every(key => next[key] === held[key])
+ return same ? held : next
+ },
+}
+
+/** The `machines` entry: every live machine part. */
+export const machinesRule: PatchRule<Part<MachineData>[]> = {
+ kinds: ['machine'],
+ apply: (held, delta) => applyByKey(held, delta.parts, 'machine', live),
+}
+
+/** The `finished-starts` entry (parts/load.ts loadFinishedStarts): every live finished start. A start that finishes moves
+ * here from the base in the same delta; the 7-day expiry's tombstone takes it out. */
+export const finishedStartsRule: PatchRule<Part<AgentStart>[]> = {
+ kinds: ['start'],
+ apply: (held, delta) => applyByKey(held, delta.parts, 'start', p => live(p) && finished(p)),
+}
+
+/** The `dormant` entry: every live dormant group. */
+export const dormantRule: PatchRule<Part<GroupData>[]> = {
+ kinds: ['group'],
+ apply: (held, delta) => applyByKey(held, delta.parts, 'group', asleep),
+}
+
+/** A `dormant:agent:{id}` entry: the live dormant groups that list this agent. A group it leaves, or that wakes, goes. */
+export function dormantAgentRule(agentId: string): PatchRule<Part<GroupData>[]> {
+ return { kinds: ['group'], apply: (held, delta) => applyByKey(held, delta.parts, 'group', p => asleep(p) && (p.data as GroupData).agentIds.includes(agentId)) }
+}
+
+/** A `dormant:project:{id}` entry: the project's live dormant groups; a group stored with no project is the default one's
+ * (projects.ts groupProject). */
+export function dormantProjectRule(projectId: string): PatchRule<Part<GroupData>[]> {
+ return { kinds: ['group'], apply: (held, delta) => applyByKey(held, delta.parts, 'group', p => asleep(p) && ((p.data as GroupData).projectId ?? 'lead') === projectId) }
+}
+
+/** A `group:{id}` entry: that live group, dormant or not, or none. */
+export function groupRule(key: string): PatchRule<Part<GroupData>[]> {
+ return { kinds: ['group'], apply: (held, delta) => applyByKey(held, delta.parts.filter(p => p.key === key), 'group', live) }
+}
+
+const isPart = (value: unknown): value is Part =>
+ !!value && typeof value === 'object' && 'kind' in value && 'key' in value && 'version' in value
+
+/** A canonical form for comparing a patched entry with a fresh load of it: keys sorted, lists of parts sorted by kind and key,
+ * and versions left out (a touch moves a version and nothing else, and moves no stamp). */
+function canonical(value: unknown): unknown {
+ if (Array.isArray(value)) {
+ const items = value.map(canonical)
+ return value.length && value.every(isPart)
+ ? items.sort((a, b) => sortKey(a).localeCompare(sortKey(b)))
+ : items
+ }
+ if (value instanceof Date) return value.toISOString()
+ if (!value || typeof value !== 'object') return value
+ const part = isPart(value)
+ return Object.fromEntries(Object.keys(value).filter(key => !(part && key === 'version')).sort()
+ .map(key => [key, canonical((value as Record<string, unknown>)[key])]))
+}
+const sortKey = (part: unknown) => `${(part as Part).kind}\u0000${(part as Part).key}`
+
+export function cacheDigest(value: unknown): string {
+ return createHash('sha256').update(JSON.stringify(canonical(value)) ?? 'undefined').digest('hex')
+}
+
+/** The `kind:key` of each part that is in one value and not the other, or differs between them (data, not version), at most
+ * `limit`: what a verify mismatch logs, without any data. */
+export function differingKeys(a: unknown, b: unknown, limit = 20): string[] {
+ const parts = (value: unknown, into = new Map<string, string>()) => {
+ if (Array.isArray(value)) for (const item of value) parts(item, into)
+ else if (isPart(value)) into.set(`${value.kind}:${value.key}`, cacheDigest(value))
+ else if (value && typeof value === 'object') for (const item of Object.values(value)) parts(item, into)
+ return into
+ }
+ const left = parts(a), right = parts(b)
+ return [...new Set([...left.keys(), ...right.keys()])].filter(k => left.get(k) !== right.get(k)).sort().slice(0, limit)
+}
diff --git a/backend/src/superTabs/cacheStats.test.ts b/backend/src/superTabs/cacheStats.test.ts
new file mode 100644
index 000000000..b8f6cd203
--- /dev/null
+++ b/backend/src/superTabs/cacheStats.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it, vi } from 'vitest'
+import { recordCache, startCacheStats } from './cacheStats.js'
+
+describe('swarm cache log', () => {
+ it('counts by entry name and reason, and logs nothing in an empty window', () => {
+ vi.useFakeTimers()
+ try {
+ const log = vi.fn()
+ const stop = startCacheStats({ everyMs: 60_000, log })
+ vi.advanceTimersByTime(60_000)
+ expect(log).not.toHaveBeenCalled()
+ recordCache('base', 'hit')
+ recordCache('group:abc', 'hit')
+ recordCache('group:def', 'patch', { parts: 3, bytes: 900 })
+ recordCache('base', 'full', { bytes: 2_000, reason: 'cold' })
+ recordCache('base', 'full', { bytes: 1_000, reason: 'age' })
+ vi.advanceTimersByTime(60_000)
+ expect(log).toHaveBeenCalledWith('swarm cache', { windowMs: 60_000, entries: {
+ base: { hits: 1, full: 2, fullBytes: 3_000, patches: 0, patchParts: 0, patchBytes: 0, reloads: { cold: 1, age: 1 }, verify: 0, mismatches: 0 },
+ group: { hits: 1, full: 0, fullBytes: 0, patches: 1, patchParts: 3, patchBytes: 900, reloads: {}, verify: 0, mismatches: 0 },
+ } })
+ stop()
+ } finally { vi.useRealTimers() }
+ })
+})
diff --git a/backend/src/superTabs/cacheStats.ts b/backend/src/superTabs/cacheStats.ts
new file mode 100644
index 000000000..3c77bc724
--- /dev/null
+++ b/backend/src/superTabs/cacheStats.ts
@@ -0,0 +1,46 @@
+/**
+ * The read cache's minute log, `swarm cache` (spec 2026-11-02, "Checking it on prod"): per entry name, how reads were
+ * served (hit, patched, loaded in full and why) and what the verify sample found. Counts only, never an id. An entry
+ * name is counted up to its first `:` (`group:abc` is `group`), so the log stays small.
+ */
+import { logger } from '../utils/logger.js'
+
+export type ReloadReason = 'cold' | 'age' | 'epoch' | 'parts' | 'error' | 'off' | 'since'
+export type CacheEvent = 'hit' | 'full' | 'patch' | 'verify' | 'mismatch'
+
+interface Counts {
+ hits: number; full: number; fullBytes: number; patches: number; patchParts: number; patchBytes: number
+ reloads: Partial<Record<ReloadReason, number>>; verify: number; mismatches: number
+}
+
+let entries = new Map<string, Counts>()
+
+export function recordCache(name: string, event: CacheEvent, detail: { bytes?: number; parts?: number; reason?: ReloadReason } = {}): void {
+ const key = name.split(':', 1)[0]!
+ let counts = entries.get(key)
+ if (!counts) entries.set(key, counts = { hits: 0, full: 0, fullBytes: 0, patches: 0, patchParts: 0, patchBytes: 0, reloads: {}, verify: 0, mismatches: 0 })
+ switch (event) {
+ case 'hit': counts.hits++; break
+ case 'full':
+ counts.full++
+ counts.fullBytes += detail.bytes ?? 0
+ if (detail.reason) counts.reloads[detail.reason] = (counts.reloads[detail.reason] ?? 0) + 1
+ break
+ case 'patch': counts.patches++; counts.patchParts += detail.parts ?? 0; counts.patchBytes += detail.bytes ?? 0; break
+ case 'verify': counts.verify++; break
+ case 'mismatch': counts.mismatches++; break
+ }
+}
+
+export function startCacheStats({ everyMs = 60_000, log = (message: string, context: Record<string, unknown>) => logger.info(message, context) }:
+ { everyMs?: number; log?: (message: string, context: Record<string, unknown>) => void } = {}): () => void {
+ let since = Date.now()
+ const timer = setInterval(() => {
+ const now = Date.now(), window = entries
+ entries = new Map()
+ if (window.size) log('swarm cache', { windowMs: now - since, entries: Object.fromEntries(window) })
+ since = now
+ }, everyMs)
+ timer.unref()
+ return () => clearInterval(timer)
+}
diff --git a/backend/src/superTabs/cachedReads.test.ts b/backend/src/superTabs/cachedReads.test.ts
index 883e61153..1688dba85 100644
--- a/backend/src/superTabs/cachedReads.test.ts
+++ b/backend/src/superTabs/cachedReads.test.ts
@@ -1,13 +1,15 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import { stableId, type AgentStart } from './model.js'
import type { Part } from './parts/index.js'
-import { namedStarts } from './cachedReads.js'
+import { namedStarts, readChanged, readDelta, readLastChangedAt, readLastChangedAts, readLight, readLightGroups, readMachines, readParts } from './cachedReads.js'
+import { CacheView } from './cache.js'
+import { baseRule, dormantRule, machinesRule } from './cachePatch.js'
/** A start, finished once it has a harness. `untouchable`: reading its request throws, so a test sees the read hash its
* agent (stableId, a sha256 of the request's machine and the harness). */
const start = (key: string, done: boolean, untouchable = false): Part<AgentStart> => {
const data = { id: key, harnessId: done ? `${key}-harness` : null } as Record<string, unknown>
- Object.defineProperty(data, 'request', { enumerable: true, get: () => {
+ Object.defineProperty(data, 'request', { enumerable: true, configurable: true, get: () => {
if (untouchable) throw new Error(`read the request of ${key}`)
return { machineId: 'host', conversationId: 'c' }
} })
@@ -16,15 +18,162 @@ const start = (key: string, done: boolean, untouchable = false): Part<AgentStart
describe('the starts a read keeps (cachedReads.ts namedStarts)', () => {
it('keeps the unfinished starts without hashing any finished one when no agent is named (prod 10-30: 873 a messages read)', () => {
- const all = [...Array.from({ length: 1000 }, (_, i) => start(`old-${i}`, true, true)), start('queued', false)]
- expect(namedStarts(all, {}).map(s => s.key)).toEqual(['queued'])
- expect(namedStarts(all, { startIds: ['old-3'] }).map(s => s.key)).toEqual(['old-3', 'queued'])
+ const finished = Array.from({ length: 1000 }, (_, i) => start(`old-${i}`, true, true)), hot = [start('queued', false)]
+ expect(namedStarts(hot, finished, {}).map(s => s.key)).toEqual(['queued'])
+ expect(namedStarts(hot, finished, { startIds: ['old-3'] }).map(s => s.key).sort()).toEqual(['old-3', 'queued'])
})
it('keeps the finished starts named by id or by the agent they started, and every one for a first load', () => {
- const all = [...Array.from({ length: 10 }, (_, i) => start(`old-${i}`, true)), start('queued', false)]
+ const finished = Array.from({ length: 10 }, (_, i) => start(`old-${i}`, true)), hot = [start('queued', false)]
const agent = stableId('host', 'old-7-harness')
- expect(namedStarts(all, { startIds: ['old-3'], startAgentIds: [agent] }).map(s => s.key)).toEqual(['old-3', 'old-7', 'queued'])
- expect(namedStarts(all, { includeRecentStarts: true })).toBe(all)
+ expect(namedStarts(hot, finished, { startIds: ['old-3'], startAgentIds: [agent] }).map(s => s.key).sort()).toEqual(['old-3', 'old-7', 'queued'])
+ expect(namedStarts(hot, finished, { includeRecentStarts: true })).toEqual([...hot, ...finished])
+ })
+
+ it('a start held in both lists (patched at different moments) comes once, its newer version', () => {
+ const hot = [{ ...start('s1', false), version: 2 }], finished = [{ ...start('s1', true), version: 3 }, start('old-1', true)]
+ expect(namedStarts(hot, finished, { includeRecentStarts: true }).map(s => [s.key, s.version])).toEqual([['s1', 3], ['old-1', 1]])
+ expect(namedStarts(hot, finished, { startIds: ['s1'] }).map(s => [s.key, s.version])).toEqual([['s1', 3]])
+ expect(namedStarts([{ ...start('s2', false), version: 5 }], [{ ...start('s2', true), version: 4 }], { startIds: ['s2'] }).map(s => s.version)).toEqual([5])
+ })
+
+ it('works out each finished start\'s agent once per held list', () => {
+ let reads = 0
+ const finished = Array.from({ length: 5 }, (_, i) => {
+ const part = start(`old-${i}`, true)
+ const data = part.data as unknown as Record<string, unknown>, request = data.request
+ Object.defineProperty(data, 'request', { enumerable: true, get: () => { reads++; return request } })
+ return part
+ })
+ const agent = stableId('host', 'old-2-harness')
+ expect(namedStarts([], finished, { startAgentIds: [agent] }).map(s => s.key)).toEqual(['old-2'])
+ expect(namedStarts([], finished, { startAgentIds: [agent] }).map(s => s.key)).toEqual(['old-2'])
+ expect(reads).toBe(5)
+ })
+})
+
+describe('finished starts are read only by the reads that name them (spec 2026-11-02, Phase 2)', () => {
+ function stubView(hot: Part<AgentStart>[], finished: Part<AgentStart>[]) {
+ const view = new CacheView(null, null), names: string[] = []
+ vi.spyOn(view, 'get').mockImplementation(async (_tabId, name) => {
+ names.push(name)
+ if (name === 'parts') return { tabId: 't', head: {}, members: [], agents: [], groups: [], machines: [], starts: hot, progress: [] }
+ if (name === 'finished-starts') return finished
+ return []
+ })
+ return { view, names }
+ }
+ const hot = [start('queued', false)], finished = [start('old-1', true), start('old-2', true)]
+
+ it('a read naming nothing never loads finished starts', async () => {
+ const { view, names } = stubView(hot, finished)
+ expect((await readParts({} as never, view, 't')).starts.map(s => s.key)).toEqual(['queued'])
+ expect((await readParts({} as never, view, 't', { startIds: ['queued'] })).starts.map(s => s.key)).toEqual(['queued'])
+ expect(names).not.toContain('finished-starts')
+ })
+
+ it('first loads, a named finished start and an agent\'s starts read them', async () => {
+ const { view, names } = stubView(hot, finished)
+ expect((await readParts({} as never, view, 't', { includeRecentStarts: true })).starts.map(s => s.key)).toEqual(['queued', 'old-1', 'old-2'])
+ expect((await readParts({} as never, view, 't', { startIds: ['old-2'] })).starts.map(s => s.key)).toEqual(['queued', 'old-2'])
+ expect((await readParts({} as never, view, 't', { startAgentIds: [stableId('host', 'old-1-harness')] })).starts.map(s => s.key)).toEqual(['queued', 'old-1'])
+ expect(names.filter(n => n === 'finished-starts')).toHaveLength(3)
+ })
+})
+
+describe('which entries a refresh patches (spec 2026-11-02, Phase 1)', () => {
+ it('each patchable read passes its rule, and the derived selections none', async () => {
+ const view = new CacheView(null, null)
+ const rules = new Map<string, unknown>()
+ vi.spyOn(view, 'get').mockImplementation(async (_tabId, name, _scope, _load, patch) => {
+ rules.set(name.startsWith('light:') ? 'light:' : name, patch)
+ if (name === 'parts') return { tabId: 't', head: {}, members: [], agents: [], groups: [], machines: [], starts: [], progress: [] }
+ if (name === 'feed') return { from: 0, parts: [] }
+ if (name === 'lastChangedAt') return null
+ if (name.startsWith('light:')) return { groups: [], starts: [] }
+ if (name.startsWith('light-group:')) return null
+ return []
+ })
+ Object.defineProperty(view, 'available', { get: () => true })
+ const db = {} as never
+ await readParts(db, view, 't', { allGroups: true, groupIds: ['g1'] })
+ await readMachines(db, view, 't')
+ await readLastChangedAt(db, view, 't')
+ await readLastChangedAts(db, view, ['t'])
+ await readLight(db, view, 't', {})
+ await readLightGroups(db, view, 't', ['g2'])
+ await readChanged(db, view, 't', 0)
+ expect(rules.get('parts')).toBe(baseRule)
+ expect(rules.get('machines')).toBe(machinesRule)
+ expect(rules.get('dormant')).toBe(dormantRule)
+ expect((rules.get('group:g1') as { kinds: unknown }).kinds).toEqual(['group'])
+ // Tiny and batched per read: dropped and read again (final review: its delta cost more than the read).
+ expect(rules.get('lastChangedAt')).toBeUndefined()
+ expect(rules.get('light:')).toBeUndefined()
+ expect(rules.get('light-group:g2')).toBeUndefined()
+ expect(rules.get('feed')).toBeUndefined()
+ })
+})
+
+describe('dormant groups by the selection a read names (spec 2026-11-02, Phase 2)', () => {
+ const group = (key: string, agentIds: string[], projectId?: string) => ({ _id: `t:${key}`, tabId: 't', key, version: 1, changedAt: { $date: '2026-11-01T00:00:00Z' },
+ ordinal: 1, deleted: false, dormant: true, data: { id: key, agentIds, ...projectId ? { projectId } : {} } })
+ function scene() {
+ const rows = [group('g1', ['a1']), group('g2', ['a1', 'a2'], 'p1'), group('g3', ['a3'], 'p1'), group('g4', ['a2'])]
+ const pipelines: unknown[] = []
+ const db = { swarmGroup: { aggregateRaw: vi.fn(async ({ pipeline }: { pipeline: Array<{ $match: Record<string, unknown> }> }) => {
+ pipelines.push(pipeline[0]!.$match)
+ const match = pipeline[0]!.$match as { agentIds?: { $in: string[] }; projectId?: { $in: Array<string | null> } }
+ return rows.filter(r => (!match.agentIds || r.data.agentIds.some(id => match.agentIds!.$in.includes(id)))
+ && (!match.projectId || match.projectId.$in.includes((r.data as { projectId?: string }).projectId ?? null)))
+ }) } } as never
+ const view = new CacheView(null, null), names: string[] = []
+ vi.spyOn(view, 'get').mockImplementation(async (_tabId, name, _scope, load) => {
+ names.push(name)
+ if (name === 'parts') return { tabId: 't', head: {}, members: [], agents: [], groups: [], machines: [], starts: [], progress: [] }
+ if (name === 'machines') return []
+ return load()
+ })
+ return { db, view, names, pipelines }
+ }
+
+ it('a read naming one agent loads that agent\'s dormant groups only', async () => {
+ const { db, view, names, pipelines } = scene()
+ const read = await readParts(db, view, 't', { agentIds: ['a2'] })
+ expect(read.groups.map(g => g.key).sort()).toEqual(['g2', 'g4'])
+ expect(names).toContain('dormant:agent:a2')
+ expect(names).not.toContain('dormant')
+ expect(pipelines).toEqual([{ tabId: 't', deleted: false, agentIds: { $in: ['a2'] }, dormant: true }])
+ })
+
+ it('several agents and projects merge without duplicates', async () => {
+ const { db, view, names } = scene()
+ const read = await readParts(db, view, 't', { agentIds: ['a1', 'a2'], projectIds: ['p1'] })
+ expect(read.groups.map(g => g.key).sort()).toEqual(['g1', 'g2', 'g3', 'g4'])
+ expect(names.filter(n => n.startsWith('dormant:')).sort()).toEqual(['dormant:agent:a1', 'dormant:agent:a2', 'dormant:project:p1'])
+ })
+
+ it('lead includes groups stored with no project', async () => {
+ const { db, view, pipelines } = scene()
+ const read = await readParts(db, view, 't', { projectIds: ['lead'] })
+ expect(read.groups.map(g => g.key).sort()).toEqual(['g1', 'g4'])
+ expect(pipelines).toEqual([{ tabId: 't', deleted: false, projectId: { $in: ['lead', null] }, dormant: true }])
+ })
+
+ it('allGroups keeps the whole dormant entry', async () => {
+ const { db, view, names } = scene()
+ expect((await readParts(db, view, 't', { allGroups: true, agentIds: ['a1'] })).groups).toHaveLength(4)
+ expect(names.filter(n => n.startsWith('dormant'))).toEqual(['dormant'])
+ })
+})
+
+describe('the delta a refresh reads', () => {
+ it('is one snapshot: read in a transaction', async () => {
+ const aggregateRaw = vi.fn(async () => [])
+ const tx = Object.fromEntries(['swarmHead', 'swarmMember', 'swarmAgent', 'swarmGroup', 'swarmMachine', 'swarmStart', 'swarmProgress'].map(m => [m, { aggregateRaw }]))
+ const db = { $transaction: vi.fn(async (body: (tx: unknown) => Promise<unknown>) => body(tx)) }
+ expect(await readDelta(db as never)('t', 5, ['group', 'start'])).toEqual({ parts: [], head: null })
+ expect(db.$transaction).toHaveBeenCalledTimes(1)
+ expect(aggregateRaw).toHaveBeenCalledTimes(2)
})
})
diff --git a/backend/src/superTabs/cachedReads.ts b/backend/src/superTabs/cachedReads.ts
index 6d46cfc6c..7acdd01e4 100644
--- a/backend/src/superTabs/cachedReads.ts
+++ b/backend/src/superTabs/cachedReads.ts
@@ -7,9 +7,9 @@
import type { Prisma, PrismaClient } from '@prisma/client'
import { stableId, type AgentStart } from './model.js'
import { CacheView } from './cache.js'
+import { baseRule, dormantAgentRule, dormantProjectRule, dormantRule, finishedStartsRule, groupRule, machinesRule } from './cachePatch.js'
import * as store from './parts/index.js'
-import type { GroupData, Part, SwarmParts } from './parts/index.js'
-import { startFinished } from './parts/write.js'
+import type { GroupData, Part, PartKind, SwarmParts, SwarmDelta } from './parts/index.js'
import { retryTransient } from './retry.js'
import { retryStaleIndex } from './parts/indexed.js'
@@ -28,12 +28,12 @@ const FEED_SLACK_MS = 15_000
/** A Swarm's live machine parts, held at both stamps: a machine's reading moves only the machine stamp. */
export const readMachines = (db: Prisma.TransactionClient, view: CacheView, tabId: string) =>
- view.get(tabId, 'machines', 'all', () => store.loadMachines(db, tabId))
+ view.get(tabId, 'machines', 'all', () => store.loadMachines(db, tabId), machinesRule)
/** The active parts, then the machines: one read of the base in a transaction, so its parts are one snapshot. A transaction
* that meets a lock it cannot get in 5 ms (an index build, a release) is tried again as a write's would be (retry.ts). */
const base = (db: Db, view: CacheView, tabId: string) => Promise.all([
- view.get(tabId, 'parts', 'main', () => retryTransient(() => retryStaleIndex(() => db.$transaction(tx => store.loadReadBase(tx, tabId))))),
+ view.get(tabId, 'parts', 'main', () => retryTransient(() => retryStaleIndex(() => db.$transaction(tx => store.loadReadBase(tx, tabId)))), baseRule),
readMachines(db, view, tabId),
])
@@ -43,29 +43,74 @@ export async function readParts(db: Db, view: CacheView, tabId: string, named: R
const held = new Set(active.groups.map(g => g.key))
const extra: Part<GroupData>[] = []
const add = (groups: Part<GroupData>[]) => { for (const g of groups) if (!held.has(g.key)) { held.add(g.key); extra.push(g) } }
- if (named.allGroups || named.agentIds?.length || named.projectIds?.length) {
- const dormant = await view.get(tabId, 'dormant', 'main', () => store.loadGroups(db, tabId, 'dormancy', { dormant: true }))
- const agents = new Set(named.agentIds ?? []), projects = new Set(named.projectIds ?? [])
- // A group stored with no project belongs to the default one (projects.ts groupProject).
- add(named.allGroups ? dormant : dormant.filter(g => g.data!.agentIds.some(id => agents.has(id)) || projects.has(g.data!.projectId ?? 'lead')))
+ if (named.allGroups) add(await view.get(tabId, 'dormant', 'main', () => store.loadGroups(db, tabId, 'dormancy', { dormant: true }), dormantRule))
+ else {
+ // Each named agent's and project's dormant groups by their own index, not every dormant group filtered: 1,544 of them
+ // (8.9 MB) on prod's busiest Swarm, where one worker's are ~126 (2026-11-02).
+ const selections = await Promise.all([
+ ...[...new Set(named.agentIds ?? [])].map(id => view.get(tabId, `dormant:agent:${id}`, 'main',
+ () => store.loadGroups(db, tabId, 'agents', { agentIds: { $in: [id] }, dormant: true }), dormantAgentRule(id))),
+ // A group stored with no project belongs to the default one (projects.ts groupProject); a null match is a missing field too.
+ ...[...new Set(named.projectIds ?? [])].map(id => view.get(tabId, `dormant:project:${id}`, 'main',
+ () => store.loadGroups(db, tabId, 'project', { projectId: { $in: id === 'lead' ? ['lead', null] : [id] }, dormant: true }), dormantProjectRule(id))),
+ ])
+ for (const groups of selections) add(groups)
}
for (const id of named.groupIds ?? []) {
- if (!held.has(id)) add(await view.get(tabId, `group:${id}`, 'main', () => store.loadGroups(db, tabId, 'key', { key: id })))
+ if (!held.has(id)) add(await view.get(tabId, `group:${id}`, 'main', () => store.loadGroups(db, tabId, 'key', { key: id }), groupRule(id)))
}
- return { ...active, machines, groups: extra.length ? [...active.groups, ...extra] : active.groups, starts: namedStarts(active.starts, named) }
+ const finished = needsFinished(active.starts, named)
+ ? await view.get(tabId, 'finished-starts', 'main', () => store.loadFinishedStarts(db, tabId), finishedStartsRule) : []
+ return { ...active, machines, groups: extra.length ? [...active.groups, ...extra] : active.groups, starts: namedStarts(active.starts, finished, named) }
}
-/** The starts loadActive gives for `named`: every unfinished one, and the finished ones named by id or by the agent they
- * started (or all of them with `includeRecentStarts`). A finished start's agent is a sha256 (stableId), so it is worked
- * out only when the read names an agent: hashing every finished start was ~40% of a messages read's CPU (local profile of
- * prod's busiest Swarm, 873 starts, 2026-10-30). */
-export function namedStarts(starts: Part<AgentStart>[], named: ReadNamed): Part<AgentStart>[] {
- if (named.includeRecentStarts) return starts
- const startIds = new Set(named.startIds ?? []), startAgents = new Set(named.startAgentIds ?? [])
- const agentOf = (start: AgentStart) => start.harnessId ? stableId(start.request.machineId, start.harnessId) : null
- return starts.filter(s => !startFinished(s.data!) || startIds.has(s.key) || (startAgents.size > 0 && startAgents.has(agentOf(s.data!) ?? '')))
+/** Whether a read needs the finished starts: a first load shows them all, and a read may name one by id or by its agent. */
+const needsFinished = (hot: Part<AgentStart>[], named: ReadNamed) => !!named.includeRecentStarts || !!named.startAgentIds?.length
+ || (named.startIds ?? []).some(id => !hot.some(s => s.key === id))
+
+/** Each held list of finished starts by the agent they started, worked out once per list: an agent is a sha256 (stableId),
+ * and hashing every finished start on each read was ~40% of a messages read's CPU (prod's busiest Swarm, 2026-10-30). */
+const startsByAgent = new WeakMap<readonly Part<AgentStart>[], Map<string, Part<AgentStart>[]>>()
+function byAgent(finished: readonly Part<AgentStart>[]): Map<string, Part<AgentStart>[]> {
+ let index = startsByAgent.get(finished)
+ if (!index) {
+ index = new Map()
+ for (const start of finished) {
+ if (!start.data!.harnessId) continue
+ const agent = stableId(start.data!.request.machineId, start.data!.harnessId)
+ index.set(agent, [...index.get(agent) ?? [], start])
+ }
+ startsByAgent.set(finished, index)
+ }
+ return index
+}
+
+/** The starts loadActive gives for `named`: every unfinished one (`hot`), and the finished ones named by id or by the agent
+ * they started, or all of them with `includeRecentStarts`. */
+export function namedStarts(hot: Part<AgentStart>[], finished: Part<AgentStart>[], named: ReadNamed): Part<AgentStart>[] {
+ const picked = named.includeRecentStarts ? finished : [...new Map(pickFinished(finished, named).map(s => [s.key, s])).values()]
+ if (!picked.length) return hot
+ // The two lists are patched at their own moments, so a start that just finished can be in both: it comes once, as its
+ // newer version (final review, Important 6).
+ const merged = new Map(hot.map(s => [s.key, s]))
+ for (const start of picked) {
+ const held = merged.get(start.key)
+ if (!held || start.version > held.version) merged.set(start.key, start)
+ }
+ return [...merged.values()]
+}
+
+const pickFinished = (finished: Part<AgentStart>[], named: ReadNamed): Part<AgentStart>[] => {
+ const ids = new Set(named.startIds ?? [])
+ const index = named.startAgentIds?.length ? byAgent(finished) : null
+ return [...finished.filter(s => ids.has(s.key)), ...(named.startAgentIds ?? []).flatMap(agent => index!.get(agent) ?? [])]
}
+/** The read cache's delta (cache.ts): one snapshot, as a base load is (final review, Important 5), and tried again on a
+ * transient error as one is. */
+export const readDelta = (db: Pick<PrismaClient, '$transaction'>) => (tabId: string, since: number, kinds: readonly PartKind[]): Promise<SwarmDelta> =>
+ retryTransient(() => db.$transaction(tx => store.loadDelta(tx, tabId, since, kinds)))
+
/** The parts loadLight gives for `opts`, held whole by what it selects. */
export async function readLight(db: Db, view: CacheView, tabId: string, opts: Omit<LightOptions, 'machines'>): Promise<SwarmParts> {
const name = `light:${JSON.stringify([opts.groups ?? 'active', !!opts.includeRecentStarts, ...(['groupIds', 'agentIds', 'projectIds'] as const)
diff --git a/backend/src/superTabs/costs/read.test.ts b/backend/src/superTabs/costs/read.test.ts
index da391da00..9f96c2edd 100644
--- a/backend/src/superTabs/costs/read.test.ts
+++ b/backend/src/superTabs/costs/read.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import type { Conversation } from '../model.js'
import type { RouteRun } from './attempts.js'
-import { summarizeCosts, type CostRow } from './read.js'
+import { shipping, summarizeCosts, type CostRow } from './read.js'
const MINUTE = 60_000
const t = (input: number, output: number) => ({ input, output, cacheRead: 0, cacheWrite: 0 })
@@ -146,3 +146,44 @@ describe('the full cost per shipped change (routing, Goals piece 3)', () => {
expect(shippedOpen.rows[0]).toMatchObject({ shipped: 1, fullCostKnown: 0.5, fullCostPerShipped: 8 })
})
})
+
+/** shipping before Part 5 (spec 2026-11-02, hot loops): every cost row filtered per shipped group. Kept here only to pin that
+ * grouping the rows once answers exactly as it did. */
+function legacyShipping(rows: CostRow[], groups: Conversation[]): Map<string, number> {
+ const shipped = new Map<string, number>()
+ for (const group of groups) {
+ const at = group.ledger?.shippedAt
+ if (at === undefined) continue
+ const ran = rows.filter(r => r.conversationId === group.id && r.run.startedAt <= at).sort((a, b) => b.run.startedAt - a.run.startedAt)[0]
+ if (ran) shipped.set(ran.assignmentId, at)
+ }
+ return shipped
+}
+
+describe('which attempt shipped each request (spec 2026-11-02, Part 5)', () => {
+ it('shipping answers as before', () => {
+ // A deterministic generator (mulberry32), so a failing case is the same on every run.
+ let seed = 20261102
+ const random = () => {
+ seed = (seed + 0x6D2B79F5) >>> 0
+ let s = seed
+ s = Math.imul(s ^ (s >>> 15), s | 1)
+ s ^= s + Math.imul(s ^ (s >>> 7), s | 61)
+ return ((s ^ (s >>> 14)) >>> 0) / 4294967296
+ }
+ const below = (n: number) => Math.floor(random() * n)
+ for (let i = 0; i < 100; i++) {
+ const groupCount = 1 + below(60)
+ // Several attempts per group, started at a few shared minutes so some start together; an assignment id now and then
+ // in two groups' rows, so a later group's ship overwrites an earlier one's.
+ const rows = Array.from({ length: below(200) }, (_, n) => row(below(10) ? `a${n}` : `a${below(n + 1)}`, {
+ conversationId: `g${below(groupCount + 5)}`, run: run({ startedAt: below(12) * 10 * MINUTE }) }))
+ const groups = Array.from({ length: groupCount }, (_, n) => {
+ // No ship, a ship before any attempt started, or one among the attempts; the same group listed twice now and then.
+ const id = below(15) ? `g${n}` : `g${below(groupCount)}`
+ return group(id, [], below(4) ? below(130) * MINUTE - 5 * MINUTE : undefined)
+ })
+ expect([...shipping(rows, groups)], `case ${i}`).toEqual([...legacyShipping(rows, groups)])
+ }
+ })
+})
diff --git a/backend/src/superTabs/costs/read.ts b/backend/src/superTabs/costs/read.ts
index d0bf0d8ce..f754b6c59 100644
--- a/backend/src/superTabs/costs/read.ts
+++ b/backend/src/superTabs/costs/read.ts
@@ -115,13 +115,22 @@ const median = (values: number[]): number | null => {
/** Each shipped request's shipping attempt and when it shipped. A request ships once, at its earliest recorded merge or first
* Done (leaderboard/record.ts shippedAt), by the attempt that was running then: the latest started by that time. Attempts
- * done after it ship nothing new; counting each Done had counted one request once per attempt (review of #2106). */
-function shipping(rows: CostRow[], groups: Conversation[]): Map<string, number> {
+ * done after it ship nothing new; counting each Done had counted one request once per attempt (review of #2106). Of attempts
+ * started together, the first read. The rows are grouped by group once: filtering every row per shipped group was 0.3 M or
+ * more calls in the 2026-11-02 prod profiles (12 profiles). */
+export function shipping(rows: CostRow[], groups: Conversation[]): Map<string, number> {
+ const byGroup = new Map<string, CostRow[]>()
+ for (const row of rows) {
+ const own = byGroup.get(row.conversationId)
+ if (own) own.push(row)
+ else byGroup.set(row.conversationId, [row])
+ }
const shipped = new Map<string, number>()
for (const group of groups) {
const at = group.ledger?.shippedAt
if (at === undefined) continue
- const ran = rows.filter(r => r.conversationId === group.id && r.run.startedAt <= at).sort((a, b) => b.run.startedAt - a.run.startedAt)[0]
+ let ran: CostRow | undefined
+ for (const row of byGroup.get(group.id) ?? []) if (row.run.startedAt <= at && (!ran || row.run.startedAt > ran.run.startedAt)) ran = row
if (ran) shipped.set(ran.assignmentId, at)
}
return shipped
diff --git a/backend/src/superTabs/migration/normalize.ts b/backend/src/superTabs/migration/normalize.ts
index fcbc975bd..43c714c7e 100644
--- a/backend/src/superTabs/migration/normalize.ts
+++ b/backend/src/superTabs/migration/normalize.ts
@@ -3,7 +3,7 @@
* applied, persisted, so behavior after the migration is identical. Link lists are restored from history beforehand
* (store.ts restorePullRequestUrls); removals that expire and the released-harness cap are left to the first write.
*/
-import { activeWork, awaitingWorkers, isLeads, numberConversations, parkLaterConversations, type Conversation, type SuperTabState } from '../model.js'
+import { activeWork, awaitingWorkers, isLeads, numberConversations, parkLaterConversations, workerIndex, type Conversation, type SuperTabState } from '../model.js'
import { assignAgentDisplayNames } from '../agentNames.js'
import { agentProjectId, placeRules, projectsOf } from '../projects.js'
import { DORMANT_AFTER_MS, type ProgressData } from '../parts/index.js'
@@ -29,7 +29,9 @@ export function normalize(original: SuperTabState, { now, lastActivity }: { now:
placeRules(state)
assignAgentDisplayNames(state.agents)
if (state.projects) for (const agent of state.agents) agent.projectId ??= agentProjectId(state, agent)
- for (const project of projectsOf(state)) for (const worker of awaitingWorkers(state, project.id)) worker.workDecision = 'awaiting'
+ // One index for every project (model.ts workerIndex): the loop sets only workDecision, which the index does not hold.
+ const workers = workerIndex(state)
+ for (const project of projectsOf(state)) for (const worker of awaitingWorkers(state, project.id, workers)) worker.workDecision = 'awaiting'
const leadGroups = new Set(projectsOf(state).map(p => p.leadConversationId))
for (const group of state.conversations) {
const finished = !!group.assignment && !activeWork(group) && group.assignment.status !== 'stopped'
diff --git a/backend/src/superTabs/model.test.ts b/backend/src/superTabs/model.test.ts
index 13acdcc13..b0c9b40be 100644
--- a/backend/src/superTabs/model.test.ts
+++ b/backend/src/superTabs/model.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { createSuperTab, visibleState, type SuperTabState } from './model.js'
+import { awaitingWorkers, createSuperTab, visibleState, workerIndex, type Agent, type SuperTabState } from './model.js'
const deepFreeze = <T>(value: T): T => {
if (value && typeof value === 'object') { Object.values(value).forEach(deepFreeze); Object.freeze(value) }
@@ -22,3 +22,40 @@ describe('the removed Leads conversation', () => {
expect(stored.conversations.find(c => c.kind === 'leads')).toMatchObject({ agentIds: ['a1'], lastMessageSequence: 3 })
})
})
+
+describe('awaitingWorkers (spec 2026-11-02, Part 5)', () => {
+ /** 50 workers, each with a finished and an active task, and a Lead: every agent's answer reads every conversation. */
+ function swarm(): SuperTabState {
+ const state = createSuperTab('tab1', 'Pilot', { id: 'u1', email: '[email protected]' }, 'prod')
+ const configuration = { engine: 'codex', model: null, effort: null, contextWindow: null, engineVersion: null } as unknown as Agent['configuration']
+ state.agents = Array.from({ length: 50 }, (_, i): Agent => ({ id: `a${i}`, machineId: 'm', harnessId: `h${i}`, machineOwnerId: 'u1',
+ contributorId: 'u1', membershipGeneration: 'g', name: `a${i}`, configuration }))
+ state.conversations[0]!.leadId = 'a0'
+ for (let i = 0; i < 100; i++) {
+ state.conversations.push({ id: `c${i}`, title: '', leadId: null, agentIds: [], archived: false, brief: '', checks: [], lastMessageSequence: 0,
+ assignment: { id: `w${i}`, agentId: `a${i % 50}`, status: i < 50 ? 'done' : i % 2 ? 'working' : 'cancelled', result: null, configuration,
+ execution: { machineId: 'm', harnessId: 'h', machineOwnerId: 'u1' } } })
+ }
+ return state
+ }
+ /** Counts scans of the conversations: a for-of, some, find or filter alike reads the first one once. */
+ function counted(state: SuperTabState): { scans: number } {
+ const count = { scans: 0 }
+ state.conversations = new Proxy(state.conversations, { get(target, key, receiver) {
+ if (key === '0') count.scans++
+ return Reflect.get(target, key, receiver)
+ } })
+ return count
+ }
+
+ it('scans the conversations a constant number of times, and none with an index built for a loop over projects', () => {
+ const state = swarm()
+ const expected = state.agents.filter((_, i) => i > 0 && i % 2 === 0).map(a => a.id)
+ const alone = counted(state)
+ expect(awaitingWorkers(state, 'lead').map(a => a.id)).toEqual(expected)
+ expect(alone.scans).toBeLessThanOrEqual(3)
+ const index = workerIndex(state), shared = counted(state)
+ expect(awaitingWorkers(state, 'lead', index).map(a => a.id)).toEqual(expected)
+ expect(shared.scans).toBe(0)
+ })
+})
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 6222de7c5..dc59cfddb 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -618,13 +618,31 @@ export const actorKey = (actor: Actor): string => actor.kind === 'person' ? `per
export const activeWork = (group: Conversation): boolean => !!group.assignment &&
!['done', 'stopped', 'cancelled', 'lost'].includes(group.assignment.status)
+/** What awaitingWorkers reads of the conversations, from one pass over them: the agents leading any conversation, those with
+ * active work, and each agent's assigned groups (not lost) in conversation order. Scanning every conversation per agent and
+ * project was 2.6 M calls in the 2026-11-02 prod profiles (12 profiles), on every read. Built per call or per caller's loop
+ * over projects, never kept on the state, since a command changes it. */
+export interface WorkerIndex { leaders: ReadonlySet<string>; working: ReadonlySet<string>; groupsByAgent: ReadonlyMap<string, Conversation[]> }
+export function workerIndex(state: SuperTabState): WorkerIndex {
+ const leaders = new Set<string>(), working = new Set<string>(), groupsByAgent = new Map<string, Conversation[]>()
+ for (const c of state.conversations) {
+ if (c.leadId !== null) leaders.add(c.leadId)
+ if (!c.assignment) continue
+ if (activeWork(c)) working.add(c.assignment.agentId)
+ // A lost task's agent did not finish it, even once the task is cancelled: it may be gone.
+ if (c.assignment.lost) continue
+ const groups = groupsByAgent.get(c.assignment.agentId)
+ if (groups) groups.push(c)
+ else groupsByAgent.set(c.assignment.agentId, [c])
+ }
+ return { leaders, working, groupsByAgent }
+}
+
/** Old states derive the finished-work mark from their closed assignments; new states persist it on the worker. */
-export function awaitingWorkers(state: SuperTabState, projectId: string): Agent[] {
+export function awaitingWorkers(state: SuperTabState, projectId: string, index = workerIndex(state)): Agent[] {
return state.agents.filter(a => {
- if (state.conversations.some(c => c.leadId === a.id)
- || state.conversations.some(c => activeWork(c) && c.assignment?.agentId === a.id)) return false
- // A lost task's agent did not finish it, even once the task is cancelled: it may be gone.
- const groups = state.conversations.filter(c => c.assignment?.agentId === a.id && !c.assignment.lost)
+ if (index.leaders.has(a.id) || index.working.has(a.id)) return false
+ const groups = index.groupsByAgent.get(a.id) ?? []
return (a.projectId ?? groups.map(c => groupProject(state, c).id)[0] ?? 'lead') === projectId &&
(a.workDecision === 'awaiting' || (!a.workDecision && groups.some(c => !activeWork(c))))
})
@@ -820,7 +838,9 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
for (const start of visible.starts ?? []) if (startPreparing(state, start, now)) start.preparing = true
visible.invitations = visible.invitations.filter(i => visible.conversations.some(c => c.id === i.conversationId))
}
- for (const project of projectsOf(visible)) for (const target of awaitingWorkers(visible, project.id)) target.workDecision = 'awaiting'
+ // One index for every project: the loop sets only workDecision, which the index does not hold.
+ const workers = workerIndex(visible)
+ for (const project of projectsOf(visible)) for (const target of awaitingWorkers(visible, project.id, workers)) target.workDecision = 'awaiting'
for (const project of visible.projects ?? []) project.skillSet = skillSetOf(project)
// An uploaded avatar's stored key stays on the server; readers get a link with each parts read (avatarLinks.ts).
// Each person as the Swarm names them (usernames.ts), their default included.
diff --git a/backend/src/superTabs/parts/index.ts b/backend/src/superTabs/parts/index.ts
index 47cfde4a7..7ff8ebc7a 100644
--- a/backend/src/superTabs/parts/index.ts
+++ b/backend/src/superTabs/parts/index.ts
@@ -7,6 +7,7 @@ export * from './types.js'
export { clock, createClock } from './clock.js'
export { knownKind, reassemble, split, toLegacyState } from './shape.js'
-export { DORMANT_PAGE, insertParts, lastChangedAt, loadActive, loadAll, loadChanged, loadDormant, loadGroups, loadMachineParts, loadMachines, loadObserved, loadReadBase, loadStartsOfAgents } from './load.js'
+export { DORMANT_PAGE, insertParts, lastChangedAt, loadActive, loadAll, loadChanged, loadDelta, loadDormant, loadFinishedStarts, loadGroups, loadMachineParts, loadMachines, loadObserved, loadReadBase, loadStartsOfAgents } from './load.js'
+export type { SwarmDelta } from './load.js'
export { loadLight, loadLightGroups } from './light.js'
export { guardedWrite, PartConflict, type PartWrite } from './write.js'
diff --git a/backend/src/superTabs/parts/load.ts b/backend/src/superTabs/parts/load.ts
index a63347527..079877ed2 100644
--- a/backend/src/superTabs/parts/load.ts
+++ b/backend/src/superTabs/parts/load.ts
@@ -1,5 +1,5 @@
import type { Prisma } from '@prisma/client'
-import { delegate, extracted, partId, type PartRow } from './write.js'
+import { delegate, extracted, partId, type HeadColumns, type PartRow } from './write.js'
import type { GroupData, HeadData, MachineData, Part, PartKind, SwarmParts } from './types.js'
import { PART_KINDS } from './types.js'
import { noteChange } from '../cache.js'
@@ -106,7 +106,18 @@ export async function loadMachineParts(tx: Transaction, ids: string[]): Promise<
* machines, which it keeps at their own stamp (`loadMachines`). Dormant groups and their like come by name (`loadGroups`). */
export function loadReadBase(tx: Transaction, tabId: string): Promise<SwarmParts> {
const live = { deleted: false }
- return assemble(tx, tabId, { member: live, agent: live, group: [['dormancy', { dormant: false }]], machine: null, start: live, progress: live })
+ // Unfinished starts only: finished ones were 59% of prod's busiest base (1,118 of 1,120, 2026-11-02) and most reads drop
+ // them; the reads that name them read `loadFinishedStarts` (cachedReads.ts readParts).
+ return assemble(tx, tabId, { member: live, agent: live, group: [['dormancy', { dormant: false }]], machine: null,
+ start: { ...live, finishedAt: null }, progress: live })
+}
+
+/** A Swarm's live finished starts (they expire 7 days after finishing, sweeps.ts). A plain match: Prisma's `not: null` on
+ * Mongo is an $expr no index bounds. */
+export async function loadFinishedStarts(tx: Transaction, tabId: string): Promise<Part<AgentStart>[]> {
+ const rows = await tx.swarmStart.aggregateRaw({ pipeline: [{ $match: { tabId, deleted: false, finishedAt: { $ne: null } } }] }) as unknown as
+ Array<Record<string, unknown>>
+ return rows.map(row => toPart<AgentStart>('start', rawPartRow(row)))
}
/** A Swarm's live machine parts. */
@@ -144,20 +155,46 @@ export async function insertParts(tx: Transaction, parts: SwarmParts): Promise<v
export async function loadChanged(tx: Transaction, tabIds: string[], since: Date, kinds: readonly PartKind[] = PART_KINDS): Promise<Map<string, Part[]>> {
const changed = new Map<string, Part[]>(tabIds.map(id => [id, []]))
if (!tabIds.length) return changed
+ for (const [kind, rows] of await changedRows(tx, tabIds, since, kinds)) {
+ for (const row of rows) changed.get(row.tabId as string)!.push(changedPart(kind, row))
+ }
+ return changed
+}
+
+/** Each kind's rows changed after `since`, read in parallel: a refresh of the read cache waits for one round trip, not seven. */
+async function changedRows(tx: Transaction, tabIds: string[], since: Date, kinds: readonly PartKind[]): Promise<Array<[PartKind, Array<Record<string, unknown>>]>> {
// Plain matches that name each kind's (tabId, changedAt) index (parts/indexed.ts). Prisma sent `tabId: { in }` as an $expr
// $or, one planned scan per Swarm, and could pick an index that is not bounded by time at all (roadmap Phase 3.5).
const after = { $gt: { $date: since.toISOString() } }
const read = (kind: PartKind) => readBy(tx, COLLECTION[kind], 'changes', [{ $match: { tabId: { $in: tabIds }, changedAt: after } }, { $project: CHANGED_FIELDS }])
- for (const kind of kinds) {
+ return Promise.all(kinds.map(async kind => {
+ if (kind !== 'machine') return [kind, await read(kind)] as [PartKind, Array<Record<string, unknown>>]
// A machine read since the cursor counts as changed too: two bounded reads, not one $or the planner cannot bound.
- const rows = kind === 'machine' ? [...new Map([...await read(kind), ...await readBy(tx, 'SwarmMachine', 'read',
- [{ $match: { tabId: { $in: tabIds }, readAt: after } }, { $project: CHANGED_FIELDS }])].map(row => [row._id as string, row])).values()] : await read(kind)
+ const [changes, readings] = await Promise.all([read(kind), readBy(tx, 'SwarmMachine', 'read',
+ [{ $match: { tabId: { $in: tabIds }, readAt: after } }, { $project: CHANGED_FIELDS }])])
+ return [kind, [...new Map([...changes, ...readings].map(row => [row._id as string, row])).values()]] as [PartKind, Array<Record<string, unknown>>]
+ }))
+}
+
+const changedPart = (kind: PartKind, row: Record<string, unknown>): Part => {
+ const readAt = row.readAt == null ? null : ms(row.readAt)
+ return { ...toPart(kind, rawPartRow(row)), ...readAt ? { readAt } : {} }
+}
+
+/** What changed in one Swarm after `since`, for the read cache to patch what it holds (cache.ts; spec 2026-11-02 Phase 1):
+ * the parts of `kinds`, and the head's own columns when the head is among them. */
+export interface SwarmDelta { parts: Part[]; head: HeadColumns | null }
+
+export async function loadDelta(tx: Transaction, tabId: string, since: number, kinds: readonly PartKind[]): Promise<SwarmDelta> {
+ const parts: Part[] = []
+ let head: HeadColumns | null = null
+ for (const [kind, rows] of await changedRows(tx, [tabId], new Date(since), kinds)) {
for (const row of rows) {
- const readAt = row.readAt == null ? null : ms(row.readAt)
- changed.get(row.tabId as string)!.push({ ...toPart(kind, rawPartRow(row)), ...readAt ? { readAt } : {} })
+ parts.push(changedPart(kind, row))
+ if (kind === 'head') head = { groupCounter: Number(row.groupCounter), visibilityEpoch: Number(row.visibilityEpoch), sequenceBase: Number(row.sequenceBase) }
}
}
- return changed
+ return { parts, head }
}
/** The live starts of these agents (an agent is its machine and harness: write.ts extracted), whole, by the (tabId, agentId)
@@ -173,7 +210,9 @@ export async function loadStartsOfAgents(tx: Transaction, tabId: string, agentId
const COLLECTION = { head: 'SwarmHead', member: 'SwarmMember', agent: 'SwarmAgent', group: 'SwarmGroup', machine: 'SwarmMachine', start: 'SwarmStart',
progress: 'SwarmProgress' } as const satisfies Record<PartKind, NamedCollection>
/** What a changed part is made of: its other fields are indexed copies of its data. */
-const CHANGED_FIELDS = { tabId: 1, key: 1, version: 1, changedAt: 1, deleted: 1, ordinal: 1, data: 1, dormant: 1, readAt: 1 }
+const CHANGED_FIELDS = { tabId: 1, key: 1, version: 1, changedAt: 1, deleted: 1, ordinal: 1, data: 1, dormant: 1, readAt: 1,
+ // The head's own columns (no other kind has them): a patched base keeps them too.
+ groupCounter: 1, visibilityEpoch: 1, sequenceBase: 1 }
export const DORMANT_PAGE = 50
diff --git a/backend/src/superTabs/projects.test.ts b/backend/src/superTabs/projects.test.ts
index e41a5fe94..d67b7b981 100644
--- a/backend/src/superTabs/projects.test.ts
+++ b/backend/src/superTabs/projects.test.ts
@@ -1,8 +1,8 @@
import { createHash } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'
-import { agentOnly, createSuperTab, SuperTabError, visibleState, type Actor, type MessageDraft } from './model.js'
-import { canReadAgent, canWatchAgent, markConfidential, projectOf, projectsOf, readConversation, skillModeOf, skillSetOf, watchersLost, workRequesterId, requestedByLine } from './projects.js'
+import { activeWork, agentOnly, awaitingWorkers, createSuperTab, fail, SuperTabError, visibleState, workerIndex, type Actor, type Agent, type Conversation, type MessageDraft, type SuperTabState, type WorkStatus } from './model.js'
+import { canReadAgent, canWatchAgent, confidentialSession, groupProject, ledProject, markConfidential, projectOf, projectsOf, readConversation, requireSingleRegistration, sessionKey, skillModeOf, skillSetOf, watchersLost, workRequesterId, requestedByLine, type OtherRegistrations, type SwarmProject } from './projects.js'
import { mayDrive } from './terminal.js'
const owner: Actor = { kind: 'person', userId: 'owner', email: '[email protected]' }
@@ -617,3 +617,177 @@ describe('whom a task\'s pull requests are for', () => {
expect(requestedByLine(f.state, project, group(plain), agentOf('host'))).toBeNull()
})
})
+
+// The implementations before Part 5 (spec 2026-11-02, hot loops), kept here only to pin that the one-pass lookups answer
+// exactly as they did.
+const legacyLedProject = (state: SuperTabState, agentId: string): SwarmProject | undefined =>
+ projectsOf(state).find(p => state.conversations.some(c => c.id === p.leadConversationId && c.leadId === agentId))
+const legacyPrivateMember = (state: SuperTabState, agentId: string) => state.conversations.some(c => !!c.audience && c.agentIds.includes(agentId))
+const legacyConfidentialSession = (state: SuperTabState, target: Agent): boolean =>
+ !!legacyLedProject(state, target.id) || legacyPrivateMember(state, target.id)
+function legacyMarkConfidential(state: SuperTabState): void {
+ for (const target of state.agents) if (!target.confidential && legacyConfidentialSession(state, target)) target.confidential = true
+}
+function legacyRequireSingleRegistration(before: SuperTabState, after: SuperTabState, elsewhere: OtherRegistrations): void {
+ const prior = new Map(before.agents.map(a => [a.id, a]))
+ for (const target of after.agents) {
+ const was = prior.get(target.id), key = sessionKey(target.machineId, target.harnessId)
+ if ((!was || was.harnessId !== target.harnessId) && elsewhere.confidential.has(key)) {
+ fail('SESSION_CONFIDENTIAL', 'This terminal reads private chats in another Swarm. Start a new agent here.')
+ }
+ const lead = !!legacyLedProject(after, target.id) && !(was && legacyLedProject(before, target.id))
+ const member = legacyPrivateMember(after, target.id) && !(was && legacyPrivateMember(before, target.id))
+ if ((lead || member) && elsewhere.registered.has(key)) {
+ fail('SESSION_CONFIDENTIAL', 'This terminal also works in another Swarm, so it cannot lead or read private chats. Start a new agent for this.')
+ }
+ }
+}
+function legacyAwaitingWorkers(state: SuperTabState, projectId: string): Agent[] {
+ return state.agents.filter(a => {
+ if (state.conversations.some(c => c.leadId === a.id)
+ || state.conversations.some(c => activeWork(c) && c.assignment?.agentId === a.id)) return false
+ const groups = state.conversations.filter(c => c.assignment?.agentId === a.id && !c.assignment.lost)
+ return (a.projectId ?? groups.map(c => groupProject(state, c).id)[0] ?? 'lead') === projectId &&
+ (a.workDecision === 'awaiting' || (!a.workDecision && groups.some(c => !activeWork(c))))
+ })
+}
+
+/** A deterministic generator (mulberry32), so a failing Swarm is the same on every run. */
+function seeded(seed: number) {
+ let s = seed >>> 0
+ const next = () => {
+ s = (s + 0x6D2B79F5) >>> 0
+ let t = s
+ t = Math.imul(t ^ (t >>> 15), t | 1)
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+ const below = (n: number) => Math.floor(next() * n)
+ const pick = <T>(items: readonly T[]): T => items[below(items.length)]!
+ return { next, below, pick, chance: (p: number) => next() < p }
+}
+type Random = ReturnType<typeof seeded>
+
+const STATUSES: WorkStatus[] = ['planned', 'working', 'needs_human', 'blocked', 'review', 'done', 'stopped', 'cancelled', 'reconciling', 'lost']
+/** A Swarm of up to 2,000 conversations, 50 agents and 20 projects (exactly that when [full]): no projects at all or the legacy
+ * single one, private projects, Leads without a conversation, an agent leading two projects, lost assignments, audience
+ * conversations, agents already marked, and the odd conversation whose project lookup refuses (a removed Leads one, a Swarm
+ * Buddy chat). Most are small, so 200 of them compare quickly against the quadratic legacy code. */
+function generatedSwarm(random: Random, full = false): SuperTabState {
+ const agentCount = full ? 50 : 1 + random.below(50), projectCount = full ? 20 : random.below(21)
+ const conversationCount = full ? 2_000 : Math.floor(random.next() ** 2 * 2_000)
+ // Sparse to dense, so some Swarms keep most agents unmarked, leading nothing and working on nothing.
+ const leadRate = random.next() * 0.1, privateRate = random.next() * 0.05, assignRate = random.next() * 0.4
+ const agentIds = Array.from({ length: agentCount }, (_, i) => `a${i}`)
+ const someAgent = () => random.chance(0.03) ? 'gone' : random.pick(agentIds)
+ const conversationIds = Array.from({ length: conversationCount }, (_, i) => `c${i}`)
+ const projects: SwarmProject[] | undefined = projectCount === 0 ? (random.chance(0.5) ? undefined : []) : Array.from({ length: projectCount }, (_, i) => ({
+ id: i === 0 && random.chance(0.8) ? 'lead' : `p${i}`, name: `P${i}`, ownerId: 'owner',
+ // A Lead conversation that does not exist: a Lead without a conversation.
+ leadConversationId: !conversationCount || random.chance(0.15) ? `missing${i}` : random.pick(conversationIds),
+ visibility: random.chance(0.4) ? 'private' : 'public', members: [], updateMinutes: 5,
+ }))
+ const projectIds = (projects ?? [{ id: 'lead' }]).map(p => p.id)
+ const agents = agentIds.map((id): Agent => ({
+ id, machineId: `m${random.below(5)}`, harnessId: `h-${id}`, machineOwnerId: 'host', contributorId: 'owner', membershipGeneration: 'g', name: id,
+ configuration: configuration as unknown as Agent['configuration'],
+ ...(random.chance(0.3) && projectIds.length ? { projectId: random.pick(projectIds) } : {}),
+ ...(random.chance(0.15) ? { confidential: true as const } : {}),
+ ...(random.chance(0.5) ? { workDecision: random.pick(['awaiting', 'keep', 'stop'] as const) } : {}),
+ }))
+ const conversations = conversationIds.map((id): Conversation => {
+ const kind = random.chance(0.01) ? 'leads' as const : random.chance(0.01) ? 'swarm-buddy' as const : random.chance(0.02) ? 'buddy' as const : undefined
+ return {
+ id, title: id, archived: false, brief: '', checks: [], lastMessageSequence: 0,
+ ...(kind ? { kind } : {}),
+ ...(random.chance(0.85) && projectIds.length ? { projectId: random.pick(projectIds) } : {}),
+ leadId: random.chance(leadRate) ? someAgent() : null,
+ agentIds: Array.from({ length: random.below(4) }, someAgent),
+ ...(random.chance(privateRate) ? { audience: { people: [] } } : {}),
+ assignment: random.chance(assignRate) ? {
+ id: `w-${id}`, agentId: someAgent(), status: random.pick(STATUSES), result: null,
+ configuration: configuration as unknown as Agent['configuration'], execution: { machineId: 'm0', harnessId: 'h', machineOwnerId: 'host' },
+ ...(random.chance(0.2) ? { lost: { reason: 'stalled', at: 1 } } : {}),
+ } : null,
+ }
+ })
+ // Most projects have a Lead; an agent leading two projects' Lead conversations.
+ for (const p of projects ?? []) { const chat = conversations.find(c => c.id === p.leadConversationId); if (chat && random.chance(0.7)) chat.leadId = someAgent() }
+ if (projects && projects.length > 1 && random.chance(0.5)) {
+ const both = random.pick(agentIds)
+ for (const p of projects.slice(0, 2)) { const chat = conversations.find(c => c.id === p.leadConversationId); if (chat) chat.leadId = both }
+ }
+ const { projects: _first, ...base } = createSuperTab('swarm', 'Team', { id: 'owner', email: '[email protected]' }, 'test')
+ return { ...base, agents, conversations, ...(projects ? { projects } : {}) }
+}
+
+/** [before] after a command: Leads replaced, conversations made private or opened, members added, sessions rebound or added. */
+function changedSwarm(random: Random, before: SuperTabState): SuperTabState {
+ const after = structuredClone(before)
+ const ids = after.agents.map(a => a.id)
+ for (const c of after.conversations) {
+ if (random.chance(0.05)) c.leadId = random.pick(ids)
+ if (random.chance(0.05)) c.audience = random.chance(0.5) ? { people: [] } : undefined
+ if (random.chance(0.05)) c.agentIds = [...c.agentIds, random.pick(ids)]
+ }
+ for (const a of after.agents) if (random.chance(0.05)) a.harnessId = `${a.harnessId}-rebound`
+ if (random.chance(0.5)) {
+ const { confidential: _marked, ...added } = after.agents[0]!
+ after.agents.push({ ...added, id: 'added', harnessId: 'h-added' })
+ if (random.chance(0.6) && after.conversations.length) after.conversations[random.below(after.conversations.length)]!.leadId = 'added'
+ }
+ return after
+}
+
+/** What a call did: its answer, or the refusal it threw. */
+function outcome<T>(call: () => T): { value: T } | { code: string; message: string } {
+ try { return { value: call() } } catch (error) {
+ if (!(error instanceof SuperTabError)) throw error
+ return { code: error.code, message: error.message }
+ }
+}
+
+describe('confidential marks, Leads and waiting workers in one pass (spec 2026-11-02, Part 5)', () => {
+ it('new and old answers agree on generated Swarms', { timeout: 30_000 }, () => {
+ const random = seeded(20261102)
+ for (let i = 0; i < 200; i++) {
+ const before = generatedSwarm(random, i === 0)
+ const after = changedSwarm(random, before)
+ for (const state of [before, after]) {
+ const ids = [...state.agents.map(a => a.id), 'gone', 'nobody']
+ expect(ids.map(id => ledProject(state, id)?.id), `swarm ${i}`).toEqual(ids.map(id => legacyLedProject(state, id)?.id))
+ expect(state.agents.map(a => confidentialSession(state, a)), `swarm ${i}`).toEqual(state.agents.map(a => legacyConfidentialSession(state, a)))
+ const marked = (mark: (s: SuperTabState) => void) => {
+ const copy = { ...state, agents: state.agents.map(a => ({ ...a })) }
+ mark(copy)
+ return copy.agents.filter(a => a.confidential).map(a => a.id)
+ }
+ expect(marked(markConfidential), `swarm ${i}`).toEqual(marked(legacyMarkConfidential))
+ const projects = projectsOf(state), index = workerIndex(state)
+ const legacy = projects.map(p => outcome(() => legacyAwaitingWorkers(state, p.id).map(a => a.id)))
+ expect(projects.map(p => outcome(() => awaitingWorkers(state, p.id).map(a => a.id))), `swarm ${i}`).toEqual(legacy)
+ expect(projects.map(p => outcome(() => awaitingWorkers(state, p.id, index).map(a => a.id))), `swarm ${i}`).toEqual(legacy)
+ }
+ const keys = after.agents.map(a => sessionKey(a.machineId, a.harnessId))
+ const someKeys = () => new Set(keys.filter(() => random.chance(0.1)))
+ for (const elsewhere of [{ registered: someKeys(), confidential: new Set<string>() }, { registered: someKeys(), confidential: someKeys() },
+ { registered: new Set(keys), confidential: new Set<string>() }]) {
+ expect(outcome(() => requireSingleRegistration(before, after, elsewhere)), `swarm ${i}`)
+ .toEqual(outcome(() => legacyRequireSingleRegistration(before, after, elsewhere)))
+ }
+ }
+ })
+
+ it('markConfidential scans the conversations a constant number of times', () => {
+ const state = generatedSwarm(seeded(7), true)
+ for (const target of state.agents) delete target.confidential
+ // Every scan, a for-of, some, find or filter alike, reads the first conversation once.
+ let scans = 0
+ state.conversations = new Proxy(state.conversations, { get(target, key, receiver) {
+ if (key === '0') scans++
+ return Reflect.get(target, key, receiver)
+ } })
+ markConfidential(state)
+ expect(scans).toBeLessThanOrEqual(3)
+ })
+})
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index 54bae306d..946865539 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -127,7 +127,11 @@ export const NO_PROJECT = ''
/** The project whose Lead (Product Manager) this agent is: the Lead of that project's Lead conversation. */
export function ledProject(state: SuperTabState, agentId: string): SwarmProject | undefined {
- return projectsOf(state).find(p => state.conversations.some(c => c.id === p.leadConversationId && c.leadId === agentId))
+ // One scan of the conversations, then one of the projects in their order: a scan of every conversation per project was
+ // ledProject's callback, 13.5 M calls in the 2026-11-02 prod profiles (12 profiles), mostly from markConfidential.
+ const led = new Set<string>()
+ for (const c of state.conversations) if (c.leadId === agentId) led.add(c.id)
+ return led.size ? projectsOf(state).find(p => led.has(p.leadConversationId)) : undefined
}
/** Whose active work other projects' Leads see and are alerted about. A private project's work stays with its own people. */
@@ -263,9 +267,24 @@ export function canReadAgent(state: SuperTabState, actor: Actor, target: Agent):
/** A session that reads people's private messages: its project's Lead (the Product Manager each person chats with privately),
* or any agent in a private conversation, so a replaced Lead's earlier screen stays closed too. */
-export const confidentialSession = (state: SuperTabState, target: Agent): boolean =>
- !!ledProject(state, target.id) || privateMember(state, target.id)
-const privateMember = (state: SuperTabState, agentId: string) => state.conversations.some(c => !!c.audience && c.agentIds.includes(agentId))
+export const confidentialSession = (state: SuperTabState, target: Agent): boolean => {
+ const { leaders, privateMembers } = confidentialSets(state)
+ return leaders.has(target.id) || privateMembers.has(target.id)
+}
+
+/** Who confidentialSession holds confidential, for every agent at once: the Leads of a project's Lead conversation, and every
+ * member of a private conversation (one with an audience). One pass over the conversations: asking per agent scanned them
+ * per project and agent on every command (markConfidential), 13.5 M of ledProject's callbacks and 1.6 M of the private
+ * member check's in the 2026-11-02 prod profiles. Built per call, never kept on the state, since a command changes it. */
+export function confidentialSets(state: SuperTabState): { leaders: ReadonlySet<string>; privateMembers: ReadonlySet<string> } {
+ const leadChats = new Set(projectsOf(state).map(p => p.leadConversationId))
+ const leaders = new Set<string>(), privateMembers = new Set<string>()
+ for (const c of state.conversations) {
+ if (c.leadId !== null && leadChats.has(c.id)) leaders.add(c.leadId)
+ if (c.audience) for (const id of c.agentIds) privateMembers.add(id)
+ }
+ return { leaders, privateMembers }
+}
/** Whether an agent's session is confidential: marked, or a Lead or private member now, here or (`elsewhere`) in another Swarm. */
export const isConfidential = (state: SuperTabState, target: Agent, elsewhere = false): boolean =>
@@ -281,13 +300,14 @@ export interface OtherRegistrations { registered: Set<string>; confidential: Set
* a session registered elsewhere a Lead or a private conversation's member. Registrations from before the rule stay. */
export function requireSingleRegistration(before: SuperTabState, after: SuperTabState, elsewhere: OtherRegistrations): void {
const prior = new Map(before.agents.map(a => [a.id, a]))
+ const then = confidentialSets(before), now = confidentialSets(after)
for (const target of after.agents) {
const was = prior.get(target.id), key = sessionKey(target.machineId, target.harnessId)
if ((!was || was.harnessId !== target.harnessId) && elsewhere.confidential.has(key)) {
fail('SESSION_CONFIDENTIAL', 'This terminal reads private chats in another Swarm. Start a new agent here.')
}
- const lead = !!ledProject(after, target.id) && !(was && ledProject(before, target.id))
- const member = privateMember(after, target.id) && !(was && privateMember(before, target.id))
+ const lead = now.leaders.has(target.id) && !(was && then.leaders.has(target.id))
+ const member = now.privateMembers.has(target.id) && !(was && then.privateMembers.has(target.id))
if ((lead || member) && elsewhere.registered.has(key)) {
fail('SESSION_CONFIDENTIAL', 'This terminal also works in another Swarm, so it cannot lead or read private chats. Start a new agent for this.')
}
@@ -297,7 +317,9 @@ export function requireSingleRegistration(before: SuperTabState, after: SuperTab
/** A session becomes confidential the moment it is a Lead or in a private conversation, and stays so until it leaves the
* Swarm (its session closes), even once that membership ends (Lead ruling, final review Critical 1). */
export function markConfidential(state: SuperTabState): void {
- for (const target of state.agents) if (!target.confidential && confidentialSession(state, target)) target.confidential = true
+ // Every command runs this for every agent: one pass for all of them, not one per agent (confidentialSets).
+ const { leaders, privateMembers } = confidentialSets(state)
+ for (const target of state.agents) if (!target.confidential && (leaders.has(target.id) || privateMembers.has(target.id))) target.confidential = true
}
/** Whether a session's terminal is closed to watching in this Swarm. A confidential session's screen and scrollback hold
diff --git a/backend/src/superTabs/read/pageDeliveries.test.ts b/backend/src/superTabs/read/pageDeliveries.test.ts
new file mode 100644
index 000000000..4435ac8a5
--- /dev/null
+++ b/backend/src/superTabs/read/pageDeliveries.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest'
+import { deliveriesByMessage } from './pageDeliveries.js'
+
+describe('the messages page\'s deliveries by message', () => {
+ it('deliveriesByMessage keeps input order per message', () => {
+ const deliveries = [
+ { id: 'd1', messageId: 'm2' }, { id: 'd2', messageId: 'm1' }, { id: 'd3', messageId: 'm2' },
+ { id: 'd4', messageId: 'm3' }, { id: 'd5', messageId: 'm1' }, { id: 'd6', messageId: 'm2' },
+ ]
+ const byMessage = deliveriesByMessage(deliveries)
+ expect([...byMessage.keys()].sort()).toEqual(['m1', 'm2', 'm3'])
+ expect(byMessage.get('m1')!.map(d => d.id)).toEqual(['d2', 'd5'])
+ expect(byMessage.get('m2')!.map(d => d.id)).toEqual(['d1', 'd3', 'd6'])
+ expect(byMessage.get('m3')!.map(d => d.id)).toEqual(['d4'])
+ expect(byMessage.get('m4')).toBeUndefined()
+ // The same rows, never copies: a page's later filter and sort work on what pageDeliveries read.
+ expect(byMessage.get('m3')![0]).toBe(deliveries[3])
+ expect(deliveriesByMessage([]).size).toBe(0)
+ })
+})
diff --git a/backend/src/superTabs/read/pageDeliveries.ts b/backend/src/superTabs/read/pageDeliveries.ts
new file mode 100644
index 000000000..c2268d6ed
--- /dev/null
+++ b/backend/src/superTabs/read/pageDeliveries.ts
@@ -0,0 +1,15 @@
+/**
+ * The messages page's receipts by message (store.ts messages). Filtering every delivery of the page per message was 1.4 M
+ * calls in the 2026-11-02 prod profiles (12 profiles), on every messages read: one pass groups them instead.
+ */
+
+/** [deliveries] by their message, each list in input order, so a page's filter and receipt sort see what they saw before. */
+export function deliveriesByMessage<D extends { messageId: string }>(deliveries: readonly D[]): ReadonlyMap<string, D[]> {
+ const byMessage = new Map<string, D[]>()
+ for (const delivery of deliveries) {
+ const own = byMessage.get(delivery.messageId)
+ if (own) own.push(delivery)
+ else byMessage.set(delivery.messageId, [delivery])
+ }
+ return byMessage
+}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index bca545c19..3018f1efb 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -16,6 +16,7 @@ import { redactCredentials } from './credentials.js'
import type { AvatarUpload } from './profile.js'
import { reactionCounts, type ReactionTarget } from './reactions.js'
import { agentOpenDeliveries, compactedDelivery, deliveredCopies, messagesById, messagesPast, OPEN_DELIVERY, type MessageEdge, pageDeliveries, pageReactions, pageThreads, refreshReplies, type PageDelivery } from './pageReads.js'
+import { deliveriesByMessage } from './read/pageDeliveries.js'
import { restoreDelivery } from './deliveryCompaction.js'
import { threadSummaries } from './threads.js'
import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVATAR_TYPES, checkedType, directUploads, errorCode, HOURLY_UPLOAD_BYTES, HOURLY_UPLOADS, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, MAX_FORM_ATTACHMENT_BYTES, objectKeyFor, peekType, PENDING_UPLOAD_PURPOSE, publicUrl, TOO_LARGE_MESSAGE, trimPrefix, typeFromHead, UPLOAD_LINK_MS,
@@ -2475,8 +2476,9 @@ export class SuperTabStore {
const context = own && !own.projectId && !forward && cursor.before === undefined && !cursor.messageId ? await this.sessionExcerpt(tx, tabId, conversationId, own.from, m => rowRead(m) && sessionReadsRow(undefined, group, state)(m)) : undefined
// Only the rows this reader is shown get file links, each signed afresh for this read (fileLinks.ts).
const linked = await this.linked(tabId, shown)
+ const byMessage = deliveriesByMessage(deliveries)
return { messages: linked.map(m => ({ ...m, mentions: m.mentions ?? [], reactions: reactions.get(m.id) ?? [],
- deliveries: deliveries.filter(d => d.messageId === m.id && shownTo(m, d)).sort(receiptOrder(m)) })), next, threads, ...(context ? { context } : {}),
+ deliveries: (byMessage.get(m.id) ?? []).filter(d => shownTo(m, d)).sort(receiptOrder(m)) })), next, threads, ...(context ? { context } : {}),
// A poll for new messages learns here that a reaction changed on a message it already shows (reactions.ts).
reactionSeq: group.reactionSeq ?? 0 }
}
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 071d6350a..9eb93b912 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config'
export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts',
'integration/superTabRead.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabInbox.test.ts', 'integration/superTabFollowedThreads.test.ts', 'integration/superTabActivity.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts',
'integration/superTabTidy.test.ts', 'integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts', 'integration/superTabIndexes.test.ts', 'integration/superTabRouteDecisions.test.ts',
- 'integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabMachineReports.test.ts',
+ 'integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabCacheDelta.test.ts', 'integration/superTabMachineReports.test.ts',
'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabNotAvailable.test.ts',
'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',
'integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts',
diff --git a/cli/src/gateway/gateway.spec.ts b/cli/src/gateway/gateway.spec.ts
index 24733c1c0..07d59c833 100644
--- a/cli/src/gateway/gateway.spec.ts
+++ b/cli/src/gateway/gateway.spec.ts
@@ -8,7 +8,7 @@
* a process on this computer. The rest of the relay's rules are held where they always were, through the
* socket and its gateway together (backendSocket.spec.ts).
*/
-import { afterEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { BackendSocket } from '../backendSocket.js'
import type { Asker } from '../core/api.js'
import * as C from '../lib/e2ee/core.js'
@@ -18,6 +18,7 @@ import { bindMessageRequest } from '../testing/socketCore.js'
import { dispatchDown, gatewayOf, relaySocket, upstreamOf } from '../testing/relaySocket.js'
import type { DeviceLogTrustOutcome } from '../lib/e2ee/deviceLogSyncer.js'
import { unknownHelloReader } from './start.js'
+import { UI_GATED_EVENTS, UI_QUIET_MS, UI_SNAPSHOT_MAX_MS } from './gateway.js'
import { env } from '../config/env.js'
/** The machine the sessions are bound to: every hello and welcome is signed over it. */
@@ -253,6 +254,151 @@ describe('events only a terminal app reads', () => {
})
})
+// Part 4 of docs/superpowers/specs/2026-11-02-swarm-cache-delta-design.md: a machine's live events go to the relay only
+// while an app could see them, once the backend has said it may hold them (`uiGate`) and counts no app (`ui: 0`).
+describe('ui gate', () => {
+ const live = ['text_delta', 'tool_start', 'tool_end', 'user_message', 'thinking_delta', 'thinking_title', 'turn_heartbeat',
+ 'agent_activity', 'turn_ended', 'turn_summary', 'subagent_finished', 'done', 'context_compact']
+ const setup = () => {
+ const socket = relaySocket(MACHINE), gateway = gatewayOf(socket)
+ const queue = upstreamOf(socket).queue
+ /** What the relay is sent for every machine-wide copy of [types], each broadcast once. */
+ const relayed = (types: string[] = live) => {
+ queue.length = 0
+ for (const type of types) gateway.broadcast({ type, agentId: 'a1', payload: {} })
+ return queue.filter(item => !(item.msg as { targetConnId?: string }).targetConnId).map(item => (item.msg as { frame: { type: string } }).frame.type)
+ }
+ const noUi = (commander = 0) => dispatchDown(socket, { type: '__clients', payload: { ui: 0, commander, commanderActive: commander, uiGate: true } }, '')
+ return { socket, gateway, queue, relayed, noUi }
+ }
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => vi.useRealTimers())
+
+ it('holds exactly the live events, for 60 s of quiet', () => {
+ expect([...UI_GATED_EVENTS].sort()).toEqual([...live].sort())
+ expect(UI_QUIET_MS).toBe(60_000)
+ })
+
+ it('a live event is not relayed while the backend says no UI and none spoke for 60 s', async () => {
+ const { socket, relayed, noUi } = setup()
+ await noUi()
+ expect(relayed()).toEqual([])
+ expect(relayed(['agent_renamed', 'swarm_changed'])).toEqual(['agent_renamed', 'swarm_changed'])
+ await socket.stop()
+ })
+
+ it('a "no UI" the backend has not repeated for UI_SNAPSHOT_MAX_MS is not trusted', async () => {
+ const { socket, relayed, noUi } = setup()
+ await noUi()
+ expect(relayed()).toEqual([])
+ // The backend repeats `__clients` every 15 s (nodeRole PRESENCE_REFRESH_MS); one that stopped may be wrong.
+ vi.advanceTimersByTime(UI_SNAPSHOT_MAX_MS)
+ expect(relayed()).toEqual(live)
+ await noUi()
+ expect(relayed()).toEqual([])
+ await socket.stop()
+ })
+
+ it('relayed with ui > 0', async () => {
+ const { socket, relayed, noUi } = setup()
+ await noUi()
+ await dispatchDown(socket, { type: '__clients', payload: { ui: 1, commander: 0, uiGate: true } }, '')
+ expect(relayed()).toEqual(live)
+ await noUi()
+ expect(relayed()).toEqual([])
+ await socket.stop()
+ })
+
+ it('relayed again at once when a remote web frame arrives (its e2e hello)', async () => {
+ const { socket, relayed, noUi } = setup()
+ await noUi()
+ // Its hello comes before it can open anything, so it misses nothing it could read.
+ const phone = await pairedClient(socket, 'phone-1')
+ expect(relayed()).toEqual(live)
+ await vi.advanceTimersByTimeAsync(UI_QUIET_MS - 1)
+ expect(relayed()).toEqual(live)
+ await dispatchDown(socket, phone.seal('agents_list', { requestId: 'r' }), 'phone-1')
+ await vi.advanceTimersByTimeAsync(UI_QUIET_MS - 1)
+ expect(relayed()).toEqual(live)
+ // The backend says it again, as it does every 15 s: its word is not stale.
+ await noUi()
+ await vi.advanceTimersByTimeAsync(1)
+ expect(relayed()).toEqual([])
+ await socket.stop()
+ })
+
+ it('a device\'s frame, the backend\'s and a viewer\'s do not count as an app viewing', async () => {
+ const { socket, relayed, noUi } = setup()
+ const dial = await pairedClient(socket, 'dial-1', { role: 'device' })
+ // The backend counts the dial as a commander, never as an app (ui).
+ await noUi(1)
+ await vi.advanceTimersByTimeAsync(UI_QUIET_MS)
+ expect(relayed()).toEqual([])
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ await dispatchDown(socket, dial.seal('agents_list', { requestId: 'd' }), 'dial-1')
+ await dispatchDown(socket, { type: '__clients_dirty', payload: {} }, '')
+ // The hub addresses this one to the connection that left: it is the backend speaking, not that app.
+ await dispatchDown(socket, { type: '__client_disconnected', payload: {} }, 'phone-8')
+ await dispatchDown(socket, { type: 'observer_ping', payload: {} }, 'phone-9')
+ expect(relayed()).toEqual([])
+ await socket.stop()
+ })
+
+ it('relayed before any __clients, and after the link drops', async () => {
+ const { socket, gateway, relayed, noUi } = setup()
+ expect(relayed()).toEqual(live)
+ await noUi()
+ expect(relayed()).toEqual([])
+ ;(gateway as unknown as { linkGone(): void }).linkGone()
+ expect(relayed()).toEqual(live)
+ await socket.stop()
+ })
+
+ it('relayed when __clients has no uiGate (older backend or switch off)', async () => {
+ const { socket, relayed } = setup()
+ await dispatchDown(socket, { type: '__clients', payload: { ui: 0, commander: 0, commanderActive: 0 } }, '')
+ expect(relayed()).toEqual(live)
+ await dispatchDown(socket, { type: '__clients', payload: { ui: 0, uiGate: 'true' } }, '')
+ expect(relayed()).toEqual(live)
+ await socket.stop()
+ })
+
+ it('turn_started, agent_synced and agent_deleted are never held', async () => {
+ // The backend reads these itself: daily turn counts and the short-turn guard, and the machine's agents.
+ const { socket, relayed, noUi } = setup()
+ await noUi()
+ expect(relayed(['turn_started', 'agent_synced', 'agent_deleted'])).toEqual(['turn_started', 'agent_synced', 'agent_deleted'])
+ await socket.stop()
+ })
+
+ it('guest copies, device, user and targeted frames are never held', async () => {
+ const { socket, gateway, queue, noUi } = setup()
+ const phone = await pairedClient(socket, 'phone-1')
+ const e2ee = (gateway as unknown as { e2ee: { guestSessions(g: string): string[]; wrapFor(c: string, f: unknown): unknown } }).e2ee
+ vi.spyOn(e2ee, 'guestSessions').mockReturnValue(['guest-conn'])
+ vi.spyOn(e2ee, 'wrapFor').mockReturnValue({ type: 'text_delta', payload: { __e2e: 'sealed' } })
+ await noUi()
+ await vi.advanceTimersByTimeAsync(UI_QUIET_MS)
+ queue.length = 0
+ const sent = () => queue.splice(0).map(item => item.msg as { targetConnId?: string; commanderEligible?: boolean; userEligible?: boolean; frame: Frame })
+
+ gateway.broadcast({ type: 'text_delta', agentId: 'a1', payload: {} }, '[email protected]')
+ expect(sent().map(msg => msg.targetConnId)).toEqual(['guest-conn'])
+ gateway.commander({ type: 'text_delta', agentId: 'a1', payload: {} })
+ expect(sent().map(msg => msg.commanderEligible)).toEqual([true])
+ gateway.user({ type: 'text_delta', payload: {} })
+ expect(sent().map(msg => msg.userEligible)).toEqual([true])
+ // A reply to one client, and the backend's own (connId ''), which goes out machine-wide.
+ gateway.reply('phone-1', 'agents_list', 'r-1', { agents: [] })
+ const targeted = sent()
+ expect(targeted.map(msg => msg.targetConnId)).toEqual(['phone-1'])
+ expect(phone.open(targeted[0].frame)).toEqual({ requestId: 'r-1', agents: [] })
+ gateway.reply('', 'machine_info', 'r-2', { name: 'm' })
+ expect(sent().map(msg => [msg.targetConnId, msg.frame.type])).toEqual([[undefined, 'machine_info_result']])
+ await socket.stop()
+ })
+})
+
describe('the trust edges the split made visible', () => {
it('a process on this computer cannot send the backend hub\'s own frames: it once could set how many devices watch', async () => {
const socket = relaySocket(MACHINE)
diff --git a/cli/src/gateway/gateway.ts b/cli/src/gateway/gateway.ts
index d5ddc23a5..184ff624f 100644
--- a/cli/src/gateway/gateway.ts
+++ b/cli/src/gateway/gateway.ts
@@ -57,6 +57,21 @@ export interface RelayGatewayOptions {
export const TUI_ONLY_EVENTS: ReadonlySet<string> = new Set(['tool_end', 'subagent_finished', 'done', 'context_compact'])
/** The longest the backend's word that a terminal app is open is taken for (backend bus.ts TUI_OPEN_FOR_MS). */
export const TUI_OPEN_MAX_MS = 180_000
+/** A machine's live events: what an app viewing it shows as it happens, and none of it read by the backend. While the
+ * backend counts no app on the machine they stay off the relay, a publish that reached no one
+ * (docs/superpowers/specs/2026-11-02-swarm-cache-delta-design.md, Part 4). `turn_started`, `agent_synced` and
+ * `agent_deleted` are not here: the backend counts turns and keeps the machine's agents from them. An app that connects
+ * lists the sessions itself, so what was held leaves nothing missing. */
+export const UI_GATED_EVENTS: ReadonlySet<string> = new Set([
+ 'text_delta', 'tool_start', 'tool_end', 'user_message', 'thinking_delta', 'thinking_title', 'turn_heartbeat',
+ 'agent_activity', 'turn_ended', 'turn_summary', 'subagent_finished', 'done', 'context_compact',
+])
+/** How long a frame from a remote app keeps live events flowing without the backend's count: an app's first frame, its
+ * E2EE hello, comes before the `__clients` that counts it. */
+export const UI_QUIET_MS = 60_000
+/** How long the backend's "no app views this machine" is believed without being said again. It repeats `__clients` every
+ * 15 s (backend nodeRole PRESENCE_REFRESH_MS); a word six repeats old may come from a backend that stopped counting. */
+export const UI_SNAPSHOT_MAX_MS = 90_000
export class RelayGateway implements GatewayPort {
/** Optional scalar-only measurement hooks. Never hand a frame or user payload to the collector. */
@@ -103,6 +118,12 @@ export class RelayGateway implements GatewayPort {
/** Until when a terminal app of the account counts as open, from the backend's `__tui_open`; null until it has said
* (an older backend, a team account, the link not yet back), when every event is relayed as before. */
private tuiUntil: number | null = null
+ /** The backend's count of apps viewing this machine, from `__clients`, kept only when the backend says live events may be
+ * held on it (`uiGate`). null until it has said so (an older backend, or its RELAY_UI_GATE off) and while the link is
+ * down, when every event is relayed as before. */
+ private uiGate: { ui: number; at: number } | null = null
+ /** When a remote app (not a device, not the backend, not a Share viewer) last sent a frame. */
+ private lastRemoteFrameAt = 0
/** Subset of commanderCount whose device is ACTIVELY rendering this machine (multi-attach). null = the
* backend doesn't send the signal (old build). */
private commanderActive: number | null = null
@@ -235,6 +256,7 @@ export class RelayGateway implements GatewayPort {
this.staleRouteLogged.clear()
this.replayCommanderOnNextSnapshot = true
this.tuiUntil = null
+ this.uiGate = null
}
/** The ONE place commander presence changes. Both callers — the `__clients` snapshot and the link going
@@ -307,7 +329,7 @@ export class RelayGateway implements GatewayPort {
} catch { /* Work continues without metrics. */ }
}
if (this.link.servesThisComputerOnly()) return
- if (!this.heldForNoTerminalApp(frame.type)) this.link.enqueue({ t: 'up', frame: this.e2ee.wrapUp(frame) })
+ if (!this.heldForNoTerminalApp(frame.type) && !this.heldForNoUi(frame.type)) this.link.enqueue({ t: 'up', frame: this.e2ee.wrapUp(frame) })
if (guest) {
for (const connId of this.e2ee.guestSessions(guest)) {
const sealed = this.e2ee.wrapFor(connId, frame)
@@ -322,6 +344,14 @@ export class RelayGateway implements GatewayPort {
return this.tuiUntil !== null && Date.now() >= this.tuiUntil && typeof type === 'string' && TUI_ONLY_EVENTS.has(type)
}
+ /** Whether [type] is a live event and no app can see it now: the backend said it may be held and counts none, and no
+ * remote app has sent a frame for a minute. A guest's own sealed copy, and every reply and targeted frame, are never held. */
+ private heldForNoUi(type: unknown): boolean {
+ return this.uiGate !== null && this.uiGate.ui === 0 && Date.now() - this.uiGate.at < UI_SNAPSHOT_MAX_MS
+ && Date.now() - this.lastRemoteFrameAt >= UI_QUIET_MS
+ && typeof type === 'string' && UI_GATED_EVENTS.has(type)
+ }
+
/** The guest a remote connection's session is (gateway/sharedTrust.ts), '' when its store did not
* record the account; undefined for everyone else. */
private guestOf(connId: string): string | undefined {
@@ -550,6 +580,10 @@ export class RelayGateway implements GatewayPort {
return
}
if (type.startsWith('observer_')) return
+ // An app that connects sends its E2EE hello first, before the backend's next `__clients` counts it: live events flow
+ // again from that frame on, so it misses nothing it could open. The backend's own frames (connId '' or `__`) and a
+ // device's are no app viewing. A reconnecting device's hello, before it is known as one, opens it for a minute.
+ if (connId && !type.startsWith('__') && !this.isDeviceConn(connId)) this.lastRemoteFrameAt = Date.now()
// E2EE control frames (pairing/handshake) are handled by the manager, never as node RPCs.
if (type.startsWith('e2e_')) {
const deviceBefore = deviceDump.enabled && (this.isDeviceConn(connId) || (type === 'e2e_pair_intent' && (frame.payload as { role?: unknown } | undefined)?.role === 'device'))
@@ -635,7 +669,9 @@ export class RelayGateway implements GatewayPort {
// Cross-instance client snapshot. Generation detects leave/join cycles that coalesce to the same
// count; count rise remains the compatibility fallback for older backends.
if (type === '__clients') {
- const payload = (frame.payload ?? {}) as { commander?: number; commanderActive?: number; commanderJoinGeneration?: number }
+ const payload = (frame.payload ?? {}) as { ui?: number; commander?: number; commanderActive?: number; commanderJoinGeneration?: number; uiGate?: unknown }
+ // A count that is no number is never 0, so it holds nothing.
+ this.uiGate = payload.uiGate === true ? { ui: Number(payload.ui ?? 0), at: Date.now() } : null
const commander = Number(payload.commander ?? 0)
const rawGeneration = payload.commanderJoinGeneration
const generation = typeof rawGeneration === 'number' && Number.isSafeInteger(rawGeneration) && rawGeneration >= 0
diff --git a/cli/src/team/boundary.spec.ts b/cli/src/team/boundary.spec.ts
new file mode 100644
index 000000000..c5b25cad2
--- /dev/null
+++ b/cli/src/team/boundary.spec.ts
@@ -0,0 +1,332 @@
+/**
+ * The boundary a Harness Team account stands on: an agent in that account is refused every read and write in the home of
+ * the Mac's or Linux computer's owner (audit of 2026-11-02, docs/security/2026-11-02-team-account-boundary.md).
+ *
+ * The other specs here check the setup script as text and the privacy check with made-up answers. Neither would notice a
+ * home folder that the kernel lets another account into. These ask the kernel, about the mode the real setup script gives,
+ * in a fixture folder: no real account, home or permission changes, and nothing here uses sudo beyond becoming `nobody`.
+ *
+ * Two ways to be the other account:
+ * - As `nobody`, through `sudo -n`, where that needs no password: CI's Linux, where it may not be missing.
+ * - Everywhere else (a shared Mac has no passwordless sudo, and its accounts are not ours to change): as this user, with the
+ * fixture's owner bits set to what the group and other bits say. A Team account on a Mac is in the owner's group (staff), so
+ * both count. At the mode setup gives, that is mode 000, so these runs show only that 000 refuses. What guards the home on
+ * such a machine is the check that no group or other bit is set, on every line of the script that changes it.
+ */
+import { spawn, spawnSync } from 'node:child_process'
+import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { createServer } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { tmpdir } from 'node:os'
+import { join, relative } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterEach, describe, expect, it } from 'vitest'
+import { SENTINEL_NAME } from './layout.js'
+import { realPrivacyDeps, runPrivacyCheck } from './privacy.js'
+import { buildLinuxSetupScript, buildSetupScript, type SetupScriptInput } from './script.js'
+
+const SETUP: SetupScriptInput = {
+ user: 'harnessteam', realName: 'Harness Team', home: '/Users/harnessteam', owner: 'owner-placeholder', ownerHome: '/Users/owner-placeholder',
+ stageDir: '/private/var/folders/aa/T/harness-team-x1', nodeRuntimeDir: '/Users/owner-placeholder/.harness/runtime/node-v24',
+ tmuxRuntimeDir: null, cliDir: '/Users/owner-placeholder/.harness/cli', ownerNode: '/Users/owner-placeholder/.harness/runtime/node-v24/bin/node',
+ ownerCli: '/Users/owner-placeholder/.harness/cli/cli.js', mintEnv: {}, signIn: 'missing',
+}
+
+/** A line of a script that changes who may enter the owner's home, indented or wrapped in anything, by variable or by its path. */
+const changesOwnerHome = (line: string): boolean => !line.trimStart().startsWith('#')
+ && /\b(chmod|chown|chgrp|setfacl)\b/.test(line)
+ && (line.includes('OWNER_HOME') || new RegExp(`${SETUP.ownerHome}(?![\\w./-])`).test(line))
+
+/**
+ * What the script does to the owner's home, as a mode. Every line of it counts, not only step 3's: a later `chmod 755`, or an ACL
+ * for the Team account, would reopen the home after that step closed it. It throws on a line it cannot read, or more than the one.
+ */
+function ownerHomeMode(script: string): number {
+ const step = script.split('\n').filter(changesOwnerHome)
+ expect(step, 'the one line that closes the owner\'s home, and no other that changes it').toHaveLength(1)
+ const line = step[0]!.trim()
+ const chmod = /^chmod (\d{3}) "\$OWNER_HOME"$/.exec(line)
+ if (chmod) return Number.parseInt(chmod[1]!, 8)
+ const acl = /^setfacl -n -m u::([rwx-]{3}),g::([rwx-]{3}),o::([rwx-]{3}) "\$OWNER_HOME"$/.exec(line)
+ if (!acl) throw new Error(`this line changes the owner's home in a way this spec cannot read: ${line}`)
+ const bits = (word: string) => (word[0] === 'r' ? 4 : 0) + (word[1] === 'w' ? 2 : 0) + (word[2] === 'x' ? 1 : 0)
+ return bits(acl[1]!) * 0o100 + bits(acl[2]!) * 0o10 + bits(acl[3]!)
+}
+
+/** Whether this process can be `nobody` with no password. */
+const sudoNobody = process.platform !== 'win32' && process.getuid?.() !== 0
+ && spawnSync('sudo', ['-n', '-u', 'nobody', '/usr/bin/id', '-u'], { stdio: 'ignore', timeout: 5_000 }).status === 0
+
+/** Each fixture's path and the mode it would have for its owner, so a test can put it back and remove it. */
+interface Fixture {
+ root: string
+ home: string
+ /** A folder of the other account's own. */
+ own: string
+ modes: Map<string, number>
+}
+
+const fixtures: Fixture[] = []
+
+/**
+ * An owner's home, as a default install leaves it: open to the group and everyone (macOS's staff, older Debian's 755), with a
+ * project folder anyone may write to, so nothing below the home's own mode would keep the other account out.
+ */
+function ownerHome(parent: string): Fixture {
+ const root = realpathSync(mkdtempSync(join(parent, 'hb-')))
+ chmodSync(root, 0o755)
+ const home = join(root, 'owner'), own = join(root, 'other')
+ mkdirSync(home)
+ mkdirSync(own)
+ chmodSync(own, 0o777)
+ const entries: Array<[string, number, string | null]> = [
+ [SENTINEL_NAME, 0o644, 'sentinel\n'],
+ ['.gitconfig', 0o644, '[user]\n\tname = owner\n'],
+ ['.ssh', 0o700, null],
+ ['.ssh/id_ed25519', 0o600, 'not a real key\n'],
+ ['code', 0o777, null],
+ ['code/project.txt', 0o666, 'project\n'],
+ ]
+ const modes = new Map<string, number>([[home, 0o755]])
+ for (const [name, mode, text] of entries) {
+ const path = join(home, name)
+ if (text === null) mkdirSync(path)
+ else writeFileSync(path, text)
+ modes.set(path, mode)
+ }
+ for (const [path, mode] of modes) chmodSync(path, mode)
+ const fixture = { root, home, own, modes }
+ fixtures.push(fixture)
+ return fixture
+}
+
+/** Every path in the home with its contents: what no refused write may change. */
+function snapshot(fixture: Fixture): Record<string, string> {
+ const seen: Record<string, string> = {}
+ const walk = (path: string): void => {
+ const info = lstatSync(path)
+ seen[relative(fixture.home, path) || '.'] = info.isDirectory() ? 'folder' : readFileSync(path, 'utf8')
+ if (info.isDirectory()) for (const name of readdirSync(path).sort()) walk(join(path, name))
+ }
+ walk(fixture.home)
+ return seen
+}
+
+/** Sets the fixture's owner bits to what its group and other bits allow: this user now gets what the other account gets. */
+function seenFromOutside(fixture: Fixture, homeMode: number): void {
+ // Files before the folders above them: a closed folder lets nothing below it change.
+ for (const [path, mode] of [...fixture.modes].reverse()) {
+ const actual = path === fixture.home ? homeMode : mode
+ chmodSync(path, (((actual >> 3) | actual) & 0o7) * 0o111)
+ }
+}
+
+/** The fixture's real modes again, so this user can read and remove it. */
+function restored(fixture: Fixture, homeMode: number): void {
+ for (const [path, mode] of fixture.modes) chmodSync(path, path === fixture.home ? homeMode : mode)
+}
+
+afterEach(() => {
+ for (const fixture of fixtures.splice(0)) {
+ for (const path of fixture.modes.keys()) { try { chmodSync(path, 0o700) } catch { /* Removed by a write that should have been refused: its test said so. */ } }
+ rmSync(fixture.root, { recursive: true, force: true })
+ }
+})
+
+type Run = (command: string) => { status: number | null; output: string }
+const asThisUser: Run = (command) => {
+ const result = spawnSync('/bin/sh', ['-c', command], { encoding: 'utf8', timeout: 10_000 })
+ return { status: result.status, output: `${result.stdout}${result.stderr}` }
+}
+const asNobody: Run = (command) => {
+ const result = spawnSync('sudo', ['-n', '-u', 'nobody', '/bin/sh', '-c', `cd /; ${command}`], { encoding: 'utf8', timeout: 10_000 })
+ return { status: result.status, output: `${result.stdout}${result.stderr}` }
+}
+
+/** Everything an agent in the other account might try, by name. A refusal must come from the kernel, not from a missing path. */
+const attempts = ({ home, own }: Fixture): Record<string, string> => ({
+ 'read the sentinel': `cat '${home}/${SENTINEL_NAME}'`,
+ 'read a world-readable dotfile': `cat '${home}/.gitconfig'`,
+ 'read a private key': `cat '${home}/.ssh/id_ed25519'`,
+ 'read a world-readable project file': `cat '${home}/code/project.txt'`,
+ 'read through its own symbolic link': `ln -sf '${home}/.gitconfig' '${own}/link' && cat '${own}/link'`,
+ 'list the home': `ls -A '${home}'`,
+ 'list .ssh': `ls -A '${home}/.ssh'`,
+ 'list a project folder': `ls -A '${home}/code'`,
+ 'stat a file by name': `ls -l '${home}/.gitconfig'`,
+ 'create a file in the home': `: > '${home}/planted'`,
+ 'make a folder in the home': `mkdir '${home}/planted-folder'`,
+ 'leave a link in the home': `ln -s /tmp '${home}/planted-link'`,
+ 'overwrite a dotfile': `: > '${home}/.gitconfig'`,
+ 'append to a world-writable project file': `echo planted >> '${home}/code/project.txt'`,
+ 'create a file in a world-writable folder': `: > '${home}/code/planted'`,
+ 'delete a file': `rm -f '${home}/code/project.txt'`,
+ 'rename a file': `mv '${home}/.gitconfig' '${home}/moved'`,
+ 'hard-link a file out': `ln '${home}/.gitconfig' '${own}/hard'`,
+})
+
+/** Every attempt ends with the kernel's refusal, and the home is as it was. */
+function expectRefused(run: Run, fixture: Fixture): void {
+ for (const [what, command] of Object.entries(attempts(fixture))) {
+ const { status, output } = run(command)
+ expect(status, `${what} was not refused: ${output}`).not.toBe(0)
+ expect(output, what).toMatch(/permission denied|not permitted/i)
+ }
+}
+
+const SCRIPTS: Array<[string, (input: SetupScriptInput) => string]> = [['macOS', buildSetupScript], ['Linux', buildLinuxSetupScript]]
+
+describe('an agent in the Team account, in the owner\'s home', () => {
+ it.each(SCRIPTS)('%s: the mode setup gives it keeps group and everyone out, before the daemon starts', (name, build) => {
+ const script = build(SETUP)
+ // Not a loosening of 700: any group or other bit would let the other account back in.
+ expect(ownerHomeMode(script) & 0o077).toBe(0)
+ const closes = script.split('\n').findIndex(changesOwnerHome)
+ const starts = script.split('\n').findIndex(line => /launchctl bootstrap system|systemctl enable --now/.test(line))
+ expect(closes, name).toBeGreaterThan(-1)
+ expect(closes, name).toBeLessThan(starts)
+ })
+
+ it.each([
+ ['a later chmod', 'chmod 755 "$OWNER_HOME"'],
+ ['an indented chmod', ' chmod 755 "$OWNER_HOME"'],
+ ['an ACL for the Team account', 'chmod +a "$TEAM allow list,search,read" "$OWNER_HOME"'],
+ ['a chmod by its path', `/bin/chmod 755 ${SETUP.ownerHome}`],
+ ['a change of group', 'chgrp staff "$OWNER_HOME"'],
+ ['a recursive ACL as the owner', 'as_owner setfacl -R -m u:harnessteam:rX "$OWNER_HOME"'],
+ ])('a script is refused when %s reopens the home after it closed', (_name, line) => {
+ const script = `${buildSetupScript(SETUP)}\n${line}\n`
+ expect(() => ownerHomeMode(script)).toThrow()
+ })
+
+ it('is let in before setup closes it: the attempts below are not refused for some other reason', () => {
+ const fixture = ownerHome(tmpdir())
+ seenFromOutside(fixture, 0o755)
+ const run = asThisUser
+ expect(run(`cat '${fixture.home}/.gitconfig'`).output).toContain('name = owner')
+ expect(run(`ls -A '${fixture.home}'`).output).toContain('.gitconfig')
+ expect(run(`cat '${fixture.home}/code/project.txt'`).status).toBe(0)
+ // The refusals that hold with the home open are the files' own, and none of the home's mode.
+ expect(run(`cat '${fixture.home}/.ssh/id_ed25519'`).status).not.toBe(0)
+ restored(fixture, 0o755)
+ })
+
+ it.each(SCRIPTS)('%s: is refused every read and write once setup closed it', (_name, build) => {
+ const fixture = ownerHome(tmpdir())
+ const mode = ownerHomeMode(build(SETUP))
+ const before = snapshot(fixture)
+ seenFromOutside(fixture, mode)
+ expectRefused(asThisUser, fixture)
+ restored(fixture, mode)
+ expect(snapshot(fixture)).toEqual(before)
+ })
+
+ // As a real other account, where one can be had for free. CI's Linux must have it: a required check is never skipped there.
+ it('CI\'s Linux can be another account', () => {
+ if (process.env.CI && process.platform === 'linux') expect(sudoNobody).toBe(true)
+ })
+
+ describe.runIf(sudoNobody)('as nobody, a real other account', () => {
+ /** Under /tmp: Vitest's own temporary folder may not be searchable by another account. */
+ const parent = '/tmp'
+
+ it('reads and lists the home before setup closes it', () => {
+ const fixture = ownerHome(parent)
+ expect(asNobody(`cat '${fixture.home}/.gitconfig'`).output).toContain('name = owner')
+ expect(asNobody(`ls -A '${fixture.home}'`).output).toContain('.gitconfig')
+ expect(asNobody(`echo planted >> '${fixture.home}/code/project.txt'`).status).toBe(0)
+ })
+
+ it.each(SCRIPTS)('%s: is refused every read and write once setup closed it', (_name, build) => {
+ const fixture = ownerHome(parent)
+ const before = snapshot(fixture)
+ chmodSync(fixture.home, ownerHomeMode(build(SETUP)))
+ expectRefused(asNobody, fixture)
+ expect(snapshot(fixture)).toEqual(before)
+ })
+ })
+})
+
+describe('the privacy check, on the real file system', () => {
+ const check = (fixture: Fixture) => runPrivacyCheck(
+ { ownerHome: fixture.home, sentinel: join(fixture.home, SENTINEL_NAME) },
+ // This process may be an administrator on a developer's Mac; the account it stands in for may not. The rest is real.
+ { ...realPrivacyDeps, platform: 'darwin', groups: () => [] },
+ )
+
+ it('passes a home closed as setup closes it', () => {
+ const fixture = ownerHome(tmpdir())
+ const mode = ownerHomeMode(buildSetupScript(SETUP))
+ seenFromOutside(fixture, mode)
+ expect(check(fixture).passed).toBe(true)
+ restored(fixture, mode)
+ })
+
+ it.each([
+ ['open to everyone (755)', 0o755],
+ ['open to the group, as a Mac makes a home (750)', 0o750],
+ // No listing, yet anyone who knows a name may open it: what a web server's home is often set to.
+ ['searchable only (711)', 0o711],
+ ['open to the group alone, to write too (770)', 0o770],
+ ])('fails a home %s', (_name, mode) => {
+ const fixture = ownerHome(tmpdir())
+ seenFromOutside(fixture, mode)
+ const result = check(fixture)
+ restored(fixture, mode)
+ expect(result.passed).toBe(false)
+ })
+
+ it('fails closed on a sentinel that is not there: a missing file means the folder above it let the search through', () => {
+ const fixture = ownerHome(tmpdir())
+ rmSync(join(fixture.home, SENTINEL_NAME))
+ fixture.modes.delete(join(fixture.home, SENTINEL_NAME))
+ seenFromOutside(fixture, 0o711)
+ const result = check(fixture)
+ restored(fixture, 0o711)
+ expect(result).toMatchObject({ passed: false, item: 'sentinel' })
+ })
+
+ it('names the home by ~ or by what it is, never by its path, which carries the owner\'s account name', () => {
+ const fixture = ownerHome(tmpdir())
+ seenFromOutside(fixture, 0o755)
+ const result = check(fixture)
+ restored(fixture, 0o755)
+ expect(JSON.stringify(result)).not.toContain(fixture.home)
+ })
+})
+
+/** A hole the audit found (finding H1), pinned as it is today: this turns red the day it is closed, and then says the opposite. */
+describe('the owner\'s credential and whoever holds the daemon\'s port', () => {
+ const NOTIFY = fileURLToPath(new URL('../../hook/notify.mjs', import.meta.url))
+ /** Made up for this test: never a real credential. */
+ const CREDENTIAL = 'A'.repeat(43)
+
+ it('H1, still open: an engine hook hands its credential to any listener on the daemon\'s port', async () => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'hc-')))
+ const data = join(root, 'data')
+ mkdirSync(data, { mode: 0o700 })
+ writeFileSync(join(data, 'hook-credential'), CREDENTIAL, { mode: 0o600 })
+ // Any account may bind a free port above 1023: an agent in the Team account, while the owner's daemon restarts.
+ const heard: string[] = []
+ const impostor = createServer((req, res) => {
+ heard.push(String(req.headers['x-harness-hook-token'] ?? ''))
+ req.resume()
+ req.on('end', () => { res.writeHead(200, { 'content-type': 'application/json' }); res.end('{}') })
+ })
+ await new Promise<void>(resolve => { impostor.listen(0, '127.0.0.1', resolve) })
+ try {
+ const port = (impostor.address() as AddressInfo).port
+ const hook = spawn(process.execPath, [NOTIFY, '--port', String(port), '--data-dir', data], {
+ stdio: ['pipe', 'ignore', 'ignore'],
+ // Its own empty tmux folder, so the pane's routing reads no real tmux server.
+ env: { PATH: process.env.PATH, HOME: root, TMUX_PANE: '%999', TMUX_TMPDIR: root },
+ })
+ hook.stdin.end(JSON.stringify({ hook_event_name: 'SessionStart', session_id: '11111111-1111-4111-8111-111111111111', cwd: root, source: 'startup' }))
+ await new Promise<void>(resolve => { hook.on('exit', () => resolve()) })
+ expect(heard).toContain(CREDENTIAL)
+ } finally {
+ await new Promise<void>(resolve => { impostor.close(() => resolve()) })
+ rmSync(root, { recursive: true, force: true })
+ }
+ }, 30_000)
+})
diff --git a/docs/plans/2026-11-02-team-account-boundary-audit-plan.md b/docs/plans/2026-11-02-team-account-boundary-audit-plan.md
new file mode 100644
index 000000000..baf5846f6
--- /dev/null
+++ b/docs/plans/2026-11-02-team-account-boundary-audit-plan.md
@@ -0,0 +1,70 @@
+# Team Account Boundary Audit Implementation Plan
+
+> **For agentic workers:** steps use checkbox (`- [ ]`) syntax. Written by the writing-plans skill, as the project's
+> instructions ask. The audit's reading came first and the spec was drafted before the rule reached this task (revision 9,
+> 2026-11-02): this plan records what was done and what is left.
+
+**Goal:** Say, with evidence, whether an agent in a Harness Team account can read, list or change the files of the machine's
+main account; pin what holds with tests; ask the PM for a fix for each hole.
+
+**Architecture:** No product code changes. One spec asks the kernel about the mode the real setup script gives the owner's
+home, in a fixture folder. One document rates the findings. Holes become fix requests, not changes in this pull request.
+
+**Tech Stack:** TypeScript, Vitest, POSIX shell tools.
+
+**Spec:** Task #2009's brief (conversation `6b8bce9ecfc60ed067d388b1`).
+
+## Global Constraints
+
+- Do not change real accounts or permissions on any shared Mac; temp users or fixtures in this task's own folders only.
+- Never run a test that signs this Mac out of the real CLI. Stop only processes this task started, by id.
+- Never print or post a secret: names of variables only, values redacted, including in evidence.
+- Two independent security reviews before merge.
+
+## Review Focus
+
+- A refusal that comes from a missing path, not from the kernel: the attempts must fail with a permission error.
+- A test that would pass with the home open: a control must show the same attempts succeed before setup closes it.
+- A required check skipped without saying: CI's Linux must have a real second account, and fails if it has none.
+- A write that is refused yet changes something: the home is compared before and after.
+- The spec reaching real state: fixtures only; the hook runs with a made-up credential and an empty tmux folder.
+
+---
+
+### Task 1: Read every path in scope
+
+**Files:** none changed.
+
+- [x] **Step 1:** Read account setup and removal, modes, the daemon, the Swarm service and purge (`cli/src/team/*`,
+ `cli/src/superTabs/teamDaemon.ts`, `cli/src/superTabs/inCore/teamPurge.ts`).
+- [x] **Step 2:** Read the limits of a Team sign-in on the server (`backend/src/lib/teamSession.ts`, `superTabs/store.ts`
+ `teamCommand`, `superTabs/terminal.ts`).
+- [x] **Step 3:** Read every loopback server and credential path (`cli/src/hookServer.ts`, `localWsServer.ts`,
+ `lib/subscriptionRelay.ts`, `lib/connectors/bridge.ts`, `lib/swarmApiShares.ts`, `hook/notify.mjs`).
+- [x] **Step 4:** Look at this Mac's real modes, listeners and process table, read-only, with values redacted.
+
+### Task 2: Boundary tests
+
+**Files:**
+- Create: `cli/src/team/boundary.spec.ts`
+
+**Interfaces:**
+- Consumes: `buildSetupScript`, `buildLinuxSetupScript`, `runPrivacyCheck`, `realPrivacyDeps`, `SENTINEL_NAME`.
+- Produces: nothing other code uses.
+
+- [x] **Step 1: Write the spec:** every attempt refused by the kernel at the mode step 3 of each real script gives; a control
+ with the home open; the same as `nobody` where `sudo -n` allows; the privacy check on the real file system; H1 pinned as it is today, so closing it turns the test red.
+- [x] **Step 2: Run it:** `npx vitest run src/team/boundary.spec.ts`. Expected: PASS.
+- [x] **Step 3: Red evidence:** take step 3's `chmod 700 "$OWNER_HOME"` out of `script.ts`, and run it again. Expected: FAIL
+ on the step's line. Put it back. Then set it to `chmod 755`. Expected: FAIL on "was not refused".
+- [x] **Step 4: Run the Team specs and the local server's spec:** `npx vitest run src/team src/hookServer.spec.ts`.
+
+### Task 3: Findings and fix requests
+
+**Files:**
+- Create: `docs/security/2026-11-02-team-account-boundary.md`
+
+- [x] **Step 1:** Write each finding: area, rating, evidence by file and line, what fixes it; what holds, each with its evidence.
+- [ ] **Step 2:** Post the rated list to Scholes in the task, and one fix request per real hole to the PM.
+- [ ] **Step 3:** Commit, open the pull request starting with its "Requested by" line, with the checklist and red/green evidence.
+- [ ] **Step 4:** Add two review steps and name free Opus Reviewers that have not worked on this task.
diff --git a/docs/security/2026-11-02-team-account-boundary.md b/docs/security/2026-11-02-team-account-boundary.md
new file mode 100644
index 000000000..e788a1bdf
--- /dev/null
+++ b/docs/security/2026-11-02-team-account-boundary.md
@@ -0,0 +1,199 @@
+# Harness Team account: can its agents reach the main account's files?
+
+Audit of 2026-11-02 (task #2009), at `origin/main` 615626874. Nothing on any real account or permission was changed. On the
+Mac Studio, modes, listeners and the process table were read, with values on command lines masked. One scan also read the contents of
+readable files in `/private/tmp`, other agents' included, as the main account (M1): it counted key-shaped text, and printed each match's
+kind, length and randomness, and its file's top folder and extension, never a value. No other file's contents were read.
+
+## Answer
+
+**The home folder holds. The account as a whole does not yet.** A Team agent is refused every direct read, list and write in
+the main account's home, and the server keeps a Team sign-in away from the owner's agents and machines. But two paths can give a
+Team agent the owner's full rights (H1, H2), and files and command lines the owner's agents leave outside the home are open to it
+(M1, M2). Both reviews of this audit changed it: H2 is theirs.
+
+| ID | Rating | Finding | Status |
+|---|---|---|---|
+| H1 | **High** | The owner's local credential goes to whoever holds the daemon's port | Proved with the real hook, fix requested |
+| H2 | **High** | A Team agent's branch runs with the owner's rights when an owner's agent builds it | Read in code, fix requested |
+| M1 | **Medium** | The owner's files in the shared `/tmp` are readable, and can be planted | Seen on the Mac Studio, fix requested |
+| M2 | **Medium** | Tokens on tmux's command line show in `ps` to every account | Seen on the Mac Studio, fix requested |
+| M3 | **Medium** | A Team agent's chat message reaches the owner's agents, which act with the owner's rights | Read in code, decision requested |
+| M4 | **Medium** | The relay forwards any path and method with the owner's vendor sign-in | Read in code, fix requested |
+| M5 | **Medium** | A Team agent can stop the owner's Swarm service, again and again, through its status file | Blocking read proved, fix requested |
+| L1 | Low | `harness team status` prints what the Team account wrote, escape codes included | Read in code, fix requested |
+| L2 | Low | The privacy check covers only the owner's home, misses some ACLs, and its result is self-reported | Read in code, noted |
+| L3 | Low | `harness team remove` trusts a computer id the Team account wrote | Read in code, fix requested |
+| L4 | Low | The owner's other loopback services are reachable | Seen on the Mac Studio, noted |
+
+## Findings
+
+### H1. The owner's local credential goes to whoever holds the daemon's port (High)
+
+Any account may bind a free loopback port above 1023, and it can simply retry until the bind works. So port 18473 can be taken:
+
+- **After every reboot, with no race.** The Team daemon starts at boot and the owner's only at login (a LaunchAgent), and the Team
+ account can edit its own `cli.js`, which that daemon runs.
+- **At every restart of the owner's daemon** (an update, a crash).
+
+- Engine hooks always post over TCP with `X-Harness-Hook-Token` (`cli/hook/notify.mjs:280`, `post`). They fire on every session
+ start and prompt, so a holder of the port hears one quickly.
+- That token is the daemon's local credential: `hookServer.ts` checks both against the same `hook-credential` value.
+- With it, the holder can use the real daemon's whole local API and its shell, as the owner. The port the daemon moved to is
+ easy to find: `/api/status` answers without a credential.
+- Holding the port makes it worse: the daemon falls back to another one (`hookServer.ts:1284`). A pane with a route record follows
+ it once the daemon publishes the new port (`lib/hookRoutes.ts`); until then, and for a pane with no record, hooks use the installed
+ port and report to the holder.
+- Other clients fall back the same way once the socket file is gone: `agentClient/daemon.ts:76`, `messages/rpc.ts:38`.
+ `devices/client.ts:24` and `superTabs/attach.ts:52` use TCP directly, and Desktop sends it over TCP when the socket is gone
+ (`desktop/lib/ws/local_daemon_transport.dart:165`).
+- Where the guest helper is installed, the owner's account runs it as root with no password, which widens what the holder gets. It is
+ not installed on the Mac Studio.
+- The connections bridge has the same shape: an agent's address carries its key in the path, on fixed port 51793
+ (`lib/connectors/bridge.ts`), so a holder of that port would hear the key to the owner's connected services.
+- Windows already refuses this: "this user's credential must never reach it" (`messages/rpc.ts:25`).
+
+**Proof:** `cli/src/team/boundary.spec.ts`, "H1, still open": the real `notify.mjs`, with a made-up credential, delivers it to a
+plain listener on the port. The listener ran as this user, in a fixture. Neither a real reboot nor a real restart was tried.
+
+**Fix:** on macOS and Linux, send the credential only over the 0600 Unix socket, or only after the listener proves itself, as
+Windows' pipe does (`lib/windows/pipeAuth.ts`). That covers the CLI's and Desktop's clients: a token for hooks alone would leave
+them open. Same for the bridge's key.
+
+### H2. A Team agent's branch runs with the owner's rights (High)
+
+A Team agent gets a GitHub token that may write (`backend/src/github/app.ts:14`), so it can push a branch. The project's workflow then
+has a Reviewer read it and a Tester build and run it, and those agents may run in the main account: the project's Reviewers are on
+the Mac Studio's main account today. Install scripts, tests, and a repository's `.claude/settings.json` or `.mcp.json` then run as the
+owner, with no race and no bug. Harness records the folder as trusted for its worktrees (`engines/claude/launch.ts:32`) and agents run
+without permission prompts, so nothing stops to ask. This was not tried. M3 is the same boundary crossed by words; this one is by code.
+
+**Fix:** build and run a branch that a Team agent wrote only in a Team account or a sandbox, never in the main account, and read it
+there with its project settings off. Until then, route those Reviewers and Testers to Team accounts.
+
+### M1. The owner's files in the shared `/tmp` are readable, and can be planted (Medium)
+
+Setup closes the home, and agents also write to `/private/tmp`, which every account shares. On the Mac Studio, the account
+`harnessteam` exists and could read, by mode:
+
+- 654 top-level entries owned by the main account, 281 of them scripts, logs or documents (reviews, helpers);
+- 31 world-writable entries within three levels: 28 in `hps-credential-*` folders, made-up fixtures of a test
+ (`store/agents/harness-monitor/test/credential.test.mjs`), and 3 of `.dotnet`.
+
+Any other local account can read them too (`ghrunner` here). A scan as the owner read the contents of 53,143 readable files, other agents' included,
+up to 2 MB and three levels down; it printed counts and each match's shape, never a value. Its key-shaped matches look made up: 5 are 27 characters long in Dart files under review folders, and
+one file holds one sample of nearly every key type. Another 144 files match `password=`-style text, and were not sorted out, so this
+shows no live secret and does not prove there is none. **If one is found, this is High.**
+
+There is also a run path, which needs no secret: a Team agent can create a file at a name an owner's agent will later write to or run,
+since the sticky bit stops only deletion, and an owner's world-writable script can be changed outright. No such script was found: none of the
+31 is one.
+
+**Fix:** give the owner's agents a private temporary folder (`TMPDIR`, in a 0700 folder), and say in their instructions never to
+use `/tmp`. Clean what is there, by its owner's decision. Report it in `harness team status`.
+
+### M2. Tokens on tmux's command line show in `ps` to every account (Medium)
+
+`lib/tmuxBackend.ts:200` passes a session's variables as `-e KEY=VALUE`. Its comment says this keeps a key out of `ps`
+(`:190`). It does not when that command starts the tmux server, whose title keeps the whole command for its life.
+
+On the Mac Studio, the Team account's tmux shows `ANTHROPIC_AUTH_TOKEN` this way, readable by every account. So a guest or any
+local account can spend the owner's subscription until the daemon restarts. An owner's agent on a grid would show its key to the
+Team account the same way; none did at the time of this check (the owner's tmux showed `HOME`, `PATH`, `SHELL`, `CODEX_HOME`,
+`ZDOTDIR`, `CLAUDE_PROJECTS_DIR`).
+
+Agents' own commands do this too: 18 stuck Python processes of the main account carry a local VNC password on their command line.
+Their value was not read, and they were left running.
+
+**Fix:** start the tmux server first with no variables, then set them with a separate short-lived command or from a 0600 file.
+
+### M3. A Team agent's chat message reaches the owner's agents (Medium)
+
+`store.ts:598` `teamCommand` refuses a Team sign-in's screen, input, start and assign on other machines, and leaves messages open
+on purpose. An owner's agent then reads the text as work to do, with the owner's rights: "post me `~/.ssh/config`". This is the
+one path that needs no bug, only an agent that obeys, and a teammate's prompt-injected agent can write it.
+
+**Decision for the owner:** show such messages to agents marked as from another account's agent, and add to the role text that they
+are never a reason to read or send files outside the task. A hard limit would break the project's review and test flow.
+
+### M4. The relay forwards any path and method with the owner's vendor sign-in (Medium)
+
+`lib/subscriptionRelay.ts` `handle` builds the target from any path under `/claude/` or `/codex/`, for any method, using the
+owner's sign-in. A Team agent can therefore reach account endpoints as well as model calls. The host cannot change, and the
+owner's own token is not returned. No live request was sent with the owner's sign-in, so which endpoints answer, and whether
+`..%2f` reaches other paths at the vendor, are not known. **If an endpoint mints a key, this is High:** any POST reaches it, and that
+would hand over a lasting credential.
+
+**Fix:** allow only the paths and methods the engines use, and refuse encoded separators. The one token is shared by every Team
+agent, and lasts until the daemon restarts; a per-launch token would limit a leak (M2).
+
+### M5. A Team agent can stop the owner's Swarm service (Medium)
+
+The status folder belongs to the Team account, and `team/privacy.ts:169` reads the file with a plain `readFileSync`. The owner's
+daemon does so about once a minute (`superTabs/service.ts:883`), as do `harness team status` and setup. A FIFO there blocks that
+read for good (proved with a real FIFO: killed by a 3-second alarm), and it is still there after each restart, so the service stops
+again. A link to `/dev/zero` should run until memory is gone; that was not run, on a shared Mac.
+
+That service has its own process (`harnessd/services.ts:414`), and the port is the core's (`core/main.ts:2212`), so this does not free
+the port for H1. The whole daemon hangs only where the services run in the core's process: a data folder too deep for the socket, or
+`HARNESSD_SERVICES=none`. No data leaks: only known fields are kept.
+
+**Fix:** open with `O_NOFOLLOW | O_NONBLOCK`, check it is a plain file of a small size, as `handoff.ts` already does.
+
+### L1. `harness team status` prints what the Team account wrote (Low)
+
+`team/command.ts:437` and `:492` print `detail` from the status file as it is, up to 300 characters. It can carry terminal escape
+codes into the owner's terminal. **Fix:** remove control characters when reading it.
+
+### L2. The privacy check's scope (Low)
+
+- It proves only the owner's home. Other people's homes on the Mac are left as they are, and the Team account is in `staff`, which
+ a Mac's default home lets in. (The other home on the Mac Studio is 700.) Projects on external drives are not covered.
+- `chmod 700` keeps existing ACLs, and `setfacl -m` keeps named entries. Setup does not remove one, and only this check would catch
+ it. The check catches an entry that lets the Team account in, as the sentinel or the listing opens.
+- The Public Folder is a way in by File Sharing, and the Team account is in its group: `~/Public` is `755` inside the closed home. No
+ SMB port listens on the Mac Studio.
+- Its result is reported by the Team daemon, in the account its agents run in, with a session file they can read. An agent could
+ report a pass. The kernel still refuses it, so this affects only the warning.
+- It runs at most every 5 minutes: an owner who reopens their home is exposed until then. Whether running agents are stopped on a
+ failure was not traced.
+
+### L3. `harness team remove` trusts a computer id the Team account wrote (Low)
+
+Removal reads the id from the Team account's files, then deletes the account's team machines with that id (`team/command.ts:544`, `:602`). A
+Team agent can write the id of the owner's Team account on another Mac, which removes that one instead. It cannot name a machine
+that is not a team machine. **Fix:** have the owner's daemon record the id at setup.
+
+### L4. The owner's other loopback services are reachable (Low)
+
+Any account can reach what listens on loopback. Five `mongod` of the main account listen on the Mac Studio, whose authentication was
+not checked; they looked like test databases. A browser's debug port would be worse: it would give the browser's sign-ins. **Fix:** say
+so in the agents' role text, and bind test services to a socket in a private folder where they can.
+
+## What holds
+
+| Area | What was found | Evidence |
+|---|---|---|
+| OS user | Separate, standard, in no admin group; random password nobody knows (Mac), locked (Linux) | `team/script.ts`, `script.spec.ts` |
+| Owner's home | Closed before the daemon starts, and no other script line changes it; `.harness`, worktrees, transcripts, memory, paste cache and caches are all inside it. Existing ACLs are kept (L2) | `boundary.spec.ts`; real check on the Mac Studio passed at the time of this audit; home is `drwx------`, its one ACL entry denies a delete |
+| Claude Code's temporary folder | `/private/tmp/claude-501` is `0700` | Seen on the Mac Studio |
+| Root in setup and removal | Never writes in a home the Team account controls; values checked and quoted; symbolic links refused | `team/script.ts`, `script.spec.ts` |
+| Daemon port | 401 with no credential; `/api/status` gives only version, process ids, computer id, socket details and whether it is supported; the socket path names the owner's account | Probed on the Mac Studio; `hookServer.spec.ts` |
+| Unix socket and credential file | `0600` in a `0700` folder | Seen on the Mac Studio |
+| tmux | Socket folder `0700`, per account | Seen on the Mac Studio |
+| Relay folder | Owner's, `0700`, one ACL entry for the Team account; a folder or file of another owner is refused | Seen on the Mac Studio; `relay.spec.ts` |
+| Harness's other local servers | Relay and API shares need a token; the bridge a key; viewer proxies a token. Others on the machine: L4 | Read in code |
+| Team sign-in on the server | Deny by default; no web relay, device lane, or other machine's agents | `teamSession.ts`; 117 unit tests run; integration `superTabTeam.test.ts` read, not run |
+| Git | No token in `GIT_CONFIG_PARAMETERS`, only a helper's path | Seen on the Mac Studio, long values masked |
+| Purge | Acts as the Team user, inside its own home, so it cannot reach the owner's files | `inCore/teamPurge.ts` |
+| Handoff code | Passed on standard input, kept in a file of the Team account, read with `O_NOFOLLOW`, deleted | `team/handoff.ts`, `team/script.ts` |
+
+## Not verified
+
+- **No real Team agent ran the attempts.** On macOS they run as this user against what the group and other bits allow, which at
+ setup's mode means mode 000: they show only that 000 refuses. What guards the home there is the test that no line of the script
+ leaves a group or other bit, or changes the home a second time. As a real second account (`nobody`) they run only on CI's Linux,
+ where the spec fails if that account is missing. ACLs are not modeled.
+- **Windows was skimmed only:** `windowsTeam.ts` and `windowsScript.ts` were not audited. Its setup and rules differ.
+- Linux's scripts were read and their modes tested; setup was not run on a Linux machine.
+- The integration suite was not run: this change touches no backend code.
diff --git a/docs/superpowers/plans/2026-11-02-swarm-cache-delta.md b/docs/superpowers/plans/2026-11-02-swarm-cache-delta.md
new file mode 100644
index 000000000..db0b8de99
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-02-swarm-cache-delta.md
@@ -0,0 +1,596 @@
+# Backend CPU, November round: Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Cut the backend's CPU and DB load per request with five changes, delivered together:
+- the Swarm read cache refreshes by delta;
+- hot and cold parts are held apart;
+- `freeze` walks each value once;
+- relay publishes are counted, gated and guarded more cheaply;
+- the hot nested loops become single passes.
+
+**Architecture:**
+- **Swarm cache.** A bump marks cache entries stale instead of dropping them. The next read loads one delta per Swarm
+ (`loadChanged` since the entry's read start − 30 s) and patches each entry by a per-entry rule, with a verify
+ sample and a minute log.
+- **Cold parts.** Finished starts and dormant groups move to their own entries.
+- **Relay gate.** The daemon's gateway stops broadcasting live events while the backend says no UI client is
+ attached.
+- **The rest** are local rewrites with unchanged answers.
+
+**Tech Stack:** TypeScript, Node 20, Fastify, Prisma on MongoDB, ioredis, vitest (backend and CLI).
+
+**Spec:** `docs/superpowers/specs/2026-11-02-swarm-cache-delta-design.md` (read it first; this plan does not repeat its reasoning).
+
+## Global Constraints
+
+- **No commits or pushes until Ken asks.** Each task ends with its tests green and the change left in the working
+ tree. Branch `perf/swarm-cache-delta` from `main`.
+- **Repository conventions:** docs and code comments in English; comments say why in plain sentences; no dead code.
+- **Backend test env:** `NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=`.
+ Integration tests run with `--config vitest.super-tabs.config.ts`; real-Redis tests with
+ `REDIS_TEST_URL=redis://127.0.0.1:6379/15`.
+- **Exact values from the spec:**
+ - `OVERLAP_MS` = 30 000 (reuse `read/cursor.ts`, do not copy it);
+ - `CACHE_MAX_AGE_MS` = 60 000, now meaning "patch after", not "reload after";
+ - `DELTA_MAX_AGE_MS` = 600 000 (full reload at least every 10 min);
+ - `DELTA_MAX_PARTS` = 500;
+ - `SWARM_CACHE_DELTA` `on|off`, default `on`;
+ - `SWARM_CACHE_VERIFY_RATE`, number 0–1, default `0.01`;
+ - `RELAY_UI_GATE` `on|off`, default `on`;
+ - the gate's quiet window for remote web frames is 60 000 ms.
+- **Responses never change.** Every read returns what it returns today. Commands keep loading in their own
+ transaction and never read the cache.
+- **Logs carry counts and ids only, never data.**
+- **Release order:** backend first, then the CLI.
+
+## Review Focus
+
+1. **A bump that never arrives** (owed, or a process killed after commit). The entry must still pick up the change
+ within 60 s, through the age-triggered delta. Test: Task 4, step 1, "age patch without a bump".
+2. **A Swarm deleted or purged while held** (head gone). The delta must not resurrect it: the read reloads and fails
+ `PARTS_MISSING` as today. Test: Task 4, "head gone → full load".
+3. **One delta moving a group between entries.** A group that wakes leaves `dormant`, `dormant:agent:*` and
+ `dormant:project:*`, and joins `parts`, all at the same stamp. Test: Task 9 equivalence, sweep then wake.
+4. **An agent removed while its dormant selection is held.** Its conversations are rewritten without it, so the
+ selection empties. Test: Task 8, step 1.
+5. **The gate and the first app.** An app attaching to a quiet machine must see live events from its first frame on.
+ A guest web client counts as UI too. Test: Task 12 and Task 10.
+
+---
+
+### Task 1: `freeze` walks each value once (Part 3)
+
+**Files:**
+- Modify: `backend/src/superTabs/cache.ts` (`freeze`, `SwarmCache.load`)
+- Test: `backend/src/superTabs/cache.test.ts`
+
+**Interfaces:**
+- Produces:
+ - `freeze(value: unknown): number`: same estimate as today. A frozen object returns its remembered size without
+ visiting children.
+ - `sizeOf(value: unknown): number`: the remembered size of a frozen object, or `freeze(value)` when not frozen.
+ Used by Task 4's patch accounting.
+
+- [ ] **Step 1: Write the failing tests** in `describe('freeze')`:
+ - `'freezes every nested object and tells the same size as before'`: a fixture `{ a: [{ b: 'x' }, new Date(0)],
+ c: 1 }`. Assert `Object.isFrozen` on each object, and that the size equals the value hard-coded from today's
+ implementation, computed once and pasted in.
+ - `'a second freeze visits no child'`: freeze a value, then wrap a child's property in a getter spy via a Proxy
+ defined *before* freezing. Assert the second `freeze(value)` returns the same size and the spy count stays 0.
+ Equivalently, spy on `Object.entries` with `vi.spyOn` and assert no call on the second freeze.
+ - `'sizeOf reads a frozen value without walking it'`.
+- [ ] **Step 2: Run, verify they fail.** `npx vitest run src/superTabs/cache.test.ts -t freeze`. Expected: FAIL on the
+ second-walk test.
+- [ ] **Step 3: Implement.** A module `WeakMap<object, number>`. `freeze` returns the cached size when
+ `Object.isFrozen(value)` and the map has it. Otherwise it recurses as today, stores the size, then freezes. Export
+ `sizeOf`.
+- [ ] **Step 4: Run the whole file.** `npx vitest run src/superTabs/cache.test.ts`. Expected: PASS.
+
+### Task 2: one delta read per Swarm (Phase 1)
+
+**Files:**
+- Modify: `backend/src/superTabs/parts/load.ts` (`loadChanged` runs kinds in parallel; new `loadDelta`;
+ `CHANGED_FIELDS` gains the head columns)
+- Test: `backend/integration/superTabCache.test.ts` (Mongo memory server; add a `describe('loadDelta')`)
+
+**Interfaces:**
+- Produces, in `parts/load.ts` (re-exported through `parts/index.ts`):
+ ```ts
+ export interface SwarmDelta { parts: Part[]; head: HeadColumns | null } // HeadColumns from parts/write.ts
+ export function loadDelta(tx: Prisma.TransactionClient, tabId: string, since: number, kinds: readonly PartKind[]): Promise<SwarmDelta>
+ ```
+ - `parts`: every part of `kinds` with `changedAt > since`. Machines also come by `readAt > since`, as
+ `loadChanged` reads them, with tombstones and dormant groups.
+ - `head`: the head row's `groupCounter`, `visibilityEpoch` and `sequenceBase` when `kinds` has `head` and the head
+ changed, else `null`.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `'loadDelta returns only what changed after since, tombstones and dormancy included'`: write a group, a start, a
+ machine reading and a removal after `since`. Assert the keys returned, `deleted` / `dormant` on the parts, and
+ that nothing older comes back.
+ - `'loadDelta carries the head columns when the head changed'`.
+ - `'loadDelta reads only the kinds asked'`: `['machine']` issues no query on other part collections. Use
+ `profiledReads` from the file.
+- [ ] **Step 2: Run, verify they fail.** `npx vitest run --config vitest.super-tabs.config.ts integration/superTabCache.test.ts -t loadDelta`
+- [ ] **Step 3: Implement.**
+ - `loadChanged`'s per-kind loop becomes `Promise.all` over kinds, keeping the result order by kind.
+ - `loadDelta(tx, tabId, since, kinds)` calls it for one Swarm and adds the head columns.
+ - Add `groupCounter`, `visibilityEpoch` and `sequenceBase` to `CHANGED_FIELDS`. The other collections lack them,
+ and `toPart` ignores them.
+- [ ] **Step 4: Run** the step 2 command plus `npx vitest run src/superTabs`. Expected: PASS, including the existing
+ `loadChanged` tests.
+
+### Task 3: patch rules and the digest (Phase 1)
+
+**Files:**
+- Create: `backend/src/superTabs/cachePatch.ts`
+- Test: `backend/src/superTabs/cachePatch.test.ts`
+
+**Interfaces:**
+- Consumes: `SwarmDelta` (Task 2), `startFinished` (`parts/write.ts`).
+- Produces:
+ ```ts
+ export interface PatchRule<T> { kinds: readonly PartKind[]; apply(held: T, delta: SwarmDelta): T | 'reload' }
+ export const baseRule: PatchRule<SwarmParts> // the 'parts' entry (loadReadBase)
+ export const machinesRule: PatchRule<Part<MachineData>[]>
+ export const dormantRule: PatchRule<Part<GroupData>[]> // all dormant groups
+ export function groupRule(key: string): PatchRule<Part<GroupData>[]> // 'group:{id}' entries (0 or 1 part)
+ export const lastChangedAtRule: PatchRule<number | null>
+ export function cacheDigest(value: unknown): string
+ ```
+- **Rules.** A part is applied only when its `version` is greater than the held one with the same key. Each rule:
+ - **`baseRule`:**
+ - replace or add by key in the kind's list;
+ - drop a `deleted` part;
+ - drop a group that is `dormant`;
+ - a non-dormant group joins;
+ - head data and the three head columns are replaced;
+ - a changed `visibilityEpoch` returns `'reload'`;
+ - machine parts are ignored, since the base holds none.
+ - **`machinesRule`:** by key; `deleted` drops.
+ - **`dormantRule`:** a part that is `dormant` and not `deleted` is added or replaced; otherwise the key is dropped.
+ - **`groupRule(key)`:** only that key; a `deleted` part empties the list.
+ - **`lastChangedAtRule`:** `max(held ?? 0, newest changedAt in delta.parts)`. Use `changedAt`, never `readAt`.
+- **Values stay frozen.** Return a new object or array when anything changed, and the same reference when nothing
+ did. Call `freeze` on new parts only (Task 1).
+- **`cacheDigest`:**
+ - canonical JSON with keys sorted;
+ - every array whose items are parts (have `kind`, `key`, `version`) sorted by `kind` then `key`;
+ - `version` dropped from parts;
+ - `sha256` hex.
+
+- [ ] **Step 1: Write the failing tests**, one `it` per rule behaviour above, each asserting the returned value's
+ content and that unchanged parts are the same references:
+ - `'an older or equal version is ignored'`;
+ - `'a tombstone removes'`;
+ - `'a group put to sleep leaves the base and joins dormant'` (two rules, one delta);
+ - `'a woken group leaves dormant and joins the base'`;
+ - `'a finished start stays in the base'` (Phase 2 changes this in Task 7);
+ - `'head columns are patched'`;
+ - `'a visibilityEpoch change asks for a reload'`;
+ - `'groupRule ignores other keys and empties on a tombstone'`;
+ - `'lastChangedAt takes the newest changedAt, not readAt'`;
+ - `'cacheDigest ignores part order and versions but not data'`.
+- [ ] **Step 2: Run, verify they fail.** `npx vitest run src/superTabs/cachePatch.test.ts`
+- [ ] **Step 3: Implement** `cachePatch.ts`. One shared helper
+ `applyByKey<T>(list: readonly Part<T>[], changed: Part[], keep: (p: Part) => boolean): Part<T>[]` carries the
+ version rule.
+- [ ] **Step 4: Run.** Expected: PASS.
+
+### Task 4: the cache patches stale entries (Phase 1)
+
+**Files:**
+- Modify: `backend/src/superTabs/cache.ts` (`SwarmCache`, `CacheView`, `configureSwarmStamps`)
+- Create: `backend/src/superTabs/cacheStats.ts` (minute log, `retryStats.ts` style)
+- Test: `backend/src/superTabs/cache.test.ts`, `backend/src/superTabs/cacheStats.test.ts`
+
+**Interfaces:**
+- Consumes: `PatchRule`, `SwarmDelta`, `sizeOf`, `OVERLAP_MS` (`read/cursor.ts`).
+- Produces:
+ - **`CacheOptions` gains:**
+ - `delta?: (tabId: string, since: number, kinds: readonly PartKind[]) => Promise<SwarmDelta>`; absent means
+ today's drop-and-reload;
+ - `deltaMaxAgeMs?` (600 000);
+ - `deltaMaxParts?` (500);
+ - `verifyRate?` (0, used by Task 5).
+ - **`CacheView`** records `at`, the time its stamps were read. `CacheView.get<T>(tabId, name, scope, load,
+ patch?: PatchRule<T>)`: a fifth parameter; every existing caller keeps working.
+ - **`Entry`** gains `readStart`, `fullAt`, `stale`, `patch?`, `load`.
+ - **`cacheStats.ts`:**
+ - `recordCache(name: string, event: 'hit' | 'full' | 'patch', detail?: { bytes?: number; parts?: number; reason?: ReloadReason })`;
+ - `type ReloadReason = 'cold' | 'age' | 'epoch' | 'parts' | 'error' | 'off' | 'since'`;
+ - `startCacheStats({ everyMs, log }): () => void`, which logs `'swarm cache'` with `{ windowMs, entries }` and
+ nothing for an empty window.
+ - `name` is the entry name up to its first `:` (`group:abc` → `group`).
+- **Behaviour.** `drop` (bus or stamp mismatch) marks entries that have `patch` as stale and deletes the others. A
+ `get` then goes one of four ways:
+ - **Hit:** a fresh entry at the view's stamps, younger than `CACHE_MAX_AGE_MS`.
+ - **Patch:** a stale entry or one past 60 s, with `delta` configured and `now − fullAt < deltaMaxAgeMs`:
+ - fetch the Swarm's delta through a single flight keyed
+ `tabId|stamp.main|stamp.machine|kinds.sort().join()`;
+ - `since` = min `readStart` of that Swarm's stale entries needing those kinds, minus `OVERLAP_MS`;
+ - an entry whose `readStart − OVERLAP_MS` is before the flight's `since` reloads with reason `since`;
+ - apply the rule. `'reload'`, or more than `deltaMaxParts` parts, means a full load with reason `epoch` or
+ `parts`. A delta error means a full load with reason `error`;
+ - on success, store the entry with the view's stamps, `readStart` = the view's `at` and `bytes` re-summed with
+ `sizeOf`.
+ - **Full load:** as today, with `fullAt` = `readStart` = the view's `at`.
+ - **Eviction:** over budget, evict stale entries first, then least recently used.
+- **Kinds per bump.** A machine-only bump marks only scope `all` entries stale, so their delta asks only for
+ `['machine']`.
+
+- [ ] **Step 1: Write the failing tests.** Use a fake `delta` that returns scripted parts and counts calls, and
+ `MemoryStamps`:
+ - `'a bump patches a held entry instead of loading it'`: `load` called once, `delta` once, value patched;
+ - `'readers of one Swarm at one stamp share one delta'`;
+ - `'a machine-only bump asks the delta for machines only'`;
+ - `'age patch without a bump'`: advance `now` 61 s, assert a delta call, no load;
+ - `'past DELTA_MAX_AGE_MS it loads in full'`;
+ - `'over DELTA_MAX_PARTS it loads in full'`;
+ - `'a delta error loads in full and counts error'`;
+ - `'reload from the rule loads in full'`;
+ - `'head gone → full load'`: the full load throws `PARTS_MISSING` to the reader;
+ - `'entries without a rule are dropped as before'`;
+ - `'without delta configured the cache behaves as today'`: rerun the existing tests unchanged;
+ - `'stale entries are evicted first'`.
+
+ In `cacheStats.test.ts`:
+ - `'counts by entry name and reason and logs nothing in an empty window'`.
+- [ ] **Step 2: Run, verify they fail.** `npx vitest run src/superTabs/cache.test.ts src/superTabs/cacheStats.test.ts`
+- [ ] **Step 3: Implement** in `cache.ts` and `cacheStats.ts`. The `stamps.subscribe` listener now calls the
+ stale-marking `drop`.
+- [ ] **Step 4: Run** the step 2 command and `npx vitest run src/superTabs/cacheRedis.test.ts` (with
+ `REDIS_TEST_URL`). Expected: PASS.
+
+### Task 5: verify sample (Phase 1)
+
+**Files:**
+- Modify: `backend/src/superTabs/cache.ts`
+- Modify: `backend/src/superTabs/cacheStats.ts` (events `verify` and `mismatch`)
+- Test: `backend/src/superTabs/cache.test.ts`
+
+**Interfaces:**
+- Consumes: `cacheDigest`, `CacheOptions.verifyRate`, `options.random?: () => number` (test seam, default
+ `Math.random`).
+- **Behaviour.** After a successful patch, if `random() < verifyRate` and no verify runs on this process:
+ - read the Swarm's stamps;
+ - run the entry's `load` in the background;
+ - read the stamps again. If they moved, the check is inconclusive and nothing is counted.
+ - Otherwise compare `cacheDigest`. A mismatch:
+ - drops the entry;
+ - logs `logger.warn('swarm cache verify mismatch', { entry, tabId, kinds, keys })`, where `keys` are the
+ differing part keys, up to 20, with no data;
+ - counts `mismatch`.
+ - Never on the request path: the reader already has its value.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `'a sampled patch is checked against a full load'`: `random = () => 0`, equal values, one `verify`, no
+ mismatch;
+ - `'a mismatch drops the entry and logs ids only'`: the load returns a part with different data; assert the warn
+ arguments contain the key and no data field;
+ - `'a stamp move during the check counts nothing'`;
+ - `'one check at a time per process'`.
+- [ ] **Step 2: Run, verify they fail.**
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** `npx vitest run src/superTabs/cache.test.ts`. Expected: PASS.
+
+### Task 6: wire the entries, switches and log (Phase 1)
+
+**Files:**
+- Modify: `backend/src/superTabs/cachedReads.ts`:
+ - `base` passes `baseRule`;
+ - `readMachines` passes `machinesRule`;
+ - the `dormant` get passes `dormantRule`;
+ - `group:${id}` passes `groupRule(id)`;
+ - `readLastChangedAt` / `readLastChangedAts` pass `lastChangedAtRule`;
+ - `light:*`, `light-group:*`, `feed` and `host:inputs` pass none.
+- Modify: `backend/src/config/env.ts`:
+ - `SWARM_CACHE_DELTA: z.enum(['on','off']).default('on')`;
+ - `SWARM_CACHE_VERIFY_RATE: z.coerce.number().min(0).max(1).default(0.01)`.
+- Modify: `backend/src/server.ts`:
+ - `configureSwarmStamps(..., { reads, maxBytes, delta: env.SWARM_CACHE_DELTA === 'on' ? (tabId, since, kinds) => loadDelta(prisma, tabId, since, kinds) : undefined, verifyRate: env.SWARM_CACHE_VERIFY_RATE })`;
+ - `const stopCacheStats = startCacheStats()` beside `startRetryStats`, stopped on shutdown beside it.
+- Test: `backend/src/superTabs/cachedReads.test.ts`
+
+- [ ] **Step 1: Write the failing test** `'each patchable read passes its rule'`. Spy on `CacheView.get` and assert the
+ fifth argument per entry name, and `undefined` for `light:`, `light-group:` and `feed`.
+- [ ] **Step 2: Run, verify it fails.** `npx vitest run src/superTabs/cachedReads.test.ts`
+- [ ] **Step 3: Implement** the wiring above.
+- [ ] **Step 4: Run** `npx tsc --noEmit` and `npx vitest run src/superTabs src/lib`. Expected: PASS.
+
+### Task 7: finished starts leave the base (Phase 2)
+
+**Files:**
+- Modify: `backend/src/superTabs/parts/load.ts`:
+ - `loadReadBase`'s start match becomes `{ deleted: false, finishedAt: null }`;
+ - new `loadFinishedStarts`.
+- Modify: `backend/src/superTabs/cachePatch.ts`:
+ - `baseRule` drops a start whose data is finished (`startFinished`);
+ - new `finishedStartsRule`.
+- Modify: `backend/src/superTabs/cachedReads.ts` (`readParts`, `namedStarts`)
+- Test: `backend/src/superTabs/cachePatch.test.ts`, `backend/src/superTabs/cachedReads.test.ts`
+
+**Interfaces:**
+- Produces:
+ ```ts
+ export function loadFinishedStarts(tx: Prisma.TransactionClient, tabId: string): Promise<Part<AgentStart>[]>
+ // aggregateRaw $match { tabId, deleted: false, finishedAt: { $ne: null } }: a plain match, not Prisma's `not`
+ export const finishedStartsRule: PatchRule<Part<AgentStart>[]> // kinds ['start']: finished and live → upsert, else drop
+ export function namedStarts(hot: Part<AgentStart>[], finished: Part<AgentStart>[] | null, named: ReadNamed): Part<AgentStart>[]
+ ```
+- **`readParts` reads the `finished-starts` entry only when** `named.includeRecentStarts`, any `named.startIds` key
+ is not among the hot starts, or `named.startAgentIds` is non-empty. A `WeakMap` keyed by the held array, built
+ once, gives the finished starts by agent (`stableId(machineId, harnessId)`).
+- **Order unchanged:** the hot starts first, then the finished ones the read named. `reassemble` sorts by `ordinal`.
+
+- [ ] **Step 1: Write the failing tests:**
+ - **In `cachePatch.test.ts`:**
+ - `'a start that finishes moves from the base to finished-starts'`;
+ - `'the 7-day expiry tombstone leaves finished-starts'`.
+ - **In `cachedReads.test.ts`:**
+ - `'a read naming nothing never loads finished starts'`: the `finished-starts` loader is not called;
+ - `'first loads, a named finished start and an agent's starts read them'`;
+ - `'the agent index is built once per held array'`.
+- [ ] **Step 2: Run, verify they fail.**
+- [ ] **Step 3: Implement.**
+ - Update `baseRule`, and its Task 3 test `'a finished start stays in the base'`, to "leaves the base".
+ - Update the existing `namedStarts` tests in `cachedReads.test.ts` (four calls) to the new signature. Split
+ `all` into its unfinished and finished lists, and keep each expected key set.
+- [ ] **Step 4: Run** `npx vitest run src/superTabs`. Expected: PASS.
+
+### Task 8: dormant groups by selection (Phase 2)
+
+**Files:**
+- Modify: `backend/src/superTabs/cachedReads.ts` (`readParts` dormant branch)
+- Modify: `backend/src/superTabs/cachePatch.ts` (new rules)
+- Test: `backend/src/superTabs/cachePatch.test.ts`, `backend/src/superTabs/cachedReads.test.ts`
+
+**Interfaces:**
+- Produces:
+ ```ts
+ export function dormantAgentRule(agentId: string): PatchRule<Part<GroupData>[]> // dormant, live, data.agentIds includes agentId
+ export function dormantProjectRule(projectId: string): PatchRule<Part<GroupData>[]> // dormant, live, (data.projectId ?? 'lead') === projectId
+ ```
+- **Entries:**
+
+ | Entry | Loads |
+ |---|---|
+ | `dormant:agent:{id}` | `store.loadGroups(db, tabId, 'agents', { agentIds: { $in: [id] }, dormant: true })` |
+ | `dormant:project:{id}` | `store.loadGroups(db, tabId, 'project', { projectId: { $in: id === 'lead' ? ['lead', null] : [id] }, dormant: true })` |
+
+ `allGroups` keeps the whole `dormant` entry with `dormantRule`. A read naming several agents or projects merges
+ their entries by key, each group once, in the order today's filter yields: dormant entry order filtered.
+ Equivalence is by set, since `reassemble` sorts.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `'a read naming one agent loads that agent's dormant groups only'`: the loader is called with that agent's
+ match, and `dormant` is never loaded;
+ - `'several agents and projects merge without duplicates'`;
+ - `'lead includes groups stored with no project'`;
+ - `'an agent removed while its selection is held'`: a delta rewriting its groups without it empties
+ `dormant:agent:{id}`;
+ - `'a woken group leaves every dormant selection'`.
+- [ ] **Step 2: Run, verify they fail.**
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** `npx vitest run src/superTabs`. Expected: PASS.
+
+### Task 9: equivalence with real commands (Phases 1–2)
+
+**Files:**
+- Create: `backend/integration/superTabCacheDelta.test.ts`, using `superTabCache.test.ts`'s `pod`, `privateScene`
+ and `MemoryStamps` setup (copy the setup block; do not import from another test file)
+- Modify: `backend/vitest.super-tabs.config.ts` (add the file to `include`)
+
+**Tests:**
+- **`'patched entries equal fresh loads after every command'`:**
+ - one pod configured with `delta: loadDelta`, and a second pod with no cache as the oracle;
+ - a seeded random sequence of 60 commands through `SuperTabStore` on `privateScene()`:
+ - `message.send`;
+ - a task assigned and finished;
+ - an `agent.start` that finishes;
+ - `sweepSwarms` putting a group to sleep, then a message waking it;
+ - `agent.remove`;
+ - a project rename;
+ - a machine reading (`observeMachine`);
+ - after each, for each held entry (`parts`, `machines`, `dormant`, `dormant:agent:*`, `dormant:project:*`,
+ `finished-starts`, `group:*`, `lastChangedAt`): `cacheDigest(patched) === cacheDigest(fresh load of the same
+ entry)`;
+ - also `readParts` for first-load, `startIds`, `startAgentIds`, `agentIds`, `projectIds` and `allGroups` equal to
+ `loadActive` in a transaction, compared by digest.
+- **`'a write committed after the load but stamped 20 s earlier is in the next patch'`:**
+ - write a part with `guardedWrite(tx, tabId, write, Date.now() - 20_000)` after the entry loaded;
+ - bump, read, and assert the patch has it.
+- **`'versions from reads are never a write guard'`:** grep-style. Read `superTabs/**/*.ts` and assert every
+ `guardedWrite(` call site's `seen:` comes from a variable loaded in the same function through `tx`. If this cannot
+ be checked mechanically, replace it with a note in the PR and a code-review item; do not ship a test that asserts
+ nothing.
+
+- [ ] **Step 1: Write the tests.**
+- [ ] **Step 2: Run** `npx vitest run --config vitest.super-tabs.config.ts integration/superTabCacheDelta.test.ts`.
+ Expected: PASS. A failure here is a bug in Tasks 3–8: fix it there.
+
+### Task 10: count publishes nobody receives, and offer the gate (Part 4, backend)
+
+**Files:**
+- Modify: `backend/src/lib/relayStats.ts` (`Counts` gains `none`; `recordRelay` counts `published` with
+ `receivers === 0`)
+- Modify: `backend/src/config/env.ts` (`RELAY_UI_GATE: z.enum(['on','off']).default('on')`)
+- Modify: `backend/src/lib/hub.ts` (`recomputeAndSendClients` payload adds `uiGate: true` unless
+ `env.RELAY_UI_GATE === 'off'`)
+- Test: `backend/src/lib/relayStats.test.ts`, `backend/src/lib/hub.test.ts`, `backend/src/lib/registry.test.ts`
+ (create if missing)
+
+- [ ] **Step 1: Write the failing tests:**
+ - `'a publish reaching no subscriber counts as none'`;
+ - `'__clients carries uiGate, and none with RELAY_UI_GATE=off'`;
+ - `'ui counts web and guest web clients, never commanders'` (`registry.clientCounts`).
+- [ ] **Step 2: Run, verify they fail.** `npx vitest run src/lib/relayStats.test.ts src/lib/hub.test.ts src/lib/registry.test.ts`
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run.** Expected: PASS.
+
+### Task 11: one guard, no extra promise, per Redis command (Part 4)
+
+**Files:**
+- Modify: `backend/src/lib/circuitBreaker.ts`:
+ - `withTimeout` builds no `AbortController` without `timeoutMs`; pass a module-level never-aborted signal;
+ - the interface gains `success(): void` and `failure(err: unknown): void`, the same accounting `run` applies.
+- Modify: `backend/src/lib/redisGuard.ts`:
+ - while `breaker.state() === 'closed'`: `send(command)`, then
+ `command.promise.then(() => breaker.success(), err => breaker.failure(err))`, and return `command.promise`;
+ - otherwise today's `breaker.run` path.
+- Test: `backend/src/lib/circuitBreaker.test.ts`, `backend/src/lib/redisGuard.test.ts`
+
+- [ ] **Step 1: Write the failing tests:**
+ - `'a closed circuit sends without run'`: spy `run`, assert 0 calls;
+ - `'five failures through the fast path open it'`;
+ - `'open refuses, and after 5 s one trial closes it on success'`;
+ - `'a reply error does not count as a failure'`.
+
+ Keep every existing test in both files unchanged and passing.
+- [ ] **Step 2: Run, verify they fail.** `npx vitest run src/lib/circuitBreaker.test.ts src/lib/redisGuard.test.ts`
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** the same command, plus `npx vitest run src/lib` with `REDIS_TEST_URL`. Expected: PASS.
+
+### Task 12: the daemon stops live events nobody views (Part 4, CLI)
+
+**Files:**
+- Modify: `cli/src/gateway/gateway.ts`
+- Test: `cli/src/gateway/gateway.spec.ts`
+
+**Interfaces:**
+- Produces:
+ - `export const UI_GATED_EVENTS: ReadonlySet<string>`, exactly: `text_delta`, `tool_start`, `tool_end`,
+ `user_message`, `thinking_delta`, `thinking_title`, `turn_heartbeat`, `agent_activity`, `turn_ended`,
+ `turn_summary`, `subagent_finished`, `done`, `context_compact`;
+ - `export const UI_QUIET_MS = 60_000`.
+- **State.** `private uiGate: { ui: number } | null = null`, set from `__clients` only when its payload has
+ `uiGate === true`, and reset to `null` in `linkGone()`. Also `private lastRemoteFrameAt = 0`.
+- **Recording remote frames.** In `dispatchDown`, after the observer hand-off, stamp `lastRemoteFrameAt = Date.now()`
+ for every frame whose `connId` is non-empty, not `observer:`, not a device connection (`isDeviceConn`), and
+ arriving over `relay` or `p2p`. This includes `e2e_*`, so place it before the `e2e_` branch.
+- **The check.** `private heldForNoUi(type: unknown): boolean` is true only if all hold:
+ - `uiGate !== null`;
+ - `uiGate.ui === 0`;
+ - `Date.now() - lastRemoteFrameAt >= UI_QUIET_MS`;
+ - `type` is in `UI_GATED_EVENTS`.
+- **In `broadcast`,** the untargeted enqueue is also skipped when `heldForNoUi(frame.type)`. Guest copies, and
+ `commander`, `user`, `observer` and `sendTo`, are untouched.
+
+- [ ] **Step 1: Write the failing tests**, in `describe('ui gate')`:
+ - `'a live event is not relayed while the backend says no UI and none spoke for 60 s'`;
+ - `'relayed with ui > 0'`;
+ - `'relayed again at once when a remote web frame arrives (its e2e hello)'`;
+ - `'relayed before any __clients, and after the link drops'`;
+ - `'relayed when __clients has no uiGate (older backend or switch off)'`;
+ - `'turn_started, agent_synced and agent_deleted are never held'`;
+ - `'guest copies, device, user and targeted frames are never held'`.
+- [ ] **Step 2: Run, verify they fail.** `cd cli && npx vitest run src/gateway/gateway.spec.ts -t "ui gate"`
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** `npx vitest run src/gateway` and `npm run typecheck`. Expected: PASS.
+
+### Task 13: confidential marks, Leads and waiting workers in one pass (Part 5)
+
+**Files:**
+- Modify: `backend/src/superTabs/projects.ts`:
+ - `ledProject` in O(projects + conversations);
+ - new `confidentialSets`;
+ - `markConfidential`, `requireSingleRegistration` and `confidentialSession` use it.
+- Modify: `backend/src/superTabs/model.ts`:
+ - `awaitingWorkers` takes an optional index;
+ - `visibleState` builds it once for all projects.
+- Modify: `backend/src/superTabs/migration/normalize.ts`: pass one index for its loop too.
+- Test: `backend/src/superTabs/projects.test.ts`, `backend/src/superTabs/model.test.ts`
+
+**Interfaces:**
+- Produces:
+ ```ts
+ // projects.ts
+ export function confidentialSets(state: SuperTabState): { leaders: ReadonlySet<string>; privateMembers: ReadonlySet<string> }
+ // model.ts
+ export interface WorkerIndex { leaders: ReadonlySet<string>; working: ReadonlySet<string>; groupsByAgent: ReadonlyMap<string, Conversation[]> }
+ export function workerIndex(state: SuperTabState): WorkerIndex
+ export function awaitingWorkers(state: SuperTabState, projectId: string, index?: WorkerIndex): Agent[]
+ ```
+- **What each lookup holds:**
+ - `leaders`: agents that are `leadId` of a conversation whose id is a project's `leadConversationId`.
+ - `privateMembers`: every agent id in a conversation with `audience`.
+ - `groupsByAgent`: groups in conversation order, `assignment.agentId` set and not `lost`.
+ - `ledProject` collects the matching Lead conversation ids in one scan. It then returns
+ `projectsOf(state).find(p => matched.has(p.leadConversationId))`, the same project order as today.
+- **Lookups are built per call** (or per caller loop), never stored on the state.
+
+- [ ] **Step 1: Write the failing tests:**
+ - **`'new and old answers agree on generated Swarms'`:**
+ - keep the current implementations as `legacyLedProject`, `legacyMarkConfidential` and
+ `legacyAwaitingWorkers` *inside the test file*, copied from today's source;
+ - generate 200 seeded Swarms of up to 2,000 conversations, 50 agents and 20 projects, including:
+ - no projects;
+ - private projects;
+ - Leads without a conversation;
+ - an agent leading two projects;
+ - lost assignments;
+ - audience conversations;
+ - an agent already marked;
+ - assert equal results for `ledProject` (every agent), `markConfidential` (the set of marked agents),
+ `requireSingleRegistration` (throws or not, same code) and `awaitingWorkers` (every project).
+ - **`'markConfidential scans the conversations a constant number of times'`:** wrap `state.conversations` in a
+ Proxy counting iterator calls; assert ≤ 3 for a 50-agent Swarm.
+- [ ] **Step 2: Run, verify the scan test fails.** `npx vitest run src/superTabs/projects.test.ts src/superTabs/model.test.ts`
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** `npx vitest run src/superTabs`. Expected: PASS.
+
+### Task 14: cost shipping and the messages page's join (Part 5)
+
+**Files:**
+- Modify: `backend/src/superTabs/costs/read.ts` (`shipping` groups rows by `conversationId` once)
+- Create: `backend/src/superTabs/read/pageDeliveries.ts`
+- Modify: `backend/src/superTabs/store.ts` (the messages return uses the new function)
+- Test: `backend/src/superTabs/costs/read.test.ts`, `backend/src/superTabs/read/pageDeliveries.test.ts`
+
+**Interfaces:**
+- Produces:
+ ```ts
+ export function deliveriesByMessage<D extends { messageId: string }>(deliveries: readonly D[]): ReadonlyMap<string, D[]> // each list in input order
+ ```
+ `store.ts` becomes
+ `(byMessage.get(m.id) ?? []).filter(d => shownTo(m, d)).sort(receiptOrder(m))`.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `'deliveriesByMessage keeps input order per message'`;
+ - `'shipping answers as before'`: legacy copy in the test, seeded rows and groups, including several attempts and
+ no attempt before `shippedAt`.
+
+ The messages route's existing tests (`superTabs.test.ts` integration: agent, person and Buddy readers) must stay
+ green unchanged.
+- [ ] **Step 2: Run, verify they fail.** `npx vitest run src/superTabs/costs/read.test.ts src/superTabs/read/pageDeliveries.test.ts`
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** the step 2 command and `npx vitest run --config vitest.super-tabs.config.ts integration/superTabs.test.ts`.
+ Expected: PASS.
+
+### Task 15: validation and measurement
+
+- [ ] **Step 1: Typecheck.** `cd backend && npm run typecheck`; `cd cli && npm run typecheck`. Expected: clean.
+- [ ] **Step 2: Backend unit suite with real Redis.**
+ `cd backend && REDIS_TEST_URL=redis://127.0.0.1:6379/15 npx vitest run`. Expected: 0 failed.
+- [ ] **Step 3: Backend integration suite.** `npx vitest run --config vitest.super-tabs.config.ts`. Expected: 0 failed
+ except the documented flaky `superTabCache` "named light conversations"; rerun it alone once.
+- [ ] **Step 4: CLI.** `cd cli && npx vitest run src/gateway`, then `npm test`. Compare any red against `main`'s known
+ failures (memory: test-suite baseline).
+- [ ] **Step 5: Benchmark on prod's busiest Swarm copy** (`harness_profile` Mongo, local Redis):
+ - `npm run bench:swarm-state -- --cache redis://127.0.0.1:6379/15`, before (on `main`) and after;
+ - record bytes read and ms per bump for one `message.send` and one task finish, and the `swarm cache` log.
+- [ ] **Step 6: Local CPU profile** of the same load (`SELF_PROFILE` as in the 2026-10-30 runs). Record `calls` and
+ self-time for:
+ - `freeze`;
+ - `ledProject`'s callback;
+ - `privateMember`;
+ - `awaitingWorkers`, `activeWork`;
+ - the messages join;
+ - `redisGuard`.
+
+ Compare against the spec's table.
+- [ ] **Step 7: Independent review.** Dispatch one fresh reviewer (Opus) with the spec, this plan and the full diff
+ versus `origin/main`. Fix what it finds, then rerun Steps 1–4.
+- [ ] **Step 8: Report to Ken:** results, numbers, review outcome, and anything that deviated from the spec. Wait for
+ his word before committing.
diff --git a/docs/superpowers/specs/2026-11-02-swarm-cache-delta-design.md b/docs/superpowers/specs/2026-11-02-swarm-cache-delta-design.md
new file mode 100644
index 000000000..a111a425d
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-02-swarm-cache-delta-design.md
@@ -0,0 +1,585 @@
+# Backend CPU, November round: a Swarm cache that refreshes by change, cheaper freezes, relay publishes and hot loops
+
+**Status:** draft for review · **Owner:** Ken · **Area:** backend (`superTabs/cache.ts`, `cachedReads.ts`, `parts/load.ts`, `lib/adapterWs.ts`, `lib/redisGuard.ts`,
+`superTabs/projects.ts`, `model.ts`, `costs/read.ts`), CLI gateway (`cli/src/gateway/gateway.ts`)
+**Builds on:** [docs/design/2026-10-28-swarm-read-cache.md](../../design/2026-10-28-swarm-read-cache.md) (the stamp cache)
+
+## Why
+
+Prod on `v1.3.78_backend` (2026-11-02, 02:27–02:50Z, 4 pods, ~3,480 requests/min):
+
+| | Friday 10-30 (before the CPU series) | Monday 11-02 (after) |
+|---|---|---|
+| CPU per request | 25 ms | 33 ms |
+| DB bytes per request | 51 KB | 148 KB |
+| `messages` reads that reload the whole Swarm | 1.6% | 11% |
+
+- **Whole-Swarm loads are 63% of the bytes read from Mongo and 30% of DB time, in 5% of the queries:**
+
+ | Query | Share of bytes |
+ |---|---|
+ | `SwarmStart {deleted, tabId}` | 27% |
+ | `SwarmGroup {deleted, dormant, tabId}` | 25% |
+ | progress, machines and agents | 11% |
+
+ Prisma parsing those rows is 19% of the JS thread in the CPU profile. Its engine also runs off the JS thread: about
+ 37% of each pod's CPU is outside the JS thread.
+- **The cause is how the cache refreshes.** Any commit to a Swarm bumps its `main` stamp. Every process then drops
+ *all* it holds of that Swarm, and its next read reloads the base:
+ - every live start;
+ - every non-dormant group;
+ - agents, members and progress;
+ - often all dormant groups as well.
+
+ Cost per bump is therefore Swarm size × processes. Held entries also expire after 60 s and reload in full.
+- **The Swarm keeps growing.** Prod's busiest Swarm `c51479bd`:
+
+ | | 10-30 | 11-02 | Unchanged part |
+ |---|---|---|---|
+ | Starts | 859 | 1,114 (+30%) | 1,111 finished |
+ | Groups | 1,248 | 1,715 (+37%) | 1,544 dormant, 8.9 of 9.6 MB |
+
+ One reload is ~1.4 MB, nearly all of it parts that did not change.
+- **Why earlier PRs did not fix it.** They made each *read* cheaper:
+ - #2364 shared light base;
+ - #2365 copy less;
+ - #2383 one index key per collection for `lastChangedAt`;
+ - #2378 machine readings move only the machine stamp;
+ - #2374 / #2391 messages read less.
+
+ None changed what a *refresh* costs. Data growth and more writes ate the savings, and new routes such as
+ `GET /deliveries/:id` (112/min) read the same base.
+
+AGENTS.md's design rule says "read cost: read only what changed". The cache breaks that rule on every bump.
+
+Five parts, one delivery (Ken, 2026-11-02: "one spec for all of it"). Each is measured in the 2026-11-02 profile
+(12 CPU profiles of 30 s, 4 pods, 02:27–02:50Z):
+
+| Part | What | Share now |
+|---|---|---|
+| **Phase 1, delta refresh** | a refresh reads only what changed | whole-Swarm loads: 63% of DB bytes; Prisma 19% of the JS thread |
+| **Phase 2, hot and cold** | finished starts and dormant groups held and read apart from the hot base | the rest of what full loads and reads carry |
+| **Part 3, `freeze`** | a held value is frozen and sized once, never walked again | `freeze` 4.4% of the JS thread, 12.4 M calls in the 12 profiles |
+| **Part 4, relay publishes** | count publishes nobody receives; a daemon stops sending live events nobody is viewing; a cheaper guard around each Redis command | `adapter-ws text` 7% of the JS thread, about a third of it the Redis publish and its guard |
+| **Part 5, hot loops** | lookups that scan every conversation for every project or agent become one pass | about 1–2% now, growing with the square of a Swarm's size |
+
+Not in this spec: the measurement's own cost (`async_hooks`, `selfProfile`, `queryStats`, about 17% of the JS thread
+inside profile windows). #2394 (measure 1 minute in 10) stays held until a week of full logs from this release, as
+Ken decided on 2026-10-31.
+
+## Goal (Phase 1)
+
+A held entry whose Swarm changed is brought up to date by reading **only the parts that changed** since it was loaded.
+It is then patched in memory. Cost per bump becomes the size of the change (usually a few KB), not the size of the
+Swarm.
+
+- **Measured success:** whole-Swarm load bytes fall by more than 70% (`db by shape`), and DB bytes per request fall
+ back toward the Friday level. The new `swarm cache` log shows patches far outnumbering full loads.
+- **Same answers:** every response is byte-for-byte what a fresh load would give. A sampled background check proves
+ this on prod.
+
+### Non-goals
+
+- Moving finished starts or dormant groups to other collections, or expiring them sooner. Phase 2 changes only what
+ the cache holds together.
+- Delta for the derived selections: `light:*`, `light-group:*`, `host:inputs`, `feed`. They keep today's drop-and-reload.
+ The new log will show whether any of them matters.
+- Any change to commands (they load in their own transaction, never from the cache), to stamps or bumps, to client
+ APIs or response shapes.
+
+### Anti-goals
+
+- A reader ever sees a part older than it would from a fresh load at the same stamp, or a removed or dormant part where
+ a fresh load has none. A wrong answer is worse than a slow one.
+- A patch silently drifting from the database with no way to notice it.
+
+## Design (Phase 1)
+
+### What changes
+
+1. **A bump marks entries stale instead of dropping them.**
+ - Today `SwarmCache.drop` (from the bus broadcast and from `held` on a stamp mismatch) deletes the entry.
+ - Now it is kept and marked stale, still counting against the LRU byte budget.
+ - Entries whose name has no patch rule are dropped as today.
+2. **A read that meets a stale entry asks for the Swarm's delta, then patches.**
+ - **One delta per Swarm per stamp.** It is shared by every entry and every concurrent reader of that Swarm on the
+ process (single flight keyed by `tabId` + the stamps the read took). Today's miss path already does this for full
+ loads.
+ - **The delta query** is `parts/load.ts loadChanged(db, [tabId], since)` with its seven kinds run in parallel.
+ Today the loop is sequential. Machines are matched by `changedAt` or `readAt`, as the change feed is.
+ - **`since`** = the oldest `readStart` among the Swarm's stale entries − `OVERLAP_MS` (30 s, `read/cursor.ts`: the
+ longest transaction plus clock drift between processes). This is the same rule client change cursors rely on.
+ - **`readStart`** is the time the read took its stamps, before any query. A full load sets it, and so does a patch.
+ - **Head columns.** The head's projection adds `groupCounter`, `visibilityEpoch` and `sequenceBase`, so the base's
+ own columns are patched too.
+3. **Each patchable entry has a patch rule.** It applies a part only if its `version` is higher than the held one, so
+ applying the same change twice, or an older one, does nothing. A changed part:
+
+ | Entry (name in `cachedReads.ts`) | Holds | A changed part is |
+ |---|---|---|
+ | `parts` (`loadReadBase`) | head, members, agents, non-dormant groups, every live start, progress | replaced by key in its kind's list; removed if `deleted`; for a group, removed if `dormant`, added if it woke; head columns replaced |
+ | `machines` | live machine parts | replaced by key (a reading moves `readAt` and the version); removed if `deleted` |
+ | `dormant` | every dormant group | added or replaced if `dormant`; removed if it woke or was `deleted` |
+ | `group:{id}` | that one group, or none | replaced if it is that key and not `deleted`; emptied if `deleted` |
+ | `lastChangedAt` | the newest `changedAt` | `max(held, newest changedAt in the delta)` |
+
+ - **List order is unaffected.** A list's order is the parts' `ordinal`, applied by `reassemble`.
+ - **Copy-on-write.** A patched value is a new frozen object. Unchanged parts are shared, since they are already
+ frozen. Part 3 makes a patch freeze and size only the new parts.
+4. **Full reload still happens** when:
+ - nothing is held (a cold read, an LRU eviction);
+ - the entry is older than `DELTA_MAX_AGE_MS` (10 min since its last full load), the safety net for anything a delta
+ cannot see;
+ - the delta changed the head's `visibilityEpoch`;
+ - the head is gone (a deleted Swarm, `PARTS_MISSING`, as today);
+ - the delta holds more than `DELTA_MAX_PARTS` (500) parts, so a reload costs about the same;
+ - the delta read failed.
+
+ **Age expiry changes too.** `CACHE_MAX_AGE_MS` (60 s) now triggers a *delta*, not a reload. The 60-second net for a
+ lost bump is kept and becomes cheap: a delta finds every commit since the load whether or not its bump arrived.
+
+### Why a patched entry is right
+
+- A full load at stamp S reads in one snapshot taken after the stamps were read. A patch at S therefore has to match
+ what such a load would read.
+- **Every commit the held entry misses is in the delta.**
+ - Any commit missing from the snapshot behind `readStart` R committed after that snapshot.
+ - It stamped each part's `changedAt` (or `readAt`) at write time from its process's clock, which is strictly
+ increasing.
+ - That time is at least R − (longest transaction 15 s + drift 15 s) = R − `OVERLAP_MS`.
+ - So `changedAt > since` finds it. The client change cursor makes the same argument (`read/cursor.ts`).
+- **A commit the delta itself misses** (committed after the delta's snapshot) bumps the stamp after it commits.
+ The next read sees a newer stamp and patches again. Holding the patched entry at S is exactly as safe as holding a
+ full load at S today.
+- **What a delta does not carry: touches.** A touch moves a part's version without changing its data or `changedAt`,
+ and bumps no stamp. A full load at the same stamp would therefore show the newer version with the *same data*, while
+ a patched entry may hold the older version number.
+ - Today's cache has this gap already: touches never bump.
+ - Versions in a read are only used to keep the higher one (clients) and are never a guard. Commands read their own
+ versions in their transactions.
+ - The equivalence check below compares data and ignores versions. A test pins that no command guards a write with a
+ version from a read.
+- **Purges.** A tombstone's data emptied at `purgeAt` (`sweeps.ts`), or removed by the Mongo TTL, is already out of
+ every entry, since entries hold no deleted parts. A deleted Swarm loses its head, which forces a full reload, which
+ fails as today.
+
+### Checking it on prod
+
+- **Verify sample.** `SWARM_CACHE_VERIFY_RATE`, default `0.01`: one patch in 100 also runs a full load in the
+ background, off the request path and capped at one at a time per process. It compares a canonical digest:
+ - parts sorted by kind and key;
+ - data only, versions left out.
+
+ A mismatch:
+ - drops the entry;
+ - logs `swarm cache verify mismatch` with the entry name, the kinds and the keys that differ (ids only, never data);
+ - counts in the minute log.
+- **`swarm cache` log, every minute per process**, in the style of `swarm retries` and `terminal relay`. Per entry
+ name it counts:
+ - hits;
+ - full loads (count and bytes);
+ - patches (count, parts applied and bytes read);
+ - reloads by reason (cold, age, epoch, too many parts, error);
+ - verify samples and mismatches.
+
+ Counts only, no ids. Nothing is logged in an empty window.
+- **Kill switch.** `SWARM_CACHE_DELTA=on|off`, default `on`. `off` restores today's drop-and-reload exactly. The verify
+ rate is its own variable (`0` turns it off).
+
+### Expected effect (estimate, to be replaced by the log)
+
+| Measure | Now | Expected |
+|---|---|---|
+| Whole-Swarm load bytes (63% of all DB bytes) | as above | most become deltas of a few KB |
+| What remains of them | | cold loads, LRU evictions, 10-minute full reloads, the four non-patched entries |
+| DB bytes per request | 148 KB | about half |
+| Prisma parse on the JS thread | 19% | under 10% |
+| CPU per request | | 10–15% lower |
+| `freeze` (4.4% of the JS thread) | | mostly gone |
+
+The HPA should then hold fewer pods at the same traffic. Memory is also a target (70% of 1 GB), and memory falls less
+than CPU.
+
+## Phase 2: hot and cold parts
+
+### Why
+
+Phase 1 makes a refresh cheap, but three costs still grow with the Swarm's history. Prod's busiest Swarm, 2026-11-02:
+
+| Part | Count | Size | Read by |
+|---|---|---|---|
+| Unfinished starts | 2 | ~0 MB | every read |
+| Finished starts (expire 7 days after finishing) | 1,118 | 1.37 MB | first loads (`includeRecentStarts`), and reads naming a start or an agent's starts |
+| Awake groups | 175 | 0.81 MB | every read |
+| Dormant groups | 1,544 | 8.86 MB | reads naming agents or projects, or all groups |
+| Agents, members, progress, machines | 77 | 0.22 MB | every read |
+
+1. **The base holds what most reads drop.** `parts` (`loadReadBase`) holds every live start, so finished starts are
+ 59% of its 2.3 MB.
+ - `readParts` then filters them out (`namedStarts`) for every read that names none, which covers messages,
+ changes, deliveries and threads.
+ - Each full load (cold, eviction, the 10-minute net) still reads, parses, freezes and holds them.
+2. **Dormant groups are held whole and filtered per read.**
+ - A read naming one agent or one project loads the `dormant` entry, all 1,544 groups (8.9 MB), on each process.
+ It then keeps the few it needs.
+ - `confidentialSessions` (`store.ts cachedState`) and every command-shaped read with `agentIds` do this.
+ - The 13 agents in dormant groups average 126 dormant groups each. The Lead, in nearly all of them, is the outlier.
+3. **Memory.**
+ - Each process holds the base and the whole dormant set of every busy Swarm it served, within the 64 MB LRU
+ budget.
+ - Memory is one of the two HPA targets (70% of 1 GB). Large cold entries also push out other Swarms' entries,
+ and those then reload.
+
+### Design
+
+1. **Finished starts leave the base.**
+ - `loadReadBase` loads `start: { deleted: false, finishedAt: null }`, the same match `loadActive` uses for
+ commands.
+ - A new entry `finished-starts` holds the live finished starts. It loads only when a read needs it:
+ - `includeRecentStarts` (first loads);
+ - `startIds` not found among the unfinished;
+ - `startAgentIds`.
+ - `namedStarts` takes the hot list plus, only in those cases, the cold one. A read naming a start or an agent's
+ starts takes them from `finished-starts` by key and by agent (`stableId`, worked out once per entry load and
+ kept beside it, not per read). It does not filter the whole list.
+ - **Patch rule:** a start part whose data is finished (`startFinished`) moves from `parts` to `finished-starts`. A
+ tombstone, or the 7-day expiry write, removes it.
+2. **Dormant groups are read by the index the read names.**
+ - `readParts` keeps one entry per selection instead of the whole `dormant` set:
+
+ | Entry | Read through |
+ |---|---|
+ | `dormant:agent:{id}` | the `agents` index, `dormant: true` |
+ | `dormant:project:{id}` | the `project` index; for `lead`, also groups with no project |
+
+ - A read naming several agents or projects joins their entries; each is loaded once and shared.
+ - **Patch rule:** a group part is in such an entry when it is dormant, not deleted, and lists that agent (or is in
+ that project). A group that wakes, leaves, or is deleted is removed.
+ - `allGroups` (mentions, route decisions) keeps the whole `dormant` entry, now patched by Phase 1.
+3. **Nothing else changes.** Commands keep `loadActive` in their transaction. Responses are unchanged:
+ - a read gets exactly the starts and groups `loadActive`'s rules give it;
+ - only where the cache holds them changes.
+
+### What it should change (estimate, to be checked with the `swarm cache` log)
+
+| Measure | Now | Expected |
+|---|---|---|
+| Base full load, busiest Swarm | ~2.3 MB | ~1 MB |
+| Per-read start filter | over 1,120 starts | over 2 starts |
+| Reads naming an agent's dormant groups (a worker) | 8.9 MB of dormant groups loaded | the agent's own ~0.7 MB, on average |
+| Memory held per busy Swarm per process | base + all dormant groups | base + the selections actually read |
+
+The Lead's own selection stays close to the whole set.
+
+### Tests (Phase 2)
+
+- **Equivalence.** The Phase 1 command-sequence test also compares `readParts` for:
+ - first loads (`includeRecentStarts`);
+ - `startIds` of finished starts;
+ - `startAgentIds`;
+ - single and several `agentIds` and `projectIds`, including `lead`;
+ - `allGroups`.
+
+ Each must equal `loadActive`'s answer in a transaction at the same moment.
+- **Moves between entries.** A start that finishes moves from hot to cold. A group put to sleep appears in its agents'
+ and project's dormant entries. Woken, it leaves them and returns to the base.
+- **Bounds.** A read naming one worker loads only that worker's dormant groups (query shape and bytes asserted on the
+ integration Mongo).
+
+## Part 3: `freeze` walks each value once
+
+### Why
+
+`cache.ts freeze` deep-freezes a loaded value and sizes it as JSON in the same pass. It recurses into every object of
+every load: 12.4 M calls in the 12 profiles (6 minutes of sampling across 4 pods), 4.4% of the JS thread. It shows inside the messages
+and changes routes, `(anonymous) cache.js:89`, the load's `then`.
+
+- Every full load walks the whole Swarm again, though most of its parts are byte-for-byte what the process froze a
+ minute earlier.
+- Phase 1 cuts the number of full loads. Part 3 makes each freeze walk only what is new, so it holds with the delta
+ switch off too.
+
+### Design
+
+1. **Frozen means done.** `freeze(value)` returns at once for an object that is already frozen, using its size
+ remembered in a module `WeakMap<object, number>` set when it was frozen. Nothing holds a part alive but its entry,
+ so the map frees with the entry.
+2. **Size by part, not by walk.**
+ - An entry's `bytes` is the sum of its parts' sizes, each sized once when frozen.
+ - A patch (Phase 1) subtracts the replaced parts' sizes and adds the new ones'. It never re-walks the list.
+3. **Same accounting.** The size is still the JSON estimate `freeze` gives today, so `SWARM_CACHE_MB` means what it
+ meant.
+4. **A value never frozen twice.** Values reach the cache only through `SwarmCache.load` and the patch. A test asserts
+ that a held value's every nested object is frozen, and that a second `freeze` of it visits no child.
+
+### Expected effect
+
+`freeze` drops from 4.4% to a share proportional to new parts (estimate: under 1%), and its call count in the
+profile's `calls` from about 12.4 M to about the number of parts loaded or patched.
+
+## Part 4: relay publishes
+
+### Why
+
+`adapter-ws text` is 7% of the JS thread: JSON frames a machine's daemon sends up `/api/adapter-ws`.
+
+| Inside it | Share |
+|---|---|
+| Parsing and routing the frame (`onMessage`) | ~25% |
+| The Redis publish, its `redisGuard` wrapper and the circuit breaker's `run` | ~30% |
+| Local delivery (`deliverUpLocal`, `terminalRoute`), moved here from the Redis loopback by #2413 | ~10% |
+
+- **Untargeted frames:** 3,713 published a minute, reaching 4,517 subscriptions in total (`terminal relay`,
+ 2026-11-02). These are a machine's live events to every app viewing it.
+- **#2416 (CLI 0.5.19, on 291 of 326 daemon connects) already cut the rest:**
+ - one heartbeat a beat;
+ - slim transcript events;
+ - terminal-app-only events held while no terminal app is open.
+
+ Its remaining holds (`agent_synced` duplicates, `swarm_changed` spacing) stay on hold for the reasons in
+ `docs/plans/2026-10-31-live-events-relay-design.md`.
+- **Two costs are left, and their size is unknown:**
+ - **Live events for a machine nobody is viewing.** The backend tells each daemon how many UI clients its machine
+ has across processes (`__clients` `ui`, `hub.ts recomputeAndSendClients`). The daemon reads only the device
+ count from it and broadcasts every live event regardless. The log keeps only totals, so how many publishes reach
+ no one is unknown; Desktop dials every machine of its account, so it may be few.
+ - **A promise chain and an AbortController per Redis command.** `redisGuard.ts` sends every command through
+ `breaker.run`, an `async` function that also builds an `AbortController` even when no timeout is set.
+
+### Design
+
+1. **Count publishes nobody receives.**
+ - `relayStats.recordRelay` adds `none` (publishes that reached 0 subscriptions) beside `published` and
+ `receivers`, per kind.
+ - This is what decides whether item 2 matters. It ships with it, and item 2's effect is read from it.
+2. **A daemon stops sending live events nobody can see.**
+ - **Backend.** `recomputeAndSendClients` adds `uiGate: true` to `__clients` unless `RELAY_UI_GATE=off`. That is
+ the kill switch, default `on`. Older backends never send it.
+ - **Daemon** (`gateway.ts`). In `broadcast`, after `productUsage.observe` and before sealing, the untargeted copy
+ of a **live event** is not sent while all of these hold:
+ - the last `__clients` said `uiGate: true` and `ui: 0`;
+ - no frame has come from a remote web connection in the last 60 s.
+
+ The gate is open again as soon as `__clients` says `ui > 0`, or any frame arrives from a remote web connection.
+ That first frame is its E2EE hello, sent before it can read anything, so it misses nothing it could have
+ decrypted. A link that drops forgets the count, and every event is sent until the next `__clients`. This is the
+ rule `tuiUntil` already follows.
+ - **What counts as a live event:** `text_delta`, `tool_start`, `tool_end`, `user_message`, `thinking_delta`,
+ `thinking_title`, `turn_heartbeat`, `agent_activity`, `turn_ended`, `turn_summary`, `subagent_finished`, `done`,
+ `context_compact`.
+ - **Never gated:**
+ - frames the backend itself reads: `agent_synced` (machine agents), `agent_deleted`, and `turn_started` (daily
+ turn counts, the short-turn guard);
+ - every reply and targeted frame;
+ - guests' sealed copies;
+ - device (commander) and user frames.
+ - **An app that connects lists the session itself** (`agents_list`, `session_get`), as for #2416's change 3, so a
+ gated event leaves nothing missing once someone views the machine.
+ - **`ui` must count every app that receives web-eligible frames:** Desktop, web and phone. A test pins that each
+ client kind adds to it.
+3. **One guard, no extra promise, per Redis command.**
+ - While the circuit is closed, `guardRedisCommands` sends the command directly. It records the outcome with one
+ `then` on the command's own promise: success resets the failure count, a failure counts toward opening.
+ - It goes through `breaker.run` only while the circuit is open or half-open.
+ - `createCircuitBreaker.withTimeout` builds no `AbortController` when `timeoutMs` is unset.
+ - The breaker's behaviour (threshold 5, open 5 s, one trial) is unchanged and its tests stay as they are.
+
+### Expected effect
+
+- Item 3: roughly a third of the guard's share, about 0.5–1% of the JS thread.
+- Item 2: whatever share of publishes `none` shows, times the 7%, plus the daemon's sealing and the Redis traffic.
+ Unknown until counted, possibly small.
+
+## Part 5: hot loops
+
+### Why
+
+The profiles' `calls` (V8 precise coverage) show callbacks run millions of times. Each scans every conversation for
+every project or agent:
+
+| Callback | Calls in the 12 profiles (6 min of sampling, 4 pods; a profile lists only its top 30) | Scan |
+|---|---|---|
+| `ledProject` (`projects.ts`): `projectsOf(state).find(p => state.conversations.some(...))` | 13.5 M | projects × conversations, per agent asked |
+| `privateMember` (`projects.ts`, behind `confidentialSession`/`isConfidential`) | 1.6 M | conversations × their agents, per agent |
+| `awaitingWorkers` (`model.ts`) | 2.6 M | agents × conversations, twice |
+| `shipping` (`costs/read.ts`): `rows.filter(...)` per shipped group | 0.3 M or more | groups × cost rows |
+| The messages page's join (`store.ts` messages, `deliveries.filter(d => d.messageId === m.id ...)` per message) | 1.4 M (116 k per profile) | page messages × the page's deliveries, on every messages read |
+
+**Where `ledProject`'s calls come from.** Per pod in 30 s that is about 1.55 M callbacks for about 435 requests and
+about 40 commands, roughly 3,600 per request. Most come from `markConfidential` (`projects.ts`), which every command
+runs after its change (`commands.ts`, beside the commit):
+
+- for each of the Swarm's agents (50 on prod's busiest), it asks `confidentialSession`;
+- that is `ledProject` (5 projects × 175 conversations) and `privateMember` (every conversation's `agentIds`);
+- about 44,000 comparisons per command, whoever sent it. At about 40 commands per pod per 30 s, that alone accounts
+ for the order of the 1.55 M measured. This is inferred from the counts, since the profile does not attribute
+ anonymous callbacks to callers.
+
+The read side adds `hostRows` (per agent row: `ledProject`, `isConfidential` twice) and `visibleState`'s
+`awaitingWorkers` (for each project, each agent scans the conversations up to three times, on every read).
+
+Each call is cheap, so together they are about 1–2% now. The cost grows with the square of a Swarm's size, and prod's
+busiest Swarm grew 30–37% in three days.
+
+### Design
+
+- Each becomes one pass that builds a lookup, then answers from it:
+
+ | Callback | Lookup |
+ |---|---|
+ | `ledProject` | Lead conversation id → project, and agent → led project |
+ | `privateMember` | agents in any conversation with an audience |
+ | `awaitingWorkers` | agents leading a conversation, agents with active work, groups by assigned agent |
+ | `shipping` | cost rows by conversation, sorted once |
+ | `markConfidential` | one pass over the conversations for the set of agents leading a project's Lead conversation and the set of agents in a conversation with an audience; then each agent is two set lookups |
+ | the messages page's join | the page's deliveries grouped by `messageId` once, each list kept in its order, then `shownTo` and `receiptOrder` per message as today |
+
+- **Never across a change.** A command changes its state while it runs, so a lookup is built per call, or per
+ caller's loop where the caller asks for many agents at once, never kept on the state. Reads, whose state is frozen,
+ get the same code.
+- **`markConfidential` first.** It is the largest single source, and it runs on every command. It keeps its rule (a
+ session is marked once it leads a project or is in a private conversation, and stays marked). Only how it finds
+ them changes.
+- **Same answers.** Each function keeps its signature and returns what it returns today. Existing tests pin that. New
+ tests compare old and new on a generated Swarm of 2,000 conversations, 50 agents and 20 projects.
+
+### Expected effect
+
+These callbacks leave the profile's `calls` top list. About 1–2% of the JS thread now, and it no longer grows with the
+square of the Swarm.
+
+## Design (AGENTS.md checklist)
+
+- **Growth (Phase 2):** more, smaller entries. Dormant selections are one per agent or project actually read, within
+ the same byte budget and LRU. A Swarm's history now costs memory only for the selections read.
+- **Growth:** unchanged. The LRU byte budget (`SWARM_CACHE_MB`, 64 MB per process) holds stale entries too, so nothing
+ new grows; over budget, stale entries are evicted before fresh ones. Entries are still dropped at the budget, and also after `DELTA_MAX_AGE_MS` without a full load. The data
+ itself is bounded as before: finished starts expire 7 days after finishing, and tombstones 7 days after removal.
+- **Concurrency:** no locks.
+ - One delta per Swarm and stamp is shared by the readers that need it, as today's loads are.
+ - A patch builds a new frozen value and swaps the entry. A reader that took the old value keeps a consistent
+ snapshot of it.
+ - Commands never read the cache.
+- **Read cost (Phase 2):** a read loads and filters only the hot base. Finished starts and dormant groups are read by
+ the index a read names, and only by reads that name them.
+- **Read cost:** a hit is one Redis `HMGET`, as today. A refresh is seven indexed range reads on `(tabId, changedAt)`
+ (and `readAt` for machines), bounded to the last `OVERLAP_MS` + time since the load, instead of the whole Swarm.
+- **Scale:** at 10x Swarms, processes or writes, the cost of a bump grows with the change, not the Swarm. Deltas
+ per minute still grow with bumps × processes. **First warning:** the `swarm cache` log's patch count and bytes per
+ patch, and the share of whole-Swarm shapes in `db by shape`. If deltas grow large, `DELTA_MAX_PARTS` turns them
+ into full loads. The log shows it.
+- **Compatibility (Part 4):**
+ - An older daemon ignores `uiGate` and keeps sending everything.
+ - A newer daemon gates only when the backend says `uiGate: true`, so with an older backend, or with
+ `RELAY_UI_GATE=off`, it sends everything.
+ - Apps are unchanged. One that connects lists what it shows, as it does today after any reconnect.
+- **Compatibility:** no response, API or client change, and no new Redis keys. Old and new processes bump the same way
+ during a rolling deploy. Old processes keep dropping and reloading, new ones patch, and both stay correct.
+- **Migration + rollback:** nothing is stored. Phase 2 changes only the cache's entries, so the previous release
+ rolls it back. With `SWARM_CACHE_DELTA=off`, Phase 2's entries drop and reload like any other.
+- **Migration + rollback (Phase 1):** nothing is stored. Roll back with `SWARM_CACHE_DELTA=off` (takes effect on restart) or the
+ previous release.
+- **Audience:** unchanged. The cache holds the stored state, the same for every reader. `readerView` applies
+ permissions after the cache, as today. A patch never decides what a reader may see.
+- **Identity:** nothing is keyed by or sent as the machine owner's login.
+- **Failure:** nothing breaks without saying so.
+ - A failed or slow delta read falls back to a full load, and the minute log counts it with its reason.
+ - Redis down means reads go to Mongo, as today.
+ - A wrong patch is caught by the verify sample, logged as a mismatch and dropped. Each entry is fully reloaded at
+ least every 10 minutes.
+- **Platforms:** backend (Node, Linux pods) for every part. Part 4's gate is also in the CLI gateway, the same code
+ on macOS, Linux and Windows. The terminal app, Desktop, web and phone are unchanged.
+- **Migration + rollback (Parts 3–5):** nothing stored.
+ - Part 3 and Part 5 roll back with the previous release.
+ - Part 4's gate is switched off on the backend (`RELAY_UI_GATE=off`), with no daemon release. Its counter and guard
+ roll back with the previous release.
+- **Audience (Part 4):** the gate only withholds a machine's live events from its own owner's apps while none is
+ connected. It never sends anything to anyone new. Guests' sealed copies are never gated.
+
+## Tests
+
+- **Unit (`cache.test.ts`, `cachedReads.test.ts`)**, each patch rule:
+ - insert, update, an older or equal version ignored;
+ - a tombstone removes;
+ - group dormant ↔ awake moves between `parts` and `dormant`;
+ - a finished start stays in `parts`;
+ - a machine reading by `readAt`;
+ - head columns patched;
+ - `visibilityEpoch` change → full reload;
+ - over `DELTA_MAX_PARTS` → full reload;
+ - delta error → full load;
+ - age at 60 s → delta, at 10 min → full load;
+ - one delta shared by concurrent readers;
+ - `off` switch → today's behaviour.
+- **Equivalence (integration, Mongo memory server, alongside `integration/superTabCache.test.ts`).** Run a random
+ sequence of real store commands, including:
+ - messages, task assignment and finishing;
+ - starts that finish;
+ - groups put to sleep by the sweep and woken;
+ - agent removal;
+ - project changes;
+ - machine readings.
+
+ After each command, every patched entry must deep-equal a fresh load of the same entry at the same stamp (data
+ equal, sorted by kind and key).
+- **Overlap.** A write whose `changedAt` is 20 s before the entry's `readStart`, committed after the entry loaded, is
+ in the next patch.
+- **Versions are never a guard from reads.** A test asserts that every `guardedWrite`'s `seen` comes from a load
+ inside its transaction.
+- **Verify path.** A planted divergence is detected, logged with ids only, and the entry is dropped.
+- **Benchmark on the local copy of prod's busiest Swarm** (`harness_profile`): bytes and ms per bump, before and after,
+ for one message send and one task finish.
+- **Part 3:**
+ - every nested object of a held value is frozen;
+ - a second `freeze` of a held value visits no child;
+ - entry `bytes` equals today's estimate for the same value, after a full load and after a patch.
+- **Part 4:**
+ - **Backend:**
+ - `none` is counted for publishes with no subscriber;
+ - `__clients` carries `uiGate: true`, and none with `RELAY_UI_GATE=off`;
+ - `ui` counts a Desktop, a web and a phone client.
+ - **Breaker:**
+ - closed circuit sends without `run`;
+ - five failures open it;
+ - open refuses;
+ - after 5 s one trial, and success closes it (the existing `circuitBreaker` and `redisGuard` tests unchanged and
+ passing).
+ - **CLI** (`npm run test:core` scope for the gateway; record it in the PR):
+ - a live event is not enqueued when `uiGate` and `ui: 0` and no web frame in 60 s;
+ - it is enqueued with `ui > 0`, after a web frame, before any `__clients`, after a link drop, and without
+ `uiGate`;
+ - `turn_started`, `agent_synced`, `agent_deleted`, replies, targeted, guest, device and user frames are never
+ gated.
+- **Part 5:** `markConfidential` marks the same agents as today on generated Swarms (Leads, private members, both,
+ neither, an agent already marked); the messages page returns the same `deliveries` per message, in the same order,
+ for an agent, a person and a Buddy reader. For each function, old and new answers equal on generated Swarms (including no projects, private
+ projects, Leads without a conversation, lost assignments), and `calls` for them in a local profile of the
+ `harness_profile` Swarm drops to about the number of agents or groups.
+
+## Rollout
+
+1. Release the backend first, with `SWARM_CACHE_DELTA=on`, `SWARM_CACHE_VERIFY_RATE=0.01` and `RELAY_UI_GATE=on`.
+ The CLI follows in its next release: its gate does nothing until it hears `uiGate`.
+2. In the first hour, read the `swarm cache` log: zero verify mismatches, patches far above full loads. Compare
+ `db by shape` (whole-Swarm shapes) and `cpu by kind` against this spec's numbers.
+3. After a day with zero mismatches, lower the verify rate to `0.001`. Keep it on: it is the drift alarm.
+4. In the `terminal relay` log, read `none` before and after the CLI release. If it was near zero, item 2 bought
+ little, and the spec says so in its result.
+5. Read the profile's `calls` and functions for `freeze`, `ledProject`, `privateMember`, `awaitingWorkers`,
+ `activeWork`, the messages page's join, the cost read and `redisGuard`, against the numbers above.
+
+## Risks
+
+| Risk | Mitigation |
+|---|---|
+| A patch misses a change and serves stale data | Overlap argument above, equivalence tests, verify sample on prod, full reload every 10 min, kill switch |
+| A part kind or field added later without a patch rule | Patch rules live next to `loadReadBase`; the equivalence test runs every command type, so a new kind or field that changes loaded data fails it |
+| Deltas get large in bursts (a migration, a mass sweep) | `DELTA_MAX_PARTS` → full load; counted in the log |
+| Stale entries hold memory longer | Same LRU byte budget; stale entries are evicted first |
+| Phase 2: a read gets fewer starts or dormant groups than `loadActive` would | Selection rules mirror `loadActive`'s matches; the equivalence test compares every named form against `loadActive` in a transaction |
+| Phase 2: many small dormant selections churn the LRU | Counted per entry name in the `swarm cache` log; `allGroups` keeps one whole entry |
+| Part 4: an app misses live events from the moment it connects | The gate opens on its first frame (the E2EE hello, before it can read anything); it lists the session itself on connect; kill switch on the backend |
+| Part 4: `ui` misses a kind of app and its live events stop | Test pins every web-eligible client kind in `ui`; `RELAY_UI_GATE=off` needs no daemon release |
+| Part 4: the backend stops counting turns for a machine nobody views | `turn_started`, `agent_synced` and `agent_deleted` are never gated; test |
+| Part 5: a lookup kept across a command's change answers wrong | Lookups are built per call or per caller loop, never stored on the state; equivalence tests on generated Swarms |
+| A process clock drifts more than 15 s | Same exposure as client change cursors today; the verify sample would show mismatches |
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index c804ec018..91cdcfde2 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -459,7 +459,8 @@ class SuperTabProject {
final int updateMinutes;
/// The project's status card text, read as the desktop's model reads it
- /// (`SwarmProjectStatusCard`).
+ /// (`SuperTabProjectStatusCard`); the phone shows it in the project menu's
+ /// Status sheet.
final SuperTabProjectStatus? status;
final Map<String, dynamic>? repository;
}
diff --git a/mobile/lib/swarm/swarm_asks.dart b/mobile/lib/swarm/swarm_asks.dart
index ebdde6149..485a3337a 100644
--- a/mobile/lib/swarm/swarm_asks.dart
+++ b/mobile/lib/swarm/swarm_asks.dart
@@ -115,6 +115,10 @@ class SwarmAsks extends ChangeNotifier {
!(reader.snapshot == null && reader.error != null) &&
_settled != reader.generation;
+ /// The last read of what waits failed: a list empty now says nothing. Tried
+ /// again each time the Swarm is read.
+ bool get readFailed => _failed;
+
/// The [SwarmReader.generation] whose asks were read, or need none.
int _settled = -1;
diff --git a/mobile/lib/swarm/swarm_home_list.dart b/mobile/lib/swarm/swarm_home_list.dart
index eb1e10051..911bb5d22 100644
--- a/mobile/lib/swarm/swarm_home_list.dart
+++ b/mobile/lib/swarm/swarm_home_list.dart
@@ -5,6 +5,15 @@ import 'swarm_unread.dart';
/// How long a project is quiet before Home folds it under "Other projects".
const swarmQuietAfter = Duration(hours: 24);
+/// How Home lays its projects out: in [sections], Pinned, Projects and the
+/// quiet ones folded under Other projects; [newest], every project not pinned
+/// in one list, nothing folded. A pin holds under both.
+enum SwarmHomeSort { sections, newest }
+
+/// Which projects Home lists: [all]; those with something new, [unread]; those
+/// where the person is tagged or asked to decide, [mentions].
+enum SwarmHomeFilter { all, unread, mentions }
+
/// What a pin names: a project in one Swarm, as the same id may be in
/// another.
String swarmHomeProjectKey(String swarmId, String projectId) =>
@@ -42,11 +51,14 @@ typedef SwarmHomeLists = ({
/// latest activity, those quiet for a day folded. A project whose time is not
/// known comes after those whose is, in the order read, and is never folded,
/// nor is one with something new in it. Nothing is folded when nothing else
-/// would be listed.
+/// would be listed. [sort] newest folds nothing; [unreadsFirst] brings those
+/// with something new to the top of each list, in the same order among them.
SwarmHomeLists swarmHomeLists(
Iterable<SwarmHomeProject> projects, {
required Set<String> pins,
required DateTime now,
+ SwarmHomeSort sort = SwarmHomeSort.sections,
+ bool unreadsFirst = false,
}) {
final pinned = <SwarmHomeProject>[];
final recent = <SwarmHomeProject>[];
@@ -55,7 +67,8 @@ SwarmHomeLists swarmHomeLists(
final active = project.active;
if (pins.contains(project.key)) {
pinned.add(project);
- } else if (active != null &&
+ } else if (sort == SwarmHomeSort.sections &&
+ active != null &&
now.difference(active) > swarmQuietAfter &&
!project.news.bold &&
project.news.tags == 0) {
@@ -68,6 +81,9 @@ SwarmHomeLists swarmHomeLists(
List<SwarmHomeProject> newest(List<SwarmHomeProject> list) {
final order = {for (final (i, p) in list.indexed) p: i};
return list..sort((a, b) {
+ if (unreadsFirst && _hasNews(a) != _hasNews(b)) {
+ return _hasNews(a) ? -1 : 1;
+ }
final (x, y) = (a.active, b.active);
if (x != null && y != null && x != y) return y.compareTo(x);
if ((x == null) != (y == null)) return x == null ? 1 : -1;
@@ -81,15 +97,25 @@ SwarmHomeLists swarmHomeLists(
return (pinned: newest(pinned), recent: newest(recent), quiet: newest(quiet));
}
-/// [lists] under Home's unread filter (`SwarmHomePrefs.unreadOnly`, the
-/// desktop's `_hasUnread`): only the projects with something new in them,
-/// bold or tags waiting, pinned ones too. None of them was folded.
-SwarmHomeLists swarmHomeUnreadOnly(SwarmHomeLists lists) {
- bool news(SwarmHomeProject p) => p.news.bold || p.news.tags > 0;
+bool _hasNews(SwarmHomeProject p) => p.news.bold || p.news.tags > 0;
+
+/// [lists] under Home's [filter] (`SwarmHomePrefs.filter`; unread is the
+/// desktop's `_hasUnread`), pinned ones too. None with something new was
+/// folded.
+SwarmHomeLists swarmHomeFiltered(SwarmHomeLists lists, SwarmHomeFilter filter) {
+ final bool Function(SwarmHomeProject) keep;
+ switch (filter) {
+ case SwarmHomeFilter.all:
+ return lists;
+ case SwarmHomeFilter.unread:
+ keep = _hasNews;
+ case SwarmHomeFilter.mentions:
+ keep = (p) => p.news.tags > 0;
+ }
return (
- pinned: lists.pinned.where(news).toList(),
- recent: lists.recent.where(news).toList(),
- quiet: lists.quiet.where(news).toList(),
+ pinned: lists.pinned.where(keep).toList(),
+ recent: lists.recent.where(keep).toList(),
+ quiet: lists.quiet.where(keep).toList(),
);
}
diff --git a/mobile/lib/swarm/swarm_home_prefs.dart b/mobile/lib/swarm/swarm_home_prefs.dart
index c63508cc9..d29597617 100644
--- a/mobile/lib/swarm/swarm_home_prefs.dart
+++ b/mobile/lib/swarm/swarm_home_prefs.dart
@@ -6,9 +6,21 @@ import 'package:flutter/foundation.dart';
import '../core/local_key_value_store.dart';
import 'swarm_home_list.dart';
+/// What [SwarmHomePrefs] read back.
+typedef _SwarmHomeKept = ({
+ List<String> pins,
+ List<String> folds,
+ String? swarmId,
+ DateTime? seenAt,
+ SwarmHomeFilter filter,
+ SwarmHomeSort sort,
+ bool unreadsFirst,
+});
+
/// What the person chose for Swarm Home on this phone (Tony, 2026-10-29):
/// the projects pinned at its top ([pins]), the one Swarm it shows
-/// ([swarmId]; none shows them all) and its unread filter ([unreadOnly]);
+/// ([swarmId]; none shows them all), its filter ([filter]) and how it sorts
+/// ([sort], [unreadsFirst]);
/// and when they last left the app ([seenAt]), what While you were away
/// counts from; and the projects whose
/// status card is folded ([folded]), as the desktop keeps it on its computer.
@@ -48,11 +60,24 @@ class SwarmHomePrefs extends ChangeNotifier {
String? get swarmId => _swarmId;
String? _swarmId;
- /// Home lists only the projects with something unread or a tag waiting
- /// (the desktop's unread filter, `SuperTabController.unreadOnly`), kept on
- /// this phone as the desktop keeps it on its computer.
- bool get unreadOnly => _unreadOnly;
- bool _unreadOnly = false;
+ /// Which projects Home lists ([swarmHomeFiltered]), kept on this phone as
+ /// the desktop keeps its unread filter on its computer.
+ SwarmHomeFilter get filter => _filter;
+ SwarmHomeFilter _filter = SwarmHomeFilter.all;
+
+ /// How Home lays its projects out ([swarmHomeLists]).
+ SwarmHomeSort get sort => _sort;
+ SwarmHomeSort _sort = SwarmHomeSort.sections;
+
+ /// Projects with something new come first in each list ([swarmHomeLists]).
+ bool get unreadsFirst => _unreadsFirst;
+ bool _unreadsFirst = false;
+
+ /// Anything but what a new phone shows: the filter button's dot.
+ bool get viewChanged =>
+ _filter != SwarmHomeFilter.all ||
+ _sort != SwarmHomeSort.sections ||
+ _unreadsFirst;
/// When the person last left the app ([seen]); null before, as on a new
/// phone.
@@ -67,7 +92,10 @@ class SwarmHomePrefs extends ChangeNotifier {
/// unfolded meanwhile, which what is read does not bring back, and whether
/// a Swarm was chosen to show, which stands over the one read.
final _unpinned = <String>{}, _unfolded = <String>{};
- bool _shownChosen = false, _unreadChosen = false;
+ bool _shownChosen = false,
+ _filterChosen = false,
+ _sortChosen = false,
+ _unreadsChosen = false;
/// The account's Swarms, as [keepOnly] last heard them; null before. What
/// is read back is held to them too.
@@ -129,10 +157,37 @@ class SwarmHomePrefs extends ChangeNotifier {
_changed();
}
- /// Turns the unread filter on or off ([unreadOnly]).
- void toggleUnreadOnly() {
- if (!_loaded) _unreadChosen = true;
- _unreadOnly = !_unreadOnly;
+ /// Home lists the projects [filter] lets through.
+ void setFilter(SwarmHomeFilter filter) {
+ if (!_loaded) {
+ // Chosen, even if as it is: what is read back does not change it.
+ _filterChosen = true;
+ _touched = true;
+ }
+ if (_filter == filter) return;
+ _filter = filter;
+ _changed();
+ }
+
+ /// Home lays its projects out by [sort].
+ void setSort(SwarmHomeSort sort) {
+ if (!_loaded) {
+ _sortChosen = true;
+ _touched = true;
+ }
+ if (_sort == sort) return;
+ _sort = sort;
+ _changed();
+ }
+
+ /// Projects with something new come first ([on]), or stay in order.
+ void setUnreadsFirst(bool on) {
+ if (!_loaded) {
+ _unreadsChosen = true;
+ _touched = true;
+ }
+ if (_unreadsFirst == on) return;
+ _unreadsFirst = on;
_changed();
}
@@ -197,9 +252,13 @@ class SwarmHomePrefs extends ChangeNotifier {
}
if (_disposed) return;
_loaded = true;
- final (pins, folds, swarmId, seenAt, unreadOnly) = text == null
- ? (const <String>[], const <String>[], null, null, false)
- : _decode(text);
+ final read = text == null ? _nothingKept : _decode(text);
+ final (pins, folds, swarmId, seenAt) = (
+ read.pins,
+ read.folds,
+ read.swarmId,
+ read.seenAt,
+ );
// Chosen meanwhile: the pins pinned and cards folded join those read,
// oldest first, those taken off or opened stay so, and a Swarm chosen
// stands.
@@ -214,7 +273,9 @@ class SwarmHomePrefs extends ChangeNotifier {
merge(_pins, pins, _unpinned);
merge(_folds, folds, _unfolded);
if (!_shownChosen) _swarmId = swarmId;
- if (!_unreadChosen) _unreadOnly = unreadOnly;
+ if (!_filterChosen) _filter = read.filter;
+ if (!_sortChosen) _sort = read.sort;
+ if (!_unreadsChosen) _unreadsFirst = read.unreadsFirst;
// Left meanwhile: the later time stands.
if (seenAt != null && seenAt.isAfter(_seenAt ?? DateTime(0))) {
_seenAt = seenAt;
@@ -228,30 +289,49 @@ class SwarmHomePrefs extends ChangeNotifier {
notifyListeners();
}
+ /// What a new phone has.
+ static const _SwarmHomeKept _nothingKept = (
+ pins: [],
+ folds: [],
+ swarmId: null,
+ seenAt: null,
+ filter: SwarmHomeFilter.all,
+ sort: SwarmHomeSort.sections,
+ unreadsFirst: false,
+ );
+
/// What was kept: written before folds were, it has none; before the
- /// unread filter, it is off.
- static (List<String>, List<String>, String?, DateTime?, bool) _decode(
- String text,
- ) {
+ /// filter's menu, `unread` alone says the filter is on Unread, as it still
+ /// does, so an older build reads it. A value this build does not know reads
+ /// as the default.
+ static _SwarmHomeKept _decode(String text) {
List<String> keys(Object? list) => [
for (final key in list is List ? list : const [])
if (key is String && key.contains('/')) key,
];
try {
final json = jsonDecode(text);
- if (json is! Map) return (const [], const [], null, null, false);
+ if (json is! Map) return _nothingKept;
return (
- keys(json['pins']),
- keys(json['folded']),
- json['swarm'] is String ? json['swarm'] as String : null,
- switch (json['seen']) {
+ pins: keys(json['pins']),
+ folds: keys(json['folded']),
+ swarmId: json['swarm'] is String ? json['swarm'] as String : null,
+ seenAt: switch (json['seen']) {
final int ms when ms > 0 => DateTime.fromMillisecondsSinceEpoch(ms),
_ => null,
},
- json['unread'] == true,
+ filter: json['filter'] == 'mentions'
+ ? SwarmHomeFilter.mentions
+ : json['unread'] == true
+ ? SwarmHomeFilter.unread
+ : SwarmHomeFilter.all,
+ sort: json['sort'] == 'newest'
+ ? SwarmHomeSort.newest
+ : SwarmHomeSort.sections,
+ unreadsFirst: json['unreadsFirst'] == true,
);
} on FormatException {
- return (const [], const [], null, null, false);
+ return _nothingKept;
}
}
@@ -263,7 +343,7 @@ class SwarmHomePrefs extends ChangeNotifier {
_folds.isEmpty &&
_swarmId == null &&
_seenAt == null &&
- !_unreadOnly) {
+ !viewChanged) {
await store.delete(_key);
} else {
await store.write(
@@ -273,7 +353,10 @@ class SwarmHomePrefs extends ChangeNotifier {
if (_folds.isNotEmpty) 'folded': [..._folds],
'swarm': ?_swarmId,
'seen': ?_seenAt?.millisecondsSinceEpoch,
- if (_unreadOnly) 'unread': true,
+ if (_filter == SwarmHomeFilter.unread) 'unread': true,
+ if (_filter == SwarmHomeFilter.mentions) 'filter': 'mentions',
+ if (_sort == SwarmHomeSort.newest) 'sort': 'newest',
+ if (_unreadsFirst) 'unreadsFirst': true,
}),
);
}
diff --git a/mobile/lib/swarm/swarm_home_view_sheet.dart b/mobile/lib/swarm/swarm_home_view_sheet.dart
new file mode 100644
index 000000000..3354a3a03
--- /dev/null
+++ b/mobile/lib/swarm/swarm_home_view_sheet.dart
@@ -0,0 +1,227 @@
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/theme/app_space.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+
+import 'swarm_home_list.dart';
+import 'swarm_home_prefs.dart';
+import 'swarm_row.dart';
+import 'swarm_session.dart';
+import 'swarm_style.dart';
+
+/// The way Home sorts, as the menu's Sort by says it (Tony, 11-02).
+String swarmHomeSortLabel(SwarmHomePrefs home) {
+ final sort = switch (home.sort) {
+ SwarmHomeSort.sections => 'Sections',
+ SwarmHomeSort.newest => 'Newest to oldest',
+ };
+ return home.unreadsFirst ? '$sort. Unreads on top.' : sort;
+}
+
+/// A filter as the menu names it.
+String swarmHomeFilterLabel(SwarmHomeFilter filter) => switch (filter) {
+ SwarmHomeFilter.all => 'All projects',
+ SwarmHomeFilter.unread => 'Unread',
+ SwarmHomeFilter.mentions => 'Mentions',
+};
+
+/// Sort by and Filter, from Home's top bar: each says what is on, and opens to
+/// its options with a tick on the one chosen. A choice applies at once and the
+/// menu stays. It holds nothing of a Swarm; signed out, another account, or no
+/// Swarm left to sort, it closes, and a tap changes nothing.
+Future<void> showSwarmHomeViewSheet(
+ BuildContext context,
+ SwarmSession session,
+) => showModalBottomSheet<void>(
+ context: context,
+ backgroundColor: AppGlass.rowFill,
+ shape: AppControl.sheetShape,
+ isScrollControlled: true,
+ builder: (_) => _ViewSheet(session: session),
+);
+
+class _ViewSheet extends StatefulWidget {
+ const _ViewSheet({required this.session});
+
+ final SwarmSession session;
+
+ @override
+ State<_ViewSheet> createState() => _ViewSheetState();
+}
+
+class _ViewSheetState extends State<_ViewSheet> {
+ bool _sortOpen = false, _filterOpen = false, _closing = false;
+
+ bool get _live =>
+ !_closing &&
+ SwarmScope.of(context) == widget.session &&
+ widget.session.inbox.swarms.isNotEmpty;
+
+ /// Closes the sheet once, after the frame it went blank in.
+ void _close() {
+ if (_closing) return;
+ _closing = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ final route = ModalRoute.of(context);
+ if (route == null || !route.isActive) return;
+ if (route.isCurrent) {
+ Navigator.of(context).pop();
+ } else {
+ Navigator.of(context).removeRoute(route);
+ }
+ });
+ }
+
+ Widget _heading({
+ required String keyName,
+ required String title,
+ required String current,
+ required bool open,
+ required VoidCallback onTap,
+ }) => Semantics(
+ expanded: open,
+ child: SwarmRow(
+ key: ValueKey(keyName),
+ title: title,
+ detail: SwarmRow.line(current, key: ValueKey('$keyName-current')),
+ trailing: Icon(
+ open ? LucideIcons.chevronUp300 : LucideIcons.chevronDown300,
+ size: 18,
+ color: AppPalette.textFaint,
+ ),
+ onTap: onTap,
+ ),
+ );
+
+ Widget _option({
+ required String keyName,
+ required String title,
+ required bool on,
+ required VoidCallback choose,
+ }) => Padding(
+ padding: const EdgeInsetsDirectional.only(start: AppSpace.m),
+ child: SwarmRow(
+ key: ValueKey(keyName),
+ title: title,
+ trailing: on
+ ? Semantics(
+ label: 'Selected',
+ excludeSemantics: true,
+ child: Icon(
+ LucideIcons.check300,
+ size: 20,
+ color: AppPalette.swarmAccent,
+ ),
+ )
+ : null,
+ chevron: null,
+ onTap: () {
+ // Signed out since the last frame: nothing to choose for.
+ if (_live) choose();
+ },
+ ),
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ final session = widget.session;
+ // First, as the session gone has its lists disposed: nothing may listen.
+ if (_closing || SwarmScope.of(context) != session) {
+ _close();
+ return const SizedBox.shrink();
+ }
+ return ListenableBuilder(
+ listenable: Listenable.merge([session.inbox, session.home]),
+ builder: (context, _) {
+ if (!_live) {
+ _close();
+ return const SizedBox.shrink();
+ }
+ final home = session.home;
+ return SafeArea(
+ top: false,
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.sizeOf(context).height * .8,
+ ),
+ child: ListView(
+ shrinkWrap: true,
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.s,
+ AppSpace.s,
+ AppSpace.s,
+ AppSpace.l,
+ ),
+ children: [
+ Center(
+ child: Container(
+ width: AppSpace.xl + AppSpace.m,
+ height: AppSpace.xs,
+ margin: const EdgeInsets.only(bottom: AppSpace.s),
+ decoration: ShapeDecoration(
+ color: AppGlass.hair,
+ shape: const StadiumBorder(),
+ ),
+ ),
+ ),
+ _heading(
+ keyName: 'swarm-view-sort',
+ title: 'Sort by',
+ current: swarmHomeSortLabel(home),
+ open: _sortOpen,
+ onTap: () => setState(() => _sortOpen = !_sortOpen),
+ ),
+ if (_sortOpen) ...[
+ for (final (sort, title) in const [
+ (SwarmHomeSort.sections, 'Sections'),
+ (SwarmHomeSort.newest, 'Newest to oldest'),
+ ])
+ _option(
+ keyName: 'swarm-view-sort-${sort.name}',
+ title: title,
+ on: home.sort == sort,
+ choose: () => home.setSort(sort),
+ ),
+ // In line with the options it heads.
+ const Padding(
+ padding: EdgeInsetsDirectional.only(
+ start: AppSpace.m + AppSpace.m,
+ ),
+ child: SwarmCaption('Unreads and mentions'),
+ ),
+ for (final (first, title) in const [
+ (false, 'Show in order'),
+ (true, 'Move to the top'),
+ ])
+ _option(
+ keyName: 'swarm-view-unreads-$first',
+ title: title,
+ on: home.unreadsFirst == first,
+ choose: () => home.setUnreadsFirst(first),
+ ),
+ ],
+ _heading(
+ keyName: 'swarm-view-filter',
+ title: 'Filter',
+ current: swarmHomeFilterLabel(home.filter),
+ open: _filterOpen,
+ onTap: () => setState(() => _filterOpen = !_filterOpen),
+ ),
+ if (_filterOpen)
+ for (final filter in SwarmHomeFilter.values)
+ _option(
+ keyName: 'swarm-view-filter-${filter.name}',
+ title: swarmHomeFilterLabel(filter),
+ on: home.filter == filter,
+ choose: () => home.setFilter(filter),
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+ }
+}
diff --git a/mobile/lib/swarm/swarm_page.dart b/mobile/lib/swarm/swarm_page.dart
index cf1dab6ad..05afa8672 100644
--- a/mobile/lib/swarm/swarm_page.dart
+++ b/mobile/lib/swarm/swarm_page.dart
@@ -26,6 +26,7 @@ import 'swarm_new_project_sheet.dart';
import 'swarm_project_page.dart';
import 'swarm_reader.dart';
import 'swarm_row.dart';
+import 'swarm_home_view_sheet.dart';
import 'swarm_session.dart';
import 'swarm_start.dart';
import 'swarm_style.dart';
@@ -360,9 +361,10 @@ class _SwarmPageState extends State<SwarmPage> {
);
}
- /// The unread filter and Mark all read, at the end of the top bar (the
- /// desktop's, on its Projects heading): the filter lit while on; Mark all
- /// read greyed with nothing unread in the Swarms [shown].
+ /// Sort and filter and Mark all read, at the end of the top bar (the
+ /// desktop's, on its Projects heading): a dot on the first with anything but
+ /// the defaults on; Mark all read greyed with nothing unread in the Swarms
+ /// [shown].
Widget _attention(
BuildContext context,
SwarmSession session,
@@ -376,13 +378,13 @@ class _SwarmPageState extends State<SwarmPage> {
mainAxisSize: MainAxisSize.min,
children: [
SwarmIconButton(
- key: const ValueKey('swarm-unread-only'),
+ key: const ValueKey('swarm-home-view'),
icon: LucideIcons.listFilter300,
- label: home.unreadOnly
- ? 'Show all projects'
- : 'Show unread projects only',
- selected: home.unreadOnly,
- onPressed: home.toggleUnreadOnly,
+ label:
+ 'Sort and filter: ${swarmHomeSortLabel(home)}, '
+ '${swarmHomeFilterLabel(home.filter)}',
+ dot: home.viewChanged,
+ onPressed: () => unawaited(showSwarmHomeViewSheet(context, session)),
),
SwarmIconButton(
key: const ValueKey('swarm-mark-all-read'),
@@ -601,13 +603,33 @@ class _SwarmPageState extends State<SwarmPage> {
reading.add(swarm.id);
}
}
- final all = swarmHomeLists(projects, pins: session.home.pins, now: now);
- final unreadOnly = session.home.unreadOnly;
- final lists = unreadOnly ? swarmHomeUnreadOnly(all) : all;
- // The filter on with nothing to list: it says so, and offers them all.
- final nothingUnread =
- unreadOnly &&
+ final home = session.home;
+ final filter = home.filter;
+ final lists = swarmHomeFiltered(
+ swarmHomeLists(
+ projects,
+ pins: home.pins,
+ now: now,
+ sort: home.sort,
+ unreadsFirst: home.unreadsFirst,
+ ),
+ filter,
+ );
+ // Mentions come from their own read: until it answers, none listed says
+ // nothing. A failed one is not none, and says so even over the mentions
+ // another Swarm has listed.
+ final mentionsOn = filter == SwarmHomeFilter.mentions;
+ final mentionsComing = mentionsOn && asking.isNotEmpty;
+ final mentionsFailed =
+ mentionsOn &&
+ shown.any((swarm) => inbox.asks(swarm.id)?.readFailed ?? false);
+ // The filter on with nothing to list, and nothing still to come: it says
+ // so, and offers them all.
+ final nothingListed =
+ filter != SwarmHomeFilter.all &&
projects.isNotEmpty &&
+ reading.isEmpty &&
+ !mentionsComing &&
lists.pinned.isEmpty &&
lists.recent.isEmpty &&
lists.quiet.isEmpty;
@@ -639,25 +661,32 @@ class _SwarmPageState extends State<SwarmPage> {
if (lists.recent.isNotEmpty ||
quiet.isNotEmpty ||
empty ||
- nothingUnread ||
+ nothingListed ||
+ mentionsFailed ||
create != null) ...[
SwarmCaption('Projects', first: first && lists.pinned.isEmpty),
SwarmGroup(
children: [
if (empty) const SwarmRow(title: 'No project yet', onTap: null),
- if (nothingUnread) ...[
+ if (mentionsFailed)
const SwarmRow(
- key: ValueKey('swarm-unread-none'),
- title: 'Nothing unread.',
+ key: ValueKey('swarm-mentions-failed'),
+ title: 'Mentions could not be read.',
+ onTap: null,
+ )
+ else if (nothingListed)
+ SwarmRow(
+ key: const ValueKey('swarm-filter-none'),
+ title: mentionsOn ? 'No mentions.' : 'Nothing unread.',
onTap: null,
),
+ if (nothingListed)
SwarmRow(
- key: const ValueKey('swarm-unread-show-all'),
+ key: const ValueKey('swarm-filter-show-all'),
title: 'Show all',
chevron: null,
- onTap: session.home.toggleUnreadOnly,
+ onTap: () => home.setFilter(SwarmHomeFilter.all),
),
- ],
for (final p in lists.recent) row(p),
if (quiet.isNotEmpty) ...[
SwarmOtherProjectsRow(
@@ -674,6 +703,11 @@ class _SwarmPageState extends State<SwarmPage> {
),
] else if (reading.isNotEmpty || failed.isNotEmpty)
SwarmCaption('Projects', first: first && lists.pinned.isEmpty),
+ // A Swarm still to be read has its skeleton below: one is enough.
+ if (mentionsComing && reading.isEmpty) ...[
+ const SizedBox(height: 8),
+ SwarmSkeletonRows(id: 'swarm-mentions-loading', dot: true),
+ ],
for (final (i, id) in reading.indexed) ...[
if (projects.isNotEmpty || i > 0) const SizedBox(height: 8),
SwarmSkeletonRows(id: 'swarm-projects-loading-$id', dot: true),
diff --git a/mobile/lib/swarm/swarm_project_page.dart b/mobile/lib/swarm/swarm_project_page.dart
index 7c0f7cdff..06622cd0c 100644
--- a/mobile/lib/swarm/swarm_project_page.dart
+++ b/mobile/lib/swarm/swarm_project_page.dart
@@ -464,6 +464,13 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {
),
);
+ void _openStatusSheet() => _openSheet(
+ (_) => SwarmProjectStatusSheet(
+ swarmId: widget.swarmId,
+ projectId: widget.projectId,
+ ),
+ );
+
void _openTeamSheet() => _openSheet(
(_) => SwarmProjectTeamSheet(
swarmId: widget.swarmId,
@@ -543,6 +550,7 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {
_ProjectMenu(
reader: reader,
projectId: project.id,
+ onStatus: _openStatusSheet,
onLeaderboard: _openLeaderboardSheet,
onTeam: _openTeamSheet,
onNotifications:
@@ -651,6 +659,9 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {
if (reader != null && snapshot != null && project != null) {
final chat = snapshot.conversation(project.leadConversationId);
final asks = session.inbox.asks(widget.swarmId);
+ // A project the person no longer reads (made private to others)
+ // keeps no sheet of its own, Status's text and decisions with it.
+ if (!swarmReadsProject(reader, project)) _closeSheet();
return _Frame(
top: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -673,16 +684,6 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {
}),
),
),
- // Over the chat, outside it: it never moves the composer.
- if (_tab == SwarmProjectTab.chat)
- SwarmProjectStatusCard(
- session: session,
- reader: reader,
- swarmId: widget.swarmId,
- projectId: project.id,
- // Read here, above the Scaffold that takes it away.
- typing: MediaQuery.viewInsetsOf(context).bottom > 0,
- ),
],
),
// Under a sheet the chat is not seen, so nothing it gets is read.
@@ -777,7 +778,8 @@ SuperTabAgent? swarmProjectPm(SuperTabSnapshot? snapshot, String projectId) {
/// ⋮ at the end of a Swarm Home C project's header: a small menu, on the
/// design system's menu surface (the theme's), of Open terminal first for
/// someone who may write (Tony, 11-01: the PM's terminal on this phone, by
-/// the Buddy row's rule and words, [swarmTerminalAction]), its Leaderboard,
+/// the Buddy row's rule and words, [swarmTerminalAction]), its Status
+/// ([SwarmProjectStatusSheet]; the chat shows no box of it), its Leaderboard,
/// its Team and its project chat's Notifications ([showSwarmNotifySheet]),
/// while that chat is read. It goes with the header: losing the project
/// closes it. Open terminal follows the Swarm and the phone's computers
@@ -786,6 +788,7 @@ class _ProjectMenu extends StatelessWidget {
const _ProjectMenu({
required this.reader,
required this.projectId,
+ required this.onStatus,
required this.onLeaderboard,
required this.onTeam,
this.onNotifications,
@@ -793,7 +796,7 @@ class _ProjectMenu extends StatelessWidget {
final SwarmReader reader;
final String projectId;
- final VoidCallback onLeaderboard, onTeam;
+ final VoidCallback onStatus, onLeaderboard, onTeam;
final VoidCallback? onNotifications;
@override
@@ -850,6 +853,7 @@ class _ProjectMenu extends StatelessWidget {
terminal.enabled ? terminal.onTap : null,
value: terminal.value,
),
+ row('swarm-project-menu-status', 'Status', onStatus),
row('swarm-project-menu-leaderboard', 'Leaderboard', onLeaderboard),
row('swarm-project-menu-team', 'Team', onTeam),
if (onNotifications case final onTap?)
diff --git a/mobile/lib/swarm/swarm_project_status.dart b/mobile/lib/swarm/swarm_project_status.dart
index 17538b021..814dbee1a 100644
--- a/mobile/lib/swarm/swarm_project_status.dart
+++ b/mobile/lib/swarm/swarm_project_status.dart
@@ -1,9 +1,7 @@
import 'dart:async';
-import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
-import 'package:flutter/rendering.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:url_launcher/url_launcher.dart';
@@ -11,13 +9,14 @@ import '../shared/theme/app_space.dart';
import '../shared/theme/app_theme.dart';
import '../shared/theme/app_type.dart';
import 'model.dart';
+import 'swarm_home_keeper.dart';
import 'swarm_inbox.dart';
+import 'swarm_leaderboard.dart' show SwarmProjectSheetFrame;
import 'swarm_need_rows.dart';
import 'swarm_activity_page.dart' show openSwarmActivity;
import 'swarm_needs_page.dart';
import 'swarm_reader.dart';
import 'swarm_session.dart';
-import 'swarm_style.dart';
/// The decisions waiting on the person in [projectId] of Swarm [swarmId], as
/// Activity lists them ([swarmNeedsOf]): each asked in a conversation of that
@@ -76,48 +75,78 @@ String swarmStatusUpdatedAt(DateTime at, DateTime now) {
Future<bool> Function(Uri url) swarmOpenStatusLink = (url) =>
launchUrl(url, mode: LaunchMode.inAppBrowserView);
-/// The status card at the top of a project's chat, as the desktop draws it
-/// (`desktop/lib/super_tabs/project_status_card.dart`): what the coordinator
-/// last reported, replaced in place by each report, and the decisions in this
+/// What a project's menu opens as Status: the project's report and what waits
+/// on the person, in a sheet over its chat (Tony, 2026-11-02: the chat shows
+/// no box of its own). The report as the coordinator last wrote it, replaced
+/// in place by each report, under "updated 09:52"; then the decisions in this
/// project waiting on the person, each opening Activity at it, where the
-/// desktop opens Notifications. Hidden while there is neither; folded to its
-/// heading by the person, remembered on this phone
-/// ([SwarmHomePrefs.folded]), and while the keyboard is up, so it never
-/// pushes the composer.
-///
-/// It reads nothing of its own: the text comes with the Swarm read, the
-/// decisions are Activity's ([swarmProjectNeedsYou]).
-class SwarmProjectStatusCard extends StatelessWidget {
- const SwarmProjectStatusCard({
+/// desktop opens Notifications. Nothing is read here: the text comes with the
+/// Swarm read, the decisions are Activity's ([swarmProjectNeedsYou]). The page
+/// under it closes it when the read, the access or the project is gone.
+class SwarmProjectStatusSheet extends StatelessWidget {
+ const SwarmProjectStatusSheet({
+ super.key,
+ required this.swarmId,
+ required this.projectId,
+ this.now = DateTime.now,
+ });
+
+ final String swarmId, projectId;
+ final DateTime Function() now;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final session = SwarmScope.of(context);
+ return SwarmProjectSheetFrame(
+ title: 'Status',
+ closeKey: 'swarm-status-close',
+ child: session == null
+ ? const SizedBox.shrink()
+ : ListenableBuilder(
+ listenable: session.inbox,
+ builder: (context, _) => switch (session.inbox.reader(swarmId)) {
+ final reader? => SwarmProjectStatus(
+ session: session,
+ reader: reader,
+ swarmId: swarmId,
+ projectId: projectId,
+ now: now,
+ ),
+ null => const SizedBox.shrink(),
+ },
+ ),
+ );
+ }
+}
+
+/// The body of [SwarmProjectStatusSheet] for [projectId] of [reader]'s Swarm.
+/// Nothing at all once the access is revoked, the project is gone or the
+/// person no longer reads it: no text, no time, no decision stays.
+class SwarmProjectStatus extends StatelessWidget {
+ const SwarmProjectStatus({
super.key,
required this.session,
required this.reader,
required this.swarmId,
required this.projectId,
- this.typing = false,
this.now = DateTime.now,
});
final SwarmSession session;
final SwarmReader reader;
final String swarmId, projectId;
-
- /// The keyboard is up. Told by the page: inside its Scaffold the inset is
- /// taken away, so the card cannot see it.
- final bool typing;
final DateTime Function() now;
- /// How tall the open card grows before its text scrolls inside it.
- static const maxBody = 200.0;
-
@override
Widget build(BuildContext context) => ListenableBuilder(
- // The session tells of answers held for Undo, which the rows say.
+ // The session tells of answers held for Undo, which the rows say; the
+ // asks, of what waits on the person being read.
listenable: Listenable.merge([
reader,
session.inbox,
- session.home,
session,
+ ?session.inbox.asks(swarmId),
]),
builder: (context, _) {
AppTheme.watch(context);
@@ -128,173 +157,69 @@ class SwarmProjectStatusCard extends StatelessWidget {
}
final status = project.status;
final waiting = swarmProjectNeedsYou(session, reader, swarmId, projectId);
- if (status == null && waiting.isEmpty) return const SizedBox.shrink();
- final chosen = session.home.folded(swarmId, projectId);
- final folded = chosen || typing;
- return Padding(
+ if (status == null && waiting.isEmpty) {
+ // "Nothing to report" only once the Swarm was read and what waits on
+ // the person with it: the view kept on the phone holds neither, and a
+ // read that failed says so rather than "nothing".
+ final asks = session.inbox.asks(swarmId);
+ final (key, line) = switch ((
+ swarmHomeKept(reader),
+ reader.error ?? asks?.error,
+ asks == null || asks.loading,
+ )) {
+ (_, final error?, _) => ('error', error),
+ (true, _, _) || (_, _, true) => ('updating', 'Updating…'),
+ _ => ('empty', 'Nothing to report yet.'),
+ };
+ return Padding(
+ padding: const EdgeInsets.all(AppSpace.screenInset),
+ child: Text(
+ line,
+ key: ValueKey('swarm-project-status-$key-$projectId'),
+ style: AppType.body(color: AppPalette.textSecondary),
+ ),
+ );
+ }
+ return ListView(
+ key: ValueKey('swarm-project-status-$projectId'),
padding: const EdgeInsets.fromLTRB(
AppSpace.screenInset,
AppSpace.xs,
AppSpace.screenInset,
- AppSpace.xs,
+ AppSpace.l,
),
- child: Semantics(
- container: true,
- label: 'Project status',
- child: DecoratedBox(
- key: ValueKey('swarm-project-status-$projectId'),
- decoration: BoxDecoration(
- color: AppPalette.cardBg,
- borderRadius: BorderRadius.circular(AppCard.radius),
- border: Border.all(color: AppGlass.hair),
- ),
- child: Padding(
- padding: EdgeInsets.fromLTRB(
- AppSpace.m,
- 0,
- 0,
- folded ? 0 : AppSpace.s,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- _heading(context, status?.at, waiting.length, folded, chosen),
- if (!folded)
- // A long report, or many decisions, scroll inside the
- // card, so the chat keeps its room. Each part takes what
- // it needs; only when both overflow do they share it
- // half and half, so a long report never hides what waits
- // on the person.
- _Shares(
- maxHeight: maxBody,
- gap: AppSpace.s,
- children: [
- if (status != null)
- SingleChildScrollView(
- key: ValueKey(
- 'swarm-project-status-body-$projectId',
- ),
- padding: const EdgeInsets.only(right: AppSpace.m),
- child: _StatusText(status.text),
- ),
- if (waiting.isNotEmpty)
- SingleChildScrollView(
- key: ValueKey(
- 'swarm-project-status-needs-$projectId',
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- for (final need in waiting)
- SwarmNeedLine(
- key: ValueKey(
- 'swarm-project-status-need-${need.key}',
- ),
- session: session,
- need: need,
- chevron: LucideIcons.chevronRight300,
- onTap: () => openSwarmActivity(
- context,
- focus: need.key,
- swarmId: swarmId,
- projectId: projectId,
- ),
- ),
- ],
- ),
- ),
- ],
- ),
- ],
+ children: [
+ if (status != null) ...[
+ if (status.at case final at?) ...[
+ Text(
+ 'updated ${swarmStatusUpdatedAt(at, now())}',
+ key: ValueKey('swarm-project-status-heading-$projectId'),
+ style: AppType.caption(color: AppPalette.textSecondary),
),
- ),
- ),
- ),
- );
- },
- );
-
- /// "Status · updated 09:52", with how many wait on the person while
- /// folded, and the fold at its end. "N need you" opens Activity on this
- /// project's rows, where they are answered: no chat shows decisions. While
- /// the keyboard alone folds it, there is no button, only its room: a tap
- /// then would save a fold, or an unfold, the person never saw.
- Widget _heading(
- BuildContext context,
- DateTime? at,
- int waiting,
- bool folded,
- bool chosen,
- ) => Row(
- children: [
- Expanded(
- child: Row(
- children: [
- Flexible(
- child: Text.rich(
- TextSpan(
- children: [
- TextSpan(
- text: 'Status',
- style: AppType.label(color: AppPalette.textPrimary),
- ),
- if (at != null)
- TextSpan(
- text: ' · updated ${swarmStatusUpdatedAt(at, now())}',
- style: AppType.caption(color: AppPalette.textSecondary),
- ),
- ],
+ const SizedBox(height: AppSpace.s),
+ ],
+ _StatusText(status.text),
+ ],
+ if (waiting.isNotEmpty) ...[
+ if (status != null) const SizedBox(height: AppSpace.m),
+ for (final need in waiting)
+ SwarmNeedLine(
+ key: ValueKey('swarm-project-status-need-${need.key}'),
+ session: session,
+ need: need,
+ chevron: LucideIcons.chevronRight300,
+ onTap: () => openSwarmActivity(
+ context,
+ focus: need.key,
+ swarmId: swarmId,
+ projectId: projectId,
),
- key: ValueKey('swarm-project-status-heading-$projectId'),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
),
- ),
- // Folded, the heading still says something waits, and leads to it.
- if (folded && waiting > 0) _needYou(context, waiting),
],
- ),
- ),
- if (typing)
- const SizedBox.square(dimension: 44)
- else
- SwarmIconButton(
- key: ValueKey('swarm-project-status-fold-$projectId'),
- label: chosen ? 'Show status' : 'Fold status',
- icon: chosen ? LucideIcons.chevronDown300 : LucideIcons.chevronUp300,
- size: 18,
- onPressed: () => session.home.fold(swarmId, projectId, !chosen),
- ),
- ],
+ ],
+ );
+ },
);
-
- /// " · 2 need you", a tap target as tall as the fold beside it: Activity,
- /// on what waits on the person in this project.
- Widget _needYou(BuildContext context, int waiting) {
- final text = '$waiting ${waiting == 1 ? 'needs' : 'need'} you';
- return Semantics(
- button: true,
- label: text,
- excludeSemantics: true,
- child: GestureDetector(
- key: ValueKey('swarm-project-status-needs-you-$projectId'),
- behavior: HitTestBehavior.opaque,
- onTap: () =>
- openSwarmActivity(context, swarmId: swarmId, projectId: projectId),
- child: ConstrainedBox(
- constraints: const BoxConstraints(minHeight: 44),
- child: Align(
- widthFactor: 1,
- child: Text(
- ' · $text',
- maxLines: 1,
- style: AppType.caption(color: AppPalette.swarmAccent),
- ),
- ),
- ),
- ),
- );
- }
}
/// The report as the coordinator wrote it, line for line, with its web links
@@ -396,101 +321,3 @@ class _StatusTextState extends State<_StatusText> {
);
}
}
-
-/// One or two scrolling parts, one over the other, no taller together than
-/// [maxHeight]: each as tall as it needs while they fit; when they do not,
-/// one that needs no more than half keeps all it needs and the other takes
-/// the rest; only when both need more than half does each take half.
-class _Shares extends MultiChildRenderObjectWidget {
- const _Shares({
- required this.maxHeight,
- required this.gap,
- required super.children,
- });
-
- final double maxHeight, gap;
-
- @override
- RenderObject createRenderObject(BuildContext context) =>
- _RenderShares(maxHeight, gap);
-
- @override
- void updateRenderObject(BuildContext context, _RenderShares render) => render
- ..maxHeight = maxHeight
- ..gap = gap;
-}
-
-class _ShareData extends ContainerBoxParentData<RenderBox> {}
-
-class _RenderShares extends RenderBox
- with
- ContainerRenderObjectMixin<RenderBox, _ShareData>,
- RenderBoxContainerDefaultsMixin<RenderBox, _ShareData> {
- _RenderShares(this._maxHeight, this._gap);
-
- double _maxHeight, _gap;
- set maxHeight(double value) {
- if (value == _maxHeight) return;
- _maxHeight = value;
- markNeedsLayout();
- }
-
- set gap(double value) {
- if (value == _gap) return;
- _gap = value;
- markNeedsLayout();
- }
-
- @override
- void setupParentData(RenderBox child) {
- if (child.parentData is! _ShareData) child.parentData = _ShareData();
- }
-
- /// The heights [needs] get within [room], as [_Shares] says.
- static List<double> share(List<double> needs, double room) {
- if (needs.fold(0.0, (a, b) => a + b) <= room) return needs;
- if (needs.length == 1) return [room];
- final half = room / 2;
- final [a, b] = needs;
- if (a <= half) return [a, room - a];
- if (b <= half) return [room - b, b];
- return [half, half];
- }
-
- @override
- void performLayout() {
- final width = constraints.maxWidth;
- final kids = getChildrenAsList();
- final gaps = kids.isEmpty ? 0.0 : _gap * (kids.length - 1);
- final room = math.max(
- 0.0,
- math.min(_maxHeight, constraints.maxHeight) - gaps,
- );
- BoxConstraints within(double height) =>
- BoxConstraints(minWidth: width, maxWidth: width, maxHeight: height);
- // What each needs, within all the room: a scroll view is as tall as its
- // content, up to its bound.
- final needs = [
- for (final kid in kids)
- (kid..layout(within(room), parentUsesSize: true)).size.height,
- ];
- final heights = share(needs, room);
- var y = 0.0;
- for (final (i, kid) in kids.indexed) {
- if (heights[i] != needs[i]) {
- kid.layout(within(heights[i]), parentUsesSize: true);
- }
- (kid.parentData! as _ShareData).offset = Offset(0, y);
- y += kid.size.height + (i < kids.length - 1 ? _gap : 0);
- }
- size = constraints.constrain(Size(width, y));
- }
-
- @override
- void paint(PaintingContext context, Offset offset) =>
- defaultPaint(context, offset);
-
- @override
- bool hitTestChildren(BoxHitTestResult result, {required Offset position}) =>
- defaultHitTestChildren(result, position: position);
-}
diff --git a/mobile/lib/swarm/swarm_style.dart b/mobile/lib/swarm/swarm_style.dart
index 313c1e9a9..01d84bbd9 100644
--- a/mobile/lib/swarm/swarm_style.dart
+++ b/mobile/lib/swarm/swarm_style.dart
@@ -751,6 +751,7 @@ class SwarmIconButton extends StatelessWidget {
required this.onPressed,
this.size = 22,
this.selected,
+ this.dot = false,
});
final IconData icon;
@@ -764,6 +765,10 @@ class SwarmIconButton extends StatelessWidget {
/// button.
final bool? selected;
+ /// A dot in the accent at the glyph's corner: something is changed from its
+ /// default. Say what in [label], as a dot is not heard.
+ final bool dot;
+
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
@@ -803,7 +808,27 @@ class SwarmIconButton extends StatelessWidget {
),
child: SizedBox.square(
dimension: 36,
- child: Icon(icon, size: size, color: color),
+ child: Stack(
+ alignment: Alignment.center,
+ children: [
+ Icon(icon, size: size, color: color),
+ if (dot)
+ PositionedDirectional(
+ top: AppSpace.xs,
+ end: AppSpace.xs,
+ child: SizedBox.square(
+ key: const ValueKey('swarm-icon-dot'),
+ dimension: AppSpace.s,
+ child: DecoratedBox(
+ decoration: ShapeDecoration(
+ color: AppPalette.swarmAccent,
+ shape: const CircleBorder(),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
),
),
),
diff --git a/mobile/test/swarm/swarm_home_view_shots_test.dart b/mobile/test/swarm/swarm_home_view_shots_test.dart
new file mode 100644
index 000000000..e9b7c8188
--- /dev/null
+++ b/mobile/test/swarm/swarm_home_view_shots_test.dart
@@ -0,0 +1,188 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/cupertino.dart' show CupertinoPageRoute;
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_page.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Review screenshots of Home's Sort by and Filter menu, at 390 wide in both
+/// phone themes, with the app's own fonts, from made-up data only, to the
+/// folder `SWARM_HOME_VIEW_SHOTS` names.
+final shots = Platform.environment['SWARM_HOME_VIEW_SHOTS'];
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ final now = DateTime.utc(2026, 11, 2, 9, 41);
+ const web = 'project-web', webLead = 'lead-web';
+
+ FakeSwarm backend() {
+ const derived = {
+ 'readMarks': {leadChat: 2, 'g1': 1, webLead: 1},
+ };
+ final at = {
+ leadChat: now.subtract(const Duration(hours: 3)).millisecondsSinceEpoch,
+ 'g1': now.subtract(const Duration(hours: 3)).millisecondsSinceEpoch,
+ webLead: now.subtract(const Duration(hours: 1)).millisecondsSinceEpoch,
+ };
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) {
+ final read = firstLoad(
+ derived: derived,
+ head: headData(
+ projects: [
+ ...headData()['projects'] as List,
+ {
+ 'id': web,
+ 'name': 'Web',
+ 'ownerId': me,
+ 'leadConversationId': webLead,
+ 'visibility': 'public',
+ 'members': <Object>[],
+ 'updateMinutes': 5,
+ },
+ ],
+ ),
+ groups: [
+ groupData('g1', title: 'Fix login', lastMessageSequence: 5),
+ {
+ ...groupData(webLead, title: 'Web', lastMessageSequence: 1),
+ 'projectId': web,
+ },
+ ],
+ );
+ return {
+ ...read,
+ 'groups': [
+ for (final part in read['groups'] as List)
+ {...part as Map<String, dynamic>, 'changedAt': at[part['key']]},
+ ],
+ };
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2', derived: derived);
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/conversations/'] = (body) => {
+ 'sequence': body?['sequence'],
+ 'messages': <Object>[],
+ 'next': null,
+ };
+ return fake;
+ }
+
+ testWidgets('Home, its menu shut and open', (tester) async {
+ await tester.binding.setSurfaceSize(const Size(390, 844));
+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ final boundary = GlobalKey();
+ Future<void> capture(String name) => tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/home-view-$name-390-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: backend().request,
+ notices: SilentSystemNotices(),
+ features: features,
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ onGenerateRoute: (_) => CupertinoPageRoute<void>(
+ builder: (_) => SwarmPage(now: () => now),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> tap(String key) async {
+ await tester.tap(find.byKey(ValueKey(key)));
+ await tester.pumpAndSettle();
+ }
+
+ await tap('swarm-home-view');
+ await capture('menu');
+ await tap('swarm-view-sort');
+ await tap('swarm-view-unreads-true');
+ await capture('sort-open');
+ await tap('swarm-view-sort');
+ await tap('swarm-view-filter');
+ await tap('swarm-view-filter-unread');
+ await capture('filter-open');
+ await tester.tapAt(const Offset(195, 60));
+ await tester.pumpAndSettle();
+ await capture('home-dot');
+
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 30));
+ host.dispose();
+ }
+ await tester.binding.setSurfaceSize(null);
+ tester.view.resetPadding();
+ AppTheme.palette.value = HarnessPalette.graphite;
+ AppTheme.brightness.value = Brightness.dark;
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_home_view_test.dart b/mobile/test/swarm/swarm_home_view_test.dart
new file mode 100644
index 000000000..1725228cb
--- /dev/null
+++ b/mobile/test/swarm/swarm_home_view_test.dart
@@ -0,0 +1,893 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter/cupertino.dart' show CupertinoPageRoute;
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_home_list.dart';
+import 'package:harness_mobile/swarm/swarm_home_prefs.dart';
+import 'package:harness_mobile/swarm/swarm_home_rows.dart';
+import 'package:harness_mobile/swarm/swarm_page.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+import 'package:harness_mobile/swarm/swarm_style.dart';
+import 'package:harness_mobile/swarm/swarm_unread.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+
+import '../voice_fakes.dart' show MemoryKeyValueStore;
+import 'swarm_fixture.dart';
+
+/// A store whose first [failures] reads fail.
+class _FailingStore extends MemoryKeyValueStore {
+ _FailingStore(this.failures);
+ int failures;
+
+ @override
+ Future<String?> read(String key) async {
+ if (failures-- > 0) throw StateError('unreadable');
+ return super.read(key);
+ }
+}
+
+/// Home's Sort by and Filter menu on the phone (Tony, 11-02): what each choice
+/// does to the Projects list, that it is kept on this phone, and that the menu
+/// goes with the account or the Swarms it sorts.
+void main() {
+ const SwarmRowNews bold = (bold: true, tags: 0);
+ const web = 'project-2';
+ const webLead = 'group-lead-web';
+ final now = DateTime.utc(2030, 1, 2, 12);
+
+ SwarmHomeProject row(
+ String id, {
+ DateTime? active,
+ SwarmRowNews news = swarmNoNews,
+ }) => SwarmHomeProject(
+ swarmId: tab,
+ project: SuperTabProject.fromJson({
+ 'id': id,
+ 'name': id,
+ 'ownerId': me,
+ 'leadConversationId': 'lead-$id',
+ 'visibility': 'public',
+ 'members': <Object>[],
+ 'updateMinutes': 5,
+ }),
+ active: active,
+ news: news,
+ );
+
+ List<String> ids(List<SwarmHomeProject> list) => [
+ for (final p in list) p.project.id,
+ ];
+
+ group('The Projects list', () {
+ final hour = const Duration(hours: 1);
+ final projects = [
+ row('old-read', active: now.subtract(hour * 48)),
+ row('new-read', active: now.subtract(hour)),
+ row('older-unread', active: now.subtract(hour * 3), news: bold),
+ row(
+ 'tagged',
+ active: now.subtract(hour * 2),
+ news: (bold: true, tags: 2),
+ ),
+ row('pinned-read', active: now.subtract(hour * 72)),
+ ];
+ final pins = {swarmHomeProjectKey(tab, 'pinned-read')};
+
+ test('Sections folds the quiet ones, as Home always has', () {
+ final lists = swarmHomeLists(projects, pins: pins, now: now);
+ expect(ids(lists.pinned), ['pinned-read']);
+ expect(ids(lists.recent), ['new-read', 'tagged', 'older-unread']);
+ expect(ids(lists.quiet), ['old-read']);
+ });
+
+ test('Newest to oldest folds nothing, and a pin still holds', () {
+ final lists = swarmHomeLists(
+ projects,
+ pins: pins,
+ now: now,
+ sort: SwarmHomeSort.newest,
+ );
+ expect(ids(lists.pinned), ['pinned-read']);
+ expect(ids(lists.recent), [
+ 'new-read',
+ 'tagged',
+ 'older-unread',
+ 'old-read',
+ ]);
+ expect(lists.quiet, isEmpty);
+ });
+
+ test('Move to the top brings what is new first, in the same order among '
+ 'them, in every list', () {
+ final lists = swarmHomeLists(
+ [
+ ...projects,
+ row('pinned-tagged', active: now.subtract(hour * 90), news: bold),
+ ],
+ pins: {...pins, swarmHomeProjectKey(tab, 'pinned-tagged')},
+ now: now,
+ unreadsFirst: true,
+ );
+ expect(ids(lists.pinned), ['pinned-tagged', 'pinned-read']);
+ expect(ids(lists.recent), ['tagged', 'older-unread', 'new-read']);
+ });
+
+ test('All leaves them; Unread keeps anything new, pinned too; Mentions '
+ 'keeps only tags', () {
+ final lists = swarmHomeLists(
+ [
+ ...projects,
+ row('pinned-unread', active: now.subtract(hour * 90), news: bold),
+ ],
+ pins: {...pins, swarmHomeProjectKey(tab, 'pinned-unread')},
+ now: now,
+ );
+ expect(
+ identical(swarmHomeFiltered(lists, SwarmHomeFilter.all), lists),
+ isTrue,
+ );
+ final unread = swarmHomeFiltered(lists, SwarmHomeFilter.unread);
+ expect(ids(unread.pinned), ['pinned-unread']);
+ expect(ids(unread.recent), ['tagged', 'older-unread']);
+ expect(unread.quiet, isEmpty);
+ final mentions = swarmHomeFiltered(lists, SwarmHomeFilter.mentions);
+ expect(mentions.pinned, isEmpty);
+ expect(ids(mentions.recent), ['tagged']);
+ });
+ });
+
+ group('Kept on this phone', () {
+ Future<void> settle() => Future<void>.delayed(Duration.zero);
+
+ test('each choice reads back; all back to the defaults leaves nothing on '
+ 'the phone', () async {
+ final store = MemoryKeyValueStore();
+ final prefs = SwarmHomePrefs(accountId: me, store: store);
+ await settle();
+ expect(prefs.viewChanged, isFalse);
+ prefs
+ ..setSort(SwarmHomeSort.newest)
+ ..setUnreadsFirst(true)
+ ..setFilter(SwarmHomeFilter.mentions);
+ await settle();
+ expect(prefs.viewChanged, isTrue);
+ prefs.dispose();
+
+ final again = SwarmHomePrefs(accountId: me, store: store);
+ await settle();
+ expect(again.sort, SwarmHomeSort.newest);
+ expect(again.unreadsFirst, isTrue);
+ expect(again.filter, SwarmHomeFilter.mentions);
+
+ again
+ ..setSort(SwarmHomeSort.sections)
+ ..setUnreadsFirst(false)
+ ..setFilter(SwarmHomeFilter.all);
+ await settle();
+ expect(store.values['swarm_home.$me'], isNull);
+ again.dispose();
+ });
+
+ test(
+ 'each default alone off is still kept: sort, unreads, filter',
+ () async {
+ for (final choose in <void Function(SwarmHomePrefs)>[
+ (p) => p.setSort(SwarmHomeSort.newest),
+ (p) => p.setUnreadsFirst(true),
+ (p) => p.setFilter(SwarmHomeFilter.unread),
+ (p) => p.setFilter(SwarmHomeFilter.mentions),
+ ]) {
+ final store = MemoryKeyValueStore();
+ final prefs = SwarmHomePrefs(accountId: me, store: store);
+ await settle();
+ choose(prefs);
+ await settle();
+ expect(store.values['swarm_home.$me'], isNotNull);
+ prefs.dispose();
+ }
+ },
+ );
+
+ test('the old filter switch, on, opens as Unread, and Unread still writes '
+ 'it for an older build; off or unknown reads as the default', () async {
+ final store = MemoryKeyValueStore()
+ ..values['swarm_home.$me'] = jsonEncode({
+ 'pins': ['$tab/$project'],
+ 'unread': true,
+ });
+ final old = SwarmHomePrefs(accountId: me, store: store);
+ await settle();
+ expect(old.filter, SwarmHomeFilter.unread);
+ expect(old.pins, {'$tab/$project'});
+ old.setSort(SwarmHomeSort.newest);
+ await settle();
+ expect(
+ jsonDecode(store.values['swarm_home.$me']!),
+ containsPair('unread', true),
+ );
+ old.dispose();
+
+ store.values['swarm_home.$me'] = jsonEncode({
+ 'pins': ['$tab/$project'],
+ 'filter': 'someday',
+ 'sort': 'someday',
+ 'unreadsFirst': 'yes',
+ });
+ final odd = SwarmHomePrefs(accountId: me, store: store);
+ await settle();
+ expect(odd.viewChanged, isFalse);
+ odd.dispose();
+ });
+
+ test('chosen before the choices are back, it stands over what is read, '
+ 'a default too, and is written', () async {
+ final store = MemoryKeyValueStore()
+ ..values['swarm_home.$me'] = jsonEncode({
+ 'pins': ['$tab/$project'],
+ 'filter': 'mentions',
+ 'sort': 'newest',
+ 'unreadsFirst': true,
+ });
+ final early = SwarmHomePrefs(accountId: me, store: store)
+ ..setFilter(SwarmHomeFilter.all)
+ ..setSort(SwarmHomeSort.sections)
+ ..setUnreadsFirst(false);
+ await settle();
+ expect(early.viewChanged, isFalse);
+ expect(early.pins, {'$tab/$project'});
+ final kept = jsonDecode(store.values['swarm_home.$me']!) as Map;
+ expect(kept.containsKey('filter'), isFalse);
+ expect(kept.containsKey('sort'), isFalse);
+ expect(kept.containsKey('unreadsFirst'), isFalse);
+ early.dispose();
+ });
+
+ test('a read answering after the session closed changes nothing', () async {
+ final store = MemoryKeyValueStore()
+ ..values['swarm_home.$me'] = jsonEncode({'filter': 'mentions'});
+ final gone = SwarmHomePrefs(accountId: me, store: store)..dispose();
+ await settle();
+ expect(gone.filter, SwarmHomeFilter.all);
+ });
+
+ test('a first read that failed leaves the defaults, and a later choice is '
+ 'still saved and read back', () async {
+ final store = _FailingStore(1);
+ final prefs = SwarmHomePrefs(accountId: me, store: store);
+ await settle();
+ expect(prefs.loaded, isTrue);
+ expect(prefs.viewChanged, isFalse);
+ prefs.setFilter(SwarmHomeFilter.unread);
+ await settle();
+ prefs.dispose();
+
+ final again = SwarmHomePrefs(accountId: me, store: store);
+ await settle();
+ expect(again.filter, SwarmHomeFilter.unread);
+ again.dispose();
+ });
+
+ test(
+ 'saved at the pin limit, the choices read back and still save',
+ () async {
+ final store = MemoryKeyValueStore()
+ ..values['swarm_home.$me'] = jsonEncode({
+ 'pins': [for (var i = 0; i < 60; i++) '$tab/p$i'],
+ 'filter': 'mentions',
+ 'unreadsFirst': true,
+ });
+ final full = SwarmHomePrefs(accountId: me, store: store);
+ await settle();
+ expect(full.pins, hasLength(SwarmHomePrefs.keptPins));
+ expect(full.filter, SwarmHomeFilter.mentions);
+ full.setSort(SwarmHomeSort.newest);
+ await settle();
+ final kept = jsonDecode(store.values['swarm_home.$me']!) as Map;
+ expect(kept['pins'], hasLength(SwarmHomePrefs.keptPins));
+ expect(kept['sort'], 'newest');
+ expect(kept['filter'], 'mentions');
+ full.dispose();
+ },
+ );
+
+ test('one account\'s choices never reach another on the phone', () async {
+ final store = MemoryKeyValueStore();
+ final mine = SwarmHomePrefs(accountId: me, store: store);
+ await settle();
+ mine.setFilter(SwarmHomeFilter.mentions);
+ await settle();
+ mine.dispose();
+ final other = SwarmHomePrefs(accountId: 'person-other', store: store);
+ await settle();
+ expect(other.filter, SwarmHomeFilter.all);
+ other.dispose();
+ });
+ });
+
+ group('Home', () {
+ final mobileAt = now.subtract(const Duration(hours: 2));
+
+ /// One Swarm: Mobile, with g1 unread; and Web, read and quiet for
+ /// [webAgo], with what waits in [mentions].
+ FakeSwarm backend({
+ Duration webAgo = const Duration(hours: 1),
+ FutureOr<Object?> Function(Map<String, dynamic>?)? mentions,
+ }) {
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ final derived = <String, dynamic>{
+ 'readMarks': {leadChat: 2, 'g1': 1, webLead: 1},
+ if (mentions != null) 'mentionsWaiting': 1,
+ };
+ final changedAt = {
+ leadChat: mobileAt.millisecondsSinceEpoch,
+ 'g1': mobileAt.millisecondsSinceEpoch,
+ webLead: now.subtract(webAgo).millisecondsSinceEpoch,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) {
+ final read = firstLoad(
+ derived: derived,
+ head: headData(
+ projects: [
+ ...headData()['projects'] as List,
+ {
+ 'id': web,
+ 'name': 'Web',
+ 'ownerId': me,
+ 'leadConversationId': webLead,
+ 'visibility': 'public',
+ 'members': <Object>[],
+ 'updateMinutes': 5,
+ },
+ ],
+ ),
+ groups: [
+ groupData('g1', title: 'Fix login', lastMessageSequence: 5),
+ {
+ ...groupData(webLead, title: 'Web', lastMessageSequence: 1),
+ 'projectId': web,
+ },
+ ],
+ );
+ return {
+ ...read,
+ 'groups': [
+ for (final part in read['groups'] as List)
+ {
+ ...part as Map<String, dynamic>,
+ 'changedAt': changedAt[part['key']],
+ },
+ ],
+ };
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2', derived: derived);
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] =
+ mentions ?? (_) => {'mentions': <Object>[]};
+ fake.routes['/api/super-tabs/$tab/conversations/'] = (body) => {
+ 'sequence': body?['sequence'],
+ 'messages': <Object>[],
+ 'next': null,
+ };
+ return fake;
+ }
+
+ Future<SwarmHost> pump(
+ WidgetTester tester,
+ FakeSwarm fake, {
+ ValueNotifier<String?>? signedIn,
+ MemoryKeyValueStore? store,
+ bool settle = true,
+ }) async {
+ tester.view.physicalSize = const Size(1170, 2532);
+ tester.view.devicePixelRatio = 3;
+ addTearDown(tester.view.reset);
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
+ final account = signedIn ?? ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: features,
+ readMarks: store ?? MemoryKeyValueStore(),
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) =>
+ SwarmScope(notifier: host, child: child!),
+ onGenerateRoute: (_) => CupertinoPageRoute<void>(
+ builder: (_) => SwarmPage(now: () => now),
+ ),
+ ),
+ );
+ if (settle) {
+ await tester.pumpAndSettle();
+ } else {
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ return host;
+ }
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+ Finder project_(String id) => key('swarm-project-$tab-$id');
+ Finder dot() => key('swarm-icon-dot');
+ Future<void> open(WidgetTester tester) async {
+ await tester.tap(key('swarm-home-view'));
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> tapRow(WidgetTester tester, String name) async {
+ await tester.tap(key(name));
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> close(WidgetTester tester) async {
+ await tester.tapAt(const Offset(195, 40));
+ await tester.pumpAndSettle();
+ }
+
+ String text(WidgetTester tester, String name) =>
+ tester.widget<Text>(key(name)).data!;
+ bool ticked(String name) => find
+ .descendant(of: key(name), matching: find.byIcon(LucideIcons.check300))
+ .evaluate()
+ .isNotEmpty;
+
+ testWidgets('the icon opens the menu, not a toggle: each row says what is '
+ 'on and opens to its options, with a tick on the current one', (
+ tester,
+ ) async {
+ final host = await pump(tester, backend());
+ expect(key('swarm-view-sort'), findsNothing);
+
+ await open(tester);
+
+ // Opening the menu changed nothing.
+ expect(host.session!.home.viewChanged, isFalse);
+ expect(project_(web), findsOneWidget);
+ expect(text(tester, 'swarm-view-sort-current'), 'Sections');
+ expect(text(tester, 'swarm-view-filter-current'), 'All projects');
+ expect(key('swarm-view-sort-sections'), findsNothing);
+ expect(key('swarm-view-filter-all'), findsNothing);
+
+ await tapRow(tester, 'swarm-view-sort');
+ await tapRow(tester, 'swarm-view-filter');
+ expect(ticked('swarm-view-sort-sections'), isTrue);
+ expect(ticked('swarm-view-sort-newest'), isFalse);
+ expect(ticked('swarm-view-unreads-false'), isTrue);
+ expect(ticked('swarm-view-unreads-true'), isFalse);
+ expect(ticked('swarm-view-filter-all'), isTrue);
+ expect(ticked('swarm-view-filter-unread'), isFalse);
+ expect(ticked('swarm-view-filter-mentions'), isFalse);
+
+ await tapRow(tester, 'swarm-view-sort');
+ expect(key('swarm-view-sort-sections'), findsNothing);
+ });
+
+ testWidgets('the icon has a dot, and says in words what is on, only with '
+ 'something other than the defaults', (tester) async {
+ final handle = tester.ensureSemantics();
+ final host = await pump(tester, backend());
+ expect(dot(), findsNothing);
+ expect(
+ tester.widget<SwarmIconButton>(key('swarm-home-view')).label,
+ 'Sort and filter: Sections, All projects',
+ );
+ await open(tester);
+
+ for (final (openRow, on, off) in [
+ (
+ 'swarm-view-sort',
+ 'swarm-view-sort-newest',
+ 'swarm-view-sort-sections',
+ ),
+ (
+ 'swarm-view-sort',
+ 'swarm-view-unreads-true',
+ 'swarm-view-unreads-false',
+ ),
+ (
+ 'swarm-view-filter',
+ 'swarm-view-filter-unread',
+ 'swarm-view-filter-all',
+ ),
+ ]) {
+ await tapRow(tester, openRow);
+ await tapRow(tester, on);
+ expect(dot(), findsOneWidget, reason: on);
+ await tapRow(tester, off);
+ expect(dot(), findsNothing, reason: off);
+ await tapRow(tester, openRow);
+ }
+ expect(host.session!.home.viewChanged, isFalse);
+ handle.dispose();
+ });
+
+ testWidgets('Newest to oldest lists the quiet project without the fold; '
+ 'the row says so and the menu stays open', (tester) async {
+ await pump(tester, backend(webAgo: const Duration(hours: 48)));
+ expect(key('swarm-other-projects'), findsOneWidget);
+ expect(project_(web), findsNothing);
+
+ await open(tester);
+ await tapRow(tester, 'swarm-view-sort');
+ await tapRow(tester, 'swarm-view-sort-newest');
+
+ expect(key('swarm-view-sort'), findsOneWidget);
+ expect(text(tester, 'swarm-view-sort-current'), 'Newest to oldest');
+ expect(ticked('swarm-view-sort-newest'), isTrue);
+ expect(key('swarm-other-projects'), findsNothing);
+ expect(project_(web), findsOneWidget);
+ });
+
+ testWidgets('Move to the top brings the unread project over a newer read '
+ 'one, and the row says so', (tester) async {
+ await pump(tester, backend());
+ double top(String id) => tester.getTopLeft(project_(id)).dy;
+ expect(top(web), lessThan(top(project)));
+
+ await open(tester);
+ await tapRow(tester, 'swarm-view-sort');
+ await tapRow(tester, 'swarm-view-unreads-true');
+
+ expect(
+ text(tester, 'swarm-view-sort-current'),
+ 'Sections. Unreads on top.',
+ );
+ expect(top(project), lessThan(top(web)));
+ });
+
+ testWidgets('Unread lists what has something new; with nothing it says so '
+ 'and Show all clears it', (tester) async {
+ final host = await pump(tester, backend());
+ await open(tester);
+ await tapRow(tester, 'swarm-view-filter');
+ await tapRow(tester, 'swarm-view-filter-unread');
+ expect(text(tester, 'swarm-view-filter-current'), 'Unread');
+ await close(tester);
+ expect(project_(project), findsOneWidget);
+ expect(project_(web), findsNothing);
+
+ await tester.tap(key('swarm-mark-all-read'));
+ await tester.pumpAndSettle();
+ expect(project_(project), findsNothing);
+ expect(key('swarm-filter-none'), findsOneWidget);
+ expect(find.text('Nothing unread.'), findsOneWidget);
+
+ await tester.tap(key('swarm-filter-show-all'));
+ await tester.pumpAndSettle();
+ expect(project_(web), findsOneWidget);
+ expect(host.session!.home.filter, SwarmHomeFilter.all);
+ expect(dot(), findsNothing);
+ await tester.pump(const Duration(seconds: 7));
+ });
+
+ Map<String, dynamic> tagInWeb() => {
+ 'mentions': [
+ {
+ 'id': 'm1',
+ 'projectId': web,
+ 'projectName': 'Web',
+ 'conversationId': webLead,
+ 'conversationTitle': 'Web',
+ 'messageId': 'msg-tag',
+ 'leadName': 'River',
+ 'text': 'Can you check the copy?',
+ },
+ ],
+ };
+
+ testWidgets('Mentions lists only where the person is tagged, not what is '
+ 'merely unread', (tester) async {
+ await pump(tester, backend(mentions: (_) => tagInWeb()));
+ await open(tester);
+ await tapRow(tester, 'swarm-view-filter');
+ await tapRow(tester, 'swarm-view-filter-mentions');
+ await close(tester);
+ expect(project_(web), findsOneWidget);
+ expect(project_(project), findsNothing);
+ expect(dot(), findsOneWidget);
+ });
+
+ testWidgets('Mentions with none says so, only once its read answered: a '
+ 'skeleton until then, never a false "No mentions"', (tester) async {
+ final answer = Completer<Object?>();
+ final store = MemoryKeyValueStore()
+ ..values['swarm_home.$me'] = jsonEncode({'filter': 'mentions'});
+ await pump(
+ tester,
+ backend(mentions: (_) => answer.future),
+ store: store,
+ settle: false,
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(project_(project), findsNothing);
+ expect(find.text('No mentions.'), findsNothing);
+
+ answer.complete({'mentions': <Object>[]});
+ await tester.pumpAndSettle();
+ expect(find.text('No mentions.'), findsOneWidget);
+ expect(key('swarm-filter-show-all'), findsOneWidget);
+ });
+
+ testWidgets('a failed read of the mentions is not none: it says so, keeps '
+ 'Show all, and a later read that answers brings them', (tester) async {
+ var fail = true;
+ final fake = backend(
+ mentions: (_) {
+ if (fail) {
+ throw SuperTabFailure('BUSY', 'Busy', statusCode: 503);
+ }
+ return tagInWeb();
+ },
+ );
+ final store = MemoryKeyValueStore()
+ ..values['swarm_home.$me'] = jsonEncode({'filter': 'mentions'});
+ final host = await pump(tester, fake, store: store);
+ expect(find.text('Mentions could not be read.'), findsOneWidget);
+ expect(find.text('No mentions.'), findsNothing);
+ expect(key('swarm-filter-show-all'), findsOneWidget);
+
+ fail = false;
+ await host.session!.inbox.asks(tab)!.load();
+ await tester.pumpAndSettle();
+ expect(project_(web), findsOneWidget);
+ expect(find.text('Mentions could not be read.'), findsNothing);
+ });
+
+ /// [fake] with a second Swarm, whose mentions [read] answers.
+ void secondSwarm(
+ FakeSwarm fake,
+ FutureOr<Object?> Function(Map<String, dynamic>?) read,
+ ) {
+ const second = 'tab-2';
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ {'id': second, 'name': 'Other Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ const derived = {'mentionsWaiting': 1};
+ fake.routes['/api/super-tabs/$second/parts'] = (_) =>
+ firstLoad(tabId: second, derived: derived);
+ fake.routes['/api/super-tabs/$second/changes'] = (_) =>
+ changes(cursor: 'c2', derived: derived);
+ fake.routes['/api/super-tabs/$second/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$second/mentions?state=waiting'] = read;
+ }
+
+ testWidgets('one Swarm\'s mentions failing says so even with another '
+ 'Swarm\'s mention listed, and goes once it answers', (tester) async {
+ var fail = true;
+ final fake = backend(mentions: (_) => tagInWeb());
+ secondSwarm(fake, (_) {
+ if (fail) {
+ throw SuperTabFailure('BUSY', 'Busy', statusCode: 503);
+ }
+ return {'mentions': <Object>[]};
+ });
+ final store = MemoryKeyValueStore()
+ ..values['swarm_home.$me'] = jsonEncode({'filter': 'mentions'});
+ final host = await pump(tester, fake, store: store);
+ expect(project_(web), findsOneWidget);
+ expect(key('swarm-mentions-failed'), findsOneWidget);
+ expect(key('swarm-filter-show-all'), findsNothing);
+
+ fail = false;
+ await host.session!.inbox.asks('tab-2')!.load();
+ await tester.pumpAndSettle();
+ expect(project_(web), findsOneWidget);
+ expect(key('swarm-mentions-failed'), findsNothing);
+ });
+
+ testWidgets('a failed read of a Swarm then taken away does not keep '
+ 'saying so', (tester) async {
+ final fake = backend(mentions: (_) => tagInWeb());
+ secondSwarm(
+ fake,
+ (_) => throw SuperTabFailure('BUSY', 'Busy', statusCode: 503),
+ );
+ final store = MemoryKeyValueStore()
+ ..values['swarm_home.$me'] = jsonEncode({'filter': 'mentions'});
+ final host = await pump(tester, fake, store: store);
+ expect(key('swarm-mentions-failed'), findsOneWidget);
+
+ host.session!.inbox.reader('tab-2')!.revoke();
+ await tester.pump();
+ for (var i = 0; i < 10; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ expect(key('swarm-mentions-failed'), findsNothing);
+ });
+
+ testWidgets('a cold start with Mentions saved shows one skeleton, not '
+ 'two', (tester) async {
+ final parts = Completer<Object?>();
+ final answer = Completer<Object?>();
+ final fake = backend(mentions: (_) => answer.future);
+ final load = fake.routes['/api/super-tabs/$tab/parts']!;
+ fake.routes['/api/super-tabs/$tab/parts'] = (body) async {
+ await parts.future;
+ return load(body);
+ };
+ final store = MemoryKeyValueStore()
+ ..values['swarm_home.$me'] = jsonEncode({'filter': 'mentions'});
+ await pump(tester, fake, store: store, settle: false);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(key('swarm-mentions-loading'), findsNothing);
+ expect(find.byType(SwarmSkeletonRows), findsOneWidget);
+
+ parts.complete();
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(key('swarm-mentions-loading'), findsWidgets);
+ answer.complete({'mentions': <Object>[]});
+ await tester.pumpAndSettle();
+ });
+
+ testWidgets('a choice is still there after the app is opened again', (
+ tester,
+ ) async {
+ final store = MemoryKeyValueStore();
+ await pump(tester, backend(), store: store);
+ await open(tester);
+ await tapRow(tester, 'swarm-view-filter');
+ await tapRow(tester, 'swarm-view-filter-unread');
+ await close(tester);
+ await tester.pumpWidget(const SizedBox());
+
+ await pump(tester, backend(), store: store);
+ expect(dot(), findsOneWidget);
+ expect(project_(web), findsNothing);
+ expect(project_(project), findsOneWidget);
+ });
+
+ testWidgets('signed out with the menu open: it closes, and nothing is '
+ 'kept of a tap', (tester) async {
+ final account = ValueNotifier<String?>(me);
+ final store = MemoryKeyValueStore();
+ await pump(tester, backend(), signedIn: account, store: store);
+ await open(tester);
+ await tapRow(tester, 'swarm-view-filter');
+ expect(key('swarm-view-filter-unread'), findsOneWidget);
+
+ account.value = null;
+ await tester.pumpAndSettle();
+
+ expect(key('swarm-view-filter'), findsNothing);
+ expect(store.values['swarm_home.$me'] ?? '', isNot(contains('unread')));
+ });
+
+ testWidgets('another account signing in with the menu open: it closes, '
+ 'and the new account has its own defaults', (tester) async {
+ final account = ValueNotifier<String?>(me);
+ final host = await pump(tester, backend(), signedIn: account);
+ await open(tester);
+ final first = host.session!;
+ first.home.setFilter(SwarmHomeFilter.unread);
+ await tester.pump();
+
+ account.value = 'person-other';
+ await tester.pumpAndSettle();
+
+ expect(key('swarm-view-filter'), findsNothing);
+ expect(host.session, isNot(first));
+ expect(host.session!.home.filter, SwarmHomeFilter.all);
+ });
+
+ testWidgets('the last Swarm gone from the list with the menu open: it '
+ 'closes', (tester) async {
+ final fake = backend();
+ final host = await pump(tester, fake);
+ await open(tester);
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': <Object>[],
+ 'next': null,
+ };
+ await host.session!.inbox.refresh();
+ await tester.pumpAndSettle();
+ expect(key('swarm-view-filter'), findsNothing);
+ });
+
+ testWidgets('access revoked with a filter on and the menu open: the '
+ 'project rows go, and the menu shows nothing of the Swarm', (
+ tester,
+ ) async {
+ final host = await pump(tester, backend());
+ await open(tester);
+ await tapRow(tester, 'swarm-view-filter');
+ await tapRow(tester, 'swarm-view-filter-unread');
+ expect(project_(project), findsOneWidget);
+
+ host.session!.inbox.reader(tab)!.revoke();
+ await tester.pump();
+ for (var i = 0; i < 10; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ expect(project_(project), findsNothing);
+ expect(project_(web), findsNothing);
+ expect(find.text('Mobile'), findsNothing);
+ expect(find.text('Web'), findsNothing);
+ });
+
+ testWidgets('a Swarm id the account does not have changes nothing under a '
+ 'filter: no row of it, no name', (tester) async {
+ final host = await pump(tester, backend());
+ host.session!.home.setFilter(SwarmHomeFilter.unread);
+ await tester.pump();
+ host.session!.home.show('tab-other-not-listed');
+ await tester.pumpAndSettle();
+ expect(find.byType(SwarmHomeProjectRow), findsOneWidget);
+ expect(project_(project), findsOneWidget);
+ });
+
+ testWidgets('a tag in a private chat or a Buddy chat does not list its '
+ 'project under Mentions', (tester) async {
+ Map<String, dynamic> tagIn(String chat) => {
+ 'id': 'm-$chat',
+ 'projectId': web,
+ 'projectName': 'Web',
+ 'conversationId': chat,
+ 'conversationTitle': 'Secret title',
+ 'messageId': 'msg-$chat',
+ 'leadName': 'River',
+ 'text': 'private',
+ };
+ final fake = backend(
+ mentions: (_) => {
+ 'mentions': [tagIn('g-private'), tagIn('g-buddy')],
+ },
+ );
+ final load = fake.routes['/api/super-tabs/$tab/parts']!;
+ fake.routes['/api/super-tabs/$tab/parts'] = (body) async {
+ final read = await load(body) as Map<String, dynamic>;
+ return {
+ ...read,
+ 'groups': [
+ ...read['groups'] as List,
+ part('g-private', 90, {
+ ...groupData(
+ 'g-private',
+ title: 'Secret title',
+ audience: [me, 'ken'],
+ ),
+ 'projectId': web,
+ }),
+ part('g-buddy', 91, {
+ ...buddyChatData('g-buddy', owner: me),
+ 'projectId': web,
+ }),
+ ],
+ };
+ };
+ final store = MemoryKeyValueStore()
+ ..values['swarm_home.$me'] = jsonEncode({'filter': 'mentions'});
+ await pump(tester, fake, store: store);
+ expect(project_(web), findsNothing);
+ expect(find.text('No mentions.'), findsOneWidget);
+ expect(find.text('Secret title'), findsNothing);
+ });
+ });
+}
diff --git a/mobile/test/swarm/swarm_mark_all_test.dart b/mobile/test/swarm/swarm_mark_all_test.dart
index e42488c1c..38285191b 100644
--- a/mobile/test/swarm/swarm_mark_all_test.dart
+++ b/mobile/test/swarm/swarm_mark_all_test.dart
@@ -1,5 +1,4 @@
import 'dart:async';
-import 'dart:convert';
import 'package:fake_async/fake_async.dart';
import 'package:flutter/cupertino.dart' show CupertinoPageRoute;
@@ -9,7 +8,6 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/notify/system_notices.dart';
import 'package:harness_mobile/settings/experimental_features.dart';
import 'package:harness_mobile/swarm/swarm_chat_notify.dart';
-import 'package:harness_mobile/swarm/swarm_home_prefs.dart';
import 'package:harness_mobile/swarm/swarm_home_rows.dart';
import 'package:harness_mobile/swarm/swarm_mark_all.dart';
import 'package:harness_mobile/swarm/swarm_page.dart';
@@ -20,12 +18,11 @@ import 'package:harness_mobile/swarm/swarm_style.dart';
import '../voice_fakes.dart' show MemoryKeyValueStore;
import 'swarm_fixture.dart';
-/// Mark all read and the unread filter on the phone, as Desktop has them
+/// Mark all read on the phone, as Desktop has it
/// (#2453): every chat shown unread reads as read at once, and its mark goes
/// to the server only once 6 s pass without Undo, since read marks never
/// move back there. Leaving the app or closing the session is no Undo; access
-/// lost sends nothing. The filter lists only the projects with something
-/// unread, kept on this phone.
+/// lost sends nothing.
void main() {
const web = 'project-2';
const webLead = 'group-lead-web';
@@ -444,51 +441,6 @@ void main() {
});
});
- group('The unread filter', () {
- test('is kept on this phone and read back', () async {
- final store = MemoryKeyValueStore();
- final prefs = SwarmHomePrefs(accountId: me, store: store);
- await settle();
- prefs.toggleUnreadOnly();
- await settle();
- prefs.dispose();
-
- final again = SwarmHomePrefs(accountId: me, store: store);
- await settle();
- expect(again.unreadOnly, isTrue);
-
- again.toggleUnreadOnly();
- await settle();
- // Nothing else chosen: nothing left on the phone.
- expect(store.values['swarm_home.$me'], isNull);
- again.dispose();
- });
-
- test('what an older phone wrote reads with it off; turned on before '
- 'the choices are back, it stays on', () async {
- final store = MemoryKeyValueStore()
- ..values['swarm_home.$me'] = jsonEncode({
- 'pins': ['$tab/$project'],
- });
- final old = SwarmHomePrefs(accountId: me, store: store);
- await settle();
- expect(old.unreadOnly, isFalse);
- expect(old.pins, {'$tab/$project'});
- old.dispose();
-
- final early = SwarmHomePrefs(accountId: me, store: store)
- ..toggleUnreadOnly();
- await settle();
- expect(early.unreadOnly, isTrue);
- expect(early.pins, {'$tab/$project'});
- expect(
- jsonDecode(store.values['swarm_home.$me']!),
- containsPair('unread', true),
- );
- early.dispose();
- });
- });
-
group('Home', () {
Future<SwarmHost> pump(
WidgetTester tester,
@@ -535,45 +487,6 @@ void main() {
SwarmIconButton button(WidgetTester tester, String k) =>
tester.widget<SwarmIconButton>(key(k));
- testWidgets('the filter lists only projects with something unread, '
- 'and says so when none has, with Show all', (tester) async {
- await pump(tester, backend());
- expect(row(project), findsOneWidget);
- expect(row(web), findsOneWidget);
- expect(button(tester, 'swarm-unread-only').selected, isFalse);
-
- await tester.tap(key('swarm-unread-only'));
- await tester.pumpAndSettle();
-
- expect(row(project), findsOneWidget);
- expect(row(web), findsNothing);
- expect(button(tester, 'swarm-unread-only').selected, isTrue);
- expect(
- tester.getSemantics(key('swarm-unread-only')),
- matchesSemantics(
- label: 'Show all projects',
- isButton: true,
- hasEnabledState: true,
- isEnabled: true,
- hasToggledState: true,
- isToggled: true,
- hasTapAction: true,
- ),
- );
-
- await tester.tap(key('swarm-mark-all-read'));
- await tester.pumpAndSettle();
- expect(row(project), findsNothing);
- expect(key('swarm-unread-none'), findsOneWidget);
-
- await tester.tap(key('swarm-unread-show-all'));
- await tester.pumpAndSettle();
- expect(row(project), findsOneWidget);
- expect(row(web), findsOneWidget);
- expect(button(tester, 'swarm-unread-only').selected, isFalse);
- await tester.pump(const Duration(seconds: 7));
- });
-
testWidgets('Mark all read tells how many with Undo; Undo puts the bold '
'back and sends nothing, and with nothing unread it is greyed', (
tester,
diff --git a/mobile/test/swarm/swarm_project_status_shots_test.dart b/mobile/test/swarm/swarm_project_status_shots_test.dart
index e385e3c8e..a3400cb1b 100644
--- a/mobile/test/swarm/swarm_project_status_shots_test.dart
+++ b/mobile/test/swarm/swarm_project_status_shots_test.dart
@@ -18,11 +18,12 @@ import 'package:harness_mobile/terminal/terminal_font_store.dart';
import '../voice_fakes.dart';
import 'swarm_fixture.dart';
-/// Review screenshots of the project status card at the top of a project's
-/// chat (Tony 11-01, task 1): open, with the report and a decision waiting
-/// (none among the messages, Dee 11-01), then folded, then the Activity its
-/// "1 needs you" opens. On a 390-point phone in both phone themes, from made-up data
-/// only, to the folder `SWARM_PROJECT_STATUS_SHOTS` names.
+/// Review screenshots of the project status (Tony 11-02: the chat shows no
+/// box): the chat with none, the ⋮ menu with its Status row, the Status sheet
+/// it opens with the report and a decision waiting (none among the messages,
+/// Dee 11-01), then the Activity that decision opens. On a 390-point phone in
+/// both phone themes, from made-up data only, to the folder
+/// `SWARM_PROJECT_STATUS_SHOTS` names.
final shots = Platform.environment['SWARM_PROJECT_STATUS_SHOTS'];
void main() {
setUpAll(() async {
@@ -66,151 +67,161 @@ void main() {
}
});
- testWidgets('the status card open and folded, in both phone themes', (
- tester,
- ) async {
- addTearDown(tester.view.reset);
- debugDisableShadows = false;
- tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);
- addTearDown(tester.view.resetPadding);
- for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
- const size = Size(390, 844);
- tester.view
- ..physicalSize = size * 3
- ..devicePixelRatio = 3;
- final brightness = palette.brightness;
- AppTheme.palette.value = palette;
- AppTheme.brightness.value = brightness;
- final now = DateTime.now().toUtc();
- String ago(int minutes) =>
- now.subtract(Duration(minutes: minutes)).toIso8601String();
- Map<String, dynamic> said(String id, int sequence, String text) => {
- 'id': id,
- 'conversationId': leadChat,
- 'text': text,
- 'sequence': sequence,
- 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},
- 'createdAt': ago(40 - sequence * 4),
- };
- final fake = FakeSwarm();
- fake.routes['/api/super-tabs/list'] = (_) => {
- 'tabs': [
- {'id': tab, 'name': 'Autonomous', 'ownerId': me},
- ],
- 'next': null,
- };
- fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(
- head: headData(
- projects: [
- {
- 'id': project,
- 'name': 'openharness',
- 'ownerId': me,
- 'leadConversationId': leadChat,
- 'visibility': 'public',
- 'members': <Object>[],
- 'updateMinutes': 5,
- 'status': {
- 'text':
- 'Running: phone status card (Lark), Activity filters '
- '(Nova)\nWaiting on you: 1 decision\nDone today: #2459 '
- 'Swarm phone direct reads, #2460 signed chat files',
- 'at': ago(12),
+ testWidgets(
+ 'the chat without a status box, the menu and the Status sheet, in both phone themes',
+ (tester) async {
+ addTearDown(tester.view.reset);
+ debugDisableShadows = false;
+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);
+ addTearDown(tester.view.resetPadding);
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ const size = Size(390, 844);
+ tester.view
+ ..physicalSize = size * 3
+ ..devicePixelRatio = 3;
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ final now = DateTime.now().toUtc();
+ String ago(int minutes) =>
+ now.subtract(Duration(minutes: minutes)).toIso8601String();
+ Map<String, dynamic> said(String id, int sequence, String text) => {
+ 'id': id,
+ 'conversationId': leadChat,
+ 'text': text,
+ 'sequence': sequence,
+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},
+ 'createdAt': ago(40 - sequence * 4),
+ };
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Autonomous', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(
+ head: headData(
+ projects: [
+ {
+ 'id': project,
+ 'name': 'openharness',
+ 'ownerId': me,
+ 'leadConversationId': leadChat,
+ 'visibility': 'public',
+ 'members': <Object>[],
+ 'updateMinutes': 5,
+ 'status': {
+ 'text':
+ 'Running: phone status card (Lark), Activity filters '
+ '(Nova)\nWaiting on you: 1 decision\nDone today: #2459 '
+ 'Swarm phone direct reads, #2460 signed chat files',
+ 'at': ago(12),
+ },
},
+ ],
+ ),
+ derived: {'decisionsWaiting': 1},
+ );
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2', derived: {'decisionsWaiting': 1});
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': [
+ {
+ 'id': 'd1',
+ 'projectId': project,
+ 'projectName': 'openharness',
+ 'conversationId': leadChat,
+ 'conversationTitle': 'openharness',
+ 'askerName': 'River',
+ 'question': 'Show status by default on small phones?',
+ 'options': ['Yes', 'No'],
+ 'recommended': 1,
+ 'unblocks': 'The card',
+ 'createdAt': ago(5),
},
],
- ),
- derived: {'decisionsWaiting': 1},
- );
- fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
- changes(cursor: 'c2', derived: {'decisionsWaiting': 1});
- fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
- 'decisions': [
- {
- 'id': 'd1',
- 'projectId': project,
- 'projectName': 'openharness',
- 'conversationId': leadChat,
- 'conversationTitle': 'openharness',
- 'askerName': 'River',
- 'question': 'Fold the card by default on small phones?',
- 'options': ['Yes', 'No'],
- 'recommended': 1,
- 'unblocks': 'The card',
- 'createdAt': ago(5),
- },
- ],
- };
- fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
- 'mentions': <Object>[],
- };
- fake.routes['/api/super-tabs/$tab/conversations/'] = (_) => {
- 'messages': [
- said('m3', 3, 'Lark has the status card mockup up for Tony.'),
- said('m2', 2, 'CI on #2460 is green; merging.'),
- said('m1', 1, 'Morning all. Phone catch-up is today\'s focus.'),
- ],
- 'next': null,
- };
- final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
- ..value = {PhoneExperiment.swarm};
- final account = ValueNotifier<String?>(me);
- final host = SwarmHost(
- accountId: () => me,
- account: account,
- request: fake.request,
- notices: SilentSystemNotices(),
- features: features,
- readMarks: MemoryKeyValueStore(),
- )..foreground = false;
- final boundary = GlobalKey();
- await tester.pumpWidget(
- RepaintBoundary(
- key: boundary,
- child: MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: buildAppTheme(brightness: brightness),
- builder: (_, child) => SwarmScope(notifier: host, child: child!),
- home: const SwarmProjectPage(
- swarmId: tab,
- projectId: project,
- tabs: SwarmProjectTab.homeC,
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/conversations/'] = (_) => {
+ 'messages': [
+ said('m3', 3, 'Lark has the status card mockup up for Tony.'),
+ said('m2', 2, 'CI on #2460 is green; merging.'),
+ said('m1', 1, 'Morning all. Phone catch-up is today\'s focus.'),
+ ],
+ 'next': null,
+ };
+ final features = ExperimentalFeaturesStore(
+ storage: MemoryKeyValueStore(),
+ )..value = {PhoneExperiment.swarm};
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => me,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: features,
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmProjectPage(
+ swarmId: tab,
+ projectId: project,
+ tabs: SwarmProjectTab.homeC,
+ ),
),
),
- ),
- );
- await tester.pumpAndSettle();
- Future<void> capture(String name) => tester.runAsync(() async {
- final image =
- await (boundary.currentContext!.findRenderObject()!
- as RenderRepaintBoundary)
- .toImage(pixelRatio: 3);
- final png = await image.toByteData(format: ui.ImageByteFormat.png);
- await File('$shots/project-status-390-$name-${brightness.name}.png')
- .writeAsBytes(png!.buffer.asUint8List());
- image.dispose();
- });
- expect(
- find.byKey(const ValueKey('swarm-project-status-$project')),
- findsOneWidget,
- );
- // The decision is on the card, never among the messages.
- expect(find.byKey(const ValueKey('swarm-ask-d1')), findsNothing);
- await capture('open');
- await tester.tap(
- find.byKey(const ValueKey('swarm-project-status-fold-$project')),
- );
- await tester.pumpAndSettle();
- await capture('folded');
- // "1 needs you" opens Activity on this project, where it is answered.
- await tester.tap(
- find.byKey(ValueKey('swarm-project-status-needs-you-$project')),
- );
- await tester.pumpAndSettle();
- await capture('activity');
- await tester.pumpWidget(const SizedBox());
- host.dispose();
- }
- debugDisableShadows = true;
- }, skip: shots == null);
+ );
+ await tester.pumpAndSettle();
+ Future<void> capture(String name) => tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/project-status-390-$name-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ // No box over the chat, and no decision among its messages.
+ expect(
+ find.byKey(const ValueKey('swarm-project-status-$project')),
+ findsNothing,
+ );
+ expect(find.byKey(const ValueKey('swarm-ask-d1')), findsNothing);
+ await capture('chat');
+ await tester.tap(find.byKey(const ValueKey('swarm-project-menu')));
+ await tester.pumpAndSettle();
+ await capture('menu');
+ await tester.tap(
+ find.byKey(const ValueKey('swarm-project-menu-status')),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('swarm-project-status-$project')),
+ findsOneWidget,
+ );
+ await capture('status');
+ // The waiting decision opens Activity at it, where it is answered.
+ await tester.tap(
+ find.byKey(const ValueKey('swarm-project-status-need-decision:d1')),
+ );
+ await tester.pumpAndSettle();
+ await capture('activity');
+ await tester.pumpWidget(const SizedBox());
+ host.dispose();
+ }
+ debugDisableShadows = true;
+ },
+ skip: shots == null,
+ );
}
diff --git a/mobile/test/swarm/swarm_project_status_test.dart b/mobile/test/swarm/swarm_project_status_test.dart
index 4e00f7442..9eca5e747 100644
--- a/mobile/test/swarm/swarm_project_status_test.dart
+++ b/mobile/test/swarm/swarm_project_status_test.dart
@@ -7,24 +7,31 @@ import 'package:harness_mobile/core/local_key_value_store.dart';
import 'package:harness_mobile/notify/system_notices.dart';
import 'package:harness_mobile/settings/experimental_features.dart';
import 'package:harness_mobile/swarm/swarm_activity_page.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/parts.dart';
+import 'package:harness_mobile/swarm/swarm_home_cache.dart';
import 'package:harness_mobile/swarm/swarm_home_prefs.dart';
+import 'package:harness_mobile/swarm/swarm_page.dart';
import 'package:harness_mobile/swarm/swarm_project_page.dart';
import 'package:harness_mobile/swarm/swarm_project_status.dart';
import 'package:harness_mobile/swarm/swarm_project_tabs.dart';
import 'package:harness_mobile/swarm/swarm_request.dart';
import 'package:harness_mobile/swarm/swarm_session.dart';
+import 'package:harness_mobile/swarm/waiting_work.dart';
import '../voice_fakes.dart';
-import 'swarm_activity_fixture.dart' show activityMessage;
import 'swarm_fixture.dart';
-/// The project status card at the top of a project's chat (Tony 11-01, task
-/// 1), as the desktop draws it (project_status_card.dart): the coordinator's
-/// last report and the decisions in this project waiting on the person.
+/// The project's status (Tony 11-01, task 1; moved 11-02): the coordinator's
+/// last report and the decisions in this project waiting on the person, in the
+/// sheet the project menu's Status row opens. The chat itself shows no box.
void main() {
const other = 'project-2', otherChat = 'group-lead-2';
const today = '2026-11-01T09:52:00.000Z';
+ /// The signed-in account of the host last pumped.
+ late ValueNotifier<String?> account;
+
Map<String, dynamic> projectData(
String id,
String chat, {
@@ -53,7 +60,7 @@ void main() {
String id, {
String projectId = project,
String chat = leadChat,
- String question = 'Fold the card by default?',
+ String question = 'Show status by default?',
}) => {
'id': id,
'projectId': projectId,
@@ -125,7 +132,7 @@ void main() {
}) async {
final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
..value = {PhoneExperiment.swarm};
- final account = ValueNotifier<String?>(me);
+ account = ValueNotifier<String?>(me);
final host = SwarmHost(
accountId: () => account.value,
account: account,
@@ -153,34 +160,81 @@ void main() {
Finder key(String value) => find.byKey(ValueKey(value));
final card = key('swarm-project-status-$project');
+ final empty = key('swarm-project-status-empty-$project');
final heading = key('swarm-project-status-heading-$project');
- final fold = key('swarm-project-status-fold-$project');
- final needsYou = key('swarm-project-status-needs-you-$project');
-
- /// The heading as read: Status, when, and how many wait while folded.
- String headingText(WidgetTester tester) => [
- tester.widget<Text>(heading).textSpan!.toPlainText(),
- if (tester.any(needsYou))
- tester
- .widget<Text>(
- find.descendant(of: needsYou, matching: find.byType(Text)),
- )
- .data!,
- ].join();
+ final menu = key('swarm-project-menu');
+ final statusRow = key('swarm-project-menu-status');
+ final sheet = key('swarm-status-close');
- group('states', () {
- testWidgets('empty: no report and nothing waiting draws no card', (
- tester,
- ) async {
- await pump(tester, backend());
+ /// ⋮, then Status.
+ Future<void> openStatus(WidgetTester tester) async {
+ await tester.tap(menu);
+ await tester.pumpAndSettle();
+ await tester.tap(statusRow);
+ await tester.pumpAndSettle();
+ }
+
+ Future<SwarmHost> pumpStatus(WidgetTester tester, FakeSwarm fake) async {
+ final session = await pump(tester, fake);
+ await openStatus(tester);
+ return session;
+ }
+
+ group('the chat', () {
+ testWidgets('shows no status box, whatever the project reported or '
+ 'waits on', (tester) async {
+ await pump(
+ tester,
+ backend(
+ status: {'text': 'Running: phone status', 'at': today},
+ decisions: [decision('d1')],
+ ),
+ );
+ expect(key('swarm-project-chat-$leadChat'), findsOneWidget);
+ expect(card, findsNothing);
+ expect(heading, findsNothing);
+ expect(find.text('Running: phone status'), findsNothing);
+ expect(find.text('River asks you'), findsNothing);
+ expect(find.text('Status'), findsNothing);
+ });
+
+ testWidgets('keeps its status one tap into ⋮: a Status row that opens it, '
+ 'closing returns to the chat', (tester) async {
+ await pump(
+ tester,
+ backend(status: {'text': 'Running: phone status', 'at': today}),
+ );
+ await tester.tap(menu);
+ await tester.pumpAndSettle();
+ expect(statusRow, findsOneWidget);
+ expect(
+ find.descendant(of: statusRow, matching: find.text('Status')),
+ findsOneWidget,
+ );
+ await tester.tap(statusRow);
+ await tester.pumpAndSettle();
+ expect(sheet, findsOneWidget);
+ expect(find.text('Running: phone status'), findsOneWidget);
+ expect(tester.widget<Text>(heading).data, startsWith('updated '));
+
+ await tester.tap(sheet);
+ await tester.pumpAndSettle();
+ expect(sheet, findsNothing);
expect(key('swarm-project-chat-$leadChat'), findsOneWidget);
+ });
+ });
+
+ group('states', () {
+ testWidgets('empty: no report and nothing waiting says so', (tester) async {
+ await pumpStatus(tester, backend());
expect(card, findsNothing);
+ expect(empty, findsOneWidget);
});
- testWidgets('running: the report word for word under Status · updated', (
+ testWidgets('running: the report word for word under updated', (
tester,
) async {
- await pump(
+ await pumpStatus(
tester,
backend(
status: {
@@ -190,7 +244,7 @@ void main() {
),
);
expect(card, findsOneWidget);
- expect(headingText(tester), startsWith('Status · updated '));
+ expect(tester.widget<Text>(heading).data, startsWith('updated '));
expect(
find.text('Running: phone status card\nDone today: #2459'),
findsOneWidget,
@@ -200,9 +254,9 @@ void main() {
testWidgets('needs you: a decision here, with no report, still shows; a '
'tap opens Activity at it', (tester) async {
- await pump(tester, backend(decisions: [decision('d1')]));
+ await pumpStatus(tester, backend(decisions: [decision('d1')]));
expect(card, findsOneWidget);
- expect(headingText(tester), 'Status');
+ expect(heading, findsNothing);
final row = key('swarm-project-status-need-decision:d1');
expect(row, findsOneWidget);
expect(
@@ -212,7 +266,7 @@ void main() {
expect(
find.descendant(
of: row,
- matching: find.text('Fold the card by default?'),
+ matching: find.text('Show status by default?'),
),
findsOneWidget,
);
@@ -227,7 +281,7 @@ void main() {
testWidgets('done and waiting: the report, then each decision, newest '
'first as Activity orders them', (tester) async {
- await pump(
+ await pumpStatus(
tester,
backend(
status: {'text': 'Done today: #2459, #2460', 'at': today},
@@ -251,123 +305,40 @@ void main() {
expect(d2.dy, lessThan(d1.dy));
});
- testWidgets('long text scrolls inside the card, which never grows past '
- 'its limit', (tester) async {
- final fake = backend(status: {'text': 'Short', 'at': today});
- await pump(tester, fake);
- final shortCard = tester.getSize(card).height;
-
- final long = List.generate(60, (i) => 'Line $i of the report').join('\n');
- fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
- statusChange({'text': long, 'at': today});
- await host(tester).inbox.reader(tab)!.refresh();
- await tester.pumpAndSettle();
-
- final longCard = tester.getSize(card).height;
- expect(longCard, greaterThan(shortCard));
- expect(
- longCard,
- lessThanOrEqualTo(SwarmProjectStatusCard.maxBody + 44 + 8 + 2),
- );
- final body = key('swarm-project-status-body-$project');
+ testWidgets('a long report scrolls inside the sheet, which keeps its '
+ 'height', (tester) async {
+ final long = List.generate(80, (i) => 'Line $i of the report').join('\n');
+ await pumpStatus(tester, backend(status: {'text': long, 'at': today}));
final scrollable = find.descendant(
- of: body,
+ of: card,
matching: find.byType(Scrollable),
);
expect(
tester.state<ScrollableState>(scrollable).position.maxScrollExtent,
greaterThan(0),
);
+ expect(
+ tester.getSize(card).height,
+ lessThan(
+ tester.view.physicalSize.height / tester.view.devicePixelRatio,
+ ),
+ );
});
});
- testWidgets('the card takes its room from the chat alone: folding it gives '
- 'the chat exactly what the card gave up, and the composer stays put', (
- tester,
- ) async {
- final long = List.generate(30, (i) => 'Line $i of the report').join('\n');
- final fake = backend(
- status: {'text': long, 'at': today},
- decisions: [decision('d1')],
- );
- // A message, so the chat has its list: decisions are not in it.
- fake.routes['/api/super-tabs/$tab/conversations/'] = (_) => {
- 'messages': [activityMessage('m1', 1)],
- 'next': null,
- };
- await pump(tester, fake);
- final chat = key('swarm-messages');
- final composer = find.byType(EditableText);
- final openCard = tester.getSize(card).height;
- final openChat = tester.getSize(chat).height;
- final openComposer = tester.getTopLeft(composer).dy;
-
- await tester.tap(fold);
- await tester.pumpAndSettle();
- final foldedCard = tester.getSize(card).height;
- final foldedChat = tester.getSize(chat).height;
-
- expect(openCard - foldedCard, greaterThan(100));
- expect(foldedChat - openChat, moreOrLessEquals(openCard - foldedCard));
- expect(tester.getTopLeft(composer).dy, openComposer);
- });
-
- testWidgets('on a 320-point phone a one-line report leaves its room to the '
- 'decisions: at least two of three show in full', (tester) async {
- tester.view
- ..physicalSize = const Size(320, 568) * 3
- ..devicePixelRatio = 3;
- addTearDown(tester.view.reset);
- await pump(
- tester,
- backend(
- status: {'text': 'Building the card', 'at': today},
- decisions: [
- for (final (i, at) in ['09:10', '09:20', '09:30'].indexed)
- {
- ...decision('d$i', question: 'Question $i?'),
- 'createdAt': '2026-11-01T$at:00.000Z',
- },
- ],
- ),
- );
- final box = tester.getRect(card);
- final shown = [
- for (final i in [0, 1, 2])
- if (tester.getRect(key('swarm-project-status-need-decision:d$i'))
- case final row when row.top >= box.top && row.bottom <= box.bottom)
- i,
- ];
- expect(shown.length, greaterThanOrEqualTo(2));
- expect(find.text('Building the card'), findsOneWidget);
- });
-
- testWidgets('a long report never hides what waits: the decision shows in '
- 'full inside the card', (tester) async {
- final long = List.generate(30, (i) => 'Line $i of the report').join('\n');
- await pump(
- tester,
- backend(status: {'text': long, 'at': today}, decisions: [decision('d1')]),
- );
- final row = tester.getRect(key('swarm-project-status-need-decision:d1'));
- final box = tester.getRect(card);
- expect(row.top, greaterThanOrEqualTo(box.top));
- expect(row.bottom, lessThanOrEqualTo(box.bottom));
- expect(row.height, greaterThanOrEqualTo(56));
- });
-
group('arrives late, fails, recovers', () {
testWidgets('a report that arrives with a later read shows then, in place '
'of none, and a newer one replaces it', (tester) async {
final fake = backend();
- final host = await pump(tester, fake);
- expect(card, findsNothing);
+ final host = await pumpStatus(tester, fake);
+ expect(empty, findsOneWidget);
fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
statusChange({'text': 'Building the card', 'at': today});
await host.session!.inbox.reader(tab)!.refresh();
await tester.pumpAndSettle();
expect(find.text('Building the card'), findsOneWidget);
+ expect(empty, findsNothing);
fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
statusChange({'text': 'Card shipped', 'at': today}, version: 3);
@@ -377,19 +348,22 @@ void main() {
expect(find.text('Building the card'), findsNothing);
});
- testWidgets('a first read that fails shows no card and no endless '
- 'loading; the read that recovers brings the card', (tester) async {
+ testWidgets('a first read that fails shows no menu and no endless '
+ 'loading; the read that recovers brings the Status row', (
+ tester,
+ ) async {
final fake = backend(status: {'text': 'Building', 'at': today});
final parts = fake.routes['/api/super-tabs/$tab/parts']!;
fake.routes['/api/super-tabs/$tab/parts'] = (_) =>
throw const SuperTabFailure('UNAVAILABLE', 'Down.', statusCode: 503);
final host = await pump(tester, fake);
- expect(card, findsNothing);
+ expect(menu, findsNothing);
expect(find.text('Down.'), findsOneWidget);
fake.routes['/api/super-tabs/$tab/parts'] = parts;
await host.session!.inbox.reader(tab)!.refresh();
await tester.pumpAndSettle();
+ await openStatus(tester);
expect(find.text('Building'), findsOneWidget);
});
@@ -402,7 +376,7 @@ void main() {
final open = fake.routes['/api/super-tabs/$tab/decisions?state=open']!;
fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) =>
throw const SuperTabFailure('UNAVAILABLE', 'Down.', statusCode: 503);
- final host = await pump(tester, fake);
+ final host = await pumpStatus(tester, fake);
expect(find.text('Building'), findsOneWidget);
expect(key('swarm-project-status-need-decision:d1'), findsNothing);
@@ -413,12 +387,131 @@ void main() {
});
});
+ group('cold start, on the Home kept', () {
+ final updating = key('swarm-project-status-updating-$project');
+ final failed = key('swarm-project-status-error-$project');
+
+ /// The phone opens on the Home kept, which holds neither report nor
+ /// decisions; the Swarm's read is [parts], the list's is [list].
+ Future<SwarmHost> coldStatus(
+ WidgetTester tester,
+ FakeSwarm fake, {
+ FutureOr<Object?> Function(Map<String, dynamic>? body)? list,
+ }) async {
+ final cache = memoryHomeCache();
+ final state = SuperTabParts.firstLoad(firstLoad(head: head())).state;
+ await tester.runAsync(
+ () => cache.write(me, [
+ (
+ id: tab,
+ name: 'Phone Swarm',
+ view: swarmHomeSwarm(
+ SuperTabSnapshot.fromJson(state),
+ swarmPartners(state),
+ ),
+ ),
+ ]),
+ );
+ // No computer answers the list, as on a cold start in a tunnel.
+ fake.routes['/api/super-tabs/list'] =
+ list ?? (_) => Completer<Object?>().future;
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
+ account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: features,
+ homeCache: cache,
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) =>
+ SwarmScope(notifier: host, child: child!),
+ home: const SwarmPage(),
+ ),
+ );
+ for (var i = 0; i < 100 && host.session!.inbox.swarms.isEmpty; i++) {
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 10)),
+ );
+ await tester.pump();
+ }
+ await tester.pump();
+ // Opened from the Home kept, as the phone does on a cold start.
+ await tester.tap(key('swarm-project-$tab-$project'));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 500));
+ return host;
+ }
+
+ testWidgets('while the Swarm is still being read, Status says Updating… '
+ 'and never "Nothing to report"; the report replaces it', (
+ tester,
+ ) async {
+ final fake = backend(
+ status: {'text': 'Report on the server', 'at': today},
+ );
+ final read = Completer<Object?>();
+ final parts = fake.routes['/api/super-tabs/$tab/parts']!;
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => read.future;
+ await coldStatus(tester, fake);
+ await openStatus(tester);
+ expect(updating, findsOneWidget);
+ expect(empty, findsNothing);
+ expect(find.text('Nothing to report yet.'), findsNothing);
+
+ read.complete(parts(null));
+ await tester.pumpAndSettle();
+ expect(find.text('Report on the server'), findsOneWidget);
+ expect(updating, findsNothing);
+ });
+
+ testWidgets('when the read fails, Status says so and never "Nothing to '
+ 'report"; the read that recovers brings the report', (tester) async {
+ final fake = backend(
+ status: {'text': 'Report on the server', 'at': today},
+ );
+ final parts = fake.routes['/api/super-tabs/$tab/parts']!;
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) =>
+ throw const SuperTabFailure('UNAVAILABLE', 'Down.', statusCode: 503);
+ final host = await coldStatus(tester, fake);
+ await openStatus(tester);
+ await tester.pumpAndSettle();
+ expect(empty, findsNothing);
+ expect(find.text('Nothing to report yet.'), findsNothing);
+ expect(failed, findsOneWidget);
+ expect(find.text('Down.'), findsOneWidget);
+
+ fake.routes['/api/super-tabs/$tab/parts'] = parts;
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ expect(find.text('Report on the server'), findsOneWidget);
+ expect(failed, findsNothing);
+ });
+
+ testWidgets('a report that read fine with decisions that fail to load '
+ 'says so, not "Nothing to report"', (tester) async {
+ final fake = backend(decisions: [decision('d1')]);
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) =>
+ throw const SuperTabFailure('UNAVAILABLE', 'Down.', statusCode: 503);
+ await pumpStatus(tester, fake);
+ await tester.pumpAndSettle();
+ expect(empty, findsNothing);
+ expect(find.text('Nothing to report yet.'), findsNothing);
+ });
+ });
+
group('privacy', () {
testWidgets('a decision from another project, or from a chat of this '
'project the person does not read, never shows, nor its title', (
tester,
) async {
- await pump(
+ await pumpStatus(
tester,
backend(
decisions: [
@@ -434,38 +527,41 @@ void main() {
),
);
expect(card, findsNothing);
+ expect(empty, findsOneWidget);
expect(find.textContaining('Secret title'), findsNothing);
expect(find.text('River asks you'), findsNothing);
});
- testWidgets('a private project the person is not a member of shows no '
- 'card, as the server reads it; made a member, it shows', (
- tester,
- ) async {
- Map<String, dynamic> privateHead({required bool member}) => headData(
- projects: [
- {
- ...projectData(
- project,
- leadChat,
- status: {'text': 'Private plans', 'at': today},
- ),
- 'ownerId': 'diego',
- 'visibility': 'private',
- 'members': [
- if (member) {'id': me, 'generation': 'gen-$me'},
- ],
- },
- projectData(other, otherChat),
- ],
- );
+ Map<String, dynamic> privateHead({required bool member}) => headData(
+ projects: [
+ {
+ ...projectData(
+ project,
+ leadChat,
+ status: {'text': 'Private plans', 'at': today},
+ ),
+ 'ownerId': 'diego',
+ 'visibility': 'private',
+ 'members': [
+ if (member) {'id': me, 'generation': 'gen-$me'},
+ ],
+ },
+ projectData(other, otherChat),
+ ],
+ );
+
+ testWidgets('a private project the person is not a member of shows '
+ 'nothing in Status, as the server reads it; made a member, it '
+ 'shows', (tester) async {
final fake = backend(decisions: [decision('d1')]);
fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(
head: privateHead(member: false),
derived: {'decisionsWaiting': 1},
);
final host = await pump(tester, fake);
- expect(key('swarm-project-chat-$leadChat'), findsOneWidget);
+ // The sheet is taken down as it opens: nothing of the project shows.
+ await openStatus(tester);
+ expect(sheet, findsNothing);
expect(card, findsNothing);
expect(find.text('Private plans'), findsNothing);
expect(find.text('River asks you'), findsNothing);
@@ -480,12 +576,37 @@ void main() {
};
await host.session!.inbox.reader(tab)!.refresh();
await tester.pumpAndSettle();
+ await openStatus(tester);
expect(find.text('Private plans'), findsOneWidget);
});
- testWidgets('access lost while the card is open takes it away, with what '
- 'it held', (tester) async {
- final host = await pump(
+ testWidgets('a project made private to others while Status is open '
+ 'closes it, with what it held', (tester) async {
+ final fake = backend(
+ status: {'text': 'Private plans', 'at': today},
+ decisions: [decision('d1')],
+ );
+ final host = await pumpStatus(tester, fake);
+ expect(find.text('Private plans'), findsOneWidget);
+
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {
+ ...changes(
+ cursor: 'c2',
+ lastChangedAt: 102,
+ derived: {'decisionsWaiting': 1},
+ ),
+ 'head': part('head', 2, privateHead(member: false)),
+ };
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ expect(sheet, findsNothing);
+ expect(find.text('Private plans'), findsNothing);
+ expect(find.text('River asks you'), findsNothing);
+ });
+
+ testWidgets('access lost while Status is open closes it, with what it '
+ 'held', (tester) async {
+ final host = await pumpStatus(
tester,
backend(
status: {'text': 'Building', 'at': today},
@@ -495,16 +616,17 @@ void main() {
expect(find.text('Building'), findsOneWidget);
host.session!.inbox.reader(tab)!.revoke();
await tester.pumpAndSettle();
+ expect(sheet, findsNothing);
expect(card, findsNothing);
expect(find.text('Building'), findsNothing);
expect(find.text('River asks you'), findsNothing);
});
- testWidgets('a project taken away by a later read takes its card with it', (
+ testWidgets('a project taken away by a later read closes its Status', (
tester,
) async {
final fake = backend(status: {'text': 'Building', 'at': today});
- final host = await pump(tester, fake);
+ final host = await pumpStatus(tester, fake);
expect(card, findsOneWidget);
fake.routes['/api/super-tabs/$tab/changes'] = (_) => {
...changes(cursor: 'c2', lastChangedAt: 102),
@@ -516,10 +638,23 @@ void main() {
};
await host.session!.inbox.reader(tab)!.refresh();
await tester.pumpAndSettle();
+ expect(sheet, findsNothing);
expect(card, findsNothing);
expect(find.text('Building'), findsNothing);
});
+ testWidgets('signing out while Status is open closes it', (tester) async {
+ await pumpStatus(
+ tester,
+ backend(status: {'text': 'Building', 'at': today}),
+ );
+ expect(find.text('Building'), findsOneWidget);
+ account.value = null;
+ await tester.pumpAndSettle();
+ expect(sheet, findsNothing);
+ expect(find.text('Building'), findsNothing);
+ });
+
testWidgets('decisions read before access was lost, answered after, are '
'never drawn', (tester) async {
final fake = backend(
@@ -529,7 +664,7 @@ void main() {
final held = Completer<Object?>();
fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) =>
held.future;
- final host = await pump(tester, fake);
+ final host = await pumpStatus(tester, fake);
expect(find.text('Building'), findsOneWidget);
host.session!.inbox.reader(tab)!.revoke();
await tester.pump();
@@ -540,95 +675,35 @@ void main() {
expect(card, findsNothing);
expect(find.text('River asks you'), findsNothing);
});
- });
-
- group('fold', () {
- testWidgets('folds to its heading, which still says what waits, and stays '
- 'folded when the project opens again', (tester) async {
- final marks = MemoryKeyValueStore();
- final fake = backend(
- status: {'text': 'Building', 'at': today},
- decisions: [decision('d1')],
- );
- await pump(tester, fake, marks: marks);
- expect(find.text('Building'), findsOneWidget);
-
- await tester.tap(fold);
- await tester.pumpAndSettle();
- expect(find.text('Building'), findsNothing);
- expect(key('swarm-project-status-need-decision:d1'), findsNothing);
- expect(headingText(tester), endsWith(' · 1 needs you'));
-
- // Opened again, with the same phone's store.
- await tester.pumpWidget(const SizedBox());
- await pump(tester, fake, marks: marks);
- expect(card, findsOneWidget);
- expect(find.text('Building'), findsNothing);
- await tester.tap(fold);
- await tester.pumpAndSettle();
- expect(find.text('Building'), findsOneWidget);
- });
- testWidgets('a report that arrives while folded changes only the heading: '
- 'the card keeps its height, so the chat does not jump', (tester) async {
- final fake = backend(status: {'text': 'Building', 'at': today});
- final host = await pump(tester, fake);
- await tester.tap(fold);
- await tester.pumpAndSettle();
- final height = tester.getSize(card).height;
- final composer = tester.getTopLeft(find.byType(EditableText)).dy;
- final before = headingText(tester);
-
- fake.routes['/api/super-tabs/$tab/changes'] = (_) => statusChange({
- 'text': List.filled(40, 'A much longer report').join('\n'),
- 'at': '2026-11-01T10:07:00.000Z',
- });
- await host.session!.inbox.reader(tab)!.refresh();
- await tester.pumpAndSettle();
- expect(find.textContaining('A much longer report'), findsNothing);
- expect(headingText(tester), isNot(before));
- expect(tester.getSize(card).height, height);
- expect(tester.getTopLeft(find.byType(EditableText)).dy, composer);
- });
-
- testWidgets('folds while the keyboard is up, so it never pushes the '
- 'composer, and opens again when it goes', (tester) async {
- await pump(tester, backend(status: {'text': 'Building', 'at': today}));
- expect(find.text('Building'), findsOneWidget);
- tester.view.viewInsets = const FakeViewPadding(bottom: 900);
- addTearDown(tester.view.resetViewInsets);
- await tester.pumpAndSettle();
- expect(card, findsOneWidget);
- expect(find.text('Building'), findsNothing);
- tester.view.resetViewInsets();
- await tester.pumpAndSettle();
- expect(find.text('Building'), findsOneWidget);
- });
-
- testWidgets('while the keyboard folds it there is no fold button, so no '
- 'tap saves a fold the person never saw', (tester) async {
- final host = await pump(
- tester,
- backend(status: {'text': 'Building', 'at': today}),
+ testWidgets('a Status opened for one project never shows another '
+ "project's report under the same Lead", (tester) async {
+ final fake = backend(status: {'text': 'Mobile report', 'at': today});
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(
+ head: headData(
+ projects: [
+ projectData(
+ project,
+ leadChat,
+ status: {'text': 'Mobile report', 'at': today},
+ ),
+ projectData(
+ other,
+ otherChat,
+ status: {'text': 'Backend secrets', 'at': today},
+ ),
+ ],
+ ),
+ groups: [
+ {
+ ...groupData(otherChat, title: 'Backend', agentIds: ['agent-lead']),
+ 'projectId': other,
+ },
+ ],
);
- tester.view.viewInsets = const FakeViewPadding(bottom: 900);
- addTearDown(tester.view.resetViewInsets);
- await tester.pumpAndSettle();
- expect(fold, findsNothing);
- final byKeyboard = tester.getSize(card).height;
- expect(host.session!.home.folded(tab, project), isFalse);
-
- // Folded by the person, then the keyboard: still no button.
- tester.view.resetViewInsets();
- await tester.pumpAndSettle();
- await tester.tap(fold);
- await tester.pumpAndSettle();
- // Folded either way, the card is as tall: no jump as the button goes.
- expect(tester.getSize(card).height, byKeyboard);
- tester.view.viewInsets = const FakeViewPadding(bottom: 900);
- await tester.pumpAndSettle();
- expect(fold, findsNothing);
- expect(host.session!.home.folded(tab, project), isTrue);
+ await pumpStatus(tester, fake);
+ expect(find.text('Mobile report'), findsOneWidget);
+ expect(find.text('Backend secrets'), findsNothing);
});
});
@@ -642,7 +717,7 @@ void main() {
return true;
};
addTearDown(() => swarmOpenStatusLink = was);
- await pump(
+ await pumpStatus(
tester,
backend(
status: {
@@ -753,7 +828,7 @@ void main() {
});
});
- group('Activity from the card', () {
+ group('Activity from Status', () {
/// River asks the same question in both projects: one decision in
/// Mobile's chat, one in Backend's.
List<Map<String, dynamic>> both() => [
@@ -787,7 +862,7 @@ void main() {
}
testWidgets('the project chat with open decisions shows none among its '
- 'messages; the card holds them', (tester) async {
+ 'messages; Status holds them', (tester) async {
await pump(
tester,
backend(
@@ -795,35 +870,18 @@ void main() {
decisions: [decision('d1')],
),
);
- expect(key('swarm-project-status-need-decision:d1'), findsOneWidget);
+ expect(key('swarm-project-status-need-decision:d1'), findsNothing);
expect(key('swarm-ask-d1'), findsNothing);
expect(key('swarm-option-d1-0'), findsNothing);
- });
-
- testWidgets('folded, "N need you" is a tap target that opens Activity on '
- 'this project alone', (tester) async {
- await pump(
- tester,
- backend(status: {'text': 'Building', 'at': today}, decisions: both()),
- );
- await tester.tap(fold);
- await tester.pumpAndSettle();
- expect(needsYou, findsOneWidget);
- expect(tester.getSize(needsYou).height, greaterThanOrEqualTo(44));
-
- await tester.tap(needsYou);
- await tester.pumpAndSettle();
- expect(
- tester.widget<SwarmActivityPage>(find.byType(SwarmActivityPage)).focus,
- isNull,
- );
- expectMobileOnly(tester);
+ await openStatus(tester);
+ expect(key('swarm-project-status-need-decision:d1'), findsOneWidget);
+ expect(key('swarm-ask-d1'), findsNothing);
});
testWidgets('a waiting line opens Activity at it, on this project alone', (
tester,
) async {
- await pump(tester, backend(decisions: both()));
+ await pumpStatus(tester, backend(decisions: both()));
await tester.tap(key('swarm-project-status-need-decision:d1'));
await tester.pumpAndSettle();
@@ -831,9 +889,7 @@ void main() {
expectMobileOnly(tester);
});
- testWidgets("answering in Activity takes it off the card's count", (
- tester,
- ) async {
+ testWidgets('answering in Activity takes it off Status', (tester) async {
final fake = backend(
status: {'text': 'Building', 'at': today},
decisions: both(),
@@ -841,15 +897,11 @@ void main() {
fake.routes['/api/super-tabs/$tab/commands'] = (_) => {
'result': <String, dynamic>{},
};
- await pump(tester, fake);
+ await pumpStatus(tester, fake);
final session = host(tester);
- await tester.tap(fold);
- await tester.pumpAndSettle();
- expect(headingText(tester), endsWith(' · 1 needs you'));
+ expect(key('swarm-project-status-need-decision:d1'), findsOneWidget);
- await tester.tap(needsYou);
- await tester.pumpAndSettle();
- await tester.tap(key('swarm-activity-row-decision:d1'));
+ await tester.tap(key('swarm-project-status-need-decision:d1'));
await tester.pumpAndSettle();
await tester.tap(key('swarm-option-d1-0'));
await tester.pump(const Duration(seconds: 10));
@@ -875,23 +927,22 @@ void main() {
await tester.tap(find.byKey(const ValueKey('tty-back')).first);
await tester.pumpAndSettle();
expect(find.byType(SwarmActivityPage), findsNothing);
+ expect(key('swarm-project-status-need-decision:d1'), findsNothing);
expect(card, findsOneWidget);
- expect(needsYou, findsNothing);
- expect(headingText(tester), isNot(contains('need')));
});
testWidgets('access lost while its Activity is open: the rows and the '
"project's name go, nothing stuck loading", (tester) async {
- await pump(tester, backend(decisions: both()));
+ await pumpStatus(tester, backend(decisions: both()));
final session = host(tester);
await tester.tap(key('swarm-project-status-need-decision:d1'));
await tester.pumpAndSettle();
- expect(find.text('Fold the card by default?'), findsWidgets);
+ expect(find.text('Show status by default?'), findsWidgets);
session.inbox.reader(tab)!.revoke();
await tester.pumpAndSettle();
expect(find.text('#Mobile'), findsNothing);
- expect(find.text('Fold the card by default?'), findsNothing);
+ expect(find.text('Show status by default?'), findsNothing);
expect(find.textContaining('River'), findsNothing);
expect(key('swarm-activity-loading'), findsNothing);
});
@@ -899,7 +950,7 @@ void main() {
testWidgets('the project made private to others while its Activity is '
'open: its rows and name go', (tester) async {
final fake = backend(decisions: both());
- await pump(tester, fake);
+ await pumpStatus(tester, fake);
final session = host(tester);
await tester.tap(key('swarm-project-status-need-decision:d1'));
await tester.pumpAndSettle();
@@ -931,7 +982,7 @@ void main() {
expect(find.text('#Mobile'), findsNothing);
expect(key('swarm-activity-open-decision:d1'), findsNothing);
expect(key('swarm-activity-row-decision:other'), findsNothing);
- expect(find.text('Fold the card by default?'), findsNothing);
+ expect(find.text('Show status by default?'), findsNothing);
});
});
}