The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-04 b1030: #2857 #2858 #2859 #2888 #2889 #2890 #2895 (#2902)
0xken15e8b4a3cc1cf8
diff --git a/backend/integration/superTabCacheDelta.test.ts b/backend/integration/superTabCacheDelta.test.tsindex 498f4346e..bf8111e9b 100644--- a/backend/integration/superTabCacheDelta.test.ts+++ b/backend/integration/superTabCacheDelta.test.ts@@ -161,6 +161,32 @@ describe('the patched cache answers as reads with no cache do', () => {expect(delta.mock.calls.length).toBeGreaterThan(30)})+ it('a host state reads its agents\' quiet conversations light, as the host rows read them (B4, #2597)', async () => {+ const { tabId } = await scene()+ // A quiet conversation of an agent on the host, with the brief and checks a whole read would carry.+ const all = await parts.loadAll(db, tabId)+ const agent = liveOf(all.agents).find(a => (a.data as { machineId: string }).machineId === 'host')!.key+ const quiet = liveOf(all.groups).find(g => g.key !== 'lead' && g.data!.agentIds.includes(agent))!+ expect(await write(tabId, () => ({ op: 'update', kind: 'group', key: quiet.key, seen: quiet.version,+ data: { ...quiet.data!, dormant: true, brief: 'b'.repeat(20_000), checks: [{ id: 'c1', description: 'd'.repeat(5_000), independent: false, status: 'pending' }] } }))).toBe(true)+ const cache = new SwarmCache(stamps, { delta: readDelta(db) })+ await db.$runCommandRaw({ profile: 2 })+ const since = new Date()+ let state: Awaited<ReturnType<typeof deriveLight>>+ try {+ state = await deriveLight(db, await cache.at([tabId]), tabId, { groups: 'working', machineId: 'host' })+ } finally {+ await db.$runCommandRaw({ profile: 0 })+ }+ const rows = await db.$runCommandRaw({ find: 'system.profile', filter: { ts: { $gte: { $date: since.toISOString() } }, ns: { $regex: '\\.SwarmGroup$' },+ 'command.pipeline.0.$match.agentIds': { $exists: true } }, projection: { _id: 0, responseLength: 1 } }) as { cursor: { firstBatch: Array<{ responseLength: number }> } }+ expect(state!.groups.map(g => g.key)).toContain(quiet.key)+ // The agent's read: light, so well under the brief it would carry whole.+ const bytes = rows.cursor.firstBatch.reduce((n, r) => n + r.responseLength, 0)+ expect(bytes).toBeGreaterThan(0)+ expect(bytes).toBeLessThan(10_000)+ })+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) })diff --git a/backend/integration/superTabCosts.test.ts b/backend/integration/superTabCosts.test.tsindex bfe8fa162..835135da2 100644--- a/backend/integration/superTabCosts.test.ts+++ b/backend/integration/superTabCosts.test.ts@@ -13,6 +13,7 @@ import type { Command } from '../src/superTabs/commands.js'import type { MachineObservation } from '../src/superTabs/machines.js'import type { TokensByModel } from '../src/superTabs/costs/tokens.js'import { poolRows } from './hostRows.test-support.js'+import { profiledReads } from './profiledReads.test-support.js'import { superTabRoutes } from '../src/routes/superTabs.js'import { errorHandler } from '../src/middlewares/errorHandler.js'@@ -231,6 +232,26 @@ describe('route decision reads', () => {})})+describe('costs and a project\'s GitHub access, read through the read cache (task #2596)', () => {+ /** The part collections' reads MongoDB served while `run` ran, as superTabCache.test.ts counts them. */+ const partReads = <T>(run: () => Promise<T>) => profiledReads(db, /\.Swarm(Head|Member|Agent|Group|Machine|Start|Progress)$/, run)++ it('reads no part at a stamp that did not move, and answers what a read straight from Mongo answers', async () => {+ const f = await swarm()+ await f.beat(opus(1000, 100))+ await f.finish(await f.assign(await f.route()), opus(7000, 1200))+ const direct = new SuperTabStore(db, () => f.clock.now, null, { readCache: null })+ for (const [name, read] of [['costs', (store: SuperTabStore) => store.costSummary(owner, f.tab, 7)],+ ['github', (store: SuperTabStore) => store.projectRepository(owner, f.tab, 'lead')]] as const) {+ await read(f.store)+ const again = await partReads(() => read(f.store))+ expect(again.reads, name).toBe(0)+ expect(again.value, name).toEqual(await read(direct))+ }+ expect((await f.store.costSummary(owner, f.tab, 7)).totals).toMatchObject({ attempts: 1, shipped: 1 })+ })+})+describe('a route decision as stored (task #2488)', () => {// As production's routes were on 2026-11-03: every engine on every machine, 13 candidates with labels of ~540 characters and// 47 exclusions of 5 reasons, ~20 KB a row. Only the pick's label and each reason once are kept; readers get the record whole.diff --git a/backend/integration/superTabFollowedThreads.test.ts b/backend/integration/superTabFollowedThreads.test.tsindex ca0f9c2df..9768fb794 100644--- a/backend/integration/superTabFollowedThreads.test.ts+++ b/backend/integration/superTabFollowedThreads.test.ts@@ -17,13 +17,14 @@ import { swarmTransaction } from '../src/superTabs/cache.js'import { guardedWrite } from '../src/superTabs/parts/write.js'import { SwarmReads } from '../src/superTabs/read/service.js'import { HostReads } from '../src/superTabs/read/host.js'-import { buddyChatId } from '../src/superTabs/buddies.js'+import { buddyChatId, openSwarmBuddyChat } from '../src/superTabs/buddies.js'import { resetInboxReads } from '../src/superTabs/read/inbox.js'import { MAX_READ_THREADS, resetThreadsReads, TAGGED_THREADS, THREADS_READS, THREADS_WINDOW_MS } from '../src/superTabs/read/followedThreads.js'import type { Author, Conversation, SuperTabState } from '../src/superTabs/model.js'import { stableId } from '../src/superTabs/model.js'import { THREAD_MARK_CAP, writeThreadFollow, writeThreadMark } from '../src/superTabs/readMarks.js'import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'+import { backfillThreads } from '../src/superTabs/threadBackfill.js'import { NOW, outsider as outsiderActor, owner as ownerActor, peer as peerActor, swarm } from '../src/superTabs/read/fixture.test-support.js'import { PROFILE_STAGES, profileEntry, type ProfileEntry } from './bench/profile.js'@@ -115,13 +116,13 @@ const personAuthor = (u: AuthUser): Author => ({ kind: 'person', id: u.sub, name/** Rows stored as the store stores them: numbered after the chat's newest, the chat's counters moved as numberMessages moves* them for rows people read (as superTabInbox.test.ts). */async function insert(tabId: string, conversationId: string, rows: Array<{ id?: string; text: string; author: Author; thread?: string | null;- source?: Record<string, unknown>; recipientIds?: string[]; mentions?: string[] }>) {+ source?: Record<string, unknown>; recipientIds?: string[]; mentions?: string[]; buddySession?: boolean; buddyProject?: string }>) {const ids: string[] = []await swarmTransaction(db, async tx => {const current = (await parts.loadActive(tx, tabId, { groupIds: [conversationId] })).groups.find(g => g.key === conversationId)!const data = structuredClone(current.data!) as Conversationconst messages: Array<{ id: string; tabId: string; conversationId: string; sequence: number; author: never; text: string;- thread: string | null; recipientIds: string[]; mentions: string[]; source?: never; createdAt: Date }> = []+ thread: string | null; recipientIds: string[]; mentions: string[]; source?: never; buddySession?: boolean; buddyProject?: string; createdAt: Date }> = []for (const row of rows) {const sequence = (data.messageSeq ?? 0) + 1const id = row.id ?? `m-${randomUUID()}`@@ -134,7 +135,7 @@ async function insert(tabId: string, conversationId: string, rows: Array<{ id?:}messages.push({ id, tabId, conversationId, sequence, author: row.author as never, text: row.text,thread: row.thread === undefined ? id : row.thread, recipientIds: row.recipientIds ?? [], mentions: row.mentions ?? [],- ...(row.source ? { source: row.source as never } : {}), createdAt: new Date() })+ ...(row.source ? { source: row.source as never } : {}), ...(row.buddySession ? { buddySession: true } : {}), ...(row.buddyProject ? { buddyProject: row.buddyProject } : {}), createdAt: new Date() })}for (let offset = 0; offset < messages.length; offset += 500) {await tx.superTabMessage.createMany({ data: messages.slice(offset, offset + 500) })@@ -414,6 +415,46 @@ describe('a person\'s followed threads (GET /threads)', () => {expect(JSON.stringify(body.data)).not.toMatch(/Hidden|hidden-agent/)})+ it('gives the same answer from the thread summaries as from the thread rows, a long thread\'s whole count included', async () => {+ const s = await followScene()+ // What a person never reads, as a reply and as a thread's newest row; a Lead's copy of a notice stays the Lead's.+ await insert(s.tabId, s.web, [{ text: 'Hidden reply', author: agentAuthor('hidden-agent'), thread: s.followed, source: { kind: 'note', recipientsOnly: true },+ recipientIds: [s.worker] }])+ // A thread the person replied in long ago, then 150 replies of the worker's, read to its end.+ const [long] = await insert(s.tabId, s.web, [{ text: 'Long', author: personAuthor(owner) }])+ await insert(s.tabId, s.web, [{ text: 'Peer reply', author: personAuthor(peer), thread: long! },+ ...Array.from({ length: 150 }, (_, i) => ({ text: `Worker ${i}`, author: agentAuthor(s.worker), thread: long! }))])+ await markRead(s.tabId, s.web, await newestIn(s.tabId, s.web), peer)+ await markThread(s.tabId, s.web, long!, await newestIn(s.tabId, s.web), peer)+ // An unread reply past the person's thread mark, in a thread they are tagged in: more, not a read thread.+ await insert(s.tabId, s.web, [{ text: 'Past the mark', author: agentAuthor(s.worker), thread: s.tagged }])+ const rows = (await threads(s.tabId, peer)).body.data+ await backfillThreads(db, Date.now())+ resetThreadsReads()+ expect((await threads(s.tabId, peer)).body.data).toEqual(rows)+ expect(roots(rows.read)).toEqual(['Long', 'Followed', 'Read'])+ expect(roots(rows.unread)).toEqual(['Tagged', 'Unread'])+ expect(rows.read[0]).toMatchObject({ rootId: long, replies: 151, lastReplier: { id: s.worker } })+ expect(rows.read[1]).toMatchObject({ rootId: s.followed, replies: 1, lastReplier: { id: s.worker } })+ expect(JSON.stringify(rows)).not.toMatch(/Hidden|hidden-agent/)+ })++ it('counts no reply of a project the person cannot read in their Swarm Buddy chat\'s thread, before and after its summaries', async () => {+ let chat = ''+ const s = await scene(f => f.edit(state => { chat = openSwarmBuddyChat(state, state.people.find(p => p.id === peer.sub)!).id }))+ const [root] = await insert(s.tabId, chat, [{ text: 'Buddy root', author: personAuthor(peer) }])+ // The Secret project is its owner's alone: a session's reply of it stays in the chat, read by no one there now.+ await insert(s.tabId, chat, [{ text: 'Buddy reply', author: agentAuthor('peer-buddy'), thread: root! },+ { text: 'Secret session reply', author: agentAuthor('peer-session'), thread: root!, buddySession: true, buddyProject: s.secret }])+ await markRead(s.tabId, chat, await newestIn(s.tabId, chat), peer)+ await markThread(s.tabId, chat, root!, await newestIn(s.tabId, chat), peer)+ const before = (await threads(s.tabId, peer)).body.data+ expect(before.read).toMatchObject([{ rootId: root, replies: 1, lastReplier: { id: 'peer-buddy' } }])+ await backfillThreads(db, Date.now())+ resetThreadsReads()+ expect((await threads(s.tabId, peer)).body.data).toEqual(before)+ })+it(`answers the ${MAX_READ_THREADS} read threads with the newest replies and says there are more`, async () => {const s = await scene()const many = await insert(s.tabId, s.web, Array.from({ length: MAX_READ_THREADS + 5 }, (_, i) => ({ text: `Root ${i}`, author: personAuthor(peer) })))@@ -458,7 +499,8 @@ describe('a person\'s followed threads (GET /threads)', () => {} finally { vi.useRealTimers() }})- it('reads by index only and examines a bounded number of messages, whatever a thread\'s length', async () => {+ /** Web: 70 roots of peer's, read to their ends in their threads; the first 10 hold 300 replies each, the rest one. */+ async function longScene() {const s = await scene()const long = await insert(s.tabId, s.web, Array.from({ length: 70 }, (_, i) => ({ text: `Long root ${i}`, author: personAuthor(peer) })))for (let batch = 0; batch < 3; batch++) {@@ -469,16 +511,26 @@ describe('a person\'s followed threads (GET /threads)', () => {// Read to their ends; the long threads' marks moved last, so they are among the candidates.const top = await newestIn(s.tabId, s.web)for (const root of long.toReversed()) await writeThreadMark(db, { tabId: s.tabId, personId: peer.sub, conversationId: s.web, threadId: root, sequence: top, now: Date.now() })- await threads(s.tabId, peer)+ return { ...s, long }+ }+ /** One threads read under the profiler, after a warm read: its reply, and the operations each collection served. */+ async function profiledThreads(tabId: string) {+ await threads(tabId, peer)await db.$runCommandRaw({ profile: 0 })await db.$runCommandRaw({ drop: 'system.profile' }).catch(() => {})await db.$runCommandRaw({ create: 'system.profile', capped: true, size: 16 * 1024 * 1024 })await db.$runCommandRaw({ profile: 2, slowms: 0 })let reply: Awaited<ReturnType<typeof threads>>- try { reply = await threads(s.tabId, peer) } finally { await db.$runCommandRaw({ profile: 0 }) }+ try { reply = await threads(tabId, peer) } finally { await db.$runCommandRaw({ profile: 0 }) }expect(reply.status).toBe(200)const rows = (await db.$runCommandRaw({ aggregate: 'system.profile', pipeline: [{ $match: { ns: { $not: { $regex: 'system\\.' } } } }, ...PROFILE_STAGES],cursor: {} }) as unknown as { cursor: { firstBatch: ProfileEntry[] } }).cursor.firstBatch.map(profileEntry)+ return { reply, rows }+ }++ it('reads by index only and examines a bounded number of messages, whatever a thread\'s length', async () => {+ const s = await longScene()+ const { reply, rows } = await profiledThreads(s.tabId)const messages = rows.filter(r => r.ns.endsWith('.SuperTabMessage'))expect(rows.filter(r => r.planSummary === 'COLLSCAN')).toEqual([])for (const r of messages) expect(r.planSummary, JSON.stringify(r)).toMatch(/^IXSCAN/)@@ -491,6 +543,23 @@ describe('a person\'s followed threads (GET /threads)', () => {// A long thread's count stops at what the scan read.expect(reply.body.data.read.every((t: any) => t.replies <= 100)).toBe(true)}, 120_000)++ it('reads the candidates\' thread summaries, never their messages, once the Swarm\'s summaries are backfilled', async () => {+ const s = await longScene()+ await backfillThreads(db, Date.now())+ const { reply, rows } = await profiledThreads(s.tabId)+ const messages = rows.filter(r => r.ns.endsWith('.SuperTabMessage')), summaries = rows.filter(r => r.ns.endsWith('.SuperTabThread'))+ expect(rows.filter(r => r.planSummary === 'COLLSCAN')).toEqual([])+ // No message read by the thread index: the 70 roots by id, and the inbox's reads, which find nothing unread.+ expect(messages.filter(r => /thread/.test(r.planSummary ?? '')), JSON.stringify(messages)).toEqual([])+ expect(messages.reduce((n, r) => n + (r.docsExamined ?? 0), 0)).toBeLessThanOrEqual(70)+ // The 60 candidates' summaries in one read by id, one small row each.+ expect(summaries.filter(r => r.op !== 'getmore')).toHaveLength(1)+ expect(summaries[0]!.planSummary).toMatch(/^IXSCAN \{ _id: 1 \}/)+ expect(summaries.reduce((n, r) => n + (r.docsExamined ?? 0), 0)).toBeLessThanOrEqual(60)+ expect(reply.body.data.read).toHaveLength(MAX_READ_THREADS)+ expect(reply.body.data.more).toBe(true)+ }, 120_000)})describe('a thread the person is tagged in, in a chat they never opened (GET /threads)', () => {diff --git a/backend/integration/superTabGroupPlans.test.ts b/backend/integration/superTabGroupPlans.test.tsindex 3d73e020e..73766821f 100644--- a/backend/integration/superTabGroupPlans.test.ts+++ b/backend/integration/superTabGroupPlans.test.ts@@ -13,6 +13,7 @@ import { migrateSwarm } from '../src/superTabs/migration/migrate.js'import { HostReads } from '../src/superTabs/read/host.js'import { DIRECT, readLight } from '../src/superTabs/cachedReads.js'import * as parts from '../src/superTabs/parts/index.js'+import { HeldParts } from '../src/superTabs/parts/held.js'import { recentDormantGroups } from '../src/superTabs/leaderboard/read.js'import { decisionsWaiting, listDecisions } from '../src/superTabs/decisions.js'import { GROUP_INDEX, groupsBy, listGroupIndexes, retryStaleIndex } from '../src/superTabs/parts/indexed.js'@@ -184,6 +185,23 @@ describe('hot SwarmGroup reads name their index and read only what they return (expect(reads.reduce((n, r) => n + r.docsExamined, 0), JSON.stringify(reads)).toBeLessThanOrEqual(groups.length + 1)})+ it('a machine\'s next report reads its conversations\' columns through the same indexes, and whole only those that changed (B3)', async () => {+ const held = new HeldParts()+ const observed = () => db.$transaction(tx => parts.loadObserved(tx, s.tabId, s.machineId, held))+ const groups = (await observed()).groups.map(g => g.key)+ const quiet = await profiled(observed)+ expectIndexed(quiet)+ // No more examined than a whole read examines, and no conversation read whole: nothing changed.+ expect(quiet.reduce((n, r) => n + r.docsExamined, 0), JSON.stringify(quiet)).toBeLessThanOrEqual(groups.length + 1)+ expect(where(quiet, ['key']).filter(r => !mentions(r.shape, 'dormant'))).toEqual([])+ await db.swarmGroup.update({ where: { id: `${s.tabId}:${s.web}` }, data: { version: { increment: 1 }, changedAt: new Date() } })+ const changed = await profiled(observed)+ expectIndexed(changed)+ // The changed one alone, by key.+ const whole = changed.filter(r => r.bytes > 0 && mentions(r.shape, 'key') && !mentions(r.shape, 'dormant'))+ expect(whole.map(r => [r.plans, r.returned]), JSON.stringify(changed)).toEqual([[['IXSCAN { tabId: 1, key: 1 }'], 1]])+ })+it('a command loads the Swarm\'s open conversations and those it names, each read through its index', async () => {const quiet = s.quietLead[5]!.keyfor (const [named, expected] of [diff --git a/backend/integration/superTabHeldParts.test.ts b/backend/integration/superTabHeldParts.test.tsnew file mode 100644index 000000000..df64c5889--- /dev/null+++ b/backend/integration/superTabHeldParts.test.ts@@ -0,0 +1,127 @@+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 } from 'vitest'+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import { PrismaClient } from '@prisma/client'+import { configureSwarmStamps, swarmTransaction } from '../src/superTabs/cache.js'+import { MemoryStamps } from '../src/superTabs/cache.test-support.js'+import * as parts from '../src/superTabs/parts/index.js'+import { HeldParts } from '../src/superTabs/parts/held.js'+import { guardedWrite } from '../src/superTabs/parts/write.js'+import { migrateSwarm } from '../src/superTabs/migration/migrate.js'+import type { SuperTabState } from '../src/superTabs/model.js'+import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'+import { richSwarm } from '../src/superTabs/read/fixture.test-support.js'+import { profiled } from './plans.test-support.js'++// A full machine report reads the parts it already holds at their exact version from memory (B3, #2597): what it loads must+// equal what a server holding nothing loads, after every kind of write a part can take. A fresh loopback replica set; this+// suite never reads DATABASE_URL.+let replica: MongoMemoryReplSet+let db: PrismaClient++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_held_parts_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 } } })+})+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})+beforeEach(() => configureSwarmStamps(new MemoryStamps()))+afterEach(() => configureSwarmStamps(null))++async function scene(): Promise<string> {+ const s = richSwarm(Date.now())+ s.contribute('spare')+ 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+}++/** One write, committed as a command commits it: 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)+const observed = (tabId: string, held: HeldParts) => db.$transaction(tx => parts.loadObserved(tx, tabId, 'host', held))++describe('a full report\'s held parts (B3, #2597)', () => {+ it('load what a server holding nothing loads, after every kind of write', { timeout: 120_000 }, async () => {+ const tabId = await scene()+ // One server that keeps what it read, and one whose cap holds almost nothing.+ const warm = new HeldParts(), tiny = new HeldParts(1)+ let n = 0+ const at = () => Date.now() + ++n+ const cases: Array<[string, () => Promise<boolean>]> = [+ ['another machine\'s settings', () => write(tabId, all => { const m = liveOf(all.machines).find(x => x.key !== 'host')!+ return { op: 'update', kind: 'machine', key: m.key, seen: m.version, data: { ...m.data!, contribution: { ...m.data!.contribution!, name: `M${n}` } },+ host: { hostChangedAt: new Date() } } }, at())],+ ['another machine\'s reading alone (dated readAt)', () => write(tabId, all => { const m = liveOf(all.machines).find(x => x.key !== 'host')!+ return { op: 'update', kind: 'machine', key: m.key, seen: m.version, data: { ...m.data!, ordinalNote: n } as never } }, at())],+ ['the reporting machine\'s reading', () => write(tabId, all => { const m = liveOf(all.machines).find(x => x.key === 'host')!+ return { op: 'update', kind: 'machine', key: m.key, seen: m.version, data: { ...m.data!, ordinalNote: n } as never } }, at())],+ ['a part touched (its version alone moves)', () => write(tabId, all => { const m = liveOf(all.machines).find(x => x.key !== 'host')!+ return { op: 'touch', kind: 'machine', key: m.key, seen: m.version } }, at())],+ ['a machine removed', () => write(tabId, all => { const m = liveOf(all.machines).find(x => x.key === 'spare')!+ return { op: 'remove', kind: 'machine', key: m.key, seen: m.version, data: m.data } }, at())],+ ['a machine added again under its key', () => write(tabId, all => { const m = all.machines.find(x => x.key === 'spare')!+ return { op: 'insert', kind: 'machine', key: m.key, ordinal: m.ordinal, data: m.data } }, at())],+ ['a new machine', () => write(tabId, all => { const m = liveOf(all.machines).find(x => x.key === 'spare')!+ return { op: 'insert', kind: 'machine', key: `new-${n}`, ordinal: 900 + n, data: { ...m.data!, machineId: `new-${n}` } } }, at())],+ ['a post in running work', () => write(tabId, all => { const g = liveOf(all.groups).find(x => x.data!.assignment?.status === 'working')!+ return { op: 'update', kind: 'group', key: g.key, seen: g.version, data: { ...g.data!, title: `T${n}` } } }, at())],+ ['running work ends', () => write(tabId, all => { const g = liveOf(all.groups).find(x => x.data!.assignment?.status === 'working')!+ return { op: 'update', kind: 'group', key: g.key, seen: g.version, data: { ...g.data!, assignment: { ...g.data!.assignment!, status: 'done' } } } }, at())],+ ['a Lead conversation put to sleep', () => write(tabId, all => { const g = liveOf(all.groups).find(x => x.key === 'lead')!+ return { op: 'update', kind: 'group', key: g.key, seen: g.version, data: { ...g.data!, dormant: true } } }, at())],+ ['and woken', () => write(tabId, all => { const g = liveOf(all.groups).find(x => x.key === 'lead')!+ return { op: 'update', kind: 'group', key: g.key, seen: g.version, data: { ...g.data!, dormant: false } } }, at())],+ ['running work removed', () => write(tabId, all => { const g = liveOf(all.groups).find(x => !!x.data!.assignment?.execution && x.key !== 'lead')+ return g ? { op: 'remove', kind: 'group', key: g.key, seen: g.version, data: g.data } : null }, at())],+ ['new running work', () => write(tabId, all => { const g = all.groups.find(x => !!x.data!.assignment?.execution)!+ return { op: 'insert', kind: 'group', key: `g-${n}`, ordinal: 900 + n, data: { ...g.data!, id: `g-${n}`, assignment: { ...g.data!.assignment!, status: 'working' } } } }, at())],+ ['a part rewritten at the version it had, under a new date (purged, then added again)', async () => {+ const row = await db.swarmMachine.findFirstOrThrow({ where: { tabId, key: { not: 'host' }, deleted: false } })+ await db.swarmMachine.update({ where: { id: row.id }, data: { changedAt: new Date(at()), data: { ...row.data as object, ordinalNote: 'rewritten' } } })+ return true+ }],+ ]+ expect(await observed(tabId, warm)).toEqual(await observed(tabId, new HeldParts()))+ for (const [name, change] of cases) {+ expect(await change(), name).toBe(true)+ const fresh = await observed(tabId, new HeldParts())+ expect(await observed(tabId, warm), name).toEqual(fresh)+ expect(await observed(tabId, tiny), name).toEqual(fresh)+ }+ })++ it('reads the machines\' columns through the Swarm\'s index, examining only what it returns, and whole only the one that changed', async () => {+ const tabId = await scene()+ await scene()+ const held = new HeldParts()+ await observed(tabId, held)+ await write(tabId, all => { const m = liveOf(all.machines).find(x => x.key === 'host')!+ return { op: 'update', kind: 'machine', key: m.key, seen: m.version, data: m.data } })+ const entries = (await profiled(db, () => observed(tabId, held))).filter(e => e.ns.endsWith('.SwarmMachine'))+ const live = (await db.swarmMachine.count({ where: { tabId, deleted: false } }))+ expect(entries.map(e => [e.planSummary?.startsWith('IXSCAN') || e.planSummary === 'IDHACK' || e.planSummary === 'EXPRESS_IXSCAN', e.docsExamined, e.nreturned]))+ .toEqual([[true, live, live], [true, 1, 1]])+ })+})diff --git a/backend/integration/superTabMachineReports.test.ts b/backend/integration/superTabMachineReports.test.tsindex 6ac01cd1e..0befd593b 100644--- a/backend/integration/superTabMachineReports.test.ts+++ b/backend/integration/superTabMachineReports.test.ts@@ -395,3 +395,42 @@ describe('a machine\'s readings for all its Swarms in one call (DB 2.5)', () =>for (const f of swarms) expect(((await f.part()).data as unknown as MachineData).contribution!.observation!.receivedAt).toBe(clock.now)})})++describe('a full report reads only the parts that changed since this server last read them (B3, #2597)', () => {+ /** What MongoDB sent back from the machine and conversation collections while [run] ran (its profiler's replies). */+ async function partBytes(run: () => Promise<unknown>): Promise<{ SwarmMachine: number; SwarmGroup: number }> {+ await db.$runCommandRaw({ profile: 2 })+ const since = new Date()+ try {+ await run()+ const rows = await db.$runCommandRaw({ find: 'system.profile', filter: { ts: { $gte: { $date: since.toISOString() } },+ ns: { $regex: '\\.Swarm(Group|Machine)$' } }, projection: { _id: 0, ns: 1, responseLength: 1 }, batchSize: 10_000 }) as+ { cursor: { firstBatch: Array<{ ns: string; responseLength?: number }> } }+ const bytes = { SwarmMachine: 0, SwarmGroup: 0 }+ for (const { ns, responseLength } of rows.cursor.firstBatch) bytes[ns.slice(ns.lastIndexOf('.') + 1) as keyof typeof bytes] += Number(responseLength ?? 0)+ return bytes+ } finally {+ await db.$runCommandRaw({ profile: 0 })+ }+ }++ it('reads under half the machine and conversation bytes on its next full report', async () => {+ const f = await swarm()+ // Eight machines, as a Swarm has: one reports, the others' parts stay as they are.+ for (let i = 0; i < 6; i++) {+ const machineId = `idle-${randomUUID()}`+ await db.machine.create({ data: { machineId, userId: host.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ await db.machineShare.create({ data: { machineId, ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email] } })+ await f.execute({ type: 'machine.contribute', machineId, name: `Idle ${i}`, cwd: '/repo', engines: ['codex'], maxAgents: 4 }, host)+ }+ // A server that remembers no report: every reading runs in full.+ const forgetful = f.store(never)+ const first = await partBytes(() => f.beat({}, forgetful))+ f.clock.now += BEAT+ const second = await partBytes(() => f.beat({}, forgetful))+ expect(first.SwarmMachine).toBeGreaterThan(0)+ expect(first.SwarmGroup).toBeGreaterThan(0)+ expect(second.SwarmMachine).toBeLessThan(first.SwarmMachine / 2)+ expect(second.SwarmGroup).toBeLessThan(first.SwarmGroup / 2)+ })+})diff --git a/backend/integration/superTabNamedReads.test.ts b/backend/integration/superTabNamedReads.test.tsindex 84afda732..874ce9d50 100644--- a/backend/integration/superTabNamedReads.test.ts+++ b/backend/integration/superTabNamedReads.test.ts@@ -47,6 +47,69 @@ afterAll(async () => {await replica?.stop()})+// Prisma sends an empty list as `$or: []`, which no index serves: a scan of the whole collection for nothing.+describe('a person with nothing to read', () => {+ const on = (entries: Array<{ ns: string }>, collection: string) => entries.filter(entry => entry.ns.endsWith(`.${collection}`))++ it('reads no heads or members for an owner with no Swarm', async () => {+ const entries = await profiled(db, () => store.hostGrids(person('no-swarm')))+ expect(on(entries, 'SwarmHead')).toEqual([])+ expect(on(entries, 'SwarmMember')).toEqual([])+ })++ it('reads no members when none of the owner\'s Swarms has a grid', async () => {+ const someone = person('no-grid')+ await swarmRow(someone.sub)+ const entries = await profiled(db, () => store.hostGrids(someone))+ expect(on(entries, 'SwarmMember')).toEqual([])+ })++ it('reads no heads for no Swarms split into parts', async () => {+ const heads = (store as unknown as { heads(rows: unknown[]): Promise<Map<string, unknown>> }).heads.bind(store)+ const entries = await profiled(db, () => heads([{ id: 'old', format: 1 }]))+ expect(on(entries, 'SwarmHead')).toEqual([])+ })++ it('reads no workspaces for a person with no invitation', async () => {+ let answer: unknown+ const entries = await profiled(db, async () => { answer = await store.workspaces.invitationsFor(person('no-invitation')) })+ expect(answer).toEqual({ invitations: [] })+ expect(on(entries, 'SwarmWorkspace')).toEqual([])+ })+})++// The Performance Advisor's suggestion from Ken's plan (2026-11-04): by tabId alone, or by date alone, this reads every row of+// the big Swarm or of the range, to return a few.+describe('operation receipts by Swarm and date', () => {+ it('reads only the Swarm\'s rows in the range, by its index', async () => {+ const row = (tabId: string, at: Date) => ({ id: randomUUID(), tabId, actorKey: 'person:x', requestHash: 'h', revision: 0, result: {}, createdAt: at })+ const old = new Date(NOW - 20 * 86_400_000), recent = new Date(NOW - 86_400_000), big = randomUUID()+ await db.superTabOperation.createMany({ data: [+ ...Array.from({ length: 300 }, () => row(big, old)), ...Array.from({ length: 300 }, () => row(randomUUID(), recent)),+ ...Array.from({ length: 5 }, () => row(big, recent)),+ ] })+ const entries = await profiled(db, () => db.superTabOperation.aggregateRaw({ pipeline: [+ { $match: { tabId: big, createdAt: { $gte: { $date: new Date(NOW - 2 * 86_400_000).toISOString() } } } }, { $project: { _id: 1 } }] }))+ const rows = reads(entries, 'SuperTabOperation', ['tabId', 'createdAt'])+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)+ expect(rows[0]!.nreturned).toBe(5)+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(5)+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ tabId: 1, createdAt: 1/)+ })++ // A write on every command: the index on tabId alone is a prefix of this one, so it would only add write cost (review of #2888).+ it('keeps one index for reads by Swarm, which still use it', async () => {+ const listed = await db.$runCommandRaw({ listIndexes: 'SuperTabOperation' }) as unknown as { cursor: { firstBatch: Array<{ key: Record<string, number> }> } }+ expect(listed.cursor.firstBatch.map(index => Object.keys(index.key).join(',')).filter(key => key.startsWith('tabId'))).toEqual(['tabId,createdAt'])+ const tab = randomUUID()+ await db.superTabOperation.create({ data: { id: randomUUID(), tabId: tab, actorKey: 'person:x', requestHash: 'h', revision: 0, result: {} } })+ const entries = await profiled(db, () => db.superTabOperation.aggregateRaw({ pipeline: [{ $match: { tabId: tab } }, { $project: { _id: 1 } }] }))+ const rows = reads(entries, 'SuperTabOperation', ['tabId'])+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ tabId: 1, createdAt: 1/)+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBe(1)+ })+})+describe('the owner\'s grid poll', () => {it('finds the owner\'s Swarms by the owner index, examining none of anyone else\'s', async () => {const mine = [await swarmRow(owner.sub), await swarmRow(owner.sub)]diff --git a/backend/integration/superTabNoticeDigest.test.ts b/backend/integration/superTabNoticeDigest.test.tsindex 5f2dd14ba..43551601e 100644--- a/backend/integration/superTabNoticeDigest.test.ts+++ b/backend/integration/superTabNoticeDigest.test.ts@@ -15,6 +15,7 @@ import { compactDeliveries } from '../src/superTabs/deliveryCompaction.js'import { revokeNativeContexts } from '../src/superTabs/native.js'import { stableId, type MessageDraft, type SuperTabState } from '../src/superTabs/model.js'import { logger } from '../src/utils/logger.js'+import { plan, profiled, reads } from './plans.test-support.js'// Ken, 2026-11-02 (docs/plans/2026-11-02-pm-notice-digest-design.md): the server's routine notices to a project's coordinator// go in one message at most every 5 minutes; what someone waits on still goes at once. A fresh loopback replica set, created here.@@ -714,6 +715,26 @@ describe('with the update request', () => {})})+// A kept message's deliveries were read by message id alone: a scan of all 43 k deliveries, 440 ms inside this write+// transaction, 21 times a day (Atlas slow log, 2026-11-04).+describe('a poll keeping a message already stored', () => {+ it('reads its deliveries by Swarm and message, examining only those', async () => {+ const f = await swarm({ fresh: true })+ await f.write({ kind: 'idle' }, f.lead)+ f.clock.now += DUE+ const { projectUpdateRequest } = await import('../src/superTabs/projectUpdates.js')+ const { state } = await f.timed.read(host, f.tab, undefined, f.lead)+ const draft = projectUpdateRequest(state, state.agents.find(a => a.id === f.lead)!, f.clock.now)!+ await db.superTabMessage.create({ data: { id: draft.id, tabId: f.tab, conversationId: draft.conversationId, sequence: 1, text: draft.text, replyTo: null, recipientIds: draft.recipients,+ mentions: [], thread: draft.id, source: draft.source as object, author: draft.author as object } })+ const entries = await profiled(db, () => f.poll())+ const rows = reads(entries, 'SuperTabDelivery', ['messageId'], ['agentId'])+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ tabId: 1, messageId: 1/)+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(1)+ })+})+// Two more kinds (docs/plans/2026-11-02-pm-digest-more-kinds-design.md): the coordinator's own skills notices, and usage-limit or// failing-model alerts. Each was delivered at once until then. A step's Stuck still is: a person must act on it (review of #2797).describe('a step\'s Stuck, skills notices and quiet alerts', () => {diff --git a/backend/integration/superTabTidy.test.ts b/backend/integration/superTabTidy.test.tsindex 9e0310eb0..8b9136c09 100644--- a/backend/integration/superTabTidy.test.ts+++ b/backend/integration/superTabTidy.test.ts@@ -17,6 +17,8 @@ import { archiveFinishedGroups, markFinishedGroups, type PullRequestState } fromimport { settleStuckDeliveries } from '../src/superTabs/deliverySettle.js'import { SuperTabError } from '../src/superTabs/model.js'import { logger } from '../src/utils/logger.js'+import { fakeApp, fakeGitHub, throwawayKey } from '../src/github/fakeGitHub.js'+import { appPullRequests } from '../src/superTabs/archive.js'// Nobody tidies a Swarm by hand: an agent idle for 15 minutes is told to its coordinator on its poll, and finished groups// archive. A fresh loopback replica set, created here.@@ -276,6 +278,67 @@ describe('a finished group', () => {expect(await open()).toBe(false)})+ /** A task in a project whose repository is acme/app, cancelled with [reason]: its group's key. */+ const cancelledIn = async (f: Awaited<ReturnType<typeof swarm>>, reason: string) => {+ const head = await db.swarmHead.findUniqueOrThrow({ where: { id: `${f.tab}:head` } }), data = head.data as unknown as HeadData+ const repository = { machineId: 'lead-host', cwd: '/repo', repositoryUrl: 'https://github.com/acme/app' }+ await db.swarmHead.update({ where: { id: head.id }, data: { data: (data.projects+ ? { ...data, projects: data.projects.map(p => p.id === 'lead' ? { ...p, repository } : p) } : { ...data, project: repository }) as object } })+ const task = String((await f.execute({ type: 'conversation.create', title: 'Port', brief: 'Port it', checks: [{ description: 'Verified', independent: false }] })).result.conversationId)+ const worker = await f.add(task, 'test-host', randomUUID(), 'Porter')+ const work = String((await f.execute({ type: 'work.assign', conversationId: task, agentId: worker })).result.assignmentId)+ await f.execute({ type: 'work.cancel', conversationId: task, assignmentId: work, reason })+ return task+ }+ const isArchived = async (f: Awaited<ReturnType<typeof swarm>>, key: string) => (await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key } })).archived++ // Diego, 11-04 (#2602): another repository's number, read in this one, kept the task open forever.+ it('waits on no "PR #N" another repository\'s name sits next to', async () => {+ const f = await swarm()+ const task = await cancelledIn(f, 'Merged PR #40. Ported from autonomous-harness PR #2716.')+ f.clock.now += 40 * MINUTE+ const prs = github({ 'https://github.com/acme/app/pull/40': 'merged' })+ await archiveFinishedGroups(db, f.timed, prs, f.clock.now)+ expect(prs.read).not.toContain('https://github.com/acme/app/pull/2716')+ expect(await isArchived(f, task)).toBe(true)+ })++ it('archives when a pull request it names is not found in its project\'s repository', async () => {+ const f = await swarm()+ const task = await cancelledIn(f, 'Merged PR #40. Ported from PR #2716.')+ f.clock.now += 40 * MINUTE+ const key = throwawayKey(), fake = fakeGitHub({ publicKey: key.publicKey, appId: '424242' })+ fake.installed.set('acme/app', 77)+ fake.pulls.set('acme/app#40', { state: 'closed', merged_at: '2026-10-27T08:00:00Z' })+ await archiveFinishedGroups(db, f.timed, appPullRequests(fakeApp(key.privateKey, fake)), f.clock.now)+ expect(fake.calls.map(c => c.path)).toContain('/repos/acme/app/pulls/2716')+ expect(await isArchived(f, task)).toBe(true)+ })++ it('logs once a pass that holds a group only for pull requests GitHub cannot read', async () => {+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {})+ try {+ const held = (group: string) => warn.mock.calls.filter(([, meta]) => (meta as { group?: string } | undefined)?.group === group)+ const f = await swarm()+ await linkPr(f)+ f.clock.now += 40 * MINUTE+ await archiveFinishedGroups(db, f.timed, github({ [PR]: null }), f.clock.now)+ expect(held(f.group)).toEqual([['[swarm-archive] group held for pull requests GitHub cannot read', { tabId: f.tab, group: f.group, pullRequests: [PR] }]])+ // An open one holds it, as it should, with nothing to say.+ warn.mockClear()+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'open' }), f.clock.now)+ expect(held(f.group)).toEqual([])+ // A number with no repository to read it in.+ const handed = String((await f.execute({ type: 'conversation.create', title: 'Sidebar', brief: 'Ship it', checks: [{ description: 'Verified', independent: false }] })).result.conversationId)+ const worker = await f.add(handed, 'test-host', randomUUID(), 'Sidebar')+ const work = String((await f.execute({ type: 'work.assign', conversationId: handed, agentId: worker })).result.assignmentId)+ await f.execute({ type: 'work.cancel', conversationId: handed, assignmentId: work, reason: 'PR #1868 is in the merge queue' })+ f.clock.now += 40 * MINUTE+ await archiveFinishedGroups(db, f.timed, github({}), f.clock.now)+ expect(held(handed)).toEqual([['[swarm-archive] group held: it names PR #N and its project has no GitHub repository', { tabId: f.tab, group: handed }]])+ } finally { warn.mockRestore() }+ })+it('stays open when its work names "PR #N" and the project has no repository to read it in', async () => {const f = await swarm()const handed = String((await f.execute({ type: 'conversation.create', title: 'Sidebar', brief: 'Ship it', checks: [{ description: 'Verified', independent: false }] })).result.conversationId)diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 277cccf11..464447093 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1374,7 +1374,10 @@ model SuperTabOperation {parts Json?createdAt DateTime @default(now())- @@index([tabId])+ /// A Swarm's receipts, and by date: Atlas's Performance Advisor saw a read scan 107 k rows to return 40 (Ken's plan, 2026-11-04). No+ /// backend read uses the date yet; check on Atlas after the release, and shorten it to tabId if nothing does. It replaces the index on+ /// tabId alone, its prefix, since this collection gets a write on every command.+ @@index([tabId, createdAt])/// A receipt goes 30 days after createdAt (superTabs/operations.ts ensureOperationExpiry). Declared so db push keeps the index; the/// schema step makes it, with its expiry, before the push.@@index([createdAt], map: "operation_expiry")diff --git a/backend/src/github/app.test.ts b/backend/src/github/app.test.tsindex c24151300..05f00968b 100644--- a/backend/src/github/app.test.ts+++ b/backend/src/github/app.test.ts@@ -231,11 +231,20 @@ describe('default branch protection', () => {expect(github.calls.at(-1)).toMatchObject({ method: 'GET', path: '/repos/acme/app/pulls/3', auth: `Bearer ${token}` })})+ // #2602: another repository's number read here is no pull request of this one, and must not hold its task open forever.+ it('answers missing for a pull request GitHub does not know in that repository', async () => {+ const { app } = setup()+ const { token } = await app.createToken(77, repo, PULL_READ_PERMISSIONS)+ expect(await app.pullRequestState(repo, 9, token)).toBe('missing')+ })+it('answers null, never a guess, when GitHub cannot say', async () => {const { app, github } = setup()const { token } = await app.createToken(77, repo, PULL_READ_PERMISSIONS)- expect(await app.pullRequestState(repo, 9, token)).toBeNull()github.pulls.set('acme/app#9', { state: 'open', merged_at: null })+ github.control.pullsStatus = 502+ expect(await app.pullRequestState(repo, 9, token)).toBeNull()+ github.control.pullsStatus = 200expect(await app.pullRequestState(repo, 9, 'ghs_not_issued')).toBeNull()github.control.down = trueexpect(await app.pullRequestState(repo, 9, token)).toBeNull()diff --git a/backend/src/github/app.ts b/backend/src/github/app.tsindex 5d0c017ae..9e4689a3f 100644--- a/backend/src/github/app.ts+++ b/backend/src/github/app.ts@@ -467,11 +467,13 @@ export class GitHubApp {}}- /** Whether pull request [number] is open, merged or closed (GET /repos/{owner}/{repo}/pulls/{number}); null when GitHub- * cannot say, which a caller must read as possibly open. */- async pullRequestState(repository: GitHubRepository, number: number, token: string): Promise<'open' | 'merged' | 'closed' | null> {+ /** Whether pull request [number] is open, merged or closed (GET /repos/{owner}/{repo}/pulls/{number}); missing when GitHub+ * answers 404, as for another repository's number read in this one (#2602); null when GitHub cannot say, which a caller+ * must read as possibly open. */+ async pullRequestState(repository: GitHubRepository, number: number, token: string): Promise<'open' | 'merged' | 'closed' | 'missing' | null> {try {const answer = await this.call('GET', `/repos/${repository.owner}/${repository.name}/pulls/${number}`, `Bearer ${token}`)+ if (answer.status === 404) return 'missing'const body = answer.body as Record<string, unknown>if (answer.status !== 200 || !['open', 'closed'].includes(String(body.state))) return nullreturn body.state === 'open' ? 'open' : typeof body.merged_at === 'string' ? 'merged' : 'closed'diff --git a/backend/src/github/fakeGitHub.ts b/backend/src/github/fakeGitHub.tsindex 51edd6781..72525306a 100644--- a/backend/src/github/fakeGitHub.ts+++ b/backend/src/github/fakeGitHub.ts@@ -37,7 +37,7 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:const issued = new Set<string>()const revoked: string[] = []let minted = 0- const control = { revokeStatus: 204, tokenStatus: 201 as number, tokenMessage: '', down: false, botId: 4242 as number | null, actionsStatus: 200, jobsStatus: 200 }+ const control = { revokeStatus: 204, tokenStatus: 201 as number, tokenMessage: '', down: false, botId: 4242 as number | null, actionsStatus: 200, jobsStatus: 200, pullsStatus: 200 }/** Each token's permissions, as it was minted. */const permissions = new Map<string, unknown>()const json = (status: number, body?: unknown) => new Response(body === undefined ? null : JSON.stringify(body), { status })@@ -122,6 +122,7 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:const repoKey = `${repoPath[1]}/${repoPath[2]}`.toLowerCase()const pull = /^\/pulls\/(\d+)$/.exec(repoPath[3] ?? '')if (pull) {+ if (control.pullsStatus !== 200) return json(control.pullsStatus, { message: 'Server Error' })const known = pulls.get(`${repoKey}#${pull[1]}`)return known ? tagged({ number: Number(pull[1]), ...known }) : json(404, { message: 'Not Found' })}diff --git a/backend/src/lib/emptyInList.test-support.ts b/backend/src/lib/emptyInList.test-support.tsindex 491608d69..505578d3e 100644--- a/backend/src/lib/emptyInList.test-support.ts+++ b/backend/src/lib/emptyInList.test-support.ts@@ -1,7 +1,7 @@/*** Finds reads that can send an empty `in` list to Prisma on MongoDB (Database optimization roadmap, phase 0.3). Prisma turns* `in: []` into `$or: []`, which no index serves: a scan of the whole collection that returns nothing, seen in the slow log on- * machines, users and SuperTab. A read of one of those models (or a raw `$in`) that names a list held in a variable must test+ * machines, users and SuperTab, and on the receipts. A read of one of those models (or a raw `$in`) that names a list held in a variable must test* that list's `.length` or `.size` first in the same function (an `if`, a `?:` or `&&`), or pass a literal list or a constant.* A filter given by name (`where`, a spread, the whole arguments) is read where it is built; one the check cannot see into (a* parameter, a call's result, one declared after the read) is flagged rather than passed. Known limits: a list inside a@@ -15,7 +15,7 @@import ts from 'typescript'/** The collections the slow log names. */-export const GUARDED_MODELS = new Set(['machine', 'user', 'superTab'])+export const GUARDED_MODELS = new Set(['machine', 'user', 'superTab', 'productUsageReceipt', 'swarmHead', 'swarmMember', 'swarmWorkspace'])export interface Unguarded { file: string; line: number; list: string }@@ -54,6 +54,10 @@ function tellsEmpty(condition: ts.Node, list: string): boolean {}const isListName = (node: ts.Expression): boolean => ts.isIdentifier(node) || (ts.isPropertyAccessExpression(node) && isListName(node.expression))const CONSTANT = /^[A-Z][A-Z0-9_]*$/+/** A list written out in the call: it holds what it names. Not one made only of spreads (`[...new Set(ids)]`), empty when they+ * are, unless each spreads a constant. Both lists production scanned with on 2026-11-04 had this form. */+const fixedList = (node: ts.Node): boolean => ts.isArrayLiteralExpression(node) && !(node.elements.length && node.elements.every(element =>+ ts.isSpreadElement(element) && !CONSTANT.test(element.expression.getText())))/** The list a `.map(...)` or `[...new Set(list)]` is as long as; the expression itself for anything else. */function listOf(node: ts.Expression): ts.Expression {@@ -150,7 +154,7 @@ export function unguardedInLists(source: string, file: string): Unguarded[] {else if (ts.isShorthandPropertyAssignment(inner) && inner.name.text === 'where') follow(inner.name, true)else if (ts.isSpreadAssignment(inner)) visitValue(inner.expression, inner.expression, false)if (ts.isPropertyAssignment(inner) && ['in', '$in'].includes(inner.name.getText().replaceAll(/['"]/g, ''))- && !ts.isArrayLiteralExpression(inner.initializer) && !(ts.isIdentifier(inner.initializer) && CONSTANT.test(inner.initializer.text))) {+ && !fixedList(inner.initializer) && !(ts.isIdentifier(inner.initializer) && CONSTANT.test(inner.initializer.text))) {const list = inner.initializer.getText()if (!(isListName(listOf(inner.initializer)) && guarded(node, inner.initializer))) {found.push({ file, line: sf.getLineAndCharacterOfPosition(inner.getStart()).line + 1, list })diff --git a/backend/src/lib/emptyInList.test.ts b/backend/src/lib/emptyInList.test.tsindex 468f6a140..aa43b2c1b 100644--- a/backend/src/lib/emptyInList.test.ts+++ b/backend/src/lib/emptyInList.test.ts@@ -126,6 +126,19 @@ describe('the empty id list check', () => {expect(lint(`function f(tx, ids) { const where = base, base = { id: { in: ids } }; return tx.user.findMany({ where }) }`)).toEqual(['base'])})+ // Both reads production scanned with on 2026-11-04 had this form, and a list written in the call used to pass.+ it('flags a list made only of spreads unless it is tested, and accepts a spread of a constant', () => {+ expect(lint(`async function f(tx, rows) { return tx.machine.findMany({ where: { machineId: { in: [...new Set(rows.map(r => r.id))] } } }) }`)).toEqual(['[...new Set(rows.map(r => r.id))]'])+ expect(lint(`async function f(tx, a, b) { return tx.user.findMany({ where: { id: { in: [...a, ...b] } } }) }`)).toEqual(['[...a, ...b]'])+ expect(lint(`async function f(tx, rows) { return rows.length ? tx.machine.findMany({ where: { machineId: { in: [...new Set(rows.map(r => r.id))] } } }) : [] }`)).toEqual([])+ expect(lint(`async function f(tx) { return tx.machine.findMany({ where: { authMode: { in: [...BILLED_MODES] } } }) }`)).toEqual([])+ expect(lint(`async function f(tx, a) { return tx.user.findMany({ where: { id: { in: ['fixed', ...a] } } }) }`)).toEqual([])+ })++ it('guards the receipts too', () => {+ expect(lint(`async function f(tx, ids) { return tx.productUsageReceipt.findMany({ where: { id: { in: ids } } }) }`)).toEqual(['ids'])+ })+it('accepts a literal list, a constant and other models', () => {expect(lint(`async function f(tx) { return tx.machine.findMany({ where: { authMode: { in: BILLED_MODES } } }) }`)).toEqual([])expect(lint(`async function f(tx) { return tx.machine.findMany({ where: { sessionKind: { in: ['team', 'person'] } } }) }`)).toEqual([])diff --git a/backend/src/lib/productUsage.test.ts b/backend/src/lib/productUsage.test.tsindex 10b6b12a3..16e4dbc6c 100644--- a/backend/src/lib/productUsage.test.ts+++ b/backend/src/lib/productUsage.test.ts@@ -179,6 +179,12 @@ describe('aggregate ingestion', () => {expect(await queued).toMatchObject({ accepted: false, reason: 'CHOICE_CHANGED', enabled: false, revision: 1 })expect(receipts()).toEqual(['receipt-1'])})+ // Prisma sends an empty list as `$or: []`: 4.1 s through all 5.1 M receipts, inside this transaction (prod slow log, 2026-11-04).+ it('reads no receipts when every report of a batch is refused', async () => {+ choices({ userId: 'a', enabled: false, revision: 1 })+ expect(await ingestProductUsage('a', report, now)).toMatchObject({ accepted: false, reason: 'CHOICE_CHANGED' })+ expect(db.productUsageReceipt.findMany).not.toHaveBeenCalled()+ })it('reports that arrive while a batch commits share the next transaction, with their totals summed', async () => {const gate = deferred()db.$transaction.mockImplementationOnce(async fn => { await gate.promise; return fn(db) })diff --git a/backend/src/lib/productUsage.ts b/backend/src/lib/productUsage.tsindex 470bf4743..c9fc6d723 100644--- a/backend/src/lib/productUsage.ts+++ b/backend/src/lib/productUsage.ts@@ -135,6 +135,8 @@ async function commitReports(reports: QueuedReport[]): Promise<IngestResult[]> {: { accepted: false, reason: 'CHOICE_CHANGED', ...choice }})const permitted = reports.filter((_, i) => results[i].accepted)+ // Every report refused: nothing to read, and an empty list would scan all the receipts (`$or: []`, 4.1 s, prod 2026-11-04).+ if (!permitted.length) return resultsconst received = new Set((await tx.productUsageReceipt.findMany({where: { id: { in: [...new Set(permitted.map(r => r.id))] } }, select: { id: true } })).map(r => r.id))// A report sent again while its first copy is in this same batch counts once too.diff --git a/backend/src/routes/community.test.ts b/backend/src/routes/community.test.tsindex 94aa6ae98..e3a0cc1e4 100644--- a/backend/src/routes/community.test.ts+++ b/backend/src/routes/community.test.ts@@ -149,6 +149,9 @@ describe('publications and access', () => {expect(feed.stats[id]).toEqual({ likes: 1, comments: 2, forks: 0, liked: false })expect((await call('GET', 'harnesses?mine=true', 'bob')).json().data.harnesses).toEqual([])expect((await call('GET', 'harnesses?mine=true')).statusCode).toBe(401)+ // An empty page reads no covers: Prisma sends an empty list as a scan of the whole collection.+ const lists = db.communityHarness.findMany.mock.calls.flatMap(([query]) => { const list = (query?.where?.id as { in?: string[] } | undefined)?.in; return list ? [list] : [] })+ expect(lists.filter(list => !list.length)).toEqual([])})it('keeps replies inside the same public harness and account environment', async () => {const id = await publish()diff --git a/backend/src/routes/community.ts b/backend/src/routes/community.tsindex baad7e352..b25cb9558 100644--- a/backend/src/routes/community.ts+++ b/backend/src/routes/community.ts@@ -201,7 +201,7 @@ export async function communityRoutes(app: FastifyInstance): Promise<void> {const [stats, covered] = await Promise.all([feedStats(ids, autonomousEnv, req.user?.sub),// Which have a cover, without reading one: a page of them is megabytes of base64.- prisma.communityHarness.findMany({ where: { id: { in: page.map(row => row.id) }, cover: { isSet: true, not: null } }, select: { id: true } }),+ page.length ? prisma.communityHarness.findMany({ where: { id: { in: page.map(row => row.id) }, cover: { isSet: true, not: null } }, select: { id: true } }) : [],])const withCover = new Set(covered.map(row => row.id))sendSuccess(reply, { harnesses: page.map(row => withCoverPath({ ...row, cover: withCover.has(row.id) ? 'set' : null })), ...(order ? { order } : {}), stats, signedIn: !!req.user, nextCursor, following: [...followed] })diff --git a/backend/src/routes/harnessShares.test.ts b/backend/src/routes/harnessShares.test.tsindex 8f1dc7bc3..edabd27b6 100644--- a/backend/src/routes/harnessShares.test.ts+++ b/backend/src/routes/harnessShares.test.ts@@ -265,6 +265,21 @@ describe('account-bound harness invitations', () => {expect((await app.inject({ method: 'GET', url: '/api/harness-shares', headers: auth })).json().data.machines).toEqual([])})+ // Prisma sends an empty list as `$or: []`, a scan of all machines (prod slow log, 2026-11-04): most people have no share.+ it('reads no machines or owners for a person with no share', async () => {+ const response = await app.inject({ method: 'GET', url: '/api/harness-shares', headers: auth })+ expect(response.json().data.machines).toEqual([])+ expect(mocks.prisma.machine.findMany).not.toHaveBeenCalled()+ expect(mocks.prisma.user.findMany).not.toHaveBeenCalled()+ })++ it('reads no owners when none of the shared machines is usable', async () => {+ mocks.prisma.harnessShare.findMany.mockResolvedValue([{ id: 's', ...input(), engine: null, ownerId: 'owner', expiresAt: new Date(input().expiresAt) }])+ mocks.prisma.machine.findMany.mockResolvedValue([])+ expect((await app.inject({ method: 'GET', url: '/api/harness-shares', headers: auth })).json().data.machines).toEqual([])+ expect(mocks.prisma.user.findMany).not.toHaveBeenCalled()+ })+it('asks the Swarms about an ordinary share too: a confidential session refuses it (final review, Critical 1)', async () => {mocks.auth.mockResolvedValue(ken)const share = { id: 'share', ...input(), superTabId: null, ownerId: owner.sub, expiresAt: new Date(input().expiresAt) }diff --git a/backend/src/routes/harnessShares.ts b/backend/src/routes/harnessShares.tsindex c324a77db..6502a9e43 100644--- a/backend/src/routes/harnessShares.ts+++ b/backend/src/routes/harnessShares.ts@@ -73,13 +73,14 @@ export async function harnessShareRoutes(app: FastifyInstance): Promise<void> {}, orderBy: { createdAt: 'asc' }, take: 1000 })// All at once: share by share, each loaded its whole Swarm again (prod 2026-10-28, p95 13.4 s).const visible = await new SuperTabStore(prisma).openableShares(req.user!, shares)- const machines = await prisma.machine.findMany({ where: {+ // Most people have no share: an empty list would scan all machines (`$or: []`, prod 2026-11-04).+ const machines = visible.length ? await prisma.machine.findMany({ where: {machineId: { in: [...new Set(visible.map(s => s.machineId))] },autonomousEnv: req.user!.autonomousEnv, ...machineAlive,- } })+ } }) : []const allowed = machines.filter(machineBillingAllowsDataPlane)- const owners = await prisma.user.findMany({ where: { id: { in: [...new Set(allowed.map(m => m.userId))] } },- select: { id: true, name: true, email: true } })+ const owners = allowed.length ? await prisma.user.findMany({ where: { id: { in: [...new Set(allowed.map(m => m.userId))] } },+ select: { id: true, name: true, email: true } }) : []const presence = await getAgentPresenceMany(allowed.map(m => m.machineId))sendSuccess(reply, { machines: allowed.flatMap(machine => {const grants = visible.filter(s => s.machineId === machine.machineId && s.ownerId === machine.userId)diff --git a/backend/src/superTabs/archive.test.ts b/backend/src/superTabs/archive.test.tsindex ef4140ea3..0a862b421 100644--- a/backend/src/superTabs/archive.test.ts+++ b/backend/src/superTabs/archive.test.ts@@ -16,6 +16,7 @@ describe('pull request states for archiving', () => {const { github, prs } = setup()expect(await prs.state('https://github.com/acme/app/pull/7')).toBe('merged')expect(await prs.state('https://github.com/acme/app/pull/8')).toBe('open')+ expect(await prs.state('https://github.com/acme/app/pull/9')).toBe('missing')const minted = github.calls.filter(c => c.path.endsWith('/access_tokens'))expect(minted).toHaveLength(1)expect(minted[0]!.body).toMatchObject({ permissions: { pull_requests: 'read', metadata: 'read' } })diff --git a/backend/src/superTabs/archive.ts b/backend/src/superTabs/archive.tsindex d9313d9ac..267b7cffc 100644--- a/backend/src/superTabs/archive.ts+++ b/backend/src/superTabs/archive.ts@@ -5,7 +5,7 @@ import { activeWork, type Conversation, type SuperTabState } from './model.js'import type { HeadData } from './parts/index.js'import type { SuperTabStore } from './store.js'import { projectsOf } from './projects.js'-import { ARCHIVE_QUIET_MS, archiveWaitsFor } from './tidy.js'+import { ARCHIVE_QUIET_MS, archiveWaitsFor, type SettledPullRequest } from './tidy.js'import { logger } from '../utils/logger.js'// A finished group archives by itself (roadmap, December: nobody tidies a Swarm by hand): its task done or cancelled, quiet@@ -15,8 +15,9 @@ import { logger } from '../utils/logger.js'// task, in the task's write (steps.ts endSteps), and never on its own clock while that task is open (task steps design): it// is taken here only once its task is done or cancelled and every pull request of both is merged or closed.-export type PullRequestState = 'open' | 'merged' | 'closed' | null-/** What a sweep asks GitHub: a pull request's state (null: it cannot say), and `done` once the sweep is over. */+export type PullRequestState = 'open' | 'merged' | 'closed' | 'missing' | null+/** What a sweep asks GitHub: a pull request's state (missing: GitHub knows no such pull request there; null: it cannot say),+ * and `done` once the sweep is over. */export interface PullRequests { state(url: string): Promise<PullRequestState>; done(): Promise<void> }/** Without the Harness GitHub App nothing can say a pull request is merged: a group that links one stays open. */@@ -106,7 +107,7 @@ export async function archiveFinishedGroups(db: PrismaClient, store: Pick<SuperTconst stateOf = (url: string) => { if (!states.has(url)) states.set(url, prs.state(url)); return states.get(url)! }// One group's failed write (a busy group's conflicts outlasting its retries, a GitHub error) skips that group for this// pass, with a warning, instead of ending the pass for every group after it (review of #2322).- const archive = async (row: { tabId: string; key: string }, checked: Record<string, 'merged' | 'closed'>, reviewOf?: string) => {+ const archive = async (row: { tabId: string; key: string }, checked: Record<string, SettledPullRequest>, reviewOf?: string) => {try {return await store.archiveFinished(row.tabId, row.key, checked, reviewOf)} catch (error) {@@ -124,21 +125,28 @@ export async function archiveFinishedGroups(db: PrismaClient, store: Pick<SuperTconst group = row.data as unknown as Conversationconst finished = ended(group), step = !!group.reviewOfif (group.audience || !(finished || (step && !activeWork(group))) || !await tidyOn(row.tabId)) continue- const checked: Record<string, 'merged' | 'closed'> = {}- // Stops at the first pull request still open, or that GitHub cannot read.+ const checked: Record<string, SettledPullRequest> = {}+ // Stops at the first pull request still open. One GitHub cannot read holds the group too, and is logged once a pass+ // when nothing open holds it: a hold nobody sees lasts forever (#2602).const settled = async (urls: string[]) => {+ const unread: string[] = []for (const url of urls) {const state = await stateOf(url)- if (state !== 'merged' && state !== 'closed') return false- checked[url] = state+ if (state === 'open') return false+ if (state === null) unread.push(url)+ else checked[url] = state}- return true+ if (unread.length) logger.warn('[swarm-archive] group held for pull requests GitHub cannot read', { tabId: row.tabId, group: row.key, pullRequests: unread })+ return !unread.length}// Its links, and a "PR #N" its result or check evidence names; none to read it in keeps it open.const head = await headOf(row.tabId)const project = head && projectsOf(head as unknown as SuperTabState).find(p => p.id === (group.projectId ?? 'lead'))const own = archiveWaitsFor(group, project?.repository?.repositoryUrl)- if (!own) continue+ if (!own) {+ logger.warn('[swarm-archive] group held: it names PR #N and its project has no GitHub repository', { tabId: row.tabId, group: row.key })+ continue+ }if (!step) {if (await settled(own) && await archive(row, checked)) archived++continuediff --git a/backend/src/superTabs/cachePatch.test.ts b/backend/src/superTabs/cachePatch.test.tsindex 0c460e337..8c54dc100 100644--- a/backend/src/superTabs/cachePatch.test.ts+++ b/backend/src/superTabs/cachePatch.test.ts@@ -1,7 +1,8 @@import { describe, expect, it } from 'vitest'import { stableId } from './model.js'-import { baseRule, cacheDigest, dormantAgentRule, feedRule, startsOfRule, dormantProjectRule, dormantRule, finishedStartsRule, groupRule, machinesRule } from './cachePatch.js'-import type { Part, PartKind, SwarmParts } from './parts/index.js'+import { baseRule, cacheDigest, dormantAgentRule, lightDormantAgentRule, feedRule, startsOfRule, dormantProjectRule, dormantRule, finishedStartsRule, groupRule, machinesRule } from './cachePatch.js'+import type { GroupData, Part, PartKind, SwarmParts } from './parts/index.js'+import { projectLightGroup } from './parts/lightSelect.js'import type { SwarmDelta } from './parts/load.js'// Part<never> fits any entry's list in these tests.@@ -140,6 +141,25 @@ describe('dormant selections', () => {})})+describe('lightDormantAgentRule (B4, #2597)', () => {+ const whole = (key: string, version: number, agentIds: string[], dormant = true) => part('group', key, version, { id: key, title: key, kind: 'task', agentIds,+ brief: 'a long brief', checks: [{ id: 'c1', description: 'Works', independent: false, status: 'pending' }], archived: false, audience: null, assignment: null },+ dormant ? { dormant: true } : {}) as Part<GroupData>++ it('holds a changed quiet conversation of the agent light, as a light load gives it', () => {+ const next = lightDormantAgentRule('a1').apply([], delta([whole('g1', 2, ['a1'])])) as Part<GroupData>[]+ expect(next).toEqual([projectLightGroup(whole('g1', 2, ['a1']))])+ expect(next[0]!.data!.brief).toBe('')+ expect(next[0]!.data!.checks).toEqual([])+ })++ it('lets go of one the agent left or that woke, and keeps the held list when nothing newer came', () => {+ const held = [projectLightGroup(whole('g1', 2, ['a1'])), projectLightGroup(whole('g2', 2, ['a1']))]+ expect((lightDormantAgentRule('a1').apply(held, delta([whole('g1', 3, ['a2']), whole('g2', 3, ['a1'], false)])) as Part[])).toEqual([])+ expect(lightDormantAgentRule('a1').apply(held, delta([whole('g1', 2, ['a1']), whole('g9', 1, ['a2'])]))).toBe(held)+ })+})+describe('feedRule (spec 2026-11-02 poll cost, Part 1.1)', () => {it('keeps tombstones, dormant groups and readAt, takes the newer version', () => {const held = { from: 500, parts: [part('group', 'g1', 1, { a: 1 }), part('machine', 'm1', 1, {}, { readAt: 900 })] }diff --git a/backend/src/superTabs/cachePatch.ts b/backend/src/superTabs/cachePatch.tsindex ebeb38f6b..161b91704 100644--- a/backend/src/superTabs/cachePatch.ts+++ b/backend/src/superTabs/cachePatch.ts@@ -12,6 +12,7 @@ import { createHash } from 'node:crypto'import { PART_KINDS, 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 { projectLightGroup } from './parts/lightSelect.js'import { stableId, type AgentStart } from './model.js'export interface PatchRule<T> {@@ -137,6 +138,14 @@ 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 `light-dormant:agent:{id}` entry (cachedReads.ts deriveLight, B4): the same selection as `dormantAgentRule`'s, each+ * conversation light (parts/lightSelect.ts projectLightGroup), as `loadLightGroups` loads it. */+export function lightDormantAgentRule(agentId: string): PatchRule<Part<GroupData>[]> {+ const keep = (p: Part) => asleep(p) && (p.data as GroupData).agentIds.includes(agentId)+ return { kinds: ['group'], apply: (held, delta) => applyByKey(held, delta.parts.map(p => p.kind === 'group' && keep(p) ? projectLightGroup(p as Part<GroupData>) : p),+ 'group', keep) }+}+/** 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>[]> {diff --git a/backend/src/superTabs/cachedReads.test.ts b/backend/src/superTabs/cachedReads.test.tsindex a0b3ef11b..44fa53119 100644--- a/backend/src/superTabs/cachedReads.test.ts+++ b/backend/src/superTabs/cachedReads.test.ts@@ -212,10 +212,10 @@ describe('light and host state derived from held entries (spec 2026-11-02 poll cexpect(light.groups.find(x => x.key === 'run')!.data!.brief).toBe('')})- it('host state takes the machine\'s agents\' dormant conversations from dormant:agent entries', async () => {- const { view, names } = stub({ 'dormant:agent:a1': [g('old', { agentIds: ['a1'] }, true)] })+ it('host state takes the machine\'s agents\' dormant conversations from light-dormant:agent entries (B4)', async () => {+ const { view, names } = stub({ 'light-dormant:agent:a1': [g('old', { agentIds: ['a1'] }, true)] })const light = await deriveLight(db, view, 't', { groups: 'working', machineId: 'm1' })- expect(names).toContain('dormant:agent:a1')+ expect(names).toContain('light-dormant:agent:a1')expect(light.groups.map(x => x.key).sort()).toEqual(['idle', 'old', 'run'])})@@ -239,7 +239,7 @@ describe('light and host state derived from held entries (spec 2026-11-02 poll cit('a machine whose agents all left derives no conversation of theirs', async () => {const { view, names } = stub()const light = await deriveLight(db, view, 't', { groups: 'working', machineId: 'gone' })- expect(names.filter(n => n.startsWith('dormant:agent:'))).toEqual([])+ expect(names.filter(n => n.startsWith('light-dormant:agent:'))).toEqual([])expect(light.groups.map(x => x.key)).toEqual(['run'])})})diff --git a/backend/src/superTabs/cachedReads.ts b/backend/src/superTabs/cachedReads.tsindex ad2457240..3700b8877 100644--- a/backend/src/superTabs/cachedReads.ts+++ b/backend/src/superTabs/cachedReads.ts@@ -7,7 +7,7 @@import type { Prisma, PrismaClient } from '@prisma/client'import { stableId, type AgentStart } from './model.js'import { CacheView } from './cache.js'-import { baseRule, dormantAgentRule, dormantProjectRule, dormantRule, feedRule, finishedStartsRule, groupRule, machinesRule } from './cachePatch.js'+import { baseRule, dormantAgentRule, dormantProjectRule, dormantRule, feedRule, finishedStartsRule, groupRule, lightDormantAgentRule, machinesRule } from './cachePatch.js'import * as store from './parts/index.js'import type { GroupData, Part, PartKind, SwarmParts, SwarmDelta } from './parts/index.js'import { retryTransient } from './retry.js'@@ -141,11 +141,12 @@ export async function deriveLight(db: Db, view: CacheView, tabId: string, opts:const awake = active.groups.map(projectLightGroup)const held = new Set(awake.map(g => g.key))const named = lightKeys(active.head, active.starts, { ...opts, groupIds }).filter(id => !held.has(id))+ // Its agents' quiet conversations light, as the host rows read them: whole, one Lead's were 3.6 MB a read on prod (B4, #2597).const [byId, ...dormant] = await Promise.all([readLightGroups(db, view, tabId, named),- ...agentIds.map(id => view.get(tabId, `dormant:agent:${id}`, 'main',- () => store.loadGroups(db, tabId, 'agents', { agentIds: { $in: [id] }, dormant: true }), dormantAgentRule(id)))])+ ...agentIds.map(id => view.get(tabId, `light-dormant:agent:${id}`, 'main',+ () => store.loadLightGroups(db, tabId, 'agents', { agentIds: { $in: [id] }, dormant: true }), lightDormantAgentRule(id)))])const candidates = new Map(awake.map(g => [g.key, g]))- for (const g of [...byId, ...dormant.flat().map(projectLightGroup)]) if (!candidates.has(g.key)) candidates.set(g.key, g)+ for (const g of [...byId, ...dormant.flat()]) if (!candidates.has(g.key)) candidates.set(g.key, g)// A machine's host state also lists every conversation of a project it has a start in (read/host.ts hostParts).const projectIds = machineId ? [...new Set(groupIds.flatMap(id => { const g = candidates.get(id); return g ? [g.data!.projectId ?? 'lead'] : [] }))]: opts.projectIds ?? []diff --git a/backend/src/superTabs/hotFilters.allowed.json b/backend/src/superTabs/hotFilters.allowed.jsonindex 8c25cb34c..936f8806e 100644--- a/backend/src/superTabs/hotFilters.allowed.json+++ b/backend/src/superTabs/hotFilters.allowed.json@@ -19,7 +19,7 @@"src/superTabs/store.ts superTabAttachment.findMany": 2,"src/superTabs/store.ts superTabAttachment.updateMany": 2,"src/superTabs/store.ts superTabDelivery.findFirst": 1,- "src/superTabs/store.ts superTabDelivery.findMany": 2,+ "src/superTabs/store.ts superTabDelivery.findMany": 1,"src/superTabs/store.ts superTabDelivery.updateMany": 11,"src/superTabs/store.ts superTabMessage.findMany": 1,"src/superTabs/store.ts superTabOperation.findMany": 1,diff --git a/backend/src/superTabs/migration/workspaces.ts b/backend/src/superTabs/migration/workspaces.tsindex be34e23de..86fce22c5 100644--- a/backend/src/superTabs/migration/workspaces.ts+++ b/backend/src/superTabs/migration/workspaces.ts@@ -45,6 +45,7 @@ async function pendingSwarms(db: PrismaClient, report: WorkspaceMigrationReport).filter(r => !r.workspaceId)report.skipped = rows.filter(r => r.format !== 2).map(r => r.id)const split = rows.filter(r => r.format === 2)+ if (!split.length) return []const heads = new Map((await db.swarmHead.findMany({ where: { id: { in: split.map(r => `${r.id}:head`) } } })).map(h => [h.tabId, h]))const members = await db.swarmMember.findMany({ where: { tabId: { in: split.map(r => r.id) }, deleted: false } })return split.flatMap(row => {diff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.tsindex 08587d0c7..a35e73566 100644--- a/backend/src/superTabs/pageReads.ts+++ b/backend/src/superTabs/pageReads.ts@@ -277,9 +277,26 @@ export async function threadReplies(tx: Transaction, tabId: string, { parts, men* left out here too.*/export async function pageThreads(tx: Transaction, tabId: string, conversationId: string, roots: string[]): Promise<ThreadReply[]> {- if (!await threadsBackfilled(tx, tabId)) return threadReplies(tx, tabId, await threadFacet(tx, tabId, conversationId, roots))- const stored = await readBy(tx, 'SuperTabThread', 'id', [{ $match: { _id: { $in: roots }, tabId, conversationId } },- { $project: { parts: 1, mentions: 1 } }]) as unknown as ThreadFacet[]+ return threadsAcross(tx, tabId, roots.map(root => ({ conversationId, root })))+}++/** pageThreads for threads of any conversations of one Swarm (read/followedThreads.ts): the summaries of all of them by root id+ * in one read, each counted only in the Swarm and conversation named for it; threadFacet per conversation before the backfill.+ * Matched by `_id` alone, so no other index of the collection (tabId, conversationId) can serve it and walk a Swarm's every+ * summary. */+export async function threadsAcross(tx: Transaction, tabId: string, threads: ReadonlyArray<{ conversationId: string; root: string }>): Promise<ThreadReply[]> {+ if (!threads.length) return []+ if (!await threadsBackfilled(tx, tabId)) {+ const byChat = new Map<string, string[]>()+ for (const t of threads) byChat.set(t.conversationId, [...byChat.get(t.conversationId) ?? [], t.root])+ const facets = []+ for (const [conversationId, roots] of byChat) facets.push(await threadFacet(tx, tabId, conversationId, roots))+ return threadReplies(tx, tabId, { parts: facets.flatMap(f => f.parts), mentions: facets.flatMap(f => f.mentions) })+ }+ const named = new Set(threads.map(t => `${t.conversationId}\u0000${t.root}`))+ const stored = (await readBy(tx, 'SuperTabThread', 'id', [{ $match: { _id: { $in: [...new Set(threads.map(t => t.root))] } } },+ { $project: { tabId: 1, conversationId: 1, parts: 1, mentions: 1 } }]) as unknown as Array<ThreadFacet & { _id: string; tabId: string; conversationId: string }>)+ .filter(t => t.tabId === tabId && named.has(`${t.conversationId}\u0000${t._id}`))return threadReplies(tx, tabId, { parts: stored.flatMap(t => t.parts), mentions: stored.flatMap(t => t.mentions) })}diff --git a/backend/src/superTabs/parts/held.ts b/backend/src/superTabs/parts/held.tsnew file mode 100644index 000000000..5e144a006--- /dev/null+++ b/backend/src/superTabs/parts/held.ts@@ -0,0 +1,156 @@+/**+ * The parts a machine's full report last read, held in this process at their exact version (B3, #2597). Every reading+ * re-read the Swarm's machine parts and its running and Lead conversations whole (prod, 2026-11-04: 1.57 GB an hour, the+ * route with the most database time), though between two reports most of them had not changed. A read here first asks+ * MongoDB, in the report's own transaction, only for each selected part's columns that every write moves (`version`,+ * `changedAt`, `readAt`, `dormant`; parts/write.ts guardedWrite), then reads whole only the parts whose columns differ from+ * what this process holds. A held part is used only when they are all equal, so the report works on what a whole read+ * would have returned. Held parts are frozen (cache.ts freeze) and shared, never changed.+ */+import type { Prisma } from '@prisma/client'+import { sizeOf } from '../cache.js'+import { recordCache } from '../cacheStats.js'+import { ms } from './light.js'+import { groupsBy, type GroupIndex } from './indexed.js'+import { partId, type PartRow } from './write.js'++type Transaction = Prisma.TransactionClient+type Where = Record<string, unknown>++/** What every process may hold, all Swarms together, measured as the read cache measures (cache.ts sizeOf). */+export const HELD_MAX_BYTES = 32 * 1024 * 1024+/** More changed machine parts than this are read in one query of them all, not one by id each. */+const FEW = 4++interface Held { columns: string; value: unknown; bytes: number; read: number }+interface Tab { tabId: string; parts: Map<string, Held>; reads: number; bytes: number }++/** The columns a write moves, as one string: a part whose string is unchanged has its data unchanged. */+function columnsOf(row: Record<string, unknown>): string {+ const date = (value: unknown) => value === null || value === undefined ? '' : value instanceof Date ? value.getTime() : ms(value)+ return `${Number(row.version)}|${date(row.changedAt)}|${date(row.readAt)}|${row.dormant ? 1 : 0}`+}+const byKey = (rows: PartRow[]) => rows.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0)+const COLUMNS = { _id: 0, key: 1, version: 1, changedAt: 1, readAt: 1, dormant: 1 }++export class HeldParts {+ private readonly tabs = new Map<string, Tab>()+ private bytes = 0+ constructor(private readonly maxBytes = HELD_MAX_BYTES) {}++ /** One report's read of a Swarm: its reads, then `done` to let go of what it no longer selects. */+ read(tabId: string): HeldRead {+ const tab = this.tabs.get(tabId) ?? { tabId, parts: new Map(), reads: 0, bytes: 0 }+ // Most recently read last: the cap lets the least recently read Swarm go first.+ this.tabs.delete(tabId)+ this.tabs.set(tabId, tab)+ return new HeldRead(this, tab, ++tab.reads)+ }++ /** @internal */ take(tab: Tab, id: string, columns: string, read: number): unknown {+ const held = tab.parts.get(id)+ if (!held || held.columns !== columns) return undefined+ held.read = read+ return held.value+ }++ /** @internal */ holds(tab: Tab, kind: 'machine' | 'group'): boolean {+ for (const id of tab.parts.keys()) if (id.startsWith(`${kind}:`)) return true+ return false+ }++ /** @internal */ keep(tab: Tab, id: string, columns: string, value: unknown, read: number): number {+ const bytes = sizeOf(value)+ // A Swarm the cap let go during this read keeps nothing.+ if (this.tabs.get(tab.tabId) !== tab) return bytes+ this.drop(tab, id)+ tab.parts.set(id, { columns, value, bytes, read })+ tab.bytes += bytes+ this.bytes += bytes+ return bytes+ }++ /** @internal */ done(tab: Tab, read: number): void {+ if (this.tabs.get(tab.tabId) !== tab) return+ // Parts no read since this one's start selected: a concurrent later read's are kept.+ for (const [id, held] of tab.parts) if (held.read < read) this.drop(tab, id)+ for (const [tabId, oldest] of this.tabs) {+ if (this.bytes <= this.maxBytes) break+ this.tabs.delete(tabId)+ this.bytes -= oldest.bytes+ }+ }++ private drop(tab: Tab, id: string): void {+ const held = tab.parts.get(id)+ if (!held) return+ tab.parts.delete(id)+ tab.bytes -= held.bytes+ this.bytes -= held.bytes+ }+}++/** The process's held parts. */+export const HELD = new HeldParts()++export class HeldRead {+ constructor(private readonly owner: HeldParts, private readonly tab: Tab, private readonly at: number) {}++ /** The Swarm's live machine parts, as `findMany({ where: { tabId, deleted: false } })` returns them, in key order. */+ async machines(tx: Transaction): Promise<PartRow[]> {+ const { tabId } = this.tab+ const all = () => tx.swarmMachine.findMany({ where: { tabId, deleted: false } }) as unknown as Promise<PartRow[]>+ // Holding none of them, the whole read alone, as before.+ if (!this.owner.holds(this.tab, 'machine')) return byKey(this.kept('machine', await all(), 'cold'))+ const listed = await tx.swarmMachine.aggregateRaw({ pipeline: [{ $match: { tabId, deleted: false } }, { $project: COLUMNS }] }) as unknown as+ Array<Record<string, unknown>>+ const rows = new Map<string, PartRow>()+ const changed: string[] = []+ for (const row of listed) {+ const value = this.owner.take(this.tab, `machine:${row.key as string}`, columnsOf(row), this.at)+ if (value) rows.set(row.key as string, value as PartRow)+ else changed.push(row.key as string)+ }+ if (!changed.length) recordCache('held-machines', 'hit')+ else {+ const read = changed.length > FEW ? (await all()).filter(row => !rows.has(row.key))+ : (await Promise.all(changed.map(key => tx.swarmMachine.findUnique({ where: { id: partId(tabId, key) } })))).filter(row => !!row && !row.deleted) as unknown as PartRow[]+ for (const row of this.kept('machine', read, 'parts')) rows.set(row.key, row)+ }+ return byKey([...rows.values()])+ }++ /** The live groups these reads find, each once, in the order the reads list them (parts/load.ts liveGroups). */+ async groups(tx: Transaction, reads: ReadonlyArray<readonly [GroupIndex, Where]>): Promise<Array<Record<string, unknown>>> {+ const { tabId } = this.tab+ const read = (columns: boolean) => Promise.all(reads.map(([index, match]) => groupsBy(tx, index, [+ { $match: { tabId, deleted: false, ...match } as Prisma.InputJsonValue }, ...columns ? [{ $project: COLUMNS }] : []])))+ const once = (rows: Array<Record<string, unknown>>) => [...new Map(rows.map(row => [row.key as string, row])).values()]+ // Holding none of them, the whole reads alone, as before.+ if (!this.owner.holds(this.tab, 'group')) return this.kept('group', once((await read(false)).flat()), 'cold')+ const listed = once((await read(true)).flat())+ const rows = new Map<string, Record<string, unknown>>()+ const changed: string[] = []+ for (const row of listed) {+ const value = this.owner.take(this.tab, `group:${row.key as string}`, columnsOf(row), this.at)+ if (value) rows.set(row.key as string, value as Record<string, unknown>)+ else changed.push(row.key as string)+ }+ if (!changed.length) recordCache('held-groups', 'hit')+ else for (const row of this.kept('group', await groupsBy(tx, 'key', [{ $match: { tabId, deleted: false, key: { $in: changed } } }]), 'parts')) rows.set(row.key as string, row)+ return listed.flatMap(row => rows.has(row.key as string) ? [rows.get(row.key as string)!] : [])+ }++ /** Holds the parts just read whole, and counts them (`swarm cache`, entries `held-machines` and `held-groups`). */+ private kept<T extends { key: string } | Record<string, unknown>>(kind: 'machine' | 'group', rows: T[], reason: 'cold' | 'parts'): T[] {+ let bytes = 0+ for (const row of rows) bytes += this.owner.keep(this.tab, `${kind}:${(row as { key: string }).key}`, columnsOf(row as Record<string, unknown>), row, this.at)+ recordCache(kind === 'machine' ? 'held-machines' : 'held-groups', 'full', { bytes, parts: rows.length, reason })+ return rows+ }++ /** Lets go of what this read no longer selected, and of the least recently read Swarms past the cap. */+ done(): void {+ this.owner.done(this.tab, this.at)+ }+}diff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.tsindex f368c1116..0091d7fbb 100644--- a/backend/src/superTabs/parts/indexed.ts+++ b/backend/src/superTabs/parts/indexed.ts@@ -76,6 +76,8 @@ export const NAMED_INDEX = {/** Unfinished deliveries in id order, a page at a time (deliverySettle.ts). Named: with a fourth status Mongo planned the pass on* `compaction` and sorted, reading far more than a page. */settle: { status: 1, _id: 1 },+ /** A message's deliveries in its Swarm. */+ byMessage: { tabId: 1, messageId: 1 },},/** Compacted receipts (pageReads.ts): a page's by message id, and a host's by the compacted delivery's id. */SuperTabReceipt: {diff --git a/backend/src/superTabs/parts/load.ts b/backend/src/superTabs/parts/load.tsindex c39d8e220..accb8d984 100644--- a/backend/src/superTabs/parts/load.ts+++ b/backend/src/superTabs/parts/load.ts@@ -6,6 +6,7 @@ import { noteChange } from '../cache.js'import type { AgentStart } from '../model.js'import { ms } from './light.js'import { groupsBy, readBy, type GroupIndex, type NamedCollection } from './indexed.js'+import { HELD, type HeldParts } from './held.js'type Transaction = Prisma.TransactionClienttype Where = Record<string, unknown>@@ -74,23 +75,30 @@ export function loadActive(tx: Transaction, tabId: string,* working agents (leaderboard/lent.ts accrueLent). A busy Swarm's finished conversations, briefs and checks were ~1.1 MB* read every 15 s per machine; the commit compares only what was loaded, so the others stay as they are. No project's report* progress either: only commands and native events note reports (projectUpdates.ts), so none is loaded or committed.+ * Machine parts and conversations come through `held` (parts/held.ts): whole only those changed since this process last+ * read them (B3, #2597).*/-export async function loadObserved(tx: Transaction, tabId: string, machineId: string): Promise<SwarmParts> {+export async function loadObserved(tx: Transaction, tabId: string, machineId: string, held: HeldParts = HELD): Promise<SwarmParts> {const live = { deleted: false }- const loaded = await assemble(tx, tabId, { member: live, agent: live, machine: live, progress: null, start: { ...live, finishedAt: null }, group: [] })+ const read = held.read(tabId)+ const [loaded, machineRows] = await Promise.all([+ assemble(tx, tabId, { member: live, agent: live, machine: null, progress: null, start: { ...live, finishedAt: null }, group: [] }),+ read.machines(tx)])+ const machines = machineRows.map(row => toPart<MachineData>('machine', row))const { projects } = loaded.head.data!// The Lead conversations; the removed Leads conversation is no longer read (model.ts leadsRemoved).const leads = projects ? projects.map(p => p.leadConversationId) : ['lead']// One read per index (parts/indexed.ts); none of them reads a quiet conversation.- const groups = await liveGroups(tx, tabId, [['running', { executionMachineId: { $ne: null }, dormant: false }],- ['key', { key: { $in: [...new Set([...leads, ...loaded.starts.map(s => s.data!.request.conversationId)])] }, dormant: false }]])+ const groups = (await read.groups(tx, [['running', { executionMachineId: { $ne: null }, dormant: false }],+ ['key', { key: { $in: [...new Set([...leads, ...loaded.starts.map(s => s.data!.request.conversationId)])] }, dormant: false }]])).map(rawGroupRow)const working = new Set(groups.flatMap(row => (row.data as GroupData).assignment?.status === 'working' ? [(row.data as GroupData).assignment!.agentId] : []))const legacy = loaded.agents.filter(a => !a.data!.projectId).map(a => a.key)const lending = loaded.agents.filter(a => a.data!.machineId === machineId && working.has(a.key)).map(a => a.key)- const more = await liveGroups(tx, tabId, [...legacy.length ? [['agents', { agentIds: { $in: legacy }, dormant: false }] as const] : [],- ...lending.length ? [['agents', { agentIds: { $in: lending }, dormant: false, 'data.audience': { $ne: null } }] as const] : []])+ const more = legacy.length || lending.length ? (await read.groups(tx, [...legacy.length ? [['agents', { agentIds: { $in: legacy }, dormant: false }] as const] : [],+ ...lending.length ? [['agents', { agentIds: { $in: lending }, dormant: false, 'data.audience': { $ne: null } }] as const] : []])).map(rawGroupRow) : []+ read.done()const rows = [...new Map([...groups, ...more].map(row => [row.key, row])).values()]- return { ...loaded, groups: rows.map(row => toPart<GroupData>('group', row)) }+ return { ...loaded, machines, groups: rows.map(row => toPart<GroupData>('group', row)) }}/** Machine parts by id (`${tabId}:${machineId}`), with their version, in one read by `_id`: what a reading-only report readsdiff --git a/backend/src/superTabs/read/followedThreads.ts b/backend/src/superTabs/read/followedThreads.tsindex b9e6d3fdf..2c832b150 100644--- a/backend/src/superTabs/read/followedThreads.ts+++ b/backend/src/superTabs/read/followedThreads.ts@@ -12,9 +12,10 @@* (chats they read now); the thread's root and replies are checked below as for any candidate. One is listed when they follow it, or started it, replied in it or were tagged in it (root or reply), and it* has a reply. Rows are those a page shows a person (inbox.ts readable): never an agent-only notice or a delivered copy.*- * Cost: the inbox's reads (without the chats' latest messages); the candidates' roots by id in one read; each candidate thread's- * newest THREAD_SCAN rows by the thread index, CHATS_PER_READ threads per read (inbox.ts perRange). `replies` counts what that- * scan read, so a longer thread says THREAD_SCAN at most. The route allows a person THREADS_READS per THREADS_WINDOW_MS in each+ * Cost: the inbox's reads (without the chats' latest messages); the candidates' roots by id in one read; the candidates' thread+ * summaries by root id in one read (pageReads.ts threadsAcross), one small row per thread whatever its length, so `replies` is+ * the whole count a chat page shows. A Swarm Buddy chat's candidates read their newest THREAD_SCAN rows by the thread index+ * instead, CHATS_PER_READ threads per read (inbox.ts perRange), and say THREAD_SCAN at most. The route allows a person THREADS_READS per THREADS_WINDOW_MS in each* Swarm, counted by every pod together, as the inbox's.*/import type { AuthUser } from '../../lib/ssoAuth.js'@@ -22,6 +23,8 @@ import { createRateLimiter } from '../../lib/rateLimit.js'import type { Author } from '../model.js'import type { ThreadReply } from '../pageReads.js'import { threadSummaries } from '../threads.js'+import { threadsAcross } from '../pageReads.js'+import { isSwarmBuddyChat } from '../buddies.js'import { readBy } from '../parts/indexed.js'import type { SuperTabStore } from '../store.js'import { taggedThreads } from '../mentions.js'@@ -78,20 +81,30 @@ export async function readFollowedThreads(store: SuperTabStore, user: AuthUser,const roots = new Map((await readable(db, tabId, found.filter(m => !isReply(m)), state)).map(m => [threadKey(m.conversationId, m.id), m]))const withRoot = candidates.filter(c => roots.has(threadKey(c.conversationId, c.threadId)))if (!withRoot.length) return { unread, read: [], more }- // Each thread's newest rows, the root among them in a short thread, by its thread index range.- const scanned = await perRange(db, withRoot.map(c => [{ $match: { tabId, conversationId: c.conversationId, thread: c.threadId } },- { $sort: { sequence: -1 } }, { $limit: THREAD_SCAN }, { $project: { ...SCAN_FIELDS, conversationId: 1 } }]))- const byThread = new Map<string, Row[]>()+ // Each thread's rows a person reads, newest first: from its summary (pageReads.ts threadsAcross), one small row per thread, which+ // stands for every row of it. A Swarm Buddy chat's are its newest rows by the thread index range instead: its summary cannot+ // tell a row of a project its person lost (buddySessions.ts lostProjectRow), which they no longer read.+ const scannedIn = withRoot.filter(c => isSwarmBuddyChat(groups.get(c.conversationId)!))+ const summedIn = withRoot.filter(c => !isSwarmBuddyChat(groups.get(c.conversationId)!))+ const byThread = new Map<string, ThreadReply[]>()+ const add = (key: string, m: ThreadReply) => byThread.set(key, [...byThread.get(key) ?? [], m])+ const chatOf = new Map(summedIn.map(c => [c.threadId, c.conversationId]))+ for (const m of (await threadsAcross(db, tabId, summedIn.map(c => ({ conversationId: c.conversationId, root: c.threadId })))).toReversed()) {+ if (!m.agentOnly && m.id !== m.thread) add(threadKey(chatOf.get(m.thread)!, m.thread), m)+ }+ const scanned = scannedIn.length ? await perRange(db, scannedIn.map(c => [{ $match: { tabId, conversationId: c.conversationId, thread: c.threadId } },+ { $sort: { sequence: -1 } }, { $limit: THREAD_SCAN }, { $project: { ...SCAN_FIELDS, conversationId: 1 } }])) : []for (const m of await readable(db, tabId, scanned.filter(isReply), state)) {- const key = threadKey(m.conversationId, m.thread!)- byThread.set(key, [...byThread.get(key) ?? [], m])+ add(threadKey(m.conversationId, m.thread!), { thread: m.thread!, id: m.id, author: m.author, mentions: m.mentions, sequence: m.sequence,+ createdAt: m.createdAt, agentOnly: false, routing: false })}const own = (a: Pick<Author, 'kind' | 'id'>) => a.kind === 'person' && a.id === personId- const inIt = (m: Row) => own(m.author) || m.mentions.includes(personId)+ const inIt = (m: Pick<Row, 'author' | 'mentions'>) => own(m.author) || m.mentions.includes(personId)const read: Array<FollowedThread & { at: number }> = []for (const c of withRoot) {const key = threadKey(c.conversationId, c.threadId), root = roots.get(key)!- // Newest first, as the scan reads them.+ // Newest first. A summary row stands for `count` rows of one author and kind, its newest and oldest among them: the newest+ // reply, each author's newest and every person's first tag are always there, which is all this reads.const replies = byThread.get(key) ?? []const newest = replies[0]if (!newest || !(c.follow === true || inIt(root) || replies.some(inIt))) continue@@ -101,8 +114,8 @@ export async function readFollowedThreads(store: SuperTabStore, user: AuthUser,const seen = Math.max(c.sequence > 0 ? c.sequence : mark, replies.find(m => own(m.author))?.sequence ?? 0)if (mark > 0 && !own(newest.author) && replies.some(m => !own(m.author) && m.sequence > seen)) { more = true; continue }// Named as a page's thread summary names them: only authors who can still read the chat (threads.ts).- const rows: ThreadReply[] = [root, ...replies.toReversed()].map(m => ({ thread: c.threadId, id: m.id, author: m.author, mentions: m.mentions,- sequence: m.sequence, createdAt: m.createdAt, agentOnly: false, routing: false }))+ const rows: ThreadReply[] = [{ thread: c.threadId, id: root.id, author: root.author, mentions: root.mentions, sequence: root.sequence,+ createdAt: root.createdAt, agentOnly: false, routing: false }, ...replies.toReversed()]const [summary] = threadSummaries(state, groups.get(c.conversationId)!, rows)if (!summary) continueread.push({ conversationId: c.conversationId, rootId: root.id, root: preview(root), replies: summary.replies, lastReplyAt: summary.lastAt.toISOString(),diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex eccccdd82..adc8bbbb9 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -49,7 +49,7 @@ import { moveChatMark } from './read/threadMarkSeeds.js'import { closedAgents, nextRemovalAt, removeClosedAgents, reopened, restoreRefusal, restoreSessions } from './closedAgents.js'import { sessionRows } from './memberRows.js'import { failRefusedStarts, judgedMachines, loseTasks, nextLossAt, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'-import { archivable, archiveLine, archiveWaitsFor, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests } from './tidy.js'+import { archivable, archiveLine, archiveWaitsFor, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests, type SettledPullRequest } from './tidy.js'import { clock, insertParts, loadActive, loadGroups, loadLightGroups, loadMachineParts, loadObserved, reassemble, split, type GroupData, type HeadData, type MachineData, type Part, type SwarmParts } from './parts/index.js'import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'import { autoJoinSwarms, machineSwarms, memberSwarms } from './swarmRows.js'@@ -1159,7 +1159,9 @@ export class SuperTabStore {/** The heads of Swarms already split into parts, by id. */private async heads(rows: Array<Pick<SwarmRow, 'id' | 'format'>>): Promise<Map<string, HeadData>> {- const heads = await this.db.swarmHead.findMany({ where: { id: { in: rows.filter(r => r.format === 2).map(r => `${r.id}:head`) } } })+ const parted = rows.filter(r => r.format === 2)+ if (!parted.length) return new Map()+ const heads = await this.db.swarmHead.findMany({ where: { id: { in: parted.map(r => `${r.id}:head`) } } })return new Map(heads.map(head => [head.tabId, head.data as unknown as HeadData]))}@@ -2560,7 +2562,8 @@ export class SuperTabStore {}}if (kept.size) {- const have = new Set((await tx.superTabDelivery.findMany({ where: { messageId: { in: [...kept] } }, select: { id: true } })).map(d => d.id))+ // By the Swarm too: by message id alone it scanned every delivery, 440 ms in this transaction (Atlas slow log, 2026-11-04).+ const have = new Set((await readBy(tx, 'SuperTabDelivery', 'byMessage', [{ $match: { tabId, messageId: { $in: [...kept] } } }, { $project: { _id: 1 } }])).map(d => d._id as string))// A delivery compacted into its message's receipts (deliveryCompaction.ts) was written too: never sent again.const compacted = await readBy(tx, 'SuperTabReceipt', 'id', [{ $match: { _id: { $in: [...kept] }, tabId } }, { $project: { deliveryIds: 1 } }])for (const receipt of compacted) for (const id of receipt.deliveryIds as string[] ?? []) have.add(id)@@ -2880,17 +2883,16 @@ export class SuperTabStore {/** What the attempts routed in the last `days` cost and how they went (costs/read.ts), over the groups the reader may read.* The decisions are read first, by index, so only the groups they name are loaded. */async costSummary(user: AuthUser, tabId: string, days: number, asAgentId?: string) {- return transaction(this.db, async tx => {- const until = this.now(), since = until - days * 24 * 60 * 60_000- const { rows, truncated } = await costRows(tx, tabId, since)- const { state } = await this.load(tx, user, tabId, { groupIds: [...new Set(rows.map(r => r.conversationId))] })- const actor = await this.actor(tx, user, state, asAgentId)- author(state, actor)- // What routed attempts cost, by engine, model and spend, is how work is routed: never a Buddy's (review of #2115).- refuseBuddyRouting(state, actor)- const readable = state.conversations.filter(c => canReadGroup(state, actor, c)), ids = new Set(readable.map(c => c.id))- return { since, until, days, truncated, ...summarizeCosts(rows.filter(r => ids.has(r.conversationId)), readable) }- })+ const until = this.now(), since = until - days * 24 * 60 * 60_000+ const { rows, truncated } = await costRows(this.db, tabId, since)+ // Through the read cache, as every read: only what the Swarm's stamp says changed is read again (task #2596).+ const { state } = await this.readLoad(user, tabId, { groupIds: [...new Set(rows.map(r => r.conversationId))] })+ const actor = await this.actor(this.db, user, state, asAgentId)+ author(state, actor)+ // What routed attempts cost, by engine, model and spend, is how work is routed: never a Buddy's (review of #2115).+ refuseBuddyRouting(state, actor)+ const readable = state.conversations.filter(c => canReadGroup(state, actor, c)), ids = new Set(readable.map(c => c.id))+ return { since, until, days, truncated, ...summarizeCosts(rows.filter(r => ids.has(r.conversationId)), readable) }}async routeDecision(user: AuthUser, tabId: string, decisionId: string, asAgentId?: string) {@@ -2940,14 +2942,13 @@ export class SuperTabStore {* other projects in the Swarm, those they may open, to name the ones its repository is approved for. */async projectRepository(user: AuthUser, tabId: string, projectId: string):Promise<{ repositoryUrl: string | null; approvalRequired: boolean; name: string; others: Array<{ id: string; name: string }> }> {- return transaction(this.db, async tx => {- const { state } = await this.load(tx, user, tabId)- const actor = await this.actor(tx, user, state)- const projects = visibleState(state, actor, this.now()).projects ?? []- const project = projects.find(p => p.id === projectId) ?? fail('NOT_FOUND', 'This project is unavailable.', 404)- return { repositoryUrl: project.repository?.repositoryUrl ?? null, approvalRequired: teamAccountRequired(), name: project.name,- others: projects.filter(p => p.id !== projectId).map(p => ({ id: p.id, name: p.name })) }- })+ // Through the read cache, as every read (task #2596): every app reads it again when the project's GitHub revision moves.+ const { state } = await this.readLoad(user, tabId)+ const actor = await this.actor(this.db, user, state)+ const projects = visibleState(state, actor, this.now()).projects ?? []+ const project = projects.find(p => p.id === projectId) ?? fail('NOT_FOUND', 'This project is unavailable.', 404)+ return { repositoryUrl: project.repository?.repositoryUrl ?? null, approvalRequired: teamAccountRequired(), name: project.name,+ others: projects.filter(p => p.id !== projectId).map(p => ({ id: p.id, name: p.name })) }}/** A project's repository for the route's read of its running CI jobs (github/ciLoad.ts), by a person or an agent of the@@ -3031,10 +3032,13 @@ export class SuperTabStore {const rows = (await readBy(this.db, 'SuperTab', 'owner', [{ $match: { autonomousEnv: user.autonomousEnv, ownerId: user.sub, format: 2, deletedAt: null } },{ $sort: { _id: 1 } }, { $limit: 100 }, { $project: { _id: 1 } }])).map(row => ({ id: row._id as string }))return transaction(this.db, async tx => {+ if (!rows.length) return []const heads = await tx.swarmHead.findMany({ where: { tabId: { in: rows.map(row => row.id) }, key: 'head' }, select: { tabId: true, data: true } })const withGrid = new Map(heads.map(head => [head.tabId, head.data as unknown as HeadData] as const).filter(([, head]) => head.localModels))- const people = new Map<string, Person[]>([...withGrid.keys()].map(tabId => [tabId, []]))- for (const member of await tx.swarmMember.findMany({ where: { tabId: { in: [...withGrid.keys()] }, deleted: false },+ const gridTabs = [...withGrid.keys()]+ if (!gridTabs.length) return []+ const people = new Map<string, Person[]>(gridTabs.map(tabId => [tabId, []]))+ for (const member of await tx.swarmMember.findMany({ where: { tabId: { in: gridTabs }, deleted: false },orderBy: { ordinal: 'asc' }, select: { tabId: true, data: true } })) people.get(member.tabId)!.push(member.data as unknown as Person)return rows.flatMap(row => withGrid.has(row.id)? [swarmGridRow(row.id, { ...withGrid.get(row.id)!, people: people.get(row.id)! } as SuperTabState)!] : [])@@ -3966,7 +3970,7 @@ export class SuperTabStore {})}- async archiveFinished(tabId: string, groupId: string, checked: Readonly<Record<string, 'merged' | 'closed'>>, reviewOf?: string): Promise<boolean> {+ async archiveFinished(tabId: string, groupId: string, checked: Readonly<Record<string, SettledPullRequest>>, reviewOf?: string): Promise<boolean> {return transaction(this.db, async tx => {const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })if (!row || row.deletedAt) return false@@ -3978,7 +3982,7 @@ export class SuperTabStore {// it in it stays open (tidy.ts archiveWaitsFor). Read only once it may close, so its project is a real one.const read = (urls: readonly string[]) => {const waits = archiveWaitsFor(group, groupProject(state, group).repository?.repositoryUrl)- return !!waits && [...urls, ...waits].every(url => checked[url] === 'merged' || checked[url] === 'closed')+ return !!waits && [...urls, ...waits].every(url => !!checked[url])}// A step's task's pull requests count too: it may yet be handed back while one is open, and need its step again.const finished = archivable(state, group, now) && read(reviewPullRequests(state, group))diff --git a/backend/src/superTabs/tidy.test.ts b/backend/src/superTabs/tidy.test.tsindex 80124f0cb..8e5deac8b 100644--- a/backend/src/superTabs/tidy.test.ts+++ b/backend/src/superTabs/tidy.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'import { agentOnly, type Agent, type Assignment, type Conversation, type SuperTabState } from './model.js'-import { ARCHIVE_QUIET_MS, archivable, IDLE_NOTICE_MS, idleNotices, linkPending, staleSwitches, SWITCH_UNCLAIMED_MS, reviewClosable, reviewCloseLine, reviewPullRequests } from './tidy.js'+import { ARCHIVE_QUIET_MS, archivable, archiveWaitsFor, IDLE_NOTICE_MS, idleNotices, linkPending, staleSwitches, SWITCH_UNCLAIMED_MS, reviewClosable, reviewCloseLine, reviewPullRequests } from './tidy.js'const MINUTE = 60_000const START = Date.parse('2026-10-27T08:00:00.000Z')@@ -171,6 +171,35 @@ describe('which finished groups archive', () => {})})+// Diego, 11-04: "Ported from autonomous-harness PR #2716" read as this project's pull/2716 kept the task open forever (#2602).+describe('what a finished group\'s archive waits on', () => {+ const repo = 'https://github.com/acme/openharness', pull = (n: number) => `${repo}/pull/${n}`+ const named = (result: string) => group({ assignment: done({ result }) })+ it('waits on a "PR #N" of its project\'s repository, never on one another repository\'s name sits next to', () => {+ expect(archiveWaitsFor(named('Merged PR #40. Ported from autonomous-harness PR #2716.'), repo)).toEqual([pull(40)])+ for (const result of ['Ported (from autonomous-harness PR #12)', 'From other/tool PR #12', 'from foo.js/bar_baz PR #12',+ 'acme/tool PR #12', 'PR #12 in acme/tool', 'PR #12 of ACME/tool']) {+ expect(archiveWaitsFor(named(result), repo)).toEqual([])+ }+ })++ // Review of #2895: dropping one of its own numbers archives it while that PR is open (#558); reading another's as its own+ // waits at most until that number of its own closes, or is not found. So a name counts only where it plainly says so.+ it('still reads a number its own repository names, or an ordinary word sits next to, as its project\'s', () => {+ for (const result of ['acme/openharness PR #12', 'ACME/OpenHarness PR #12', 'openharness PR #12', 'Follow-up PR #12', 'Re-opened PR #12',+ 'Merged. PR #12', 'Merged PR #12', 'PR #12 in review', 'PR #12 of the batch', 'from openharness PR #12', 'from acme/openharness PR #12',+ 'Desktop/CLI PR #12 is open', 'test-only PR #12', 'docs-only PR #12', 'backend-only PR #12', 'CLI-side PR #12', 'v0.5.33 PR #12',+ 'fix/2598-relay-offline-hold PR #12', 'PR #12 in docs/plans', 'PR #12 in desktop/src', 'PR #12 of 2026-11-04', 'PR #12 of autonomous-harness']) {+ expect(archiveWaitsFor(named(result), repo)).toEqual([pull(12)])+ }+ })++ it('stays open for a bare number with no repository to read it in, but not for another repository\'s', () => {+ expect(archiveWaitsFor(named('PR #12'), null)).toBeNull()+ expect(archiveWaitsFor(named('Ported from autonomous-harness PR #2716.'), null)).toEqual([])+ })+})+// Ken, 2026-10-30: 28 of 31 open review groups waited for a Reviewer on pull requests already merged or closed.describe('which reviews nobody reviews may close', () => {const quiet = START + ARCHIVE_QUIET_MS@@ -238,6 +267,11 @@ describe('which reviews nobody reviews may close', () => {expect(reviewCloseLine(state, review(state), { [PR]: 'merged', [SECOND]: 'closed' }, quiet)).toMatchObject({ conversationId: 'r1', recipients: [],author: { kind: 'agent', id: 'L' }, source: { kind: 'auto-archive' }, text: 'Closed: #2288 merged, #2290 closed; no Swarm review is needed now.' })})++ it('says a pull request GitHub does not know was not found', () => {+ const state = reviewState({}, [PR])+ expect(reviewCloseLine(state, review(state), { [PR]: 'missing' }, quiet)?.text).toBe('Closed: #2288 not found; no Swarm review is needed now.')+ })})describe('staleSwitches', () => {diff --git a/backend/src/superTabs/tidy.ts b/backend/src/superTabs/tidy.tsindex 3b3e0d5e7..1fb66ac5a 100644--- a/backend/src/superTabs/tidy.ts+++ b/backend/src/superTabs/tidy.ts@@ -2,7 +2,7 @@ import { checksOpenWork, isStep, taskEnded } from './steps.js'import { isBuddy } from './buddies.js'import { expiredModelRequests, unservedBuddyModels } from './buddyModel.js'import { agentDisplayName } from './agentNames.js'-import { githubRepository } from '../github/repository.js'+import { githubRepository, type GitHubRepository } from '../github/repository.js'import { activeWork, appendPullRequestUrls, stableId, type Actor, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'import { agentProjectId, canReadGroup, groupProject, ledProject, projectsOf } from './projects.js'import { toLead } from './terminal.js'@@ -154,17 +154,46 @@ export const cancelReason = (group: Conversation): string => (group.assignment?./** "PR #1875", as a Lead's cancel or a builder's result names a pull request without its link. */const PR_NUMBER = /\bPR #([1-9][0-9]{0,8})\b/gi+/** A repository's name, or owner/name, as a result writes it next to "PR #N": "from autonomous-harness PR #2716", "PR #12 in acme/tool". */+const REPO_NAME = '([A-Za-z0-9](?:[\\w.-]*\\w)?(?:/[A-Za-z0-9](?:[\\w.-]*\\w)?)?)'+const NAME_BEFORE = new RegExp(`(?:^|[\\s(])(from\\s+)?${REPO_NAME}\\s+$`, 'i'), NAME_AFTER = new RegExp(`^\\s+(?:in|of)\\s+${REPO_NAME}`, 'i')+/** English compounds a result writes before "PR", which look like a repository's name and are none. */+const COMPOUND = /^(?:follow-(?:up|on)|(?:re|co|pre|non|one)-\w+)$/i++/** Whether [name] next to a "PR #N" plainly names a repository other than the project's. Dropping one of its own numbers+ * archives a group while that pull request is open (#558); reading another's as its own waits at most until that number+ * closes here or is not found. So "Desktop/CLI PR #12", "test-only PR #12" and "PR #12 in docs/plans" stay its own (review+ * of #2895): a name counts after "from" ("Ported from autonomous-harness PR #2716"), or as owner/name of the project's owner. */+function otherRepository(name: string | undefined, from: boolean, repository: GitHubRepository | null): boolean {+ if (!name) return false+ const [owner, repo] = name.toLowerCase().split('/')+ if (repo === undefined) return from && /^[a-z]/.test(owner!) && /[._-]/.test(owner!) && !COMPOUND.test(owner!) && owner !== repository?.name.toLowerCase()+ if (name.toLowerCase() === repository?.fullName.toLowerCase()) return false+ return from || owner === repository?.owner.toLowerCase()+}++/** How a pull request an archive waits on ended: merged, closed, or missing, a number GitHub knows no pull request by in+ * that repository (another repository's, #2602). */+export type SettledPullRequest = 'merged' | 'closed' | 'missing'/** The pull requests a group's archive waits on: those it links, and those its result and check evidence name, a "PR #N"* read in its project's repository. A cancel saying "Handed off as PR #1875" linked nothing, so the group archived while- * that PR was open (#558). Null when it names a number with no GitHub repository to read it in: it stays open. */+ * that PR was open (#558). A number another repository's name sits next to is that repository's, and never waited on+ * ("Ported from autonomous-harness PR #2716" held a task open forever, #2602). Null when it names a number with no GitHub+ * repository to read it in: it stays open. */export function archiveWaitsFor(group: Conversation, repositoryUrl: string | null | undefined): string[] | null {const texts = [group.assignment?.result, ...group.checks.map(check => check.evidence)]const named = { pullRequestUrls: [...group.pullRequestUrls ?? []] } as ConversationappendPullRequestUrls(named, texts)- const numbers = texts.flatMap(text => [...(text ?? '').matchAll(PR_NUMBER)].map(match => match[1]!))- if (!numbers.length) return named.pullRequestUrls!const repository = githubRepository(repositoryUrl)+ const numbers = texts.flatMap(text => [...(text ?? '').matchAll(PR_NUMBER)]+ .filter(match => {+ const before = NAME_BEFORE.exec(text!.slice(0, match.index))+ return !otherRepository(before?.[2], !!before?.[1], repository)+ && !otherRepository(NAME_AFTER.exec(text!.slice(match.index + match[0].length))?.[1], false, repository)+ })+ .map(match => match[1]!))+ if (!numbers.length) return named.pullRequestUrls!if (!repository) return nullreturn [...new Set([...named.pullRequestUrls!, ...numbers.map(n => `https://github.com/${repository.fullName}/pull/${n}`)])]}@@ -216,7 +245,7 @@ export function reviewClosable(state: SuperTabState, review: Conversation, now:const pullNumber = (url: string) => `#${url.slice(url.lastIndexOf('/') + 1)}`/** The one quiet line a closed review gets, naming each pull request and how it ended. */-export function reviewCloseLine(state: SuperTabState, review: Conversation, settled: Readonly<Record<string, 'merged' | 'closed'>>, now: number): MessageDraft | null {- const prs = reviewPullRequests(state, review).map(url => `${pullNumber(url)} ${settled[url]}`).join(', ')+export function reviewCloseLine(state: SuperTabState, review: Conversation, settled: Readonly<Record<string, SettledPullRequest>>, now: number): MessageDraft | null {+ const prs = reviewPullRequests(state, review).map(url => `${pullNumber(url)} ${settled[url] === 'missing' ? 'not found' : settled[url]}`).join(', ')return leadLine(state, review, now, `Closed: ${prs}; no Swarm review is needed now.`)}diff --git a/backend/src/superTabs/workspaceStore.ts b/backend/src/superTabs/workspaceStore.tsindex de84a5049..83d54d8a0 100644--- a/backend/src/superTabs/workspaceStore.ts+++ b/backend/src/superTabs/workspaceStore.ts@@ -229,6 +229,7 @@ export class SwarmWorkspaces {/** Invitations waiting for the signed-in person. */async invitationsFor(user: AuthUser) {const rows = await this.db.swarmWorkspaceInvitation.findMany({ where: { email: user.email.trim().toLowerCase(), expiresAt: { gt: new Date(this.deps.now()) } }, take: 100 })+ if (!rows.length) return { invitations: [] }const workspaces = await this.db.swarmWorkspace.findMany({ where: { id: { in: rows.map(r => r.workspaceId) }, autonomousEnv: user.autonomousEnv } })return { invitations: rows.flatMap(row => {const workspace = workspaces.find(o => o.id === row.workspaceId && !o.deletedAt)diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex f13304bfc..484fcb7f7 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/superTabAutoJoin.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/superTabCacheDelta.test.ts', 'integration/superTabHostGroups.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/superTabHostGroups.test.ts', 'integration/superTabMachineReports.test.ts', 'integration/superTabHeldParts.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/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts','integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts',diff --git a/docs/plans/2026-11-04-archive-other-repo-pr-plan.md b/docs/plans/2026-11-04-archive-other-repo-pr-plan.mdnew file mode 100644index 000000000..c07062689--- /dev/null+++ b/docs/plans/2026-11-04-archive-other-repo-pr-plan.md@@ -0,0 +1,89 @@+# Archive: another repository's PR #N Implementation Plan++> **For agentic workers:** Follow the project Engineer workflow: plan first in a draft PR; implement task by task with a committed failing test before its passing code; one independent review step on the pull request.++**Goal:** A finished task whose result or check evidence names another repository's pull request ("Ported from autonomous-harness PR #2716") archives once its own pull requests are merged or closed, and a group the pass still holds for a pull request nobody can read says so in the log. Strengthens "reviewed and tested before merge" and "dozens of agents run at once": a step left open keeps its Reviewer or Tester busy (AGENT_BUSY) forever.++**Architecture:** Three small changes on the archive path. `archiveWaitsFor` (tidy.ts) reads a "PR #N" as the project's only when nothing next to it names another repository. `pullRequestState` (github/app.ts) answers `'missing'` for a 404 instead of null, and the pass (archive.ts `settled`) and the archive write (store.ts `archiveFinished`) count a missing pull request as settled. The pass logs one warning per group it holds only for pull requests it cannot read.++**Tech Stack:** TypeScript, Vitest, MongoDB memory replica set (integration).++**Spec:** Task #2602 in Super Tab conversation c0b45c5f4e35d958d92aa9b4 (Diego, 2026-11-04; brief from River).++## Global Constraints++- Example result `'Merged PR #40. Ported from autonomous-harness PR #2716.'` on repository `acme/openharness` waits only on `https://github.com/acme/openharness/pull/40`.+- A number is another repository's only where the text plainly says so (review of #2895: dropping one of the project's own numbers archives while that PR is open, #558; reading another's as the project's waits at most until that number closes here or is not found): a name right after "from" (`from autonomous-harness PR #2716`, `from other/tool PR #12`), or `owner/name` of the project's owner other than the project, before "PR" or after "in"/"of". The project's own `owner/repo` or name keeps it the project's, and so do ordinary words and paths (`Desktop/CLI`, `test-only`, `v0.5.33`, `fix/2598-…`, `in docs/plans`, `of 2026-11-04`). Common English compounds (`follow-up`, `follow-on`, `re-…`, `co-…`, `pre-…`, `non-…`, `one-…`) are words, not repositories.+- 404 means not a pull request of that repository: skipped (settled). 5xx, network errors, refused tokens and no installation stay null: try again next pass.+- Kept as they are: integration cases "waits for a pull request its cancel names only as PR #N" ('Handed off as PR #1875', open, then archives on merge) and "stays open when its work names PR #N and the project has no repository".+- Log line: `logger.warn('[swarm-archive] group held for pull requests GitHub cannot read', { tabId, group, pullRequests })`, and for the no-repository case `logger.warn('[swarm-archive] group held: it names PR #N and its project has no GitHub repository', { tabId, group })`; once per group per pass, and never for a group an open pull request holds.+- Swarm code stays out of cli/src/core. PR body starts with "Requested by [email protected] through Harness."++## Review Focus++1. "Follow-up PR #13" or "Re-opened PR #13" must still wait on #13 in the project's repository (pinned in Task 1).+2. A sentence boundary before "PR" ("Merged. PR #3") is no repository name (pinned in Task 1).+3. A number of another repository when the project has no repository archives instead of holding forever; a bare project number with no repository still holds (pinned in Task 1).+4. GitHub down during a pass never archives a group: only a 404 is settled (pinned in Task 2 and Task 3).+5. A review step's close line names a missing pull request readably ("#2716 not found"), not as "missing" (pinned in Task 3).++---++### Task 1: archiveWaitsFor skips another repository's number++**Files:**+- Modify: `backend/src/superTabs/tidy.ts` (PR_NUMBER, archiveWaitsFor)+- Test: `backend/src/superTabs/tidy.test.ts`, `backend/integration/superTabTidy.test.ts`++**Interfaces:**+- Produces: `archiveWaitsFor(group, repositoryUrl): string[] | null`, unchanged signature.++- [x] **Step 1: Write the failing tests** in tidy.test.ts, `describe('what a finished group\'s archive waits on')`, with `const repo = 'https://github.com/acme/openharness'` and `named = (result: string) => group({ assignment: done({ result }) })`:+ - `archiveWaitsFor(named('Merged PR #40. Ported from autonomous-harness PR #2716.'), repo)` equals `['https://github.com/acme/openharness/pull/40']`.+ - `'other/tool PR #12'`, `'PR #12 in other/tool'`, `'PR #12 of autonomous-harness'` each wait on nothing (`[]`).+ - `'acme/openharness PR #12'`, `'openharness PR #12'`, `'Follow-up PR #12'`, `'Re-opened PR #12'`, `'Merged. PR #12'`, `'PR #12 in review'` each wait on `.../pull/12`.+ - With no repository: `'Ported from autonomous-harness PR #2716.'` waits on `[]`; `'PR #12'` stays `null`.+ - Integration, in `describe('a finished group')`: a cancel with reason `'Merged PR #40. Ported from autonomous-harness PR #2716.'` in a project with repository `https://github.com/acme/app` archives with a stub answering merged for `.../acme/app/pull/40` only, and the stub never read `pull/2716`.+- [x] **Step 2: Run** `npx vitest run src/superTabs/tidy.test.ts` and `npx vitest run --config vitest.super-tabs.config.ts integration/superTabTidy.test.ts -t "another repository"`: FAIL (2716 is read as acme's).+- [x] **Step 3: Implement** in archiveWaitsFor: for each PR_NUMBER match, look at the text before it (`/(?:^|[\s(])([A-Za-z0-9][\w.-]*(?:\/[\w.-]*\w)?)\s+$/` on the slice) and after it (`/^\s+(?:in|of)\s+([A-Za-z0-9][\w.-]*(?:\/[\w.-]*\w)?)/i`), and drop the number when either names another repository by the Global Constraints. Compute the repository before the null check, so a project with no repository that names only other repositories' numbers waits on its links alone.+- [x] **Step 4: Run** the same commands: PASS.+- [x] **Step 5: Commit** test first, then code.++### Task 2: pullRequestState tells a 404 apart++**Files:**+- Modify: `backend/src/github/app.ts` (pullRequestState), `backend/src/github/fakeGitHub.ts` (a `pullsStatus` control), `backend/src/superTabs/archive.ts` (PullRequestState type)+- Test: `backend/src/github/app.test.ts`, `backend/src/superTabs/archive.test.ts`++**Interfaces:**+- Produces: `pullRequestState(...): Promise<'open' | 'merged' | 'closed' | 'missing' | null>`; `PullRequestState = 'open' | 'merged' | 'closed' | 'missing' | null`.++- [x] **Step 1: Write the failing tests:** app.test.ts "answers missing for a pull request GitHub does not know, null when GitHub cannot say": unknown `#9` is `'missing'`; with `github.control.pullsStatus = 502` a known `#9` is null; a refused token and `control.down` stay null. archive.test.ts: `prs.state('https://github.com/acme/app/pull/9')` (not in the fake) is `'missing'`.+- [x] **Step 2: Run** `npx vitest run src/github/app.test.ts src/superTabs/archive.test.ts`: FAIL (null).+- [x] **Step 3: Implement:** `if (answer.status === 404) return 'missing'` before the 200 check.+- [x] **Step 4: Run** the same command: PASS.+- [x] **Step 5: Commit** test first, then code.++### Task 3: the pass and the write settle a missing pull request, and log what holds a group++**Files:**+- Modify: `backend/src/superTabs/archive.ts` (settled, the no-repository skip), `backend/src/superTabs/store.ts` (archiveFinished's checked type and read), `backend/src/superTabs/tidy.ts` (`SettledPullRequest` type, reviewCloseLine)+- Test: `backend/integration/superTabTidy.test.ts`, `backend/src/superTabs/tidy.test.ts`++**Interfaces:**+- Consumes: `PullRequestState` with `'missing'` (Task 2).+- Produces: `export type SettledPullRequest = 'merged' | 'closed' | 'missing'` in tidy.ts; `archiveFinished(tabId, groupId, checked: Readonly<Record<string, SettledPullRequest>>, reviewOf?)`; `reviewCloseLine(..., settled: Readonly<Record<string, SettledPullRequest>>, ...)`.++- [x] **Step 1: Write the failing tests:**+ - Integration "archives when a pull request it names is not found in the project's repository": repository `https://github.com/acme/app`, cancel reason `'Merged PR #40. Ported from PR #2716.'`, pass with `appPullRequests(fakeApp(...))` over a `fakeGitHub` that has `acme/app` installed, `#40` merged and no `#2716` (a real 404): archived.+ - Integration "logs once a group held only for a pull request GitHub cannot read": spy `logger.warn`; a group linking `PR` with the stub answering null: one `'[swarm-archive] group held for pull requests GitHub cannot read'` call with `{ group: f.group, pullRequests: [PR] }` per pass; with the stub answering open: none. A group naming `PR #1868` with no repository: one `'… its project has no GitHub repository'` call.+ - tidy.test.ts: `reviewCloseLine` with `{ [url]: 'missing' }` reads `#N not found`.+- [x] **Step 2: Run** `npx vitest run --config vitest.super-tabs.config.ts integration/superTabTidy.test.ts` and `npx vitest run src/superTabs/tidy.test.ts`: FAIL.+- [x] **Step 3: Implement:** `settled` reads every URL unless one is open (an open one returns false with no log); merged, closed and missing are recorded in `checked`; null ones are collected, logged once, and return false. The `!own` skip logs its line. store.ts `read` accepts `'missing'`. reviewCloseLine prints `not found` for `'missing'`.+- [x] **Step 4: Run** the same commands: PASS.+- [x] **Step 5: Commit** test first, then code.++### Finish++- [x] `npx tsc --noEmit` and the tests of what changed, locally; the PR's CI runs the whole backend suite once it is ready, and its green run is the suite evidence (Ken, 2026-11-04).+- [x] Red/green evidence in a PR comment; mark the PR ready; add the review step.diff --git a/docs/plans/2026-11-04-backend-db-hot-scans-plan.md b/docs/plans/2026-11-04-backend-db-hot-scans-plan.mdnew file mode 100644index 000000000..1b7f3a81e--- /dev/null+++ b/docs/plans/2026-11-04-backend-db-hot-scans-plan.md@@ -0,0 +1,80 @@+# Backend DB, group A: three hot-path scans: implementation plan++The Engineer implements this plan task by task, test first, on one branch, and opens one pull request. Nobody is asked to+choose an execution mode. Steps use checkboxes.++**Goal:** Stop three reads from scanning whole collections: deliveries read without `tabId`, empty `in` lists, and the+operations read by Swarm and date.++**Architecture:** The delivery read becomes a plain `$match` with `tabId`, served by the existing `[tabId, messageId]` index.+Each Prisma `in` list on a hot path that can be empty is tested first and sends no query when empty. The empty-list check gets+the hole closed that let the two production cases through. One new index, built by the release's schema step.++**Tech Stack:** TypeScript, Prisma on MongoDB, Vitest, plan tests on `mongodb-memory-server`.++**Spec:** Ken's plan in the project chat (2026-11-04), group A, and task #2595's brief.++## Global Constraints++- Measure before and after; aggregates only; never print the read-only login.+- Ships with the next backend release; merges through the PM's batch.+- PR body first line: `Requested by [email protected] through Harness.`++## Review Focus++- A retry whose message is already stored: its deliveries are still written once, and never sent twice.+- A batch with some reports refused and some accepted: receipts are still read for the accepted ones.+- A person with no shares, no invitations or no Swarm: the same empty answer as before, with no query.+- A list built only of spreads (`[...new Set(ids)]`): the check must flag it unless tested. A spread of a constant passes.+- A shared machine whose billing refuses it: the owners read is skipped and the answer stays empty.++## Design++- **Growth:** no new collection. On `SuperTabOperation`, `[tabId, createdAt]` replaces its prefix `[tabId]`, so it stays one index per write; the 30-day TTL removes its rows.+- **Concurrency:** N/A because reads and one index only; no write changes shape.+- **Read cost:** the point of the change. Numbers are in the pull request.+- **Scale:** at 10x (1.2M operations) the new index is about 15 MB; backend CPU and Atlas's slow log warn first.+- **Compatibility:** no API or client change. An old pod keeps its old reads until it is replaced.+- **Migration + rollback:** the release's schema step builds the new index and drops the old one (`db push`). Nothing else is+ needed. Declaring `[tabId]` again restores it on a later release.+- **Audience:** N/A because no data is exposed or newly stored.+- **Identity:** N/A because no account is involved.+- **Failure:** a skipped read returns the same empty answer; a failing index build fails the schema step and says so.+- **Platforms:** backend only.++## Left out++- `product_usage_totals {machineId, dayUtc}`: no row has that field, its model forbids it, and no backend code filters by it.+- `communityReports`, `confidential.ts`: not hot, or their lists are never empty in practice. Raw `$in: []` reads do not scan.++---++### Task 1: The delivery read carries tabId++**Files:** Modify `backend/src/superTabs/store.ts`, `backend/src/superTabs/hotFilters.allowed.json`. Test `backend/integration/superTabNoticeDigest.test.ts`.++**Interfaces:** none new.++- [x] Write a failing plan test on a real poll with a stored message: one read by `tabId` and `messageId`, `IXSCAN`, examining only its rows.+- [x] Watch it fail; commit.+- [x] Implement; watch it pass; commit.++### Task 2: Empty lists send no query++**Files:** Modify `backend/src/lib/productUsage.ts`, `backend/src/routes/harnessShares.ts`, `backend/src/routes/community.ts`, `backend/src/superTabs/store.ts`, `backend/src/superTabs/workspaceStore.ts`, `backend/src/lib/emptyInList.test-support.ts`. Test the matching test files and `backend/integration/superTabNamedReads.test.ts`.++**Interfaces:** `GUARDED_MODELS` gains the models fixed here.++- [x] Write failing tests for each read, and for the check on a spread-only list.+- [x] Watch them fail; commit.+- [x] Implement; watch them pass; commit.++### Task 3: The operations index++**Files:** Modify `backend/prisma/schema.prisma`. Test `backend/integration/superTabNamedReads.test.ts`.++**Interfaces:** the index `[tabId, createdAt]` on `SuperTabOperation`, in place of `[tabId]`.++- [x] Write a failing plan test: a small Swarm's wide date range examines only its rows.+- [x] Watch it fail; commit.+- [x] Add the index; watch it pass; run `npm test`; post the numbers; mark the PR ready; add one review step.diff --git a/docs/plans/2026-11-04-host-reads-only-changed-plan.md b/docs/plans/2026-11-04-host-reads-only-changed-plan.mdnew file mode 100644index 000000000..d2cde151e--- /dev/null+++ b/docs/plans/2026-11-04-host-reads-only-changed-plan.md@@ -0,0 +1,123 @@+# Host readings and host changes read only what changed Implementation Plan++> **For agentic workers:** Written by the writing-plans skill as the project's instructions adapt it (Engineer role,+> revision 54). The Engineer implements it task by task, test first, in this session; the pull request's Review step is+> the one independent review. No execution handoff.++**Goal:** A machine's full reading (POST /hosts/:machineId/readings) and a host's changes read (POST+/hosts/:machineId/changes) stop reading from MongoDB, again and again, Swarm data that did not change, and every host+sees exactly the rows and decisions it sees today.++**Architecture:** B3: a full reading's machine parts and conversations (parts/load.ts `loadObserved`) come from a+per-process store of parts held at their exact version (`parts/held.ts`). Inside the reading's transaction each read+first asks MongoDB only for the selected parts' version columns (`key, version, changedAt, readAt, dormant`), then reads+whole only the parts whose columns differ from what the process holds. A part is reused only when every column a write+moves is equal, so what the reading works on is what the old read returned. B4: the host state's dormant conversations of+the machine's agents (cachedReads.ts `deriveLight`) are read through the light projection (parts/light.ts+`loadLightGroups`) and held as their own cache entry, patched as today, instead of whole conversations projected after+the read.++**Tech Stack:** TypeScript, Prisma on MongoDB (`aggregateRaw`), vitest; integration on `mongodb-memory-server`.++**Spec:** the task's brief (#2597, Ken's plan of 2026-11-04, group B items 3 and 4); backend/AGENTS.md (one index per+query, measure before and after); docs/superpowers/specs/2026-11-02-swarm-cache-delta-design.md (patch rules).++## Global Constraints++- Hosts see exactly the same changes as before: same reading decisions, same stored parts, same host rows and etags.+- No schema change, no new index, no production write. Every read names an index it already uses.+- No `in` list through Prisma on these paths (it is sent as an N-branch `$or`, and an empty one as `$or: []`, a scan):+ raw `$match` with `$in`, and no read at all for an empty list.+- Optimizations ship on, with no switch. Swarm code stays out of `cli/src/core`.+- Backend unit suite (`npm test`) before Ready; the Super Tab integration suite runs in PR CI.++## Review Focus++- A part written with no visible change to `changedAt` (a reading, dated `readAt`): the version moves, so it is read again.+- A part purged and added again under the same key, starting again at an old version: `changedAt` differs, read again.+- A part removed (tombstoned) or put to sleep (`dormant`) since the last read: it leaves the selection as before.+- Two readings of one Swarm at once in one process: held parts are frozen and shared, never mutated (store.ts+ `loadedFrom` freezes them, the reading works on a clone).+- A transaction retried after a conflict reads the version columns again; nothing it held from the failed attempt is+ trusted without that check.++## Design++- **Growth: what deletes it.** Nothing is stored in MongoDB. The held parts live in process memory, capped at 32 MB+ (least recently used Swarm out), measured as the read cache measures (cache.ts `sizeOf`). A part that leaves the+ selection leaves the held set on the next read of its Swarm. The B4 entry lives in the existing read cache, under its+ cap.+- **Concurrency: lock level.** None added. The reading's transaction reads the version columns and the changed parts in+ one snapshot; writes stay version-guarded (parts/write.ts). Held parts are frozen and shared read-only.+- **Read cost: only what changed.** B3: per full reading, one small columns read per selection plus the whole rows of+ the parts that changed since this process last read them (usually the reporting machine alone). B4: a miss reads light+ rows instead of whole conversations; a hit patches from the delta as today.+- **Scale: 10x, and the first warning.** 10x machines per Swarm: the columns read grows to ~1 KB per 10 machines; the+ first warning is `db by shape` bytes for `SwarmMachine aggregate` on the readings route. Held memory at 10x Swarms+ per process hits the 32 MB cap and falls back to whole reads, seen as `swarm cache` misses for `held`.+- **Compatibility: old and new clients.** No wire change: hosts and clients get the same answers.+- **Migration + rollback.** None: no stored data changes. Rolling back the release restores the whole reads.+- **Audience: the server enforces it.** N/A because no new data reaches any reader; the same checks run on the same parts.+- **Identity.** N/A because nothing here uses a login.+- **Failure: nothing breaks without saying so.** A failed read fails the reading as today. A held part is never used+ without its columns matching the database's in the same snapshot, so there is no stale state to go unseen.+- **Platforms.** Backend only.++## File Structure++- Create `backend/src/superTabs/parts/held.ts`: `HeldParts`, the process store, and `heldMachines`, `heldGroups`.+- Modify `backend/src/superTabs/parts/load.ts`: `loadObserved` reads machines and conversations through `parts/held.ts`.+- Modify `backend/src/superTabs/cachedReads.ts`: `deriveLight` reads `light-dormant:agent:{id}`.+- Modify `backend/src/superTabs/cachePatch.ts`: `lightDormantAgentRule`.+- Tests: `backend/integration/superTabMachineReports.test.ts` (B3), `backend/src/superTabs/cachePatch.test.ts` and+ `backend/integration/superTabCacheDelta.test.ts` (B4).++### Task 1: A full reading reads only the parts that changed (B3)++**Files:**+- Create: `backend/src/superTabs/parts/held.ts`+- Modify: `backend/src/superTabs/parts/load.ts` (`loadObserved`), `backend/src/superTabs/parts/index.ts` (export)+- Test: `backend/integration/superTabMachineReports.test.ts`++**Interfaces:**+- Produces: `class HeldParts { constructor(maxBytes?: number) }`; `heldMachines(tx, tabId, held?: HeldParts):+ Promise<Part<MachineData>[]>` (every live machine part, in key order); `heldGroups(tx, tabId, reads: GroupReads, held?:+ HeldParts): Promise<PartRow[]>` (as `liveGroups`: each read's rows in its index order, each key once);+ `loadObserved(tx, tabId, machineId, held?: HeldParts)`.++- [ ] **Step 1: Failing tests** in `superTabMachineReports.test.ts`, describe "a full report reads only what changed+ (B3)": (a) with three machines contributed, a second full report (a server that remembers no report) returns from+ `SwarmMachine` and `SwarmGroup` under half the bytes of the first (profiler `responseLength`), and stores the same+ machine part a fresh server stores; (b) for each change kind, `loadObserved` through a warm `HeldParts` equals it+ through a new one: another machine's settings, another machine's reading only, a machine removed, a machine added, a+ post in a running conversation, a conversation put to sleep and woken, a conversation removed, a new Lead conversation,+ and a part rewritten at the same version with a new `changedAt`.+- [ ] **Step 2: Run** `npx vitest run --config vitest.super-tabs.config.ts integration/superTabMachineReports.test.ts`;+ expect (a) to FAIL on bytes, (b) to FAIL to compile (no `held` argument). Commit the failing tests.+- [ ] **Step 3: Implement** `parts/held.ts`: per selection, a raw `$match` (machines: `{ tabId, deleted: false }` on the+ `(tabId, key)` index; conversations: each `GroupReads` entry through its named index) projecting the columns; the+ changed keys read whole in one raw `$match` by `_id`/`key` `$in` (no read for none); held entries replaced and LRU'd.+ `loadObserved` uses them; `assemble` reads no machines for it.+- [ ] **Step 4: Run** the file and `src/superTabs` unit tests; expect PASS. Commit.++### Task 2: A host's dormant conversations are read light (B4)++**Files:**+- Modify: `backend/src/superTabs/cachedReads.ts` (`deriveLight`), `backend/src/superTabs/cachePatch.ts`+- Test: `backend/src/superTabs/cachePatch.test.ts`, `backend/integration/superTabCacheDelta.test.ts`++**Interfaces:**+- Consumes: `store.loadLightGroups(db, tabId, 'agents', match)`, `projectLightGroup`.+- Produces: `lightDormantAgentRule(agentId): PatchRule<Part<GroupData>[]>` (as `dormantAgentRule`, holding each changed+ part projected light).++- [ ] **Step 1: Failing tests**: (a) unit: the rule keeps a light projection of a changed dormant group of the agent,+ drops one it left or that woke, ignores an older version; (b) integration: a host's changes read on a cold cache reads+ its agent's dormant conversations with the light projection (profiler shows no whole `SwarmGroup` rows for the+ `agents` read; bytes under a quarter of the whole rows), and its rows and etag equal the rows built from whole+ conversations; after a dormant conversation changes, the patched entry equals a fresh load.+- [ ] **Step 2: Run** them; expect FAIL. Commit the failing tests.+- [ ] **Step 3: Implement**: `deriveLight` reads `light-dormant:agent:{id}` through `loadLightGroups` with+ `lightDormantAgentRule(id)`, and no longer projects after the read.+- [ ] **Step 4: Run** the tests, `npm test`, and the bench (`integration/bench/observeReads.ts`) for the numbers; expect+ PASS. Commit.diff --git a/docs/plans/2026-11-04-threads-costs-reads-plan.md b/docs/plans/2026-11-04-threads-costs-reads-plan.mdnew file mode 100644index 000000000..5723a7280--- /dev/null+++ b/docs/plans/2026-11-04-threads-costs-reads-plan.md@@ -0,0 +1,115 @@+# Threads, costs and project GitHub reads Implementation Plan++> Implemented by the task's Engineer task by task, each failing test committed before its code (project instructions,+> Engineer). One independent review on the pull request.++**Goal:** GET /:tabId/threads answers from the stored thread summaries instead of scanning each candidate thread's newest+100 messages, and GET /:tabId/costs and GET /:tabId/projects/:projectId/github read the Swarm through `readParts` and the+read cache instead of loading it in a transaction on every request (task #2596, Ken's DB plan, group B items 1 and 2).++**Architecture:** `readFollowedThreads` (read/followedThreads.ts) keeps its candidates and root checks and replaces its+`perRange` scan with one read of `SuperTabThread` by root id (pageReads.ts, as `pageThreads` already reads them for chat+pages), judging each thread from the summary rows `threadReplies` gives. Buddy chats keep the scan: their summaries cannot+tell a row of a project the chat's person lost (buddySessions.ts lostProjectRow). `costSummary` and `projectRepository`+(store.ts) switch from `transaction` + `load` to `readLoad`, as `messages` and `mentions` read.++**Tech Stack:** TypeScript, Prisma 5 on MongoDB (aggregateRaw), Vitest with mongodb-memory-server integration suites.++**Spec:** task #2596's brief (Ken's DB plan of 2026-11-04, group B1 and B2); no separate design (no stored data changes).++## Global Constraints++- Measure before and after each item: `db by shape` (per-route bytes and ms), `route latency`, the Atlas slow log; numbers+ in the PR, aggregates only, from the read-only production login's environment file, never printed.+- A failing test first for each fix; red/green evidence in a PR comment; backend `npm test` before Ready.+- Prisma sends `in` lists as N-branch `$or` and an empty list as `$or: []` (a full scan): raw `$match` only, never an+ empty `$in`.+- `$unionWith` branches ignore hints.+- Every thread summary the apps show stays as it is, the chat tag's ask state (#2867) included: summaries are only read.+- Swarm code stays out of cli/src/core.++## Design++- growth: N/A because nothing new is stored; `SuperTabThread` rows are removed with their Swarm (purge.ts).+- concurrency: N/A because these are reads; summaries are written in the reply's transaction as before.+- read cost: threads read one small summary per candidate (by `_id`), not up to 100 messages each; costs and GitHub read+ the parts the cache's stamp says changed.+- scale: at 10x threads per person the candidates stay capped (READ_CANDIDATES + TAGGED_THREADS); `db by shape` bytes for+ `http GET /api/super-tabs/:tabId/threads` warns first.+- compatibility: the response shape is unchanged. A thread longer than 100 rows now says its full reply count, as its chat+ page's reply line does, instead of stopping at 100.+- migration + rollback: none; a rollback returns to the scan.+- audience: unchanged checks (roots by `readable`, chats the person reads, `canReadGroup` in summaries, the same+ `actor`/`visibleState`/`canReadGroup` for costs and GitHub).+- identity: N/A because no machine login is used.+- failure: a Swarm not backfilled yet falls back to `threadFacet`, as pages do; nothing is silently dropped.+- platforms: backend only.++## Review Focus++1. A thread whose newest reply is agent-only, or a delivered Lead copy: it must neither count nor move "last reply" (Task 1+ test "skips what a person never reads").+2. A Swarm whose summaries are not backfilled yet: the answer must equal the backfilled one (Task 1 test "same answer").+3. A Buddy chat thread with a lost project's row: still judged by the scan (Task 1 test "Buddy chats keep the scan").+4. An unread reply after the person's thread mark, in a thread they replied in: still "more", not listed read (existing+ tests, run on the summary path in Task 1).+5. Costs for a group named by a decision but dormant: still loaded by name through the cache (Task 2 test "same answer").++---++### Task 1: Followed threads from the stored summaries++**Files:**+- Modify: `backend/src/superTabs/pageReads.ts` (new `threadRows`, `pageThreads` on it)+- Modify: `backend/src/superTabs/read/followedThreads.ts`+- Test: `backend/integration/superTabFollowedThreads.test.ts`++**Interfaces:**+- Produces: `threadRows(tx: Transaction, tabId: string, threads: ReadonlyArray<{ conversationId: string; root: string }>):+ Promise<ThreadReply[]>`: every named thread's summary rows (threadReplies), oldest first, from `SuperTabThread` by `_id`+ in one read when the Swarm is backfilled (a stored row counts only in the conversation named for it), else from+ `threadFacet` per conversation. `pageThreads(tx, tabId, conversationId, roots)` returns `threadRows` of those roots.++- [ ] **Step 1: Write the failing tests** in the "GET /threads" profile describe:+ - "reads the candidates' summaries, never their messages, once the Swarm is backfilled": the existing long-thread scene,+ `backfillThreads(db, Date.now())`, then under the profiler: no `SuperTabMessage` read on the thread index+ (`planSummary` without `thread`), `SuperTabMessage` docsExamined ≤ 70 (roots by id), one `SuperTabThread` read with+ IXSCAN on `_id`, and `read` has 30 threads with `more: true`; a long thread says its full count (301).+ - "gives the same answer from summaries as from the thread rows": a scene with own replies, tags, an agent-only reply+ and an unread reply past the mark; `threads()` before and after `backfillThreads` are equal.+- [ ] **Step 2: Run** `npx vitest run --config vitest.super-tabs.config.ts integration/superTabFollowedThreads.test.ts`;+ expected FAIL: the thread index read is present and the long count is 100.+- [ ] **Step 3: Implement** `threadRows` and use it in `readFollowedThreads` for candidates outside Buddy chats; the+ existing scan stays for Buddy chats. Judge each thread from its rows: `replies` = rows other than the root, newest first;+ `inIt` on those rows; `seen` and the unread check from the newest own and non-own rows; the summary from+ `threadSummaries(state, group, rows)`.+- [ ] **Step 4: Run** the same command; expected PASS, with the rest of the file.+- [ ] **Step 5: Commit** test, then code.++### Task 2: Costs and project GitHub through the read cache++**Files:**+- Modify: `backend/src/superTabs/store.ts` (`costSummary`, `projectRepository`)+- Test: `backend/integration/superTabCache.test.ts`++**Interfaces:**+- Consumes: `SuperTabStore.readLoad(user, tabId, named?)` (exists).++- [ ] **Step 1: Write the failing tests** in "reads through the cache":+ - "answers costs and a project's GitHub access from the cache when the stamp did not move": with one pod, a first+ `costSummary(owner, tabId, 7)` and `projectRepository(owner, tabId, 'lead')`, then the second of each reads 0 part+ documents (`partReads`), and each answer equals a cache-off pod's.+- [ ] **Step 2: Run** `npx vitest run --config vitest.super-tabs.config.ts integration/superTabCache.test.ts`; expected FAIL:+ the second reads read parts.+- [ ] **Step 3: Implement**: both methods read `this.readLoad(...)` (costs with its decisions' `groupIds`) and+ `this.actor(this.db, ...)`, outside any transaction.+- [ ] **Step 4: Run** the same command and `integration/superTabCosts.test.ts`, `integration/superTabGithub.test.ts`;+ expected PASS.+- [ ] **Step 5: Commit** test, then code.++### Task 3: Evidence++- [ ] `npm test` and `npm run typecheck` in backend.+- [ ] Before/after numbers in the PR: the local profiler (docs examined, bytes returned) for both items, and production's+ `db by shape` / `route latency` / Atlas slow log for the two routes before and after the release.+- [ ] Red/green evidence in a PR comment.diff --git a/mobile/lib/swarm/swarm_home_rows.dart b/mobile/lib/swarm/swarm_home_rows.dartindex b7cd1e46f..cc653f803 100644--- a/mobile/lib/swarm/swarm_home_rows.dart+++ b/mobile/lib/swarm/swarm_home_rows.dart@@ -136,8 +136,9 @@ class SwarmInvitationRow extends StatelessWidget {/// waits is on its way ([tagsLoading]). No dot for how its team is: one on/// every row said little, and the name already says what waits on the person/// (Tony, 2026-11-03). No second line: who reads it and how long ago it moved-/// were the same on every row. A tap opens it; a long press offers its pin-/// ([onLongPress]).+/// were the same on every row. A private project has a lock at its end,+/// after its tags, as the desktop's sidebar marks it. A tap opens it; a long+/// press offers its pin ([onLongPress]).class SwarmHomeProjectRow extends StatelessWidget {const SwarmHomeProjectRow({super.key,@@ -166,7 +167,10 @@ class SwarmHomeProjectRow extends StatelessWidget {AppTheme.watch(context);final news = project.news;final bright = news.bold || news.tags > 0;- final name = '#${project.project.name}';+ // A private project's lock takes the # mark's place, as the desktop's+ // sidebar marks it (#2876): the row's right side is for its notifications.+ final private = project.project.isPrivate;+ final name = private ? project.project.name : '#${project.project.name}';return _Tap(onTap: onTap,onLongPress: onLongPress,@@ -179,6 +183,16 @@ class SwarmHomeProjectRow extends StatelessWidget {),child: Row(children: [+ if (private) ...[+ Icon(+ LucideIcons.lock300,+ key: const ValueKey('swarm-project-private'),+ size: 14,+ color: AppPalette.textSecondary,+ semanticLabel: 'Private project',+ ),+ const SizedBox(width: AppSpace.xs),+ ],Expanded(child: Semantics(label: bright && news.tags == 0 ? 'Unread messages' : null,diff --git a/mobile/lib/swarm/swarm_machine_details.dart b/mobile/lib/swarm/swarm_machine_details.dartnew file mode 100644index 000000000..bd383f2c5--- /dev/null+++ b/mobile/lib/swarm/swarm_machine_details.dart@@ -0,0 +1,489 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_icon_size.dart';+import '../shared/theme/app_space.dart';+import '../shared/theme/app_theme.dart';+import '../shared/theme/app_type.dart';+import '../widgets/engine_identity.dart';+import 'model.dart';+import 'swarm_buddy.dart';+import 'swarm_reader.dart';++/// The engines a machine's allowances are read for, Claude first (Desktop `machines.dart` `_chipEngines`).+const _engines = ['claude', 'codex'];++/// A reading this old is offline (Desktop `kSuperTabMachineOfflineAfter`).+const _offlineAfter = Duration(seconds: 35);++/// What a machine's reading says of its hardware, each figure checked as Desktop's `MachineResources.fromJson` checks+/// it: one out of range is no reading.+class SwarmMachineResources {+ const SwarmMachineResources({+ this.cpuPercent,+ this.gpuPercent,+ this.memoryUsedBytes,+ this.memoryTotalBytes,+ this.diskFreeBytes,+ this.diskTotalBytes,+ this.projectDiskFreeBytes,+ this.projectDiskTotalBytes,+ this.deviceType,+ this.chip,+ this.os,+ });++ factory SwarmMachineResources.read(Map<String, dynamic> json) {+ double? number(String key) => switch (json[key]) {+ final num v when v.isFinite && v >= 0 => v.toDouble(),+ _ => null,+ };+ String? label(String key) => switch (json[key]) {+ final String v when v.isNotEmpty && v.length <= 120 => v,+ _ => null,+ };+ final cpu = number('cpuPercent'), gpu = number('gpuPercent');+ final used = number('memoryUsedBytes'), total = number('memoryTotalBytes');+ final memory = used != null && total != null && total > 0 && used <= total;+ final free = number('diskFreeBytes'), size = number('diskTotalBytes');+ final disk = free != null && size != null && size > 0 && free <= size;+ return SwarmMachineResources(+ cpuPercent: cpu != null && cpu <= 100 ? cpu : null,+ gpuPercent: gpu != null && gpu <= 100 ? gpu : null,+ memoryUsedBytes: memory ? used : null,+ memoryTotalBytes: memory ? total : null,+ diskFreeBytes: disk ? free : null,+ diskTotalBytes: disk ? size : null,+ projectDiskFreeBytes: number('projectDiskFreeBytes'),+ projectDiskTotalBytes: number('projectDiskTotalBytes'),+ deviceType: label('deviceType'),+ chip: label('chip'),+ os: label('os'),+ );+ }++ final double? cpuPercent, gpuPercent;+ final double? memoryUsedBytes, memoryTotalBytes;+ final double? diskFreeBytes, diskTotalBytes;+ final double? projectDiskFreeBytes, projectDiskTotalBytes;+ final String? deviceType, chip, os;+}++/// One window of an allowance: its name, the share [left] (0–100), and when it resets (`resets in 2h 10m`).+typedef SwarmAllowanceWindow = ({String window, double left, String? reset});++/// One engine's allowance on a machine, as Desktop's details list it: the provider's [name] (`Claude Code`, `Codex`),+/// the share left of the window that stops work first ([figure]), and each window, the tightest first.+typedef SwarmMachineAllowance = ({+ String engine,+ String name,+ String figure,+ List<SwarmAllowanceWindow> windows,+});++/// What a machine's details say of its subscriptions (Desktop `machines.dart` `_subscriptions` and `_quotaRow`), from+/// its own pool, since a Mac's Harness Team account spends the Mac owner's subscriptions: the engines it offers (null+/// when its pool names none), and each allowance with a figure. An allowance with none is left out, as Desktop's+/// details leave it out; so is one whose window reset since a current reading.+///+/// [reading] is the pool the machine's row reads ([SuperTabSnapshot.readingPoolOf]), [readingDim] whether that reading+/// is old.+({List<String>? engines, List<SwarmMachineAllowance> allowances})+swarmMachineSubscriptions(+ SuperTabSnapshot snapshot,+ String machineId, {+ required Map<String, dynamic>? reading,+ required bool readingDim,+ required DateTime now,+}) {+ final pool =+ snapshot.pool(machineId) ?? snapshot.teamPoolOf(machineId) ?? reading;+ final observation = superTabMap(+ pool?['observation'] ?? const <String, dynamic>{},+ );+ final readAt = switch (observation['receivedAt']) {+ final num at => _epoch(at),+ _ => null,+ };+ final stale = identical(pool, reading)+ ? readingDim+ : readAt == null || now.difference(readAt) >= _offlineAfter;+ final quotas = <String, Map<String, dynamic>>{+ for (final raw in _list(observation['quotas']))+ if (superTabMap(raw)['engine'] case final String engine+ when _engines.contains(engine))+ engine: superTabMap(raw),+ };+ final configured = pool?['engines'] is List+ ? (pool!['engines'] as List).whereType<String>()+ : null;+ final readiness = observation['readiness'];+ final installed = {+ for (final raw in _list(readiness is Map ? readiness['engines'] : null))+ if (raw is Map && raw['installed'] == true) raw['engine'],+ };+ // A list that still names a retired engine (OpenCode) cannot say which of the two it offers: Claude and Codex come+ // from what it reported or has installed.+ final engines = configured?.any((e) => !_engines.contains(e)) == true+ ? [+ for (final engine in _engines)+ if (configured!.contains(engine) ||+ quotas.containsKey(engine) ||+ installed.contains(engine))+ engine,+ ]+ : configured?.where(_engines.contains).toList();+ return (+ engines: engines,+ allowances: [+ if (readAt != null)+ for (final MapEntry(key: engine, value: quota) in quotas.entries)+ ?_allowance(engine, quota, old: stale, now: now),+ ],+ );+}++/// [quota]'s allowance with its figure; null when it has none. [old]: the machine is offline, so this is its last+/// reading, whose windows may have reset since; the figures stay, as when they were read.+SwarmMachineAllowance? _allowance(+ String engine,+ Map<String, dynamic> quota, {+ required bool old,+ required DateTime now,+}) {+ final windows = [for (final raw in _list(quota['windows'])) superTabMap(raw)];+ double? used(Map<String, dynamic> w) => switch (w['usedPercent']) {+ final num v when v.isFinite => v.toDouble().clamp(0.0, 100.0),+ _ => null,+ };+ // A window without its share cannot say whether it is the one that stops work first.+ if (quota['known'] != true ||+ windows.isEmpty ||+ windows.any((w) => used(w) == null)) {+ return null;+ }+ windows.sort((a, b) => used(b)!.compareTo(used(a)!));+ if (!old &&+ windows.any((w) => _reset(w['resetsAt'])?.isBefore(now) == true)) {+ return null;+ }+ final left = 100 - used(windows.first)!;+ return (+ engine: engine,+ name: engine == 'claude' ? 'Claude Code' : 'Codex',+ figure: left > 0 && left < 1 ? '<1%' : '${left.floor()}%',+ windows: [+ for (final w in windows)+ if (w['name'] case final String name when name.isNotEmpty)+ (+ window: name,+ left: 100 - used(w)!,+ reset: switch (_reset(w['resetsAt'])) {+ final at? when at.isAfter(now) => 'resets in ${_until(at, now)}',+ _ => null,+ },+ ),+ ],+ );+}++List<Object?> _list(Object? value) => value is List ? value : const [];++/// [milliseconds] since the epoch as a time; null for one no time has.+DateTime? _epoch(num milliseconds) =>+ milliseconds.isFinite && milliseconds.abs() <= 8640000000000000+ ? DateTime.fromMillisecondsSinceEpoch(milliseconds.toInt())+ : null;++/// A window's reset, in seconds or milliseconds since the epoch, or as a date.+DateTime? _reset(Object? raw) => switch (raw) {+ final num v => _epoch(v > 100000000000 ? v : v * 1000),+ final String v => DateTime.tryParse(v),+ _ => null,+};++/// How long until [when]: `45m`, `2h 10m`, `3d`.+String _until(DateTime when, DateTime now) {+ final minutes = when.difference(now).inMinutes;+ return minutes <= 0+ ? 'now'+ : minutes < 60+ ? '${minutes}m'+ : minutes < 1440+ ? '${minutes ~/ 60}h ${minutes % 60}m'+ : '${minutes ~/ 1440}d';+}++/// A share as Desktop writes it: `80`, `62.5`.+String _share(double value) => value == value.roundToDouble()+ ? '${value.round()}'+ : value.toStringAsFixed(1);++String _percent(double value) => '${value.round()}%';++String _bytes(double value) {+ if (value == 0) return '0 GB';+ if (value < 1000000000) return '${(value / 1000000).round()} MB';+ return '${(value / 1000000000).round()} GB';+}++/// A titled group of a machine's details.+Widget swarmMachineDetailHeading(String title) => Padding(+ padding: const EdgeInsets.only(top: AppSpace.xl, bottom: AppSpace.s),+ child: Semantics(+ header: true,+ child: Text(title, style: AppType.heading(color: AppPalette.textPrimary)),+ ),+);++/// One of a machine's details: its label on the left, its value on the right. [narrow] for a short label (an+/// allowance's window), whose value takes the room.+Widget swarmMachineDetailRow(+ String label,+ String text, {+ Color? color,+ bool narrow = false,+}) => _detailRow(+ label,+ Text(+ text,+ textAlign: TextAlign.right,+ style: AppType.body(color: color ?? AppPalette.textPrimary),+ ),+ narrow: narrow,+);++Widget _detailRow(String label, Widget value, {bool narrow = false}) => Padding(+ padding: const EdgeInsets.symmetric(vertical: AppSpace.xs),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Expanded(+ flex: narrow ? 1 : 2,+ child: Text(+ label,+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ),+ const SizedBox(width: AppSpace.m),+ Expanded(flex: 3, child: value),+ ],+ ),+);++/// A machine's details, as Desktop's (`desktop/lib/super_tabs/machine_details.dart` `SuperTabMachineDetails`) show+/// them, read only: who owns it and its state, its available capacity, its model allowances, and its hardware and+/// engines. Old readings are not passed in: their sections are left out.+class SwarmMachineDetails extends StatelessWidget {+ const SwarmMachineDetails({+ super.key,+ required this.name,+ required this.status,+ this.owner,+ this.resources,+ this.engines,+ this.allowances = const [],+ this.footer,+ });++ final String name, status;+ final String? owner;+ final SwarmMachineResources? resources;+ final List<String>? engines;+ final List<SwarmMachineAllowance> allowances;++ /// Below the details: what the Swarm adds about the machine ([SwarmMachineLocalModels]).+ final Widget? footer;++ /// A window's share in the footer's colours: neutral above 20%, amber to 6%, red at 5% or less.+ static Color _ink(double left) {+ final percent = left.floor();+ return percent > 20+ ? AppPalette.textPrimary+ : percent <= 5+ ? AppPalette.usageCritical+ : AppPalette.usageLow;+ }++ List<Widget> _allowance(SwarmMachineAllowance allowance) => [+ Padding(+ padding: const EdgeInsets.only(top: AppSpace.s, bottom: AppSpace.xs),+ child: Row(+ children: [+ EngineMark(engine: allowance.engine, size: AppIconSize.besideText),+ const SizedBox(width: AppSpace.s),+ Expanded(+ child: Text(+ allowance.name,+ style: AppType.label(color: AppPalette.textPrimary),+ ),+ ),+ // Without its windows the allowance's one figure stands for them.+ if (allowance.windows.isEmpty)+ Text(+ '${allowance.figure} left',+ style: AppType.body(color: AppPalette.textPrimary),+ ),+ ],+ ),+ ),+ for (final window in allowance.windows)+ swarmMachineDetailRow(+ window.window,+ ['${_share(window.left)}% left', ?window.reset].join(' · '),+ color: _ink(window.left),+ narrow: true,+ ),+ ];++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final value = resources;+ final diskTotal = value?.projectDiskTotalBytes ?? value?.diskTotalBytes;+ final diskFree = value?.projectDiskTotalBytes == null+ ? value?.diskFreeBytes+ : value?.projectDiskFreeBytes;+ final memoryFree =+ value?.memoryTotalBytes == null || value?.memoryUsedBytes == null+ ? null+ : (value!.memoryTotalBytes! - value.memoryUsedBytes!).clamp(+ 0.0,+ value.memoryTotalBytes!,+ );+ String free(double used) => _percent((100 - used).clamp(0.0, 100.0));+ String capacity(double available, double? total) =>+ '${_bytes(available)}${total == null ? '' : ' of ${_bytes(total)}'}';+ final readings = [+ if (value?.cpuPercent case final cpu?) ('CPU', free(cpu)),+ if (value?.gpuPercent case final gpu?) ('GPU', free(gpu)),+ if (memoryFree != null)+ ('RAM', capacity(memoryFree, value?.memoryTotalBytes)),+ if (diskFree != null) ('SSD', capacity(diskFree, diskTotal)),+ ];+ // A Swarm's reading names no graphics card, only the busiest one's use: Desktop's Graphics row has nothing here.+ final hardware = [+ ('Computer', name),+ if (value?.deviceType case final device?) ('Device', device),+ if (value?.chip case final chip?) ('Chip', chip),+ if (value?.os case final os?) ('System', os),+ if (engines?.isNotEmpty == true)+ ('Engines', engines!.map((e) => engineIdentity(e).label).join(', ')),+ ];+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ if (owner case final owner?) swarmMachineDetailRow('Owner', owner),+ swarmMachineDetailRow('Status', status),+ if (readings.isNotEmpty) ...[+ swarmMachineDetailHeading('Available capacity'),+ for (final (label, text) in readings)+ swarmMachineDetailRow(label, text),+ ],+ if (allowances.isNotEmpty) ...[+ swarmMachineDetailHeading('Model allowances'),+ for (final allowance in allowances) ..._allowance(allowance),+ ],+ swarmMachineDetailHeading('Details'),+ for (final (label, text) in hardware)+ swarmMachineDetailRow(label, text),+ ?footer,+ ],+ );+ }+}++/// The models part of a machine's details (Desktop `local_models.dart` `SuperTabMachineLocalModels`): what it serves+/// the Swarm now, from a fresh reading only, as the route reads it. Nothing while the Swarm's models are off.+class SwarmMachineLocalModels extends StatelessWidget {+ const SwarmMachineLocalModels({+ super.key,+ required this.reader,+ required this.machineId,+ this.now = DateTime.now,+ });++ final SwarmReader reader;+ final String machineId;+ final DateTime Function() now;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final snapshot = reader.snapshot, local = snapshot?.localModels;+ if (snapshot == null || local == null || !local.enabled) {+ return const SizedBox.shrink();+ }+ final pool = snapshot.pool(machineId);+ final fresh = superTabServedModels(pool, local.grid, now: now());+ final apis = <SuperTabServedModel>[], models = <SuperTabServedModel>[];+ final observed = pool?['observation'];+ for (final m in _list(observed is Map ? observed['localModels'] : null)) {+ if (m is! Map || m['grid'] != local.grid || m['model'] is! String) {+ continue;+ }+ final model = m['model'] as String;+ if (!fresh.any((f) => f.model == model)) continue;+ if (m['kind'] == 'api') {+ // An API's model without its provider's folder ("deepseek/…").+ apis.add((+ model: model,+ name: model.substring(model.lastIndexOf('/') + 1),+ ));+ } else {+ models.add((+ model: model,+ name: m['name'] is String ? m['name'] as String : model,+ ));+ }+ }+ // Whoever serves a model sees whose Buddy runs on it (Desktop `local_models.dart`; PRODUCT.md, Contribution:+ // seen), from the Buddies every member's read carries.+ String? usedBy(String model) {+ final people = {+ for (final a in snapshot.agents)+ if (a.buddyOf case final person? when a.gridModel == model)+ "${swarmBuddyPersonName(reader, person)}'s Buddy",+ };+ return people.isEmpty ? null : 'Used by ${people.join(', ')}';+ }++ Widget line(String label, List<SuperTabServedModel> served) => _detailRow(+ label,+ served.isEmpty+ ? Text(+ 'None',+ textAlign: TextAlign.right,+ style: AppType.body(color: AppPalette.textSecondary),+ )+ : Column(+ crossAxisAlignment: CrossAxisAlignment.end,+ children: [+ for (final s in served) ...[+ Text(+ s.name,+ textAlign: TextAlign.right,+ style: AppType.body(color: AppPalette.textPrimary),+ ),+ if (usedBy(s.model) case final used?)+ Text(+ used,+ textAlign: TextAlign.right,+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ],+ ],+ ),+ );+ return Column(+ key: ValueKey('swarm-machine-local-models-$machineId'),+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ swarmMachineDetailHeading('Models for this Swarm'),+ line('API models', apis),+ line('Local models', models),+ ],+ );+ }+}diff --git a/mobile/lib/swarm/swarm_machines.dart b/mobile/lib/swarm/swarm_machines.dartindex 7aa8b2bf2..e96127b90 100644--- a/mobile/lib/swarm/swarm_machines.dart+++ b/mobile/lib/swarm/swarm_machines.dart@@ -10,6 +10,7 @@ import '../shared/theme/app_theme.dart';import '../shared/theme/app_type.dart';import 'model.dart';import 'swarm_buddy.dart';+import 'swarm_machine_details.dart';import 'swarm_machine_menu.dart';import 'swarm_reader.dart';import 'swarm_style.dart';@@ -230,14 +231,13 @@ class SwarmMachineSheet extends StatelessWidget {reader,refreshing: refreshing,);- final r = view.resources;- final total = _number(r['memoryTotalBytes']);- final used = _number(r['memoryUsedBytes']);- final diskTotal =- _number(r['projectDiskTotalBytes']) ?? _number(r['diskTotalBytes']);- final diskFree = r['projectDiskTotalBytes'] == null- ? _number(r['diskFreeBytes'])- : _number(r['projectDiskFreeBytes']);+ final subscriptions = swarmMachineSubscriptions(+ snapshot,+ machineId,+ reading: view.reading,+ readingDim: view.dim,+ now: DateTime.now(),+ );final agents = swarmTeamGlance(snapshot).agents.where((a) =>snapshot.placeOf(a.agent.machineId) == machineId &&@@ -268,46 +268,27 @@ class SwarmMachineSheet extends StatelessWidget {),],),- _detail('Status', view.status),- if (view.owner case final owner?)- _detail('Owner', owner.shownName),- _heading('Hardware'),- if (view.dim)- _detail('Readings', 'Current readings unavailable')- else ...[- _detail('CPU', _percent(r['cpuPercent'])),- _detail('GPU', _percent(r['gpuPercent'])),- _detail(- 'RAM',- total == null || used == null- ? 'Unavailable'- : '${_bytes((total - used).clamp(0, total))} free of ${_bytes(total)}',- ),- _detail(- 'SSD',- diskFree == null- ? 'Unavailable'- : '${_bytes(diskFree)} free${diskTotal == null ? '' : ' of ${_bytes(diskTotal)}'}',+ SwarmMachineDetails(+ name: view.name,+ owner: view.owner?.shownName,+ status: view.details,+ // Details follow the same freshness rule as the row: old readings are not shown as current.+ resources: view.dim+ ? null+ : SwarmMachineResources.read(view.resources),+ engines: subscriptions.engines,+ allowances: view.dim ? const [] : subscriptions.allowances,+ footer: SwarmMachineLocalModels(+ reader: reader,+ machineId: machineId,),- for (final (label, field) in [- ('Device', 'deviceType'),- ('Chip', 'chip'),- ('System', 'os'),- ])- if (r[field] case final String text) _detail(label, text),- ],- _heading('Model allowances'),- if (view.dim)- _detail('Allowances', 'Current allowances unavailable')- else- for (final engine in ['claude', 'codex'])- ..._allowance(view, engine),- _heading('Agents'),+ ),+ swarmMachineDetailHeading('Agents'),if (agents.isEmpty)- _detail('Running here', 'No agents running')+ swarmMachineDetailRow('Running here', 'No agents running')elsefor (final a in agents)- _detail(+ swarmMachineDetailRow(a.name,'${snapshot.roleOf(a.agent.id)?.badge ?? 'Dev'} · ${a.label}',),@@ -320,85 +301,7 @@ class SwarmMachineSheet extends StatelessWidget {);}-Widget _heading(String title) => Padding(- padding: const EdgeInsets.only(top: AppSpace.xl, bottom: AppSpace.s),- child: Text(title, style: AppType.heading(color: AppPalette.textPrimary)),-);--Widget _detail(String label, String text) => Padding(- padding: const EdgeInsets.symmetric(vertical: AppSpace.xs),- child: Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Expanded(- flex: 2,- child: Text(- label,- style: AppType.caption(color: AppPalette.textSecondary),- ),- ),- const SizedBox(width: AppSpace.m),- Expanded(- flex: 3,- child: Text(- text,- textAlign: TextAlign.right,- style: AppType.body(color: AppPalette.textPrimary),- ),- ),- ],- ),-);-double? _number(Object? v) => v is num && v.isFinite ? v.toDouble() : null;-String _percent(Object? value) => switch (_number(value)) {- final n? => '${n.clamp(0, 100).round()}% in use',- null => 'Unavailable',-};-String _bytes(num bytes) =>- '${(bytes / 1073741824).toStringAsFixed(bytes % 1073741824 == 0 ? 0 : 1)} GB';--List<Widget> _allowance(_MachineView view, String engine) {- final quota = (view.observation['quotas'] as List? ?? [])- .map(superTabMap)- .where((q) => q['engine'] == engine)- .firstOrNull;- final windows = (quota?['windows'] as List? ?? []).map(superTabMap).toList();- DateTime? reset(Object? raw) => raw is num- ? DateTime.fromMillisecondsSinceEpoch(- raw > 100000000000 ? raw.toInt() : (raw * 1000).toInt(),- )- : raw is String- ? DateTime.tryParse(raw)- : null;- final known =- quota?['known'] == true &&- windows.isNotEmpty &&- windows.every(- (w) =>- _number(w['usedPercent']) != null &&- !(reset(w['resetsAt'])?.isBefore(DateTime.now()) ?? false),- );- final name = engine == 'claude' ? 'Claude' : 'Codex';- if (!known) return [_detail(name, 'Allowance unavailable')];- return [- for (final w in windows)- _detail(- name,- '${w['name'] ?? 'Allowance'}: ${(100 - _number(w['usedPercent'])!).clamp(0, 100).round()}% left'- '${reset(w['resetsAt']) == null ? '' : '\nResets ${_resetIn(reset(w['resetsAt'])!)}'}',- ),- ];-}--String _resetIn(DateTime at) {- final minutes = at.difference(DateTime.now()).inMinutes;- return minutes <= 0- ? 'now'- : minutes < 60- ? 'in ${minutes}m'- : 'in ${minutes ~/ 60}h ${minutes % 60}m';-}class _MachineView {_MachineView(@@ -420,9 +323,15 @@ class _MachineView {(pool?['contributorId'] ?? agents.firstOrNull?.contributorId),).firstOrNull;- name = pool?['name'] as String? ?? 'Unavailable machine';- final reading = snapshot.readingPoolOf(id, reader.accountId);- observation = superTabMap(+ name =+ pool?['name'] as String? ??+ // The Swarm knows no name for it, and sharing its own would be new data: it is named by its owner, as Desktop+ // names it.+ (pool == null && snapshot.teamPoolOf(id) == null && owner != null+ ? "${owner!.shownName}'s computer"+ : 'Unavailable machine');+ reading = snapshot.readingPoolOf(id, reader.accountId);+ final observation = superTabMap(reading?['observation'] ?? const <String, dynamic>{},);resources = superTabMap(@@ -452,13 +361,30 @@ class _MachineView {: live? 'Online': 'Late';+ final paused = reading?['paused'] == true;+ final removal = pool?['removal'];+ // What its details say of its state, in Desktop's words (`machines.dart` `_view`): late is still online there.+ details = removal is Map && removal['state'] == 'cleaning'+ ? 'Cleaning up'+ : reader.error != null+ ? "Can't reach Harness"+ : refreshing+ ? 'Refreshing…'+ : offline+ ? (paused ? 'Offline, new work paused' : 'Offline')+ : paused+ ? 'New work paused'+ : 'Online';}final SuperTabSnapshot snapshot;final String id;- late final String name, status;+ late final String name, status, details;late final SuperTabPerson? owner;late final List<SuperTabAgent> agents;- late final Map<String, dynamic> observation, resources;++ /// The pool whose reading the row shows ([SuperTabSnapshot.readingPoolOf]).+ late final Map<String, dynamic>? reading;+ late final Map<String, dynamic> resources;late final bool offline, live, dim;bool get laptop =>(resources['deviceType'] as String? ?? name).toLowerCase().contains(diff --git a/mobile/lib/swarm/swarm_new_project_sheet.dart b/mobile/lib/swarm/swarm_new_project_sheet.dartindex f1526c57e..097a42742 100644--- a/mobile/lib/swarm/swarm_new_project_sheet.dart+++ b/mobile/lib/swarm/swarm_new_project_sheet.dart@@ -5,21 +5,28 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:harness_mobile/shared/theme/app_icon_size.dart';import 'package:harness_mobile/shared/theme/app_space.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/shared/theme/app_type.dart';import 'package:harness_mobile/theme/app_theme.dart' show AppColors;+import 'package:harness_mobile/widgets/engine_identity.dart' show EngineMark;import 'model.dart';+import 'swarm_attach.dart' show SwarmOutgoingChips;import 'swarm_buddy.dart' show swarmCanWrite;+import 'swarm_choices.dart' show swarmSendsFiles;+import 'swarm_conversation_page.dart' show SwarmAttachButton, attachSwarmFiles;import 'swarm_home_list.dart' show swarmProjectActivity;import 'swarm_home_top.dart' show swarmHomeOffers;import 'swarm_inbox.dart';+import 'swarm_outgoing_files.dart';import 'swarm_reader.dart';import 'swarm_request.dart';import 'swarm_row.dart';import 'swarm_session.dart';import 'swarm_style.dart';+import 'swarm_uploads.dart';/// New project from the phone (Tony, 10-30): Swarm Home's last Projects row/// ([SwarmNewProjectRow]) opens a sheet ([showSwarmNewProjectSheet]) that@@ -164,7 +171,10 @@ class SwarmLeadMachine {/// Its line under its name, in words: why it cannot take the Product/// Manager, or the engine it starts it with and its room (Desktop's/// `leadMachineDetail`).- String get detail {+ String get detail => detailFor(null);++ /// [detail], naming [chosen] as its engine where it runs it.+ String detailFor(String? chosen) {if (unavailable case final why?) return why;if (!online) return 'Offline';if (leadEngines.isEmpty) {@@ -172,7 +182,7 @@ class SwarmLeadMachine {return 'Can’t run a Product Manager: ''${{for (final engine in swarmLeadEngines) ?engineRefusals[engine]}.join(', ')}';}- final engine = this.engine!;+ final engine = chosen != null && runs(chosen) ? chosen : this.engine!;return [swarmLeadEngineLabel(engine),freeAgents <= 0@@ -233,6 +243,45 @@ Map<String, String> swarmLeadModelListRefusals(Map<String, dynamic>? answer) {};}+/// The model a Claude Product Manager runs when its person chose none: its+/// role's default (Desktop's `kLeadModel`, backend+/// `BUILT_IN_ROLE_DEFAULTS.lead`).+const _leadModel = (model: 'opus', label: 'Opus 5.5', effort: 'xhigh');++/// Whether the Swarm's model list, from the tab's routing-policy read+/// ([answer]), leaves a Claude Product Manager's default model on: that+/// effort's row when the list has one, else any row of the model at an+/// effort; a model it does not name, a backend that sends its `catalog`, or+/// no read, is on (Desktop's `LeadModelList.modelOn`).+bool swarmLeadModelOn(Map<String, dynamic>? answer) {+ if (answer == null || answer.containsKey('catalog')) return true;+ final policy = answer['policy'] is Map ? superTabMap(answer['policy']) : null;+ final named = <String, bool>{};+ for (final row in policy?['models'] as List? ?? const []) {+ if (row+ case {+ 'engine': 'claude',+ 'model': final String model,+ 'effort': final String effort,+ 'enabled': final bool on,+ }+ when model == _leadModel.model) {+ named[effort] = (named[effort] ?? false) || on;+ }+ }+ return named.isEmpty ||+ (named[_leadModel.effort] ?? named.values.any((on) => on));+}++/// The model a new project's Product Manager runs on [engine], as New+/// project names it (Desktop's `leadModelLabel`): no model is sent, and the+/// Swarm fills Claude's role default where its model list leaves it on+/// ([leadModelOn]); else the engine runs its own.+String swarmLeadModelLabel(String engine, {bool leadModelOn = true}) =>+ engine == 'claude' && leadModelOn+ ? '${_leadModel.label} · ${_leadModel.effort}'+ : 'Default model';+/// The Swarm's machines a new project's Product Manager could start on, one/// row per computer, best first: Desktop's `leadMachinesOf`, where every start/// is the Swarm's (`lead.start`), never the phone's. The person's own machine@@ -445,16 +494,25 @@ List<SwarmLeadMachine> swarmLeadMachines();}-/// Why the Product Manager cannot start on [machineId] now, in words that-/// say what to do; null when it can (Desktop's `checkLeadMachine`).+/// Why the Product Manager cannot start on [machineId] now, with [engine]+/// when the person chose one, in words that say what to do; null when it can+/// (Desktop's `checkLeadMachine`).String? swarmLeadMachineRefusal(List<SwarmLeadMachine> machines,- String machineId,-) {+ String machineId, {+ String? engine,+}) {final chosen = machines.where((m) => m.id == machineId).firstOrNull;if (chosen == null) return 'Choose one of this Swarm’s machines.';- if (chosen.startable) return null;final name = chosen.name;+ if (chosen.startable) {+ return switch (engine == null ? null : chosen.engineRefusals[engine]) {+ final why? =>+ '$name can’t run ${swarmLeadEngineLabel(engine!)}: $why. '+ 'Choose another engine.',+ null => null,+ };+ }if (chosen.unavailable case final why?) {// One full stop, whether its reason ends with one or not.return '$name: ${why.endsWith('.') ? why : '$why.'} '@@ -566,17 +624,22 @@ class SwarmNewProjectGone implements Exception {/// person's access to it or their account, and never outlive the session.final _heldSteps = Expando<SwarmNewProjectSteps>('New project steps');+/// How long a file of the brief may go up without a byte moving before it is+/// given up, as a chat's (`SwarmConversation.uploadTimeout`'s default).+const _uploadTimeout = Duration(minutes: 2);+/// One New project's steps in one Swarm, as Desktop's `startInSwarm` runs-/// them: the project, its brief in its chat, its Product Manager's start on-/// the machine picked, then its name. Each request is kept as first sent,-/// under one operation id, until the steps finish: Create again repeats only-/// what has not answered, and the Swarm answers a repeated operation with its-/// receipt, so a lost answer never makes a second project. Only a definite+/// them: the project, its brief and files in its chat, its Product Manager's+/// start on the machine and engine picked, then its name. Each request is+/// kept as first sent, under one operation id, until the steps finish:+/// Create again repeats only what has not answered, and the Swarm answers a+/// repeated operation with its receipt, so a lost answer never makes a second+/// project, and a file that went up never goes up again. Only a definite/// refusal drops a request, so the next attempt (perhaps on another machine)/// is a new one. The Swarm's reader holds them ([SwarmNewProjectSteps.of]):/// the sheet closed or torn down between steps, opening it again resumes-/// them (Lead's ruling on #2324).-class SwarmNewProjectSteps {+/// them (Lead's ruling on #2324). Listeners hear the files go up.+class SwarmNewProjectSteps with ChangeNotifier {SwarmNewProjectSteps._(this.reader);/// The steps [reader]'s Swarm holds, or new ones it holds from now on.@@ -592,22 +655,42 @@ class SwarmNewProjectSteps {String? _projectId, _conversationId;bool _briefPosted = false, _started = false, _named = false;+ /// The files its brief goes with, as they were when its creation was+ /// asked for.+ List<SwarmOutgoingFile>? _files;++ /// Those files on their way to the project's chat, and the ids of those+ /// already up.+ SwarmUploads? _uploads;+Future<void>? _running;/// The run under way, if any: the next waits for it.Future<void>? get running => _running;/// What the sheet last chose and last said, to show again when it opens- /// on these steps.- String? chosenMachine, chosenRepository, failure;+ /// on these steps. [chosenEngine] is null while the person left the+ /// machine's own.+ String? chosenMachine, chosenRepository, chosenEngine, failure;/// The project exists: its Swarm, brief and visibility are what it was/// made with.String? get projectId => _projectId;- /// Its creation was asked for: Swarm, brief and visibility stay as sent.+ /// Its creation was asked for: Swarm, brief, files and visibility stay as+ /// sent.bool get sent => _create != null || _projectId != null;+ /// The files its brief goes with, once [sent].+ List<SwarmOutgoingFile> get sentFiles => _files ?? const [];++ /// Whether [file] is on its way to the project's chat.+ bool isUploading(SwarmOutgoingFile file) =>+ _uploads?.isUploading(file) ?? false;++ /// How much of [file] has gone up, from 0 to 1, while it is going up.+ double? uploadProgress(SwarmOutgoingFile file) => _uploads?.progress(file);+/// Its creation was asked for and never answered: the Swarm may have made/// it all the same. A refusal made nothing, and drops the request.bool get createUnanswered => _create != null && _projectId == null;@@ -636,28 +719,35 @@ class SwarmNewProjectSteps {String? get startRepository =>superTabMap(_start?['command'] ?? const {})['repositoryUrl'] as String?;+ /// The engine of the start under way, if any.+ String? get startEngine =>+ superTabMap(_start?['command'] ?? const {})['engine'] as String?;+/// Done with: the Swarm holds them no more.void forget() {if (identical(_heldSteps[reader], this)) _heldSteps[reader] = null;}/// Runs what is left: creates the project with [brief] and [visibility],- /// posts [brief] in its chat, starts its Product Manager on [machineId]- /// with the repository [repositoryUrl], then names it after that- /// repository. Answers the project's id once all of it is done and read.- /// Each answer is kept before [live] is asked: once it says no, nothing- /// more is sent and [SwarmNewProjectGone] is thrown, and the next run- /// starts after what was answered. [machinesOf] lists the machines from a- /// fresh read before a start is first sent, as Desktop checks the machine- /// again: one that can no longer take it is refused with why, and nothing- /// is sent. A project made in an earlier run is looked for first, and one- /// deleted since lets the steps go. A name the Swarm refuses counts as- /// done. One run at a time: a second waits for the first.+ /// posts [brief] in its chat with [files], starts its Product Manager on+ /// [machineId] with [engine] (the machine's first when null) and the+ /// repository [repositoryUrl], then names it after that repository.+ /// Answers the project's id once all of it is done and read. Each answer is+ /// kept before [live] is asked: once it says no, nothing more is sent and+ /// [SwarmNewProjectGone] is thrown, and the next run starts after what was+ /// answered. [machinesOf] lists the machines from a fresh read before a+ /// start is first sent, as Desktop checks the machine again: one that can+ /// no longer take it, or no longer runs [engine], is refused with why, and+ /// nothing is sent. A project made in an earlier run is looked for first,+ /// and one deleted since lets the steps go. A name the Swarm refuses counts+ /// as done. One run at a time: a second waits for the first.Future<String> run({required String brief,required String visibility,required String machineId,required String repositoryUrl,+ String? engine,+ List<SwarmOutgoingFile> files = const [],required bool Function() live,required List<SwarmLeadMachine> Function(SuperTabSnapshot snapshot)machinesOf,@@ -673,6 +763,8 @@ class SwarmNewProjectSteps {visibility: visibility,machineId: machineId,repositoryUrl: repositoryUrl,+ engine: engine,+ files: files,live: live,machinesOf: machinesOf,);@@ -687,6 +779,8 @@ class SwarmNewProjectSteps {required String visibility,required String machineId,required String repositoryUrl,+ required String? engine,+ required List<SwarmOutgoingFile> files,required bool Function() live,required List<SwarmLeadMachine> Function(SuperTabSnapshot snapshot)machinesOf,@@ -713,15 +807,19 @@ class SwarmNewProjectSteps {}}if (_projectId == null) {- _create ??= {- 'operationId': superTabOperationId(),- 'command': {- 'type': 'project.create',- 'name': 'New project',- 'visibility': visibility,- 'brief': text,- },- };+ if (_create == null) {+ // The files go with the brief it is made with.+ _files = List.unmodifiable(files);+ _create = {+ 'operationId': superTabOperationId(),+ 'command': {+ 'type': 'project.create',+ 'name': 'New project',+ 'visibility': visibility,+ 'brief': text,+ },+ };+ }final result = await _send(() => _create, (v) => _create = v);final (projectId, conversationId) = switch (result) {{@@ -738,20 +836,35 @@ class SwarmNewProjectSteps {check();}final projectId = _projectId!;- // The brief the project was made with, whatever the field says now.+ // The brief and files the project was made with, whatever the sheet+ // holds now.final posted = sentBrief ?? text;- if (!_briefPosted && posted.isNotEmpty) {- _brief ??= {- 'operationId': superTabOperationId(),- 'command': {- 'type': 'message.send',- 'conversationId': _conversationId,- 'text': posted,- 'replyTo': null,- 'recipientIds': const <String>[],- },- };- await _send(() => _brief, (v) => _brief = v);+ final attached = sentFiles;+ if (!_briefPosted && (posted.isNotEmpty || attached.isNotEmpty)) {+ if (_brief == null) {+ // Up once, to its chat, before the message they go with: written+ // with their ids, it is repeated as it is.+ final ids = await _upload(attached, live);+ check();+ _brief = {+ 'operationId': superTabOperationId(),+ 'command': {+ 'type': 'message.send',+ 'conversationId': _conversationId,+ 'text': posted,+ 'replyTo': null,+ 'recipientIds': const <String>[],+ if (ids.isNotEmpty) 'attachmentIds': ids,+ },+ };+ }+ try {+ await _send(() => _brief, (v) => _brief = v);+ } on SuperTabFailure catch (failure) {+ // Refused, its files go up afresh with the next one.+ if (_refusedOutright(failure)) _uploads?.forget(attached);+ rethrow;+ }_briefPosted = true;check();}@@ -771,7 +884,8 @@ class SwarmNewProjectSteps {}if (deleted) _gone();final machines = machinesOf(snapshot);- if (swarmLeadMachineRefusal(machines, machineId) case final why?) {+ if (swarmLeadMachineRefusal(machines, machineId, engine: engine)+ case final why?) {throw SuperTabFailure('MACHINE_UNAVAILABLE', why);}final machine = machines.firstWhere((m) => m.id == machineId);@@ -783,7 +897,7 @@ class SwarmNewProjectSteps {'machineId': machineId,// No model: the Swarm fills its role's default where the owner's// model list and rules allow it (backend commands.ts lead.start).- 'engine': machine.engine,+ 'engine': engine ?? machine.engine,'repositoryUrl': repositoryUrl,},};@@ -859,6 +973,36 @@ class SwarmNewProjectSteps {);}+ /// Uploads each of [files] not up yet to the project's chat and answers+ /// their ids, those up kept for the next run. A failure says why in the+ /// chat's words ([swarmUploadError]). No file starts once [live] says no.+ Future<List<String>> _upload(+ List<SwarmOutgoingFile> files,+ bool Function() live,+ ) async {+ if (files.isEmpty) return const [];+ final uploads = _uploads ??= SwarmUploads(+ reader,+ _conversationId!,+ timeout: _uploadTimeout,+ onChanged: notifyListeners,+ onProgress: notifyListeners,+ );+ final up = await uploads.upload(files, live: live);+ // Gone meanwhile: its caller's check ends the run.+ if (!live()) return const [];+ if (up.ids case final ids?) return ids;+ final failure = up.failure;+ if (failure is SuperTabFailure) throw failure;+ throw SuperTabFailure(+ 'UPLOAD_FAILED',+ failure == null+ ? 'Could not upload ${files.length == 1 ? 'the file' : 'the files'}. '+ 'Try again.'+ : swarmUploadError(failure, files.length),+ );+ }+/// Sends the request [held] holds exactly as it was first written and/// answers its result. A definite refusal drops it ([drop] with null).Future<Map<String, dynamic>> _send(@@ -1017,11 +1161,22 @@ class SwarmNewProjectSheet extends StatefulWidget {}/// What the sheet shows in place of its form: one of its choices' lists.-enum _Pick { swarm, visibility, repository, link, machine }+enum _Pick { swarm, visibility, repository, link, machine, engine }-class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {+class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet>+ implements SwarmFilesBox {final _brief = TextEditingController();final _link = TextEditingController();++ /// The files going with the brief: in memory, or a large one on disk in+ /// the app's temporary folder while it is held (here, or by the steps once+ /// sent).+ final _files = SwarmOutgoingFiles();++ /// What the last pick of files left out, if anything.+ String? _attachNote;+ bool _attaching = false;+String? _swarmId;String _visibility = 'public';@@ -1030,6 +1185,10 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {String? _repository;bool _repositoryPicked = false;String? _machineId;++ /// The engine the person chose for the Product Manager; until then, the+ /// machine's first, as before there was a choice.+ String? _engine;_Pick? _picking;String? _linkError;@@ -1042,8 +1201,10 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {/// until the next Create or another Swarm.bool _maybeMade = false;- /// The model list of the Swarm [_policySwarm], once read.+ /// The model list of the Swarm [_policySwarm], once read: the engines it+ /// rules out, and whether it leaves Claude's default model on.Map<String, String> _modelList = const {};+ bool _leadModelOn = true;String? _policySwarm;int _policyReads = 0;@@ -1101,6 +1262,7 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {paused: _paused,);if (_steps case final steps?) _resume(steps);+ _files.addListener(_filesChanged);if (_swarmId case final id?) unawaited(_readModelList(id));}@@ -1115,6 +1277,9 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {_repositoryPicked = true;}_machineId = steps.chosenMachine;+ _engine = steps.chosenEngine;+ // The files its brief went with, held as sent.+ if (steps.sent) _files.add(steps.sentFiles);_error = steps.failure;if (_error != null) _showError();if (steps.running case final running?) {@@ -1156,11 +1321,49 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {@overridevoid dispose() {_dropUnsent();+ _files+ ..removeListener(_filesChanged)+ ..dispose();_brief.dispose();_link.dispose();super.dispose();}+ void _filesChanged() {+ if (mounted && !_closing) setState(() {});+ }++ @override+ SwarmOutgoingFiles get files => _files;++ @override+ bool isUploading(SwarmOutgoingFile file) =>+ _steps?.isUploading(file) ?? false;++ @override+ double? uploadProgress(SwarmOutgoingFile file) =>+ _steps?.uploadProgress(file);++ /// +'s sheet and picker ([attachSwarmFiles]), their files into [_files];+ /// what a pick left out is said under them.+ Future<void> _attach() async {+ if (_attaching || _busy) return;+ _attaching = true;+ try {+ await attachSwarmFiles(+ context,+ _files,+ stillWanted: () =>+ mounted && !_closing && !_busy && !(_steps?.sent ?? false),+ note: (note) {+ if (mounted && !_closing) setState(() => _attachNote = note);+ },+ );+ } finally {+ _attaching = false;+ }+ }+/// The sheet still stands for [swarmId]: open, the account's session the/// same, and the person still able to write in it.bool _live(String swarmId, SwarmReader reader) =>@@ -1177,6 +1380,7 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {if (reader == null) return;final read = ++_policyReads;Map<String, String> refusals = const {};+ var leadModelOn = true;try {final answer = superTabMap(await reader.request(@@ -1185,6 +1389,7 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {),);refusals = swarmLeadModelListRefusals(answer);+ leadModelOn = swarmLeadModelOn(answer);} catch (_) {// Unread: the start's own checks still apply.}@@ -1195,11 +1400,13 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {}setState(() {_modelList = refusals;+ _leadModelOn = leadModelOn;_policySwarm = swarmId;});}- /// Closes the sheet once, after the frame it went blank in.+ /// Closes the sheet once, after the frame it went blank in. A sheet or+ /// dialog over it (+'s, or one it opened) goes too.void _close() {if (_closing) return;_closing = true;@@ -1207,10 +1414,12 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {if (!mounted) return;final route = ModalRoute.of(context);if (route == null || !route.isActive) return;+ final navigator = Navigator.of(context);+ navigator.popUntil((top) => top == route || top is! PopupRoute);if (route.isCurrent) {- Navigator.of(context).pop();+ navigator.pop();} else {- Navigator.of(context).removeRoute(route);+ navigator.removeRoute(route);}});}@@ -1222,9 +1431,25 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {snapshot,widget.session.inbox.reader(swarmId)?.accountId ?? '',now: widget.now(),- modelList: _policySwarm == swarmId ? _modelList : const {},+ modelList: _modelListOf(swarmId),);+ /// The engines Swarm [swarmId]'s model list rules out, once read.+ Map<String, String> _modelListOf(String swarmId) =>+ _policySwarm == swarmId ? _modelList : const {};++ /// The engine the Product Manager starts with: the start's, once sent;+ /// else the person's choice; else [machine]'s first, as before there was a+ /// choice; else the first the Swarm's model list leaves.+ String _engineOf(String swarmId, SwarmLeadMachine? machine) =>+ _steps?.startEngine ??+ _engine ??+ machine?.engine ??+ swarmLeadEngines+ .where((engine) => !_modelListOf(swarmId).containsKey(engine))+ .firstOrNull ??+ swarmLeadEngines.first;+@overrideWidget build(BuildContext context) {AppTheme.watch(context);@@ -1241,6 +1466,8 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {// Not one replaced since: the inbox disposes it.for (final MapEntry(:key, :value) in _readers.entries)if (value != null && identical(_inbox.reader(key), value)) value,+ // Its files going up.+ ?_steps,]),builder: (context, _) {final writable = _writable;@@ -1410,6 +1637,7 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {final machine = machines.where((m) => m.id == machineId).firstOrNull;final sent = steps?.sent ?? false;final startSent = steps?.startSent ?? false;+ final engine = _engineOf(swarmId, machine);final blocked = _blocked(snapshot, machines, machine, repository);final swarmName =_inbox.swarms.where((s) => s.id == swarmId).firstOrNull?.name ??@@ -1468,6 +1696,19 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {),),),+ if (swarmSendsFiles) ...[+ const SizedBox(height: AppSpace.s),+ _attachments(locked: sent || _busy),+ if (_attachNote case final note?)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),+ child: SwarmRow.line(+ note,+ key: const ValueKey('swarm-new-project-attach-note'),+ lines: 3,+ ),+ ),+ ],const SizedBox(height: AppSpace.m),SwarmGroup(children: [@@ -1500,11 +1741,23 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {key: const ValueKey('swarm-new-project-machine'),label: 'PM runs on',value: machine?.name ?? 'Choose',- detail: machine?.detail,+ detail: machine?.detailFor(engine),onTap: startSent || _busy? null: () => setState(() => _picking = _Pick.machine),),+ // The engine and the model it runs, as Desktop's Agent and Model+ // (Desktop's `leadModelLabel`: through the Swarm no model is+ // sent, so the one it gets is shown, not chosen).+ _Field(+ key: const ValueKey('swarm-new-project-agent'),+ label: 'Agent',+ value: swarmLeadEngineLabel(engine),+ detail: swarmLeadModelLabel(engine, leadModelOn: _leadModelOn),+ onTap: startSent || _busy+ ? null+ : () => setState(() => _picking = _Pick.engine),+ ),],),if (_maybeMade)@@ -1588,6 +1841,26 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {);}+ /// + and the files going with the brief, in a row under it (Desktop's 📎+ /// and its chips); fixed, as the brief is, once the project was asked for.+ Widget _attachments({required bool locked}) => Row(+ children: [+ SwarmAttachButton(+ key: const ValueKey('swarm-new-project-attach'),+ onTap: locked || _files.room <= 0 ? null : () => unawaited(_attach()),+ ),+ if (_files.files.isNotEmpty) ...[+ const SizedBox(width: AppSpace.s),+ Expanded(+ child: IgnorePointer(+ ignoring: locked,+ child: SwarmOutgoingChips(box: this),+ ),+ ),+ ],+ ],+ );+/// Lets the Swarm's steps go: the fields open again, and the next Create/// makes a new project. One already made stays in the list; one whose/// create was never answered may be there too, and the sheet says so.@@ -1622,6 +1895,12 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {return '${machine.name} cannot start the Product Manager. ''Choose another machine.';}+ if (_engine case final engine?) {+ if (machine.engineRefusals[engine] case final why?) {+ return '${machine.name} can’t run ${swarmLeadEngineLabel(engine)}: '+ '$why. Choose another engine.';+ }+ }return null;}@@ -1636,6 +1915,7 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {final steps = SwarmNewProjectSteps.of(reader)..chosenMachine = machineId..chosenRepository = repository+ ..chosenEngine = _engine..failure = null;setState(() {_busy = true;@@ -1648,6 +1928,8 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {visibility: _visibility,machineId: machineId,repositoryUrl: repository,+ engine: _engine,+ files: _files.files,live: () => _live(swarmId, reader),machinesOf: (snapshot) => _machinesOf(swarmId, snapshot),);@@ -1709,6 +1991,7 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {_Pick.repository => 'Repository',_Pick.link => 'Enter a link',_Pick.machine => 'PM runs on',+ _Pick.engine => 'Agent',},SwarmIconButton(key: const ValueKey('swarm-new-project-back'),@@ -1746,7 +2029,9 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {_repository = null;_repositoryPicked = false;_machineId = null;+ _engine = null;_modelList = const {};+ _leadModelOn = true;_policySwarm = null;unawaited(_readModelList(id));}),@@ -1946,11 +2231,17 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {color: AppPalette.textSecondary,),title: m.name,- detail: m.detail,+ detail: m.detailFor(_engine),trailing: m.id == _machineId ? tick() : null,onTap: m.startable? () => setState(() {_machineId = m.id;+ // The machine chosen last wins over an engine+ // it cannot run (Desktop's chooseLeadMachine).+ if (_engine case final engine?+ when !m.runs(engine)) {+ _engine = null;+ }_picking = null;_error = null;})@@ -1960,6 +2251,43 @@ class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {),],);+ case _Pick.engine:+ final machine = _machinesOf(+ swarmId,+ snapshot,+ ).where((m) => m.id == _machineId).firstOrNull;+ final chosen = _engineOf(swarmId, machine);+ // Each engine a Product Manager runs on, with the model it gets; one+ // the machine chosen (or, before one is, the Swarm's model list)+ // rules out says why.+ Widget option(String engine) {+ final why =+ (machine?.engineRefusals ?? _modelListOf(swarmId))[engine];+ return _Option(+ key: ValueKey('swarm-new-project-pick-agent-$engine'),+ leading: EngineMark(engine: engine, size: AppIconSize.besideText),+ title: swarmLeadEngineLabel(engine),+ detail:+ why ?? swarmLeadModelLabel(engine, leadModelOn: _leadModelOn),+ trailing: engine == chosen ? tick() : null,+ onTap: why == null+ ? () => setState(() {+ _engine = engine;+ _picking = null;+ _error = null;+ })+ : null,+ );+ }++ return _frame(+ header: header,+ children: [+ SwarmGroup(+ children: [for (final engine in swarmLeadEngines) option(engine)],+ ),+ ],+ );}}diff --git a/mobile/lib/swarm/swarm_project_page.dart b/mobile/lib/swarm/swarm_project_page.dartindex 2254b85ab..de135143f 100644--- a/mobile/lib/swarm/swarm_project_page.dart+++ b/mobile/lib/swarm/swarm_project_page.dart@@ -27,6 +27,7 @@ import 'swarm_leaderboard.dart';import 'swarm_message_row.dart';import 'swarm_pm_chat.dart';import 'swarm_project_details.dart';+import 'swarm_project_settings.dart';import 'swarm_project_status.dart';import 'swarm_project_tabs.dart';import 'swarm_project_tasks.dart';@@ -373,6 +374,9 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {/// the project is gone ([_closeSheet]).ModalRoute<void>? _sheet;+ /// Project settings…'s rows while they are up: they go as [_sheet] does.+ Route<void>? _settings;+@overridevoid didChangeDependencies() {super.didChangeDependencies();@@ -553,11 +557,43 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {);}+ void _openSharingSheet(SwarmReader reader) => _openSheet(+ (_) => SwarmProjectSharingSheet(+ reader: reader,+ projectId: widget.projectId,+ ),+ );++ /// Project settings…'s Project details ([SwarmProjectInfoSheet]): not the+ /// sheet a tap on its name opens ([_openDetails]).+ void _openInfoSheet(SwarmReader reader) => _openSheet(+ (_) => SwarmProjectInfoSheet(reader: reader, projectId: widget.projectId),+ );++ Future<void> _openSettings(SwarmReader reader) async {+ Route<void>? shown;+ await showSwarmProjectSettings(+ context,+ reader,+ widget.projectId,+ onShown: (route) => _settings = shown = route,+ onDetails: () => _openInfoSheet(reader),+ );+ if (_settings == shown) _settings = null;+ }+/// Closes the sheet open, if any, and a dialog or sheet over it, with what/// it shows (Approve's question): once this frame is done, as a page that/// lost its project, or is going away, may not change the navigator while/// it does.void _closeSheet() {+ final settings = _settings;+ _settings = null;+ if (settings != null) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (settings.isActive) settings.navigator?.removeRoute(settings);+ });+ }final sheet = _sheet;_sheet = null;if (sheet == null) return;@@ -633,6 +669,10 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {onLeaderboard: _openLeaderboardSheet,onWork: _openWork,onTeam: _openTeamSheet,+ onSharing: swarmManagesProject(reader, project.id)+ ? () => _openSharingSheet(reader)+ : null,+ onSettings: () => unawaited(_openSettings(reader)),onNotifications:snapshot.conversation(project.leadConversationId) == null? null@@ -861,8 +901,10 @@ SuperTabAgent? swarmProjectPm(SuperTabSnapshot? snapshot, String projectId) {/// someone who may write (Tony, 11-01: the PM's terminal on this phone, by/// 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+/// its Team, its Sharing for its owner who may write, its project chat's+/// Notifications ([showSwarmNotifySheet]), while that chat is read, and its+/// Project settings… ([showSwarmProjectSettings]), as the desktop's project+/// menu has them. It goes with the header: losing the project/// closes it. Open terminal follows the Swarm and the phone's computers/// while open, and at the tap reads the PM of [projectId] again.class _ProjectMenu extends StatelessWidget {@@ -873,13 +915,15 @@ class _ProjectMenu extends StatelessWidget {required this.onLeaderboard,required this.onWork,required this.onTeam,+ required this.onSettings,+ this.onSharing,this.onNotifications,});final SwarmReader reader;final String projectId;- final VoidCallback onStatus, onLeaderboard, onWork, onTeam;- final VoidCallback? onNotifications;+ final VoidCallback onStatus, onLeaderboard, onWork, onTeam, onSettings;+ final VoidCallback? onSharing, onNotifications;@overrideWidget build(BuildContext context) {@@ -928,11 +972,11 @@ class _ProjectMenu extends StatelessWidget {return MenuTheme(data: MenuThemeData(submenuIcon: MenuTheme.of(context).submenuIcon,- // Home C sits near the top of the phone. Six rows at their 48-point+ // Home C sits near the top of the phone. Eight rows at their 48-point// layout height, panel padding, and a small edge fit without scrolling.style: AppMenu.style(maxHeight:- 6 * (minTouchTarget + AppSpace.xs) ++ 8 * (minTouchTarget + AppSpace.xs) +AppMenu.panelPadding.vertical +AppSpace.xs,),@@ -951,8 +995,11 @@ class _ProjectMenu extends StatelessWidget {row('swarm-project-menu-leaderboard', 'Leaderboard', onLeaderboard),row('swarm-project-menu-work', 'Work', onWork),row('swarm-project-menu-team', 'Team', onTeam),+ if (onSharing case final onTap?)+ row('swarm-project-menu-sharing', 'Sharing', onTap),if (onNotifications case final onTap?)row('swarm-project-menu-notifications', 'Notifications', onTap),+ row('swarm-project-menu-settings', 'Project settings…', onSettings),],builder: (context, menu, _) => SwarmIconButton(key: const ValueKey('swarm-project-menu'),diff --git a/mobile/lib/swarm/swarm_project_settings.dart b/mobile/lib/swarm/swarm_project_settings.dartnew file mode 100644index 000000000..7ce2a887d--- /dev/null+++ b/mobile/lib/swarm/swarm_project_settings.dart@@ -0,0 +1,664 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/phone_sheet.dart';+import 'package:harness_mobile/shared/theme/app_icon_size.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;++import 'model.dart';+import 'swarm_buddy.dart' show swarmCanWrite;+import 'swarm_leaderboard.dart' show SwarmProjectSheetFrame;+import 'swarm_reader.dart';+import 'swarm_request.dart';+import 'swarm_row.dart';+import 'swarm_style.dart';++/// Whether the person may rename [projectId] and change its sharing: its+/// owner, while they may write (the desktop's `editable && owner`; the+/// server's `manageProject`).+bool swarmManagesProject(SwarmReader reader, String projectId) {+ final project = reader.accessRevoked+ ? null+ : reader.snapshot?.projectById(projectId);+ return project != null &&+ project.ownerId == reader.accountId &&+ swarmCanWrite(reader);+}++/// Renames [projectId] to [name], trimmed (backend `project.rename`); null+/// once the server kept it and the Swarm is read again, else the sentence to+/// show.+Future<String?> swarmRenameProject(+ SwarmReader reader,+ String projectId,+ String name,+) => _send(reader, projectId, {+ 'type': 'project.rename',+ 'projectId': projectId,+ 'name': name.trim(),+});++/// Makes [projectId] private to its owner and [memberIds], or public to the+/// whole Swarm (backend `project.sharing`); null once the server kept it and+/// the Swarm is read again, else the sentence to show. Only people still in+/// the Swarm are sent: the server refuses an id it no longer has.+Future<String?> swarmShareProject(+ SwarmReader reader,+ String projectId, {+ required bool private,+ required Iterable<String> memberIds,+}) {+ final people = {+ for (final person in reader.snapshot?.people ?? const <SuperTabPerson>[])+ person.id,+ };+ return _send(reader, projectId, {+ 'type': 'project.sharing',+ 'projectId': projectId,+ 'visibility': private ? 'private' : 'public',+ 'memberIds': [+ for (final id in memberIds)+ if (people.contains(id)) id,+ ],+ });+}++Future<String?> _send(+ SwarmReader reader,+ String projectId,+ Map<String, dynamic> command,+) async {+ if (!swarmManagesProject(reader, projectId)) return _notAllowed;+ try {+ await reader.request(+ 'POST',+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',+ body: {'operationId': superTabOperationId(), 'command': command},+ );+ } on SuperTabFailure catch (failure) {+ return failure.message;+ } catch (_) {+ // A call lost on the way (a timeout, a socket dropped) is no answer.+ return _notSent;+ }+ await reader.refresh();+ return null;+}++const _notAllowed = 'Only the project owner can manage this project.';+const _notSent = 'Could not reach this Swarm. Try again.';++/// The project menu's Project settings… (the desktop's `showProjectSettings`):+/// Rename project for its owner who may write, and Project details+/// ([onDetails]) for everyone who reads it. Each runs once the sheet has+/// closed. [onShown] is handed its route, for the page to take it down with+/// the project.+Future<void> showSwarmProjectSettings(+ BuildContext context,+ SwarmReader reader,+ String projectId, {+ required VoidCallback onDetails,+ void Function(Route<void> route)? onShown,+}) => showPhoneSheet(+ context,+ title: 'Project settings',+ onShown: onShown,+ // Made the owner's, or no longer, on another device meanwhile.+ rebuildOn: reader,+ rows: () => (+ actions: [+ if (swarmManagesProject(reader, projectId))+ PhoneSheetAction(+ icon: LucideIcons.pencil300,+ label: 'Rename project',+ onTap: () =>+ unawaited(showSwarmRenameProject(context, reader, projectId)),+ ),+ PhoneSheetAction(+ icon: LucideIcons.info300,+ label: 'Project details',+ chevron: true,+ onTap: onDetails,+ ),+ ],+ sections: const <PhoneSheetSection>[],+ ),+);++/// Renames project [projectId] in a dialog: its name to edit, Save, and the+/// server's refusal under the field. It goes once the person can no longer+/// manage the project ([swarmManagesProject]): access lost, a viewer now,+/// another owner, or the project gone.+Future<void> showSwarmRenameProject(+ BuildContext context,+ SwarmReader reader,+ String projectId,+) async {+ if (!context.mounted || !swarmManagesProject(reader, projectId)) return;+ await showDialog<void>(+ context: context,+ builder: (_) => SwarmGoesWithProject(+ reader: reader,+ projectId: projectId,+ child: SwarmRenameProjectDialog(reader: reader, projectId: projectId),+ ),+ );+}++/// Closes the route it is in once the person can no longer manage project+/// [projectId] ([swarmManagesProject]).+class SwarmGoesWithProject extends StatefulWidget {+ const SwarmGoesWithProject({+ super.key,+ required this.reader,+ required this.projectId,+ required this.child,+ });++ final SwarmReader reader;+ final String projectId;+ final Widget child;++ @override+ State<SwarmGoesWithProject> createState() => _SwarmGoesWithProjectState();+}++class _SwarmGoesWithProjectState extends State<SwarmGoesWithProject> {+ bool _closed = false;++ @override+ void initState() {+ super.initState();+ widget.reader.addListener(_moved);+ }++ @override+ void dispose() {+ widget.reader.removeListener(_moved);+ super.dispose();+ }++ void _moved() {+ if (_closed ||+ !mounted ||+ swarmManagesProject(widget.reader, widget.projectId)) {+ return;+ }+ _closed = true;+ // Not while the reader tells its listeners: once this frame is done,+ // and only its own route, whatever is over it.+ 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);+ }+ });+ }++ @override+ Widget build(BuildContext context) => widget.child;+}++/// What [showSwarmRenameProject] shows: the desktop's Rename project, its+/// name trimmed, never empty, at most the backend's 160 characters.+class SwarmRenameProjectDialog extends StatefulWidget {+ const SwarmRenameProjectDialog({+ super.key,+ required this.reader,+ required this.projectId,+ });++ final SwarmReader reader;+ final String projectId;++ @override+ State<SwarmRenameProjectDialog> createState() =>+ _SwarmRenameProjectDialogState();+}++class _SwarmRenameProjectDialogState extends State<SwarmRenameProjectDialog> {+ /// The backend's limit (commands.ts `title`).+ static const _maxLength = 160;++ late final _name = TextEditingController(+ text: widget.reader.snapshot?.projectById(widget.projectId)?.name ?? '',+ );+ bool _saving = false;+ String? _error;++ @override+ void dispose() {+ _name.dispose();+ super.dispose();+ }++ Future<void> _save() async {+ if (_saving || _name.text.trim().isEmpty) return;+ setState(() {+ _saving = true;+ _error = null;+ });+ final error = await swarmRenameProject(+ widget.reader,+ widget.projectId,+ _name.text,+ );+ // Closed meanwhile (access lost, the project gone): the answer is for+ // nobody.+ if (!mounted) return;+ if (error == null) {+ Navigator.of(context).pop();+ return;+ }+ setState(() {+ _saving = false;+ _error = error;+ });+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final empty = _name.text.trim().isEmpty;+ return AlertDialog(+ // A short phone with the keyboard up still shows the field and Save.+ scrollable: true,+ title: Text(+ 'Rename project',+ style: AppType.heading(color: AppPalette.textPrimary),+ ),+ content: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ TextField(+ key: const ValueKey('swarm-project-name'),+ controller: _name,+ autofocus: true,+ enabled: !_saving,+ maxLength: _maxLength,+ textInputAction: TextInputAction.done,+ style: AppType.body(color: AppPalette.textPrimary),+ decoration: InputDecoration(+ counterText: '',+ filled: true,+ fillColor: AppPalette.swarmField,+ border: OutlineInputBorder(+ borderRadius: BorderRadius.circular(AppControl.radius),+ borderSide: BorderSide.none,+ ),+ ),+ onChanged: (_) => setState(() => _error = null),+ onSubmitted: (_) => unawaited(_save()),+ ),+ if (_error case final error?)+ Padding(+ padding: const EdgeInsets.only(top: AppSpace.s),+ child: Text(+ error,+ key: const ValueKey('swarm-project-name-error'),+ style: AppType.caption(color: AppColors.danger),+ ),+ ),+ ],+ ),+ actions: [+ SwarmButton(+ key: const ValueKey('swarm-project-name-cancel'),+ label: 'Cancel',+ style: SwarmButtonStyle.link,+ onPressed: _saving ? null : () => Navigator.of(context).pop(),+ ),+ SwarmButton(+ key: const ValueKey('swarm-project-name-save'),+ label: 'Save',+ style: SwarmButtonStyle.fill,+ busy: _saving,+ busyLabel: 'Saving…',+ onPressed: _saving || empty ? null : () => unawaited(_save()),+ ),+ ],+ );+ }+}++/// A string at [key] of [map], when it is one with something in it.+String? _text(Map<String, dynamic>? map, String key) => switch (map?[key]) {+ final String value when value.trim().isNotEmpty => value,+ _ => null,+};++/// Project details from Project settings…, read only, as the desktop's+/// details dialog has them: under the project's name, its description (its+/// chat's brief), its repository, and its coordinator by the name the project+/// gives it. Not the sheet a tap on the project's name opens+/// (`SwarmProjectDetailsSheet`), which is its actions. The page under it+/// closes it when the read, the access or the project is gone.+class SwarmProjectInfoSheet extends StatelessWidget {+ const SwarmProjectInfoSheet({+ super.key,+ required this.reader,+ required this.projectId,+ });++ final SwarmReader reader;+ final String projectId;++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: reader,+ builder: (context, _) {+ AppTheme.watch(context);+ final snapshot = reader.accessRevoked ? null : reader.snapshot;+ final project = snapshot?.projectById(projectId);+ if (snapshot == null || project == null) return const SizedBox.shrink();+ final chat = snapshot.conversation(project.leadConversationId);+ final brief = chat?.brief.trim() ?? '';+ final repository =+ _text(project.repository, 'repositoryUrl') ??+ _text(project.repository, 'cwd') ??+ 'Not set';+ final lead = chat?.leadId;+ return SwarmProjectSheetFrame(+ title: project.name,+ closeKey: 'swarm-project-info-close',+ child: ListView(+ key: ValueKey('swarm-project-info-$projectId'),+ padding: const EdgeInsets.fromLTRB(+ AppSpace.screenInset,+ AppSpace.xs,+ AppSpace.screenInset,+ AppSpace.l,+ ),+ children: [+ if (brief.isEmpty)+ Text(+ 'No description yet',+ key: const ValueKey('swarm-project-info-description'),+ style: AppType.body(color: AppPalette.textSecondary),+ )+ else+ SelectableText(+ brief,+ key: const ValueKey('swarm-project-info-description'),+ style: AppType.body(color: AppPalette.textPrimary, height: 1.4),+ ),+ const SizedBox(height: AppSpace.l),+ SwarmGroup(+ children: [+ SwarmRow(+ key: const ValueKey('swarm-project-info-repository'),+ title: 'Repository',+ detail: SelectableText(+ repository,+ style: AppType.caption(+ color: AppPalette.textSecondary,+ height: 1.35,+ ),+ ),+ onTap: null,+ ),+ SwarmRow(+ key: const ValueKey('swarm-project-info-coordinator'),+ title: snapshot.coordinatorNameOf(project.id),+ detail: SwarmRow.line(+ lead == null ? 'Starting…' : snapshot.agentName(lead),+ ),+ onTap: null,+ ),+ ],+ ),+ ],+ ),+ );+ },+ );+}++/// The project menu's Sharing, for its owner who may write (the desktop's+/// Sharing dialog): Public or Private, and with Private the people of the+/// Swarm to tick, its owner always in; then Save. It goes once the person can+/// no longer manage the project ([SwarmGoesWithProject]); the page under it+/// closes it when the read or the project is gone.+class SwarmProjectSharingSheet extends StatefulWidget {+ const SwarmProjectSharingSheet({+ super.key,+ required this.reader,+ required this.projectId,+ });++ final SwarmReader reader;+ final String projectId;++ @override+ State<SwarmProjectSharingSheet> createState() =>+ _SwarmProjectSharingSheetState();+}++class _SwarmProjectSharingSheetState extends State<SwarmProjectSharingSheet> {+ late bool _private;++ /// Who is ticked: the project's members as the server counts them+ /// ([SuperTabProject.hasMember]), so someone who left the Swarm and came+ /// back is not, until ticked again.+ late final Set<String> _members;+ bool _saving = false;+ String? _error;++ @override+ void initState() {+ super.initState();+ final snapshot = widget.reader.snapshot;+ final project = snapshot?.projectById(widget.projectId);+ _private = project?.isPrivate ?? false;+ _members = {+ if (project != null)+ for (final person in snapshot!.people)+ if (project.hasMember(person)) person.id,+ };+ }++ Future<void> _save() async {+ if (_saving) return;+ setState(() {+ _saving = true;+ _error = null;+ });+ final error = await swarmShareProject(+ widget.reader,+ widget.projectId,+ private: _private,+ memberIds: _members,+ );+ // Closed meanwhile (access lost, the project gone): the answer is for+ // nobody.+ if (!mounted) return;+ if (error == null) {+ Navigator.of(context).pop();+ return;+ }+ setState(() {+ _saving = false;+ _error = error;+ });+ }++ Widget _visibility(String id, String title, String detail, IconData icon) {+ final on = (id == 'private') == _private;+ return SwarmRow(+ key: ValueKey('swarm-sharing-$id'),+ leading: Icon(+ icon,+ size: AppIconSize.besideText,+ color: AppPalette.textSecondary,+ ),+ title: title,+ detail: SwarmRow.line(detail),+ trailing: on+ ? Semantics(+ label: 'Selected',+ excludeSemantics: true,+ child: Icon(+ LucideIcons.check300,+ size: AppIconSize.besideText,+ color: AppPalette.swarmAccent,+ ),+ )+ : null,+ chevron: null,+ onTap: _saving+ ? null+ : () => setState(() {+ _private = id == 'private';+ _error = null;+ }),+ );+ }++ Widget _person(SuperTabPerson person, String ownerId) {+ final owner = person.id == ownerId;+ final ticked = owner || _members.contains(person.id);+ void toggle() => setState(() {+ _error = null;+ if (!_members.remove(person.id)) _members.add(person.id);+ });+ final enabled = !owner && !_saving;+ return SwarmRow(+ key: ValueKey('swarm-sharing-person-${person.id}'),+ // By the name the Swarm shows them by, over the email the desktop+ // lists: two of one name are still told apart.+ title: person.shownName,+ detail: SwarmRow.line(+ [person.email, if (owner) 'Project owner'].join(' · '),+ ),+ trailing: Checkbox(+ key: ValueKey('swarm-sharing-person-${person.id}-check'),+ value: ticked,+ visualDensity: VisualDensity.compact,+ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,+ onChanged: enabled ? (_) => toggle() : null,+ ),+ chevron: null,+ onTap: enabled ? toggle : null,+ );+ }++ @override+ Widget build(BuildContext context) => SwarmGoesWithProject(+ reader: widget.reader,+ projectId: widget.projectId,+ child: ListenableBuilder(+ listenable: widget.reader,+ builder: (context, _) {+ AppTheme.watch(context);+ final snapshot = widget.reader.accessRevoked+ ? null+ : widget.reader.snapshot;+ final project = snapshot?.projectById(widget.projectId);+ if (snapshot == null || project == null) {+ return const SizedBox.shrink();+ }+ return SwarmProjectSheetFrame(+ title: 'Sharing',+ closeKey: 'swarm-sharing-close',+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Expanded(+ child: ListView(+ key: const ValueKey('swarm-sharing-list'),+ padding: const EdgeInsets.fromLTRB(+ AppSpace.screenInset,+ AppSpace.xs,+ AppSpace.screenInset,+ AppSpace.l,+ ),+ children: [+ SwarmGroup(+ children: [+ _visibility(+ 'public',+ 'Public',+ 'Everyone in this Swarm',+ LucideIcons.users300,+ ),+ _visibility(+ 'private',+ 'Private',+ 'Only people you invite to this project',+ LucideIcons.lock300,+ ),+ ],+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ AppSpace.l,+ AppSpace.xs,+ AppSpace.s,+ ),+ child: Text(+ _private+ ? 'Only the people below can open this project.'+ : 'Everyone in this Swarm can open this project.',+ key: const ValueKey('swarm-sharing-line'),+ style: AppType.body(color: AppPalette.textSecondary),+ ),+ ),+ if (_private)+ SwarmGroup(+ children: [+ for (final person in snapshot.people)+ _person(person, project.ownerId),+ ],+ ),+ ],+ ),+ ),+ Padding(+ padding: EdgeInsets.fromLTRB(+ AppSpace.screenInset,+ AppSpace.s,+ AppSpace.screenInset,+ AppSpace.l + MediaQuery.paddingOf(context).bottom,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (_error case final error?)+ Padding(+ padding: const EdgeInsets.only(bottom: AppSpace.s),+ child: Text(+ error,+ key: const ValueKey('swarm-sharing-error'),+ style: AppType.caption(color: AppColors.danger),+ ),+ ),+ SwarmButton(+ key: const ValueKey('swarm-sharing-save'),+ label: 'Save',+ style: SwarmButtonStyle.fill,+ wide: true,+ busy: _saving,+ busyLabel: 'Saving…',+ onPressed: _saving ? null : () => unawaited(_save()),+ ),+ ],+ ),+ ),+ ],+ ),+ );+ },+ ),+ );+}diff --git a/mobile/lib/swarm/swarm_uploads.dart b/mobile/lib/swarm/swarm_uploads.dartindex e32dca841..c29b937bd 100644--- a/mobile/lib/swarm/swarm_uploads.dart+++ b/mobile/lib/swarm/swarm_uploads.dart@@ -73,8 +73,12 @@ class SwarmUploads {double? progress(SwarmOutgoingFile file) => _progress[file];/// Uploads each of [outgoing] that has not gone up yet and returns their- /// ids, what stopped it, or neither when it was given up meanwhile.- Future<SwarmUploaded> upload(List<SwarmOutgoingFile> outgoing) async {+ /// ids, what stopped it, or neither when it was given up meanwhile, or when+ /// [live] says no before a file starts.+ Future<SwarmUploaded> upload(+ List<SwarmOutgoingFile> outgoing, {+ bool Function()? live,+ }) async {if (outgoing.isEmpty) return (ids: const <String>[], failure: null);final run = ++_run;_uploading = true;@@ -86,6 +90,7 @@ class SwarmUploads {for (final file in outgoing) {var id = _uploaded[file];if (id == null) {+ if (live?.call() == false) return (ids: null, failure: null);final answer = await _uploadFile(file);if (run != _run) return (ids: null, failure: null);id = superTabMap(answer['attachment'])['id'] as String;diff --git a/mobile/test/swarm/swarm_machine_details_test.dart b/mobile/test/swarm/swarm_machine_details_test.dartnew file mode 100644index 000000000..5254fe4e0--- /dev/null+++ b/mobile/test/swarm/swarm_machine_details_test.dart@@ -0,0 +1,271 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/parts.dart';+import 'package:harness_mobile/swarm/swarm_machine_details.dart';++import 'swarm_fixture.dart';++/// What a machine's details read from its Swarm reading, as Desktop's+/// (`machines.dart` `_subscriptions`, `_quotaRow`, `MachineResources.fromJson`)+/// read it.+void main() {+ final now = DateTime.utc(2026, 11, 3, 4);+ final fresh = now.subtract(const Duration(seconds: 5));++ Map<String, dynamic> machine({+ String id = 'mac-1',+ Object? engines = const ['claude', 'codex'],+ List<Map<String, dynamic>> quotas = const [],+ Map<String, dynamic>? readiness,+ DateTime? at,+ bool reported = true,+ }) => {+ 'machineId': id,+ 'name': 'Mac',+ 'contributorId': me,+ 'engines': ?engines,+ 'observation': {+ if (reported) 'receivedAt': (at ?? fresh).millisecondsSinceEpoch,+ 'quotas': quotas,+ 'readiness': ?readiness,+ },+ };++ Map<String, dynamic> quota(+ String engine,+ List<Map<String, dynamic>> windows, {+ bool known = true,+ }) => {'engine': engine, 'known': known, 'windows': windows};++ SuperTabSnapshot snapshot(List<Map<String, dynamic>> machines) {+ final data = firstLoad();+ data['machines'] = [+ for (final (i, m) in machines.indexed)+ part(m['machineId'] as String, 1 + i, m),+ ];+ return SuperTabSnapshot.fromJson(SuperTabParts.firstLoad(data).state);+ }++ ({List<String>? engines, List<SwarmMachineAllowance> allowances}) read(+ Map<String, dynamic> pool, {+ bool dim = false,+ }) {+ final s = snapshot([pool]);+ return swarmMachineSubscriptions(+ s,+ 'mac-1',+ reading: s.pool('mac-1'),+ readingDim: dim,+ now: now,+ );+ }++ group('engines', () {+ test('the Claude and Codex its pool offers, in its order', () {+ expect(read(machine(engines: ['codex', 'claude'])).engines, [+ 'codex',+ 'claude',+ ]);+ expect(read(machine(engines: ['claude', 'cursor'])).engines, ['claude']);+ });++ test('a pool that names none says nothing', () {+ expect(read(machine(engines: null)).engines, isNull);+ expect(read(machine(engines: 'claude')).engines, isNull);+ });++ test(+ 'a list naming a retired engine reads them from its quotas and installs',+ () {+ expect(read(machine(engines: ['opencode'])).engines, isEmpty);+ expect(+ read(+ machine(+ engines: ['opencode'],+ quotas: [+ quota('codex', [+ {'name': 'Weekly', 'usedPercent': 10},+ ]),+ ],+ readiness: {+ 'engines': [+ {'engine': 'claude', 'installed': true, 'signedIn': null},+ ],+ },+ ),+ ).engines,+ ['claude', 'codex'],+ );+ },+ );+ });++ group('allowances', () {+ test('the share of the tightest window, its windows tightest first', () {+ final allowance = read(+ machine(+ quotas: [+ quota('claude', [+ {+ 'name': '5-hour',+ 'usedPercent': 30,+ 'resetsAt': now+ .add(const Duration(minutes: 45, seconds: 30))+ .toIso8601String(),+ },+ {'name': 'Weekly', 'usedPercent': 99.5},+ ]),+ ],+ ),+ ).allowances.single;+ expect(allowance.engine, 'claude');+ expect(allowance.name, 'Claude Code');+ expect(allowance.figure, '<1%');+ expect(allowance.windows, [+ (window: 'Weekly', left: 0.5, reset: null),+ (window: '5-hour', left: 70.0, reset: 'resets in 45m'),+ ]);+ });++ test('an allowance with no figure is left out', () {+ for (final q in [+ quota('claude', [+ {'name': 'Weekly', 'usedPercent': 10},+ ], known: false),+ quota('claude', const []),+ quota('claude', [+ {'name': 'Weekly', 'usedPercent': 10},+ {'name': '5-hour'},+ ]),+ quota('claude', [+ {'name': 'Weekly', 'usedPercent': double.nan},+ ]),+ quota('opencode', [+ {'name': 'Weekly', 'usedPercent': 10},+ ]),+ ]) {+ expect(read(machine(quotas: [q])).allowances, isEmpty, reason: '$q');+ }+ });++ test('times no date can hold are no times, and never throw', () {+ final pool = machine(+ quotas: [+ quota('claude', [+ {'name': 'Weekly', 'usedPercent': 10, 'resetsAt': 1e300},+ ]),+ ],+ );+ expect(read(pool).allowances.single.windows.single.reset, isNull);+ (pool['observation'] as Map<String, dynamic>)['receivedAt'] = 1e300;+ expect(read(pool).allowances, isEmpty);+ });++ test('a machine that never reported has no allowances', () {+ expect(+ read(+ machine(+ reported: false,+ quotas: [+ quota('claude', [+ {'name': 'Weekly', 'usedPercent': 10},+ ]),+ ],+ ),+ ).allowances,+ isEmpty,+ );+ });++ test('a window reset since a current reading leaves it out; an old reading keeps its figures', () {+ final pool = machine(+ quotas: [+ quota('codex', [+ {+ 'name': 'Weekly',+ 'usedPercent': 40,+ // In seconds, as some readings send it.+ 'resetsAt':+ now+ .subtract(const Duration(minutes: 1))+ .millisecondsSinceEpoch ~/+ 1000,+ },+ ]),+ ],+ );+ expect(read(pool).allowances, isEmpty);+ final old = read(pool, dim: true).allowances.single;+ expect(old.figure, '60%');+ expect(old.windows.single, (window: 'Weekly', left: 60.0, reset: null));+ });+ });++ test(+ "a Mac's allowances are its own pool's, not its Harness Team account's",+ () {+ final mac = machine(+ quotas: [+ quota('claude', [+ {'name': 'Weekly', 'usedPercent': 25},+ ]),+ ],+ )..['contributorId'] = 'person-dee';+ final team =+ machine(+ id: 'team-1',+ quotas: [+ quota('claude', [+ {'name': 'Weekly', 'usedPercent': 90},+ ]),+ ],+ )+ ..['contributorId'] = 'person-dee'+ ..['hostMachineId'] = 'mac-1';+ final s = snapshot([mac, team]);+ final result = swarmMachineSubscriptions(+ s,+ 'mac-1',+ reading: s.readingPoolOf('mac-1', me),+ readingDim: false,+ now: now,+ );+ expect(s.readingPoolOf('mac-1', me)?['machineId'], 'team-1');+ expect(result.allowances.single.figure, '75%');+ },+ );++ test('resources out of range are no readings', () {+ final r = SwarmMachineResources.read({+ 'cpuPercent': 101,+ 'gpuPercent': -1,+ 'memoryUsedBytes': 9,+ 'memoryTotalBytes': 8,+ 'diskFreeBytes': 5,+ 'diskTotalBytes': 0,+ 'projectDiskFreeBytes': double.infinity,+ 'deviceType': 'Mac Studio',+ 'chip': '',+ 'os': 42,+ });+ expect(r.cpuPercent, isNull);+ expect(r.gpuPercent, isNull);+ expect(r.memoryUsedBytes, isNull);+ expect(r.memoryTotalBytes, isNull);+ expect(r.diskFreeBytes, isNull);+ expect(r.diskTotalBytes, isNull);+ expect(r.projectDiskFreeBytes, isNull);+ expect(r.deviceType, 'Mac Studio');+ expect(r.chip, isNull);+ expect(r.os, isNull);++ final ok = SwarmMachineResources.read({+ 'cpuPercent': 12.5,+ 'memoryUsedBytes': 4,+ 'memoryTotalBytes': 8,+ });+ expect(ok.cpuPercent, 12.5);+ expect(ok.memoryUsedBytes, 4);+ expect(ok.memoryTotalBytes, 8);+ });+}diff --git a/mobile/test/swarm/swarm_machines_shots_test.dart b/mobile/test/swarm/swarm_machines_shots_test.dartindex 5535eb6b7..64b55b12f 100644--- a/mobile/test/swarm/swarm_machines_shots_test.dart+++ b/mobile/test/swarm/swarm_machines_shots_test.dart@@ -10,7 +10,7 @@ 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_devices_page.dart';import 'package:harness_mobile/swarm/swarm_machines.dart';import 'swarm_machines_test.dart' show machinePool;@@ -47,7 +47,7 @@ void main() {}});- testWidgets('machine drawer and sheet in both phone themes', (tester) async {+ testWidgets('machine list and sheet in both phone themes', (tester) async {await tester.binding.setSurfaceSize(const Size(390, 844));addTearDown(() => tester.binding.setSurfaceSize(null));for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {@@ -108,13 +108,12 @@ void main() {debugShowCheckedModeBanner: false,theme: buildAppTheme(brightness: brightness),builder: (_, child) => SwarmScope(notifier: host, child: child!),- home: const SwarmPage(),+ // The Swarm's machines are on Your devices (Lead, 10-29): the drawer that held them is gone.+ home: const SwarmDevicesPage(),),),);await tester.pumpAndSettle();- await tester.tap(find.byKey(const ValueKey('swarm-menu')));- await tester.pumpAndSettle();Future<void> capture(String name) => tester.runAsync(() async {final image =await (boundary.currentContext!.findRenderObject()!@@ -125,7 +124,7 @@ void main() {.writeAsBytes(png!.buffer.asUint8List());image.dispose();});- await capture('drawer');+ await capture('devices');await tester.tap(find.byKey(const ValueKey('swarm-machine-$tab-mac-1')));await tester.pumpAndSettle();await capture('hardware');diff --git a/mobile/test/swarm/swarm_machines_test.dart b/mobile/test/swarm/swarm_machines_test.dartindex 5cb927add..43cc6cc1c 100644--- a/mobile/test/swarm/swarm_machines_test.dart+++ b/mobile/test/swarm/swarm_machines_test.dart@@ -5,6 +5,7 @@ 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/shared/theme/app_theme.dart';import 'package:harness_mobile/swarm/swarm_devices_page.dart';import 'package:harness_mobile/swarm/swarm_machine_menu.dart';import 'package:harness_mobile/swarm/swarm_machines.dart';@@ -67,6 +68,8 @@ void main() {List<Map<String, dynamic>>? machines,List<Map<String, dynamic>>? agents,String role = 'owner',+ Map<String, dynamic>? localModels,+ String? memberName,void Function(FakeSwarm fake)? routes,}) async {tester.view.physicalSize = const Size(1170, 2532);@@ -81,8 +84,15 @@ void main() {};final rows = machines ?? [machinePool('mac-1', 'Tony’s Mac')];fake.routes['/api/super-tabs/$tab/parts'] = (_) => {- ...firstLoad(agents: agents),- 'members': [part(me, 1, person(me, role: role))],+ ...firstLoad(+ agents: agents,+ head: localModels == null+ ? null+ : {...headData(), 'localModels': localModels},+ ),+ 'members': [+ part(me, 1, {...person(me, role: role), 'name': ?memberName}),+ ],'machines': [for (final m in rows) part(m['machineId'] as String, 1, m)],};fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');@@ -132,13 +142,17 @@ void main() {await open(tester);await tester.tap(key('swarm-machine-$tab-mac-1'));await tester.pumpAndSettle();+ // What is free, in Desktop's words and units (machine_details.dart).+ expect(find.text('Available capacity'), findsOneWidget);expect(find.text('CPU'), findsOneWidget);- expect(find.text('25% in use'), findsOneWidget);- expect(find.text('40% in use'), findsOneWidget);- expect(find.text('12 GB free of 16 GB'), findsOneWidget);- expect(find.text('128 GB free of 512 GB'), findsOneWidget);- expect(find.textContaining('80% left'), findsWidgets);- expect(find.textContaining('Resets'), findsWidgets);+ expect(find.text('75%'), findsOneWidget);+ expect(find.text('60%'), findsOneWidget);+ expect(find.text('13 GB of 17 GB'), findsOneWidget);+ expect(find.text('137 GB of 550 GB'), findsOneWidget);+ expect(find.text('Model allowances'), findsOneWidget);+ expect(find.text('Claude Code'), findsOneWidget);+ expect(find.text('Session'), findsOneWidget);+ expect(find.textContaining('80% left · resets in '), findsOneWidget);expect(find.descendant(of: find.byType(SwarmMachineSheet),@@ -214,8 +228,8 @@ void main() {expect(key('swarm-machine-$tab-team-1'), findsNothing);await tester.tap(key('swarm-machine-$tab-mac-1'));await tester.pumpAndSettle();- expect(find.text('12% in use'), findsOneWidget);- expect(find.text('99% in use'), findsNothing);+ expect(find.text('88%'), findsOneWidget);+ expect(find.text('1%'), findsNothing);expect(find.text('Robin'), findsOneWidget);});@@ -237,9 +251,20 @@ void main() {await tester.tap(key('swarm-machine-$tab-mac-1'));await tester.pumpAndSettle();expect(find.text('Offline'), findsWidgets);- expect(find.text('25% in use'), findsNothing);+ expect(find.text('75%'), findsNothing);expect(find.textContaining('80% left'), findsNothing);- expect(find.textContaining('unavailable'), findsWidgets);+ // As Desktop's details: old readings leave their sections out, never shown as current.+ expect(find.text('Available capacity'), findsNothing);+ expect(find.text('Model allowances'), findsNothing);+ expect(find.text('Device'), findsNothing);+ expect(+ find.descendant(+ of: find.byType(SwarmMachineSheet),+ matching: find.text('Away Mac'),+ ),+ findsNWidgets(2),+ );+ expect(find.text('Claude, Codex'), findsOneWidget);},);testWidgets(@@ -250,7 +275,7 @@ void main() {await tester.pumpAndSettle();host.features.value = const {};await tester.pumpAndSettle();- expect(find.text('25% in use'), findsNothing);+ expect(find.text('75%'), findsNothing);expect(find.text('Access ended'), findsOneWidget);},);@@ -266,7 +291,7 @@ void main() {await host.session!.inbox.reader(tab)!.refresh();await tester.pumpAndSettle();expect(find.text("Can't reach Harness"), findsWidgets);- expect(find.text('25% in use'), findsNothing);+ expect(find.text('75%'), findsNothing);expect(find.text('Offline'), findsNothing);},);@@ -283,8 +308,8 @@ void main() {);await tester.tap(key('swarm-machine-$tab-mac-1'));await tester.pumpAndSettle();- expect(find.text('31% in use'), findsOneWidget);- expect(find.text('98% in use'), findsNothing);+ expect(find.text('69%'), findsOneWidget);+ expect(find.text('2%'), findsNothing);});testWidgets(@@ -320,7 +345,8 @@ void main() {await tester.tap(key('swarm-machine-$tab-mac-1'));await tester.pumpAndSettle();expect(find.textContaining('80% left'), findsNothing);- expect(find.text('Allowance unavailable'), findsWidgets);+ // An allowance with no figure is left out, as Desktop's details leave it out.+ expect(find.text('Model allowances'), findsNothing);expect(find.text('Gone'), findsNothing);expect(find.text('No agents running'), findsOneWidget);},@@ -331,8 +357,19 @@ void main() {await open(tester, machines: []);await tester.tap(key('swarm-machine-$tab-mac-1'));await tester.pumpAndSettle();- expect(find.text('Current readings unavailable'), findsOneWidget);expect(tester.takeException(), isNull);+ final owner = host.session!.inbox.reader(tab)!.snapshot!.people.single;+ // The Swarm knows no name for it: Desktop names it by its owner.+ expect(+ find.descendant(+ of: find.byType(SwarmMachineSheet),+ matching: find.text("${owner.username}'s computer"),+ ),+ findsNWidgets(2),+ );+ expect(find.text('Offline'), findsOneWidget);+ expect(find.text('Available capacity'), findsNothing);+ expect(find.text('Engines'), findsNothing);});testWidgets('hardware labels and values share a row, label left and value right',@@ -341,7 +378,7 @@ void main() {await tester.tap(key('swarm-machine-$tab-mac-1'));await tester.pumpAndSettle();final label = find.text('CPU');- final value = find.text('25% in use');+ final value = find.text('75%');expect(tester.getTopLeft(label).dy,closeTo(tester.getTopLeft(value).dy, 1),@@ -855,4 +892,379 @@ void main() {},);});++ group("details, as Desktop's machine details show them", () {+ Finder inSheet(Finder finder) =>+ find.descendant(of: find.byType(SwarmMachineSheet), matching: finder);++ Future<void> details(WidgetTester tester, [String id = 'mac-1']) async {+ await tester.tap(key('swarm-machine-$tab-$id'));+ await tester.pumpAndSettle();+ }++ double top(WidgetTester tester, String text) =>+ tester.getTopLeft(inSheet(find.text(text)).first).dy;++ testWidgets(+ 'Owner and Status come first; Details names the computer, its hardware and engines',+ (tester) async {+ await open(tester);+ await details(tester);+ final owner = host.session!.inbox.reader(tab)!.snapshot!.people.single;+ expect(inSheet(find.text('Owner')), findsOneWidget);+ expect(inSheet(find.text(owner.username)), findsOneWidget);+ expect(inSheet(find.text('Online')), findsOneWidget);+ expect(top(tester, 'Owner'), lessThan(top(tester, 'Status')));+ expect(+ top(tester, 'Status'),+ lessThan(top(tester, 'Available capacity')),+ );+ expect(+ top(tester, 'Model allowances'),+ lessThan(top(tester, 'Details')),+ );+ for (final (label, value) in [+ ('Computer', 'Tony’s Mac'),+ ('Device', 'MacBook Pro'),+ ('Chip', 'Apple M2'),+ ('System', 'macOS'),+ ('Engines', 'Claude, Codex'),+ ]) {+ expect(inSheet(find.text(label)), findsOneWidget, reason: label);+ expect(+ tester.getTopLeft(inSheet(find.text(label))).dy,+ closeTo(tester.getTopLeft(inSheet(find.text(value)).last).dy, 1),+ reason: label,+ );+ }+ // Nothing the Swarm's models add while they are off.+ expect(key('swarm-machine-local-models-mac-1'), findsNothing);+ expect(find.text('Models for this Swarm'), findsNothing);+ },+ );++ testWidgets(+ "its state in Desktop's words: late is online, pauses and cleaning say so",+ (tester) async {+ final ago = DateTime.now()+ .subtract(const Duration(seconds: 25))+ .millisecondsSinceEpoch;+ final away = DateTime.now()+ .subtract(const Duration(minutes: 2))+ .millisecondsSinceEpoch;+ for (final (pool, status) in [+ (machinePool('mac-1', 'Mac', receivedAt: ago), 'Online'),+ (+ {...machinePool('mac-1', 'Mac'), 'paused': true},+ 'New work paused',+ ),+ (+ {...machinePool('mac-1', 'Mac', receivedAt: away), 'paused': true},+ 'Offline, new work paused',+ ),+ (+ {+ ...machinePool('mac-1', 'Mac'),+ 'removal': {'state': 'cleaning'},+ },+ 'Cleaning up',+ ),+ ]) {+ await open(tester, machines: [pool]);+ await details(tester);+ expect(inSheet(find.text(status)), findsOneWidget, reason: status);+ expect(inSheet(find.text('Late')), findsNothing);+ await tester.pumpWidget(const SizedBox());+ }+ },+ );++ testWidgets(+ 'each allowance by its provider, the window that stops work first on top, low shares coloured',+ (tester) async {+ final pool = machinePool('mac-1', 'Mac');+ final later = DateTime.now().add(const Duration(days: 3, hours: 1));+ (pool['observation'] as Map<String, dynamic>)['quotas'] = [+ {+ 'engine': 'claude',+ 'known': true,+ 'windows': [+ {+ 'name': 'Session',+ 'usedPercent': 20,+ 'resetsAt': DateTime.now()+ .add(const Duration(hours: 2, minutes: 30))+ .millisecondsSinceEpoch,+ },+ {+ 'name': 'Weekly',+ 'usedPercent': 96.5,+ 'resetsAt': later.millisecondsSinceEpoch ~/ 1000,+ },+ ],+ },+ // Its windows name nothing: its one figure stands for them.+ {+ 'engine': 'codex',+ 'known': true,+ 'windows': [+ {'name': '', 'usedPercent': 50},+ ],+ },+ // An engine the details do not read.+ {+ 'engine': 'opencode',+ 'known': true,+ 'windows': [+ {'name': 'Daily', 'usedPercent': 10},+ ],+ },+ ];+ await open(tester, machines: [pool]);+ await details(tester);+ expect(inSheet(find.text('Claude Code')), findsOneWidget);+ expect(inSheet(find.text('Codex')), findsOneWidget);+ expect(inSheet(find.text('50% left')), findsOneWidget);+ expect(inSheet(find.text('Daily')), findsNothing);+ final weekly = find.text('3.5% left · resets in 3d');+ expect(inSheet(weekly), findsOneWidget);+ expect(+ inSheet(find.textContaining('80% left · resets in 2h')),+ findsOneWidget,+ );+ expect(top(tester, 'Weekly'), lessThan(top(tester, 'Session')));+ expect(+ tester.widget<Text>(weekly).style?.color,+ AppPalette.usageCritical,+ );+ expect(+ tester+ .widget<Text>(find.textContaining('80% left · resets in'))+ .style+ ?.color,+ AppPalette.textPrimary,+ );+ },+ );++ testWidgets(+ "a teammate reads a Mac's allowances from the Mac, its capacity from its Team account",+ (tester) async {+ Map<String, dynamic> withClaude(Map<String, dynamic> pool, num used) {+ (pool['observation'] as Map<String, dynamic>)['quotas'] = [+ {+ 'engine': 'claude',+ 'known': true,+ 'windows': [+ {'name': 'Session', 'usedPercent': used},+ ],+ },+ ];+ return pool;+ }++ await open(+ tester,+ machines: [+ withClaude(+ machinePool('mac-1', 'Shared Mac', owner: 'other', cpu: 99),+ 20,+ ),+ withClaude(+ machinePool(+ 'team-1',+ 'Team account',+ owner: 'other',+ host: 'mac-1',+ cpu: 12,+ ),+ 70,+ ),+ ],+ );+ await details(tester);+ expect(inSheet(find.text('88%')), findsOneWidget);+ expect(inSheet(find.text('80% left')), findsOneWidget);+ expect(inSheet(find.text('30% left')), findsNothing);+ },+ );++ testWidgets(+ 'Models for this Swarm lists what a fresh reading serves, by kind',+ (tester) async {+ Map<String, dynamic> serving({int? receivedAt}) {+ final pool = machinePool('mac-1', 'Mac', receivedAt: receivedAt);+ (pool['observation'] as Map<String, dynamic>)['localModels'] = [+ {+ 'grid': 'swarm-grid',+ 'model': 'deepseek/deepseek-v3',+ 'kind': 'api',+ 'name': 'deepseek-v3 · OpenRouter',+ },+ {+ 'grid': 'swarm-grid',+ 'model': 'qwen3:8b',+ 'kind': 'local',+ 'name': 'Qwen3 8B',+ },+ {'grid': 'swarm-grid', 'model': 'llama:70b', 'starting': true},+ {'grid': 'another-grid', 'model': 'gemma', 'kind': 'shared'},+ ];+ return pool;+ }++ const models = {'grid': 'swarm-grid', 'enabled': true, 'ready': true};+ await open(tester, machines: [serving()], localModels: models);+ await details(tester);+ await tester.dragUntilVisible(+ key('swarm-machine-local-models-mac-1'),+ inSheet(find.byType(SingleChildScrollView)),+ const Offset(0, -200),+ );+ expect(find.text('Models for this Swarm'), findsOneWidget);+ expect(find.text('deepseek-v3'), findsOneWidget);+ expect(find.text('Qwen3 8B'), findsOneWidget);+ expect(find.textContaining('llama'), findsNothing);+ expect(find.textContaining('gemma'), findsNothing);+ await tester.pumpWidget(const SizedBox());++ // An offline machine's old reading serves nothing now.+ await open(+ tester,+ machines: [+ serving(+ receivedAt: DateTime.now()+ .subtract(const Duration(minutes: 2))+ .millisecondsSinceEpoch,+ ),+ ],+ localModels: models,+ );+ await details(tester);+ await tester.dragUntilVisible(+ key('swarm-machine-local-models-mac-1'),+ inSheet(find.byType(SingleChildScrollView)),+ const Offset(0, -200),+ );+ expect(find.text('None'), findsNWidgets(2));+ expect(find.text('Qwen3 8B'), findsNothing);+ },+ );++ testWidgets(+ 'each served model names whose Buddy runs on it, by the name they set',+ (tester) async {+ final pool = machinePool('mac-1', 'Mac');+ (pool['observation'] as Map<String, dynamic>)['localModels'] = [+ {+ 'grid': 'swarm-grid',+ 'model': 'deepseek/deepseek-v3',+ 'kind': 'api',+ },+ {+ 'grid': 'swarm-grid',+ 'model': 'qwen3:8b',+ 'kind': 'local',+ 'name': 'Qwen3 8B',+ },+ ];+ await open(+ tester,+ machines: [pool],+ memberName: 'Minh Nguyen',+ localModels: const {+ 'grid': 'swarm-grid',+ 'enabled': true,+ 'ready': true,+ },+ agents: [+ // Not a Buddy: it says nothing of whose it is.+ {+ ...agent('agent-builder', displayName: 'Nova'),+ 'gridModel': 'qwen3:8b',+ },+ {+ ...agent('agent-buddy', name: 'Buddy'),+ 'buddyOf': {'personId': me},+ 'gridModel': 'qwen3:8b',+ },+ ],+ );+ await details(tester);+ await tester.dragUntilVisible(+ key('swarm-machine-local-models-mac-1'),+ inSheet(find.byType(SingleChildScrollView)),+ const Offset(0, -200),+ );+ final used = inSheet(find.text("Used by Minh Nguyen's Buddy"));+ expect(used, findsOneWidget);+ // One line, under the model the Buddy runs on alone.+ expect(+ tester.getTopLeft(used).dy,+ greaterThan(tester.getTopLeft(inSheet(find.text('Qwen3 8B'))).dy),+ );+ expect(inSheet(find.text('deepseek-v3')), findsOneWidget);+ expect(inSheet(find.textContaining('Used by')), findsOneWidget);+ },+ );++ testWidgets('its owner by the name they set for the Swarm', (+ tester,+ ) async {+ await open(tester, memberName: 'Minh Nguyen');+ await details(tester);+ expect(inSheet(find.text('Owner')), findsOneWidget);+ expect(inSheet(find.text('Minh Nguyen')), findsOneWidget);+ expect(inSheet(find.text(me)), findsNothing);+ await tester.pumpWidget(const SizedBox());++ // A computer the Swarm knows only by its agents is named by its owner.+ await open(tester, machines: [], memberName: 'Minh Nguyen');+ await details(tester);+ expect(+ inSheet(find.text("Minh Nguyen's computer")),+ findsNWidgets(2),+ );+ });++ testWidgets(+ 'out-of-range readings are no readings, and the project disk wins',+ (tester) async {+ final pool = machinePool('mac-1', 'Mac');+ final resources =+ (pool['observation'] as Map<String, dynamic>)['resources']+ as Map<String, dynamic>;+ resources+ ..['cpuPercent'] = 140+ ..remove('gpuPercent')+ ..['memoryUsedBytes'] = 32 * 1073741824+ ..['projectDiskTotalBytes'] = 100000000000+ ..['projectDiskFreeBytes'] = 500000000+ ..['chip'] = ''+ ..['os'] = 'x' * 121;+ await open(tester, machines: [pool]);+ await details(tester);+ for (final label in ['CPU', 'GPU', 'RAM', 'Chip', 'System']) {+ expect(inSheet(find.text(label)), findsNothing, reason: label);+ }+ expect(inSheet(find.text('500 MB of 100 GB')), findsOneWidget);+ expect(tester.takeException(), isNull);+ },+ );++ testWidgets('Pause new work and Remove from Swarm stay as they were', (+ tester,+ ) async {+ await open(tester, agents: [agent('agent-builder', displayName: 'Nova')]);+ await details(tester);+ await tester.dragUntilVisible(+ key('swarm-machine-pause'),+ inSheet(find.byType(SingleChildScrollView)),+ const Offset(0, -200),+ );+ expect(find.text('Pause new work'), findsOneWidget);+ // Remove stays in the long-press menu, out of the read-only details.+ expect(inSheet(find.text('Remove from Swarm')), findsNothing);+ });+ });}diff --git a/mobile/test/swarm/swarm_new_project_shots_test.dart b/mobile/test/swarm/swarm_new_project_shots_test.dartindex aa267c0cf..86b1ea79b 100644--- a/mobile/test/swarm/swarm_new_project_shots_test.dart+++ b/mobile/test/swarm/swarm_new_project_shots_test.dart@@ -11,16 +11,19 @@ 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_file_picker.dart';import 'package:harness_mobile/swarm/swarm_page.dart';import 'package:harness_mobile/swarm/swarm_request.dart';import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:image_picker/image_picker.dart' show XFile;import '../voice_fakes.dart';import 'swarm_fixture.dart';import 'swarm_new_project_fixture.dart';/// Review screenshots of + New project: Home's row, the sheet filled in, PM-/// runs on, the brief written with the keyboard up, a long error (with the+/// runs on, Agent, files attached under the brief (and +'s sheet), the+/// brief written with the keyboard up, a long error (with the/// keyboard up too), a Product Manager that did not start, and no machine able to run/// one. On a 390-point and a 320-point phone in both phone themes, from/// made-up data only, to the folder `SWARM_NEW_PROJECT_SHOTS` names. The@@ -191,6 +194,32 @@ void main() {await tap('swarm-new-project-pick-machine-mac-studio');await capture('sheet');+ // Agent: each engine with the model it gets.+ await tap('swarm-new-project-agent');+ await capture('agents');+ await tap('swarm-new-project-back');++ // Two files under the brief, then taken off again.+ final picker = (files: pickSwarmFiles, copies: swarmPickerCopyFolders);+ pickSwarmFiles = () async => [+ for (final name in ['product-brief.pdf', 'build.log'])+ XFile.fromData(+ Uint8List.fromList(List.filled(48 * 1024, 1)),+ name: name,+ path: '/copies/$name',+ ),+ ];+ swarmPickerCopyFolders = () async => const [];+ await tap('swarm-new-project-attach');+ await capture('attach');+ await tap('swarm-attach-files');+ await capture('files');+ for (final name in ['product-brief.pdf', 'build.log']) {+ await tap('swarm-outgoing-remove-$name');+ }+ pickSwarmFiles = picker.files;+ swarmPickerCopyFolders = picker.copies;+// The keyboard up while the brief is written: it and Create stay in// sight.Future<void> raiseKeyboard() async {diff --git a/mobile/test/swarm/swarm_new_project_test.dart b/mobile/test/swarm/swarm_new_project_test.dartindex eba365d7d..16952327b 100644--- a/mobile/test/swarm/swarm_new_project_test.dart+++ b/mobile/test/swarm/swarm_new_project_test.dart@@ -1,17 +1,23 @@import 'dart:async';import 'dart:convert';+import 'dart:typed_data';import 'package:flutter/cupertino.dart' show CupertinoPageRoute;import 'package:flutter/material.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/swarm/swarm_conversation_page.dart'+ show SwarmAttachButton;+import 'package:harness_mobile/swarm/swarm_file_picker.dart';import 'package:harness_mobile/swarm/swarm_new_project_sheet.dart';+import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';import 'package:harness_mobile/swarm/swarm_page.dart';import 'package:harness_mobile/swarm/swarm_reader.dart';import 'package:harness_mobile/swarm/swarm_request.dart';import 'package:harness_mobile/swarm/swarm_session.dart';import 'package:harness_mobile/swarm/swarm_style.dart' show SwarmButton;+import 'package:image_picker/image_picker.dart' show XFile;import '../voice_fakes.dart';import 'swarm_fixture.dart';@@ -242,6 +248,106 @@ void main() {'Choose one of this Swarm’s machines.',);});++ test('its line names the engine chosen where it runs it, else its own', () {+ final [studio] = machines([leadPool('mac-1', name: 'Studio')]);+ expect(studio.detailFor('codex'), 'Codex · 2 agents free');+ expect(studio.detailFor(null), studio.detail);+ final [claudeOnly] = machines([+ leadPool('mac-1', engines: ['claude']),+ ]);+ expect(claudeOnly.detailFor('codex'), 'Claude Code · 2 agents free');+ });++ test('an engine chosen that the machine cannot run is refused, saying '+ 'to choose another engine', () {+ final listed = machines([+ leadPool('mac-1', name: 'Studio', engines: ['claude']),+ ]);+ expect(swarmLeadMachineRefusal(listed, 'mac-1'), isNull);+ expect(+ swarmLeadMachineRefusal(listed, 'mac-1', engine: 'claude'),+ isNull,+ );+ expect(+ swarmLeadMachineRefusal(listed, 'mac-1', engine: 'codex'),+ 'Studio can’t run Codex: Codex isn’t offered here. '+ 'Choose another engine.',+ );+ });+ });++ group('the model a Product Manager gets', () {+ Map<String, dynamic> list(List<Map<String, dynamic>> rows) => {+ 'policy': {'models': rows},+ };+ Map<String, dynamic> row(+ String engine,+ String model,+ String effort, {+ required bool on,+ }) => {'engine': engine, 'model': model, 'effort': effort, 'enabled': on};++ test('Claude gets its role\'s default, Opus 5.5 at xhigh, unless the '+ 'Swarm\'s list turns it off; Codex runs its own', () {+ expect(swarmLeadModelLabel('claude'), 'Opus 5.5 · xhigh');+ expect(+ swarmLeadModelLabel('claude', leadModelOn: false),+ 'Default model',+ );+ expect(swarmLeadModelLabel('codex'), 'Default model');+ });++ test('the Swarm\'s list leaves it on unless its effort\'s row, or with '+ 'none, every row of the model, is off', () {+ expect(swarmLeadModelOn(null), isTrue);+ expect(swarmLeadModelOn({'policy': null}), isTrue);+ expect(swarmLeadModelOn(list([])), isTrue);+ expect(+ swarmLeadModelOn(+ list([+ row('claude', 'opus', 'xhigh', on: false),+ row('claude', 'opus', 'high', on: true),+ ]),+ ),+ isFalse,+ );+ expect(+ swarmLeadModelOn(+ list([+ row('claude', 'opus', 'xhigh', on: true),+ row('claude', 'opus', 'high', on: false),+ ]),+ ),+ isTrue,+ );+ expect(+ swarmLeadModelOn(list([row('claude', 'opus', 'high', on: true)])),+ isTrue,+ );+ expect(+ swarmLeadModelOn(list([row('claude', 'opus', 'high', on: false)])),+ isFalse,+ );+ // Other models and engines say nothing of it.+ expect(+ swarmLeadModelOn(+ list([+ row('claude', 'sonnet', 'xhigh', on: false),+ row('codex', 'opus', 'xhigh', on: false),+ ]),+ ),+ isTrue,+ );+ // With its catalog, the list is the Swarm's advice.+ expect(+ swarmLeadModelOn({+ ...list([row('claude', 'opus', 'xhigh', on: false)]),+ 'catalog': {'models': <Object>[]},+ }),+ isTrue,+ );+ });});group('repositories', () {@@ -317,12 +423,19 @@ void main() {group('SwarmNewProjectSteps', () {late FakeSwarm fake;late NewProjectSwarm swarm;+ late FakeUploads uploads;late SwarmReader reader;setUp(() async {fake = FakeSwarm();swarm = NewProjectSwarm()..install(fake);- reader = SwarmReader(tabId: tab, accountId: me, request: fake.request);+ uploads = FakeUploads();+ reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: fake.request,+ upload: uploads.upload,+ );await reader.refresh();});tearDown(() => reader.dispose());@@ -332,17 +445,236 @@ void main() {String brief = 'Ship the phone flow',String machineId = 'mac-1',String repositoryUrl = harnessRepo,+ String? engine,+ List<SwarmOutgoingFile> files = const [],bool Function()? live,}) => steps.run(brief: brief,visibility: 'private',machineId: machineId,repositoryUrl: repositoryUrl,+ engine: engine,+ files: files,live: live ?? () => true,machinesOf: (snapshot) =>swarmLeadMachines(snapshot, me, now: newProjectNow),);+ SwarmOutgoingFile file(String name) =>+ SwarmOutgoingFile(name, Uint8List.fromList([1, 2, 3]));++ test(+ 'starts its Product Manager with the engine the person chose',+ () async {+ await run(SwarmNewProjectSteps.of(reader), engine: 'codex');+ expect(+ (swarm.commands('lead.start').single['command'] as Map)['engine'],+ 'codex',+ );+ },+ );++ test('an engine the machine no longer runs on a fresh read is refused '+ 'with why, and no start is sent; another engine starts it on the '+ 'same project', () async {+ final steps = SwarmNewProjectSteps.of(reader);+ swarm.machines = [+ leadPool('mac-1', name: 'Studio', engines: ['claude']),+ ];+ await expectLater(+ run(steps, engine: 'codex'),+ throwsA(+ isA<SuperTabFailure>().having(+ (f) => f.message,+ 'message',+ 'Studio can’t run Codex: Codex isn’t offered here. '+ 'Choose another engine.',+ ),+ ),+ );+ expect(swarm.commands('lead.start'), isEmpty);++ await run(steps, engine: 'claude');+ expect(swarm.commands('project.create'), hasLength(1));+ expect(+ (swarm.commands('lead.start').single['command'] as Map)['engine'],+ 'claude',+ );+ });++ test('its files go up to the new project\'s chat, then go with its '+ 'brief', () async {+ final made = await run(+ SwarmNewProjectSteps.of(reader),+ files: [file('spec.pdf'), file('build.log')],+ );+ expect(uploads.names, ['spec.pdf', 'build.log']);+ expect(+ {for (final u in uploads.asked) u.conversationId},+ {'project-$made'},+ );+ expect({for (final u in uploads.asked) u.tabId}, {tab});+ expect(swarm.commands('message.send').single['command'], {+ 'type': 'message.send',+ 'conversationId': 'project-$made',+ 'text': 'Ship the phone flow',+ 'replyTo': null,+ 'recipientIds': <String>[],+ 'attachmentIds': ['id-spec.pdf', 'id-build.log'],+ });+ expect(+ [for (final b in swarm.sent) (b['command'] as Map)['type']],+ ['project.create', 'message.send', 'lead.start', 'project.rename'],+ );+ });++ test('files with no brief still go, in a message of no text', () async {+ await run(+ SwarmNewProjectSteps.of(reader),+ brief: ' ',+ files: [file('a.png')],+ );+ final send = swarm.commands('message.send').single['command'] as Map;+ expect(send['text'], '');+ expect(send['attachmentIds'], ['id-a.png']);+ expect(+ (swarm.commands('project.create').single['command'] as Map)['brief'],+ '',+ );+ });++ test('an upload refused says why and sends no message; Create again '+ 'uploads only what did not go up, with the files first sent', () async {+ uploads.refuse['b.log'] = const SuperTabFailure(+ 'TOO_LARGE',+ 'b.log is too large.',+ statusCode: 413,+ );+ final steps = SwarmNewProjectSteps.of(reader);+ await expectLater(+ run(steps, files: [file('a.log'), file('b.log')]),+ throwsA(+ isA<SuperTabFailure>().having(+ (f) => f.message,+ 'message',+ 'b.log is too large.',+ ),+ ),+ );+ expect(steps.projectId, isNotNull);+ expect(swarm.commands('message.send'), isEmpty);+ expect(swarm.commands('lead.start'), isEmpty);+ expect([for (final f in steps.sentFiles) f.name], ['a.log', 'b.log']);++ uploads.refuse.clear();+ await run(steps, files: [file('other.log')]);+ expect(uploads.names, ['a.log', 'b.log', 'b.log']);+ expect(+ (swarm.commands('message.send').single['command']+ as Map)['attachmentIds'],+ ['id-a.log', 'id-b.log'],+ );+ expect(swarm.commands('project.create'), hasLength(1));+ });++ test('no file starts going up once the sheet has gone, and a Create later '+ 'keeps what went up', () async {+ uploads.answersAtOnce = false;+ var live = true;+ final steps = SwarmNewProjectSteps.of(reader);+ final files = [file('a.log'), file('b.log'), file('c.log')];+ final running = run(steps, files: files, live: () => live);+ for (var i = 0; i < 50 && uploads.asked.isEmpty; i++) {+ await settle();+ }+ expect(uploads.names, ['a.log']);+ live = false;+ uploads.asked.single.answer.complete({+ 'attachment': {'id': 'id-a'},+ });+ await expectLater(running, throwsA(isA<SwarmNewProjectGone>()));+ await settle();+ expect(uploads.names, ['a.log'], reason: 'b.log and c.log never started');+ expect(swarm.commands('message.send'), isEmpty);++ uploads.answersAtOnce = true;+ await run(steps, files: files);+ expect(uploads.names, ['a.log', 'b.log', 'c.log']);+ });++ test('an upload that fails without the backend\'s words says so in the '+ 'chat\'s', () async {+ uploads.answersAtOnce = false;+ final running = run(+ SwarmNewProjectSteps.of(reader),+ files: [file('a.log')],+ );+ for (var i = 0; i < 50 && uploads.asked.isEmpty; i++) {+ await settle();+ }+ uploads.asked.single.answer.completeError(StateError('offline'));+ await expectLater(+ running,+ throwsA(+ isA<SuperTabFailure>().having(+ (f) => f.message,+ 'message',+ 'Could not upload the file. Try again.',+ ),+ ),+ );+ expect(swarm.commands('message.send'), isEmpty);+ });++ test('a brief whose answer was lost is sent again as it was, its files '+ 'not uploaded again', () async {+ var lose = true;+ swarm.answer = (command) {+ if (command['type'] == 'message.send' && lose) {+ lose = false;+ throw const SuperTabFailure('NETWORK', 'The Swarm didn’t answer.');+ }+ return null;+ };+ final steps = SwarmNewProjectSteps.of(reader);+ await expectLater(+ run(steps, files: [file('a.log')]),+ throwsA(isA<SuperTabFailure>()),+ );+ await run(steps);+ expect(uploads.names, ['a.log']);+ final sends = swarm.commands('message.send');+ expect(sends, hasLength(2));+ expect(sends[0]['operationId'], sends[1]['operationId']);+ expect(sends[1]['command'], sends[0]['command']);+ });++ test('a brief with files refused outright sends them up afresh with the '+ 'next, a new request', () async {+ var refuse = true;+ swarm.answer = (command) {+ if (command['type'] == 'message.send' && refuse) {+ refuse = false;+ throw const SuperTabFailure(+ 'ATTACHMENT_UNKNOWN',+ 'A file is no longer there.',+ statusCode: 400,+ );+ }+ return null;+ };+ final steps = SwarmNewProjectSteps.of(reader);+ await expectLater(+ run(steps, files: [file('a.log')]),+ throwsA(isA<SuperTabFailure>()),+ );+ await run(steps);+ expect(uploads.names, ['a.log', 'a.log']);+ final sends = swarm.commands('message.send');+ expect(sends, hasLength(2));+ expect(sends[0]['operationId'], isNot(sends[1]['operationId']));+ });+test('creates the project, posts its brief, starts its Product Manager ''on the machine picked, then names it after its repository', () async {final steps = SwarmNewProjectSteps.of(reader);@@ -798,6 +1130,7 @@ void main() {WidgetTester tester,List<NewProjectSwarm> swarms, {ValueNotifier<String?>? account,+ SwarmUpload upload = refuseSwarmUpload,bool settle = true,}) async {tester.view.physicalSize = const Size(1170, 2532);@@ -810,6 +1143,7 @@ void main() {accountId: () => signedIn.value,account: signedIn,request: newProjectBackend(swarms).request,+ upload: upload,notices: SilentSystemNotices(),features: features,readMarks: MemoryKeyValueStore(),@@ -849,6 +1183,35 @@ void main() {}}+ /// [text] on the Agent row.+ Finder onAgent(String text) => find.descendant(+ of: key('swarm-new-project-agent'),+ matching: find.text(text),+ );++ /// Files hands over [names], each a few bytes.+ void picks(List<String> names) => pickSwarmFiles = () async => [+ for (final name in names)+ XFile.fromData(+ Uint8List.fromList([1, 2, 3]),+ name: name,+ path: '/copies/$name',+ ),+ ];++ /// +, then Files.+ Future<void> attachFiles(WidgetTester tester) async {+ await tap(tester, 'swarm-new-project-attach');+ await tap(tester, 'swarm-attach-files');+ }++ final picker = (files: pickSwarmFiles, copies: swarmPickerCopyFolders);+ setUp(() => swarmPickerCopyFolders = () async => const []);+ tearDown(() {+ pickSwarmFiles = picker.files;+ swarmPickerCopyFolders = picker.copies;+ });+testWidgets('+ New project is the last row of Projects for someone who ''may write in the Swarm', (tester) async {await pump(tester, [NewProjectSwarm()]);@@ -1878,5 +2241,397 @@ void main() {expect(find.text('#openharness'), findsNothing);expect(find.byType(SwarmPage), findsOneWidget);});++ group('options (Desktop\'s New Project)', () {+ testWidgets('Agent shows the machine\'s engine and the model it gets; '+ 'left alone, Create starts it as before', (tester) async {+ final swarm = NewProjectSwarm();+ await pump(tester, [swarm]);+ await tap(tester, 'swarm-new-project');+ expect(onAgent('Claude Code'), findsOneWidget);+ expect(onAgent('Opus 5.5 · xhigh'), findsOneWidget);+ await pickMachine(tester, 'mac-1');+ expect(+ find.descendant(+ of: key('swarm-new-project-machine'),+ matching: find.text('Claude Code · 2 agents free'),+ ),+ findsOneWidget,+ );+ await tap(tester, 'swarm-new-project-create');+ final start = swarm.commands('lead.start').single['command'] as Map;+ expect(start['engine'], 'claude');+ expect(+ start.containsKey('model'),+ isFalse,+ reason: 'the Swarm fills it',+ );+ expect(+ swarm.commands('message.send'),+ isEmpty,+ reason: 'no brief and no files: nothing posted, as before',+ );+ });++ testWidgets('Agent lists each engine with its model; one the machine '+ 'cannot run says why, a machine chosen last wins, and Codex chosen '+ 'starts it with Codex', (tester) async {+ final swarm = NewProjectSwarm(+ machines: [+ leadPool('mac-1', name: 'Studio'),+ leadPool('mac-2', name: 'Mini', engines: ['claude']),+ ],+ );+ await pump(tester, [swarm]);+ await tap(tester, 'swarm-new-project');+ await tap(tester, 'swarm-new-project-agent');+ expect(+ find.descendant(+ of: key('swarm-new-project-pick-agent-claude'),+ matching: find.text('Opus 5.5 · xhigh'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: key('swarm-new-project-pick-agent-codex'),+ matching: find.text('Default model'),+ ),+ findsOneWidget,+ );+ await tap(tester, 'swarm-new-project-pick-agent-codex');+ expect(onAgent('Codex'), findsOneWidget);+ expect(onAgent('Default model'), findsOneWidget);++ // Mini runs Claude Code only: chosen last, it wins.+ await pickMachine(tester, 'mac-2');+ expect(onAgent('Claude Code'), findsOneWidget);+ await tap(tester, 'swarm-new-project-agent');+ expect(+ find.descendant(+ of: key('swarm-new-project-pick-agent-codex'),+ matching: find.text('Codex isn’t offered here'),+ ),+ findsOneWidget,+ );+ await tester.tap(key('swarm-new-project-pick-agent-codex'));+ await tester.pumpAndSettle();+ expect(+ key('swarm-new-project-pick-agent-codex'),+ findsOneWidget,+ reason: 'not taken',+ );+ await tap(tester, 'swarm-new-project-back');++ // Studio runs both: Codex there, its line saying so.+ await pickMachine(tester, 'mac-1');+ await tap(tester, 'swarm-new-project-agent');+ await tap(tester, 'swarm-new-project-pick-agent-codex');+ expect(+ find.descendant(+ of: key('swarm-new-project-machine'),+ matching: find.text('Codex · 2 agents free'),+ ),+ findsOneWidget,+ );+ await tap(tester, 'swarm-new-project-create');+ expect(+ (swarm.commands('lead.start').single['command'] as Map)['engine'],+ 'codex',+ );+ });++ testWidgets('the engine chosen, no longer run by its machine, keeps '+ 'Create off and says to choose another engine', (tester) async {+ final swarm = NewProjectSwarm();+ final host = await pump(tester, [swarm]);+ await tap(tester, 'swarm-new-project');+ await pickMachine(tester, 'mac-1');+ await tap(tester, 'swarm-new-project-agent');+ await tap(tester, 'swarm-new-project-pick-agent-codex');+ swarm.machines = [+ leadPool('mac-1', name: 'Studio.local', engines: ['claude']),+ ];+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();+ expect(+ tester.widget<Text>(key('swarm-new-project-note')).data,+ 'Studio can’t run Codex: Codex isn’t offered here. '+ 'Choose another engine.',+ );+ expect(+ tester.widget<SwarmButton>(key('swarm-new-project-create')).onPressed,+ isNull,+ );+ await tap(tester, 'swarm-new-project-agent');+ await tap(tester, 'swarm-new-project-pick-agent-claude');+ expect(key('swarm-new-project-note'), findsNothing);+ });++ testWidgets('a model list that turns Claude\'s default off says the '+ 'engine runs its own model', (tester) async {+ final swarm = NewProjectSwarm()+ ..policy = {+ 'models': [+ {+ 'engine': 'claude',+ 'model': 'opus',+ 'effort': 'xhigh',+ 'enabled': false,+ },+ {+ 'engine': 'claude',+ 'model': 'sonnet',+ 'effort': 'high',+ 'enabled': true,+ },+ ],+ };+ await pump(tester, [swarm]);+ await tap(tester, 'swarm-new-project');+ expect(onAgent('Claude Code'), findsOneWidget);+ expect(onAgent('Default model'), findsOneWidget);+ });++ testWidgets('a model list with no Claude model offers Codex, Claude '+ 'saying why', (tester) async {+ final swarm = NewProjectSwarm()+ ..policy = {+ 'models': [+ {'engine': 'claude', 'model': 'opus', 'enabled': false},+ {'engine': 'codex', 'model': 'gpt-5', 'enabled': true},+ ],+ };+ await pump(tester, [swarm]);+ await tap(tester, 'swarm-new-project');+ expect(onAgent('Codex'), findsOneWidget);+ await tap(tester, 'swarm-new-project-agent');+ expect(+ find.descendant(+ of: key('swarm-new-project-pick-agent-claude'),+ matching: find.text(+ 'The Swarm’s model list has no enabled Claude model',+ ),+ ),+ findsOneWidget,+ );+ });++ testWidgets('signing out while +\'s sheet is over it closes both', (+ tester,+ ) async {+ final account = ValueNotifier<String?>(me);+ await pump(tester, [NewProjectSwarm()], account: account);+ await tap(tester, 'swarm-new-project');+ await tap(tester, 'swarm-new-project-attach');+ expect(key('swarm-attach-files'), findsOneWidget);+ account.value = null;+ await tester.pumpAndSettle();+ expect(key('swarm-attach-files'), findsNothing);+ expect(key('swarm-new-project-sheet'), findsNothing);+ expect(find.byType(BottomSheet), findsNothing);+ expect(tester.takeException(), isNull);+ });++ testWidgets('+ attaches files under the brief; they go up to the new '+ 'project\'s chat and with its brief', (tester) async {+ final uploads = FakeUploads();+ final swarm = NewProjectSwarm();+ picks(['spec.pdf']);+ await pump(tester, [swarm], upload: uploads.upload);+ await tap(tester, 'swarm-new-project');+ await attachFiles(tester);+ expect(key('swarm-outgoing-spec.pdf'), findsOneWidget);+ await pickMachine(tester, 'mac-1');+ await tap(tester, 'swarm-new-project-create');++ final made = swarm.commands('project.create').single['operationId'];+ expect(uploads.names, ['spec.pdf']);+ expect(uploads.asked.single.conversationId, 'project-p-$made');+ final send = swarm.commands('message.send').single['command'] as Map;+ expect(send['text'], '');+ expect(send['attachmentIds'], ['id-spec.pdf']);+ expectHomeCProject('openharness');+ });++ testWidgets('a pick past ten files says what was left out', (+ tester,+ ) async {+ picks([for (var i = 1; i <= 11; i++) 'f$i.log']);+ await pump(tester, [NewProjectSwarm()], upload: FakeUploads().upload);+ await tap(tester, 'swarm-new-project');+ await attachFiles(tester);+ expect(+ tester.widget<Text>(key('swarm-new-project-attach-note')).data,+ 'Attach at most 10 files.',+ );+ expect(+ tester+ .widget<SwarmAttachButton>(key('swarm-new-project-attach'))+ .onTap,+ isNull,+ reason: 'no room left',+ );+ });++ testWidgets('closed after its brief\'s answer was lost, it opens on the '+ 'request as sent: its files and Agent fixed; Create again uploads '+ 'nothing twice and makes one project', (tester) async {+ final uploads = FakeUploads();+ final swarm = NewProjectSwarm();+ var lose = true;+ swarm.answer = (command) {+ if (command['type'] == 'message.send' && lose) {+ lose = false;+ throw const SuperTabFailure('NETWORK', 'The Swarm didn’t answer.');+ }+ return null;+ };+ picks(['build.log']);+ await pump(tester, [swarm], upload: uploads.upload);+ await tap(tester, 'swarm-new-project');+ await attachFiles(tester);+ await tap(tester, 'swarm-new-project-agent');+ await tap(tester, 'swarm-new-project-pick-agent-codex');+ await pickMachine(tester, 'mac-1');+ await tap(tester, 'swarm-new-project-create');+ expect(key('swarm-new-project-error'), findsOneWidget);+ await tap(tester, 'swarm-new-project-close');+ expect(key('swarm-new-project-sheet'), findsNothing);++ await tap(tester, 'swarm-new-project');+ expect(key('swarm-outgoing-build.log'), findsOneWidget);+ expect(onAgent('Codex'), findsOneWidget);+ expect(+ tester+ .widget<SwarmAttachButton>(key('swarm-new-project-attach'))+ .onTap,+ isNull,+ reason: 'its files are fixed, as its brief is',+ );+ await tester.tap(+ key('swarm-outgoing-remove-build.log'),+ warnIfMissed: false,+ );+ await tester.pumpAndSettle();+ expect(key('swarm-outgoing-build.log'), findsOneWidget);+ await tap(tester, 'swarm-new-project-create');++ expect(uploads.names, ['build.log']);+ final sends = swarm.commands('message.send');+ expect(sends, hasLength(2));+ expect(sends[0]['operationId'], sends[1]['operationId']);+ expect(swarm.commands('project.create'), hasLength(1));+ expect(+ (swarm.commands('lead.start').single['command'] as Map)['engine'],+ 'codex',+ );+ expectHomeCProject('openharness');+ });++ testWidgets('Start over opens its files again, and the next Create '+ 'sends them to the new project', (tester) async {+ final uploads = FakeUploads();+ final swarm = NewProjectSwarm();+ swarm.answer = (command) => command['type'] == 'lead.start'+ ? throw const SuperTabFailure(+ 'HOST_OUTDATED',+ 'Update Harness on Studio to run a Product Manager there.',+ statusCode: 409,+ )+ : null;+ picks(['build.log']);+ await pump(tester, [swarm], upload: uploads.upload);+ await tap(tester, 'swarm-new-project');+ await attachFiles(tester);+ await pickMachine(tester, 'mac-1');+ await tap(tester, 'swarm-new-project-create');+ await tap(tester, 'swarm-new-project-start-over');+ expect(+ tester+ .widget<SwarmAttachButton>(key('swarm-new-project-attach'))+ .onTap,+ isNotNull,+ );+ expect(key('swarm-outgoing-build.log'), findsOneWidget);++ swarm.answer = null;+ await pickMachine(tester, 'mac-1');+ await tap(tester, 'swarm-new-project-create');+ final creates = swarm.commands('project.create');+ expect(creates, hasLength(2));+ expect(uploads.names, ['build.log', 'build.log']);+ expect(+ [for (final u in uploads.asked) u.conversationId],+ [+ 'project-p-${creates[0]['operationId']}',+ 'project-p-${creates[1]['operationId']}',+ ],+ );+ });++ testWidgets('on a 320 by 568 phone with the keyboard up and files '+ 'attached, the brief typed in, its files and Create stay in sight', (+ tester,+ ) async {+ picks(['spec.pdf', 'build.log']);+ await pump(tester, [NewProjectSwarm()], upload: FakeUploads().upload);+ tester.view.physicalSize = const Size(960, 1704);+ tester.view.padding = const FakeViewPadding(top: 60);+ await tester.pumpAndSettle();+ await tap(tester, 'swarm-new-project');+ await attachFiles(tester);+ await pickMachine(tester, 'mac-1');+ await tap(tester, 'swarm-new-project-brief');+ tester.view.viewInsets = const FakeViewPadding(bottom: 260 * 3);+ await tester.pumpAndSettle();+ await tester.enterText(+ key('swarm-new-project-brief'),+ List.filled(6, 'Ship the phone flow.').join('\n'),+ );+ await tester.pumpAndSettle();+ expect(tester.takeException(), isNull);++ final scroll = find.descendant(+ of: key('swarm-new-project-sheet'),+ matching: find.byType(SingleChildScrollView),+ );+ final create = tester.getRect(key('swarm-new-project-create'));+ expect(create.bottom, lessThanOrEqualTo(568 - 260));+ final view = tester.getRect(scroll);+ expect(view.top, greaterThanOrEqualTo(20), reason: 'under the bar');+ expect(view.bottom, lessThanOrEqualTo(create.top));+ // The line typed in, in sight.+ final editable = tester+ .state<EditableTextState>(+ find.descendant(+ of: key('swarm-new-project-brief'),+ matching: find.byType(EditableText),+ ),+ )+ .renderEditable;+ final caret = MatrixUtils.transformRect(+ editable.getTransformTo(null),+ editable.getLocalRectForCaret(+ TextPosition(offset: editable.text!.toPlainText().length),+ ),+ );+ expect(caret.top, greaterThanOrEqualTo(view.top));+ expect(caret.bottom, lessThanOrEqualTo(view.bottom));+ // Its files scroll with the form, a scroll away, and Create stays.+ for (final name in ['spec.pdf', 'build.log']) {+ expect(+ find.descendant(of: scroll, matching: key('swarm-outgoing-$name')),+ findsOneWidget,+ );+ }+ await tester.ensureVisible(key('swarm-new-project-attach'));+ await tester.pumpAndSettle();+ final attach = tester.getRect(key('swarm-new-project-attach'));+ expect(attach.top, greaterThanOrEqualTo(view.top));+ expect(attach.bottom, lessThanOrEqualTo(view.bottom));+ expect(tester.getRect(key('swarm-new-project-create')), create);+ });+ });});}diff --git a/mobile/test/swarm/swarm_project_settings_test.dart b/mobile/test/swarm/swarm_project_settings_test.dartnew file mode 100644index 000000000..77624fba7--- /dev/null+++ b/mobile/test/swarm/swarm_project_settings_test.dart@@ -0,0 +1,1119 @@+import 'dart:async';++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/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/widgets/touch_target.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/parts.dart';+import 'package:harness_mobile/swarm/swarm_home_list.dart';+import 'package:harness_mobile/swarm/swarm_home_rows.dart';+import 'package:harness_mobile/swarm/swarm_project_page.dart';+import 'package:harness_mobile/swarm/swarm_project_settings.dart';+import 'package:harness_mobile/swarm/swarm_project_tabs.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.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 '../support/real_fonts.dart';+import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Project settings…, Sharing and the lock of a private project on the+/// phone, as the desktop's project menu has them (task 37): Rename project+/// and Sharing for the project's owner who may write, Project details for+/// everyone who reads it, and never Delete Project.+void main() {+ late FakeSwarm swarm;+ late SwarmHost host;+ late ValueNotifier<String?> account;+ late String name, owner, visibility, role, brief;+ late List<({String id, String generation})> members;+ late String? leadId, coordinatorName;+ late Map<String, dynamic>? repository;+ var version = 1;++ /// What the next command answers instead of the server, once.+ FutureOr<Object?> Function()? answer;++ Map<String, dynamic> projectData() => {+ 'id': project,+ 'name': name,+ 'ownerId': owner,+ 'leadConversationId': leadChat,+ 'visibility': visibility,+ 'members': [+ for (final m in members) {'id': m.id, 'generation': m.generation},+ ],+ 'updateMinutes': 5,+ 'coordinatorName': ?coordinatorName,+ 'repository': ?repository,+ };++ Map<String, dynamic> leadChatData() => {+ ...groupData(+ leadChat,+ title: 'Mobile',+ agentIds: ['agent-lead'],+ leadId: leadId,+ ),+ 'brief': brief,+ };++ List<Map<String, dynamic>> people(int at) => [+ part(me, at, person(me, role: role)),+ part('diego', at, person('diego', role: 'collaborator')),+ // Shown by the name they set for the Swarm.+ part('ken', at, {+ ...person('ken', role: 'collaborator'),+ 'name': 'Ken Tran',+ }),+ ];++ /// Moves the Swarm on: the next change read carries the project and its+ /// people as they are now.+ Map<String, dynamic> changed() {+ version++;+ return {+ ...changes(cursor: 'c$version', lastChangedAt: 100 + version),+ 'head': part('head', version, headData(projects: [projectData()])),+ 'members': people(version),+ 'groups': [part(leadChat, version, leadChatData())],+ };+ }++ Future<void> pump(+ WidgetTester tester, {+ String ownerId = me,+ String myRole = 'owner',+ String projectVisibility = 'public',+ List<({String id, String generation})> projectMembers = const [],+ String description = '',+ String? lead = 'agent-lead',+ String? coordinator,+ Map<String, dynamic>? repo,+ }) async {+ name = 'Mobile';+ owner = ownerId;+ role = myRole;+ visibility = projectVisibility;+ members = [...projectMembers];+ brief = description;+ leadId = lead;+ coordinatorName = coordinator;+ repository = repo;+ version = 1;+ answer = null;+ swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(head: headData(projects: [projectData()])),+ 'groups': [part(leadChat, 1, leadChatData())],+ 'members': people(1),+ };+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changed();+ swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ swarm.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] = (+ _,+ ) => {'messages': <Object>[], 'next': null};+ swarm.routes['/api/super-tabs/$tab/commands'] = (body) {+ final command = body!['command'] as Map<String, dynamic>;+ if (answer case final once?) {+ answer = null;+ return once();+ }+ switch (command['type']) {+ case 'project.rename':+ name = command['name'] as String;+ case 'project.sharing':+ visibility = command['visibility'] as String;+ members = [+ for (final id in command['memberIds'] as List)+ (id: id as String, generation: 'gen-$id'),+ ];+ }+ return {'ok': true};+ };+ account = ValueNotifier<String?>(me);+ host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: swarm.request,+ upload: refuseSwarmUpload,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: const SwarmProjectPage(+ swarmId: tab,+ projectId: project,+ tabs: SwarmProjectTab.homeC,+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ SwarmReader reader() => host.session!.inbox.reader(tab)!;+ Finder key(String value) => find.byKey(ValueKey(value));+ final sharingRow = key('swarm-project-menu-sharing');+ final settingsRow = key('swarm-project-menu-settings');++ List<Map<String, dynamic>> sent(String type) => [+ for (final c in swarm.commands)+ if (c['type'] == type) c,+ ];++ /// Lets a write and the read after it land.+ Future<void> settle(WidgetTester tester) async {+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ await tester.pumpAndSettle();+ }++ /// The Swarm read again, with what the test changed.+ Future<void> moveOn(WidgetTester tester) async {+ await reader().refresh();+ await tester.pumpAndSettle();+ }++ Future<void> openMenu(WidgetTester tester) async {+ await tester.tap(key('swarm-project-menu'));+ await tester.pumpAndSettle();+ }++ Future<void> openSettings(WidgetTester tester) async {+ await openMenu(tester);+ await tester.tap(settingsRow);+ await tester.pumpAndSettle();+ }++ Future<void> openRename(WidgetTester tester) async {+ await openSettings(tester);+ await tester.tap(find.text('Rename project'));+ await tester.pumpAndSettle();+ expect(key('swarm-project-name'), findsOneWidget);+ }++ Future<void> openDetails(WidgetTester tester) async {+ await openSettings(tester);+ await tester.tap(find.text('Project details'));+ await tester.pumpAndSettle();+ }++ Future<void> openSharing(WidgetTester tester) async {+ await openMenu(tester);+ await tester.tap(sharingRow);+ await tester.pumpAndSettle();+ expect(key('swarm-sharing-close'), findsOneWidget);+ }++ bool? ticked(WidgetTester tester, String id) =>+ tester.widget<Checkbox>(key('swarm-sharing-person-$id-check')).value;++ bool tickable(WidgetTester tester, String id) =>+ tester+ .widget<Checkbox>(key('swarm-sharing-person-$id-check'))+ .onChanged !=+ null;++ /// The phones the menu must fit: a common one and the narrowest, 320+ /// points (iPhone SE, 1st generation), each with its status bar.+ const phones = [+ ('a phone', Size(390, 844), 47.0),+ ('a 320-point phone', Size(320, 568), 20.0),+ ];++ /// Opens the menu of its owner who may write on a phone of [size], with+ /// [top] for its status bar: all eight rows, the most it ever has, each a+ /// finger tall, inside the panel and the panel on the screen, with nothing+ /// to scroll; with [across], each label whole inside the panel too.+ Future<void> menuFits(+ WidgetTester tester,+ Size size,+ double top, {+ required bool across,+ }) async {+ addTearDown(tester.view.reset);+ tester.view+ ..physicalSize = size * 3+ ..devicePixelRatio = 3+ ..padding = FakeViewPadding(top: top * 3);+ await pump(tester);+ await openMenu(tester);+ expect(tester.takeException(), isNull);++ final rows = [+ for (final row in [+ 'terminal',+ 'status',+ 'leaderboard',+ 'work',+ 'team',+ 'sharing',+ 'notifications',+ 'settings',+ ])+ key('swarm-project-menu-$row'),+ ];+ for (final row in rows) {+ expect(row, findsOneWidget);+ }+ // The menu's panel: the nearest Material over a row.+ final panelFinder = find+ .ancestor(of: settingsRow, matching: find.byType(Material))+ .first;+ final panel = tester.getRect(panelFinder);+ expect(panel.top, greaterThanOrEqualTo(top));+ expect(panel.bottom, lessThanOrEqualTo(size.height));+ if (across) {+ expect(panel.left, greaterThanOrEqualTo(0));+ expect(panel.right, lessThanOrEqualTo(size.width));+ }+ for (final row in rows) {+ final rect = tester.getRect(row);+ expect(rect.top, greaterThanOrEqualTo(panel.top));+ expect(rect.bottom, lessThanOrEqualTo(panel.bottom));+ expect(rect.height, greaterThanOrEqualTo(minTouchTarget));+ if (!across) continue;+ // Each label whole, never cut at the panel's edge.+ for (final text+ in find.descendant(of: row, matching: find.byType(Text)).evaluate()) {+ final box = text.renderObject! as RenderBox;+ final rect = box.localToGlobal(Offset.zero) & box.size;+ expect(rect.left, greaterThanOrEqualTo(panel.left));+ expect(rect.right, lessThanOrEqualTo(panel.right));+ }+ }+ final list = tester.state<ScrollableState>(+ find.descendant(of: panelFinder, matching: find.byType(Scrollable)).first,+ );+ expect(list.position.maxScrollExtent, 0, reason: 'nothing to scroll');+ }++ group('the menu', () {+ testWidgets('its owner who may write gets Sharing above Notifications '+ 'and Project settings… last; never Delete Project', (tester) async {+ await pump(tester);+ await openMenu(tester);++ expect(+ find.descendant(of: sharingRow, matching: find.text('Sharing')),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: settingsRow,+ matching: find.text('Project settings…'),+ ),+ findsOneWidget,+ );+ final notifications = key('swarm-project-menu-notifications');+ final team = tester.getTopLeft(key('swarm-project-menu-team')).dy;+ final sharing = tester.getTopLeft(sharingRow).dy;+ expect(team, lessThan(sharing));+ expect(sharing, lessThan(tester.getTopLeft(notifications).dy));+ expect(+ tester.getTopLeft(notifications).dy,+ lessThan(tester.getTopLeft(settingsRow).dy),+ );+ expect(find.textContaining('Delete'), findsNothing);+ });++ // Tall enough for all eight, whatever the face: across is measured in+ // the phone's faces, in the last group.+ for (final (phone, size, top) in phones) {+ testWidgets('on $phone all eight rows fit the menu and the screen, '+ 'Project settings… included, with no scrolling', (tester) async {+ await menuFits(tester, size, top, across: false);+ });+ }++ testWidgets('a collaborator who is not its owner gets Project settings… '+ 'but no Sharing', (tester) async {+ await pump(tester, ownerId: 'diego', myRole: 'collaborator');+ await openMenu(tester);+ expect(sharingRow, findsNothing);+ expect(settingsRow, findsOneWidget);+ });++ testWidgets('its owner as a viewer now gets no Sharing', (tester) async {+ await pump(tester, myRole: 'viewer');+ await openMenu(tester);+ expect(sharingRow, findsNothing);+ expect(settingsRow, findsOneWidget);+ });++ testWidgets('Sharing goes from the menu once the project is another\'s', (+ tester,+ ) async {+ await pump(tester);+ await openMenu(tester);+ expect(sharingRow, findsOneWidget);+ await tester.tap(key('swarm-project-menu'));+ await tester.pumpAndSettle();++ owner = 'diego';+ await moveOn(tester);+ await openMenu(tester);+ expect(sharingRow, findsNothing);+ });+ });++ group('Project settings…', () {+ testWidgets('its owner gets Rename project and Project details', (+ tester,+ ) async {+ await pump(tester);+ await openSettings(tester);+ expect(find.text('Project settings'), findsOneWidget);+ expect(find.text('Rename project'), findsOneWidget);+ expect(find.text('Project details'), findsOneWidget);+ expect(find.textContaining('Delete'), findsNothing);+ });++ testWidgets('someone else gets Project details alone', (tester) async {+ await pump(tester, ownerId: 'diego', myRole: 'collaborator');+ await openSettings(tester);+ expect(find.text('Rename project'), findsNothing);+ expect(find.text('Project details'), findsOneWidget);+ });++ testWidgets('a viewer gets Project details alone', (tester) async {+ await pump(tester, myRole: 'viewer');+ await openSettings(tester);+ expect(find.text('Rename project'), findsNothing);+ expect(find.text('Project details'), findsOneWidget);+ });++ testWidgets('the project taken off the Swarm with it open: it closes', (+ tester,+ ) async {+ await pump(tester);+ await openSettings(tester);+ expect(find.text('Project settings'), findsOneWidget);++ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {+ ...changes(cursor: 'c9', lastChangedAt: 300),+ 'head': part('head', 9, headData(projects: const [])),+ };+ await moveOn(tester);+ expect(find.text('Project settings'), findsNothing);+ expect(find.text('Rename project'), findsNothing);+ });++ testWidgets('access lost with it open: it closes', (tester) async {+ await pump(tester);+ await openSettings(tester);+ reader().revoke();+ await tester.pumpAndSettle();+ expect(find.text('Project settings'), findsNothing);+ expect(find.text('Rename project'), findsNothing);+ });++ testWidgets('the account signing out with it open: it closes', (+ tester,+ ) async {+ await pump(tester);+ await openSettings(tester);+ account.value = null;+ await tester.pumpAndSettle();+ expect(find.text('Project settings'), findsNothing);+ expect(find.text('Rename project'), findsNothing);+ });++ testWidgets('Project details opens from it once it has closed', (+ tester,+ ) async {+ await pump(tester);+ await openDetails(tester);+ expect(find.text('Project settings'), findsNothing);+ expect(key('swarm-project-info-close'), findsOneWidget);+ await tester.tap(key('swarm-project-info-close'));+ await tester.pumpAndSettle();+ expect(find.byType(BottomSheet), findsNothing);++ // And again: nothing of the first stays in the way.+ await openDetails(tester);+ expect(key('swarm-project-info-close'), findsOneWidget);+ });+ });++ group('Rename project', () {+ testWidgets('a new name, trimmed, is the server\'s at once, in the '+ 'header', (tester) async {+ await pump(tester);+ await openRename(tester);+ expect(find.text('Rename project'), findsOneWidget);+ expect(+ tester.widget<TextField>(key('swarm-project-name')).controller!.text,+ 'Mobile',+ );+ await tester.enterText(key('swarm-project-name'), ' Phone app ');+ await tester.pump();+ await tester.tap(key('swarm-project-name-save'));+ await settle(tester);++ expect(sent('project.rename'), [+ {'type': 'project.rename', 'projectId': project, 'name': 'Phone app'},+ ]);+ expect(key('swarm-project-name'), findsNothing);+ expect(reader().snapshot!.projectById(project)!.name, 'Phone app');+ expect(find.text('#Phone app'), findsOneWidget);+ });++ testWidgets('an empty name cannot be saved', (tester) async {+ await pump(tester);+ await openRename(tester);+ await tester.enterText(key('swarm-project-name'), ' ');+ await tester.pump();+ await tester.tap(key('swarm-project-name-save'));+ await settle(tester);+ expect(sent('project.rename'), isEmpty);+ expect(key('swarm-project-name'), findsOneWidget);+ });++ testWidgets('a name at the 160-character limit saves; one longer is cut '+ 'to fit', (tester) async {+ await pump(tester);+ await openRename(tester);+ final longest = 'a' * 160;+ await tester.enterText(key('swarm-project-name'), '${longest}b');+ await tester.pump();+ await tester.tap(key('swarm-project-name-save'));+ await settle(tester);+ expect(sent('project.rename').single['name'], longest);+ });++ testWidgets('a refused name says why under the field and stays open', (+ tester,+ ) async {+ await pump(tester);+ await openRename(tester);+ answer = () => throw const SuperTabFailure(+ 'PROJECT_OWNER_REQUIRED',+ 'Only the project owner can manage this project.',+ statusCode: 403,+ );+ await tester.enterText(key('swarm-project-name'), 'Another');+ await tester.pump();+ await tester.tap(key('swarm-project-name-save'));+ await settle(tester);++ expect(+ tester.widget<Text>(key('swarm-project-name-error')).data,+ 'Only the project owner can manage this project.',+ );+ expect(key('swarm-project-name'), findsOneWidget);+ expect(reader().snapshot!.projectById(project)!.name, 'Mobile');+ });++ testWidgets('offline: a call lost on the way says so, never stays '+ 'Saving', (tester) async {+ await pump(tester);+ await openRename(tester);+ answer = () => throw TimeoutException('no answer');+ await tester.enterText(key('swarm-project-name'), 'Another');+ await tester.pump();+ await tester.tap(key('swarm-project-name-save'));+ await settle(tester);+ expect(find.text('Could not reach this Swarm. Try again.'), findsOne);+ expect(find.text('Saving…'), findsNothing);+ expect(key('swarm-project-name'), findsOneWidget);+ });++ testWidgets('the project made someone else\'s while it is open: it '+ 'goes, and nothing is sent', (tester) async {+ await pump(tester);+ await openRename(tester);+ owner = 'diego';+ await moveOn(tester);+ expect(key('swarm-project-name'), findsNothing);+ expect(sent('project.rename'), isEmpty);+ });++ testWidgets('access lost while it is open: it goes, and nothing of the '+ 'project stays', (tester) async {+ await pump(tester);+ await openRename(tester);+ reader().revoke();+ await tester.pumpAndSettle();+ expect(key('swarm-project-name'), findsNothing);+ expect(find.textContaining('Mobile'), findsNothing);+ });++ testWidgets('the account signing out while it is open: it goes, and '+ 'nothing of the project stays', (tester) async {+ await pump(tester);+ await openRename(tester);+ account.value = null;+ await tester.pumpAndSettle();+ expect(key('swarm-project-name'), findsNothing);+ expect(find.textContaining('Mobile'), findsNothing);+ expect(sent('project.rename'), isEmpty);+ });++ for (final (phone, size, keyboard) in [+ ('a phone', const Size(390, 844), 336.0),+ ('a short phone', const Size(320, 568), 260.0),+ ]) {+ testWidgets('on $phone the keyboard up keeps the field and Save in '+ 'sight above it', (tester) async {+ addTearDown(tester.view.reset);+ tester.view+ ..physicalSize = size * 3+ ..devicePixelRatio = 3;+ await pump(tester);+ await openRename(tester);+ final before = tester.getRect(key('swarm-project-name-save'));++ tester.view.viewInsets = FakeViewPadding(bottom: keyboard * 3);+ await tester.pumpAndSettle();++ expect(tester.takeException(), isNull);+ final top = size.height - keyboard;+ final field = tester.getRect(key('swarm-project-name'));+ final save = tester.getRect(key('swarm-project-name-save'));+ expect(field.top, greaterThanOrEqualTo(0));+ expect(field.bottom, lessThanOrEqualTo(top));+ expect(save.bottom, lessThanOrEqualTo(top));+ expect(save.bottom, lessThan(before.bottom), reason: 'it moved up');+ await tester.tap(key('swarm-project-name-save'));+ await settle(tester);+ expect(sent('project.rename').single['name'], 'Mobile');+ });+ }+ });++ group('Project details', () {+ testWidgets('its name over its description, its repository and its '+ 'Product Manager', (tester) async {+ await pump(+ tester,+ description: 'The phone app for Harness.',+ repo: {+ 'repositoryUrl': 'https://github.com/acme/mobile',+ 'cwd': '/Users/me/mobile',+ },+ );+ await openDetails(tester);++ expect(key('swarm-project-info-close'), findsOneWidget);+ expect(+ find.descendant(+ of: find.byType(BottomSheet),+ matching: find.text('Mobile'),+ ),+ findsOneWidget,+ );+ expect(find.text('The phone app for Harness.'), findsOneWidget);+ final repository = key('swarm-project-info-repository');+ expect(+ find.descendant(of: repository, matching: find.text('Repository')),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: repository,+ matching: find.text('https://github.com/acme/mobile'),+ ),+ findsOneWidget,+ );+ final pm = key('swarm-project-info-coordinator');+ expect(+ find.descendant(of: pm, matching: find.text('Product Manager')),+ findsOneWidget,+ );+ expect(+ find.descendant(of: pm, matching: find.text('River')),+ findsOneWidget,+ );+ });++ testWidgets('nothing set yet: No description yet, Not set, and the PM '+ 'Starting…', (tester) async {+ await pump(tester, lead: null);+ await openDetails(tester);+ expect(find.text('No description yet'), findsOneWidget);+ expect(+ find.descendant(+ of: key('swarm-project-info-repository'),+ matching: find.text('Not set'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: key('swarm-project-info-coordinator'),+ matching: find.text('Starting…'),+ ),+ findsOneWidget,+ );+ });++ testWidgets('a repository with no link names its folder; the '+ 'coordinator goes by the project\'s own name for it', (tester) async {+ await pump(+ tester,+ coordinator: 'Tech Lead',+ repo: {'repositoryUrl': 7, 'cwd': '/Users/me/mobile'},+ );+ await openDetails(tester);+ expect(find.text('/Users/me/mobile'), findsOneWidget);+ expect(find.text('Tech Lead'), findsOneWidget);+ expect(tester.takeException(), isNull);+ });++ testWidgets('a viewer reads them too, and a rename elsewhere shows at '+ 'once', (tester) async {+ await pump(tester, myRole: 'viewer');+ await openDetails(tester);+ expect(key('swarm-project-info-close'), findsOneWidget);+ name = 'Phone app';+ await moveOn(tester);+ expect(+ find.descendant(+ of: find.byType(BottomSheet),+ matching: find.text('Phone app'),+ ),+ findsOneWidget,+ );+ });++ testWidgets('the project taken off the Swarm with them open: they '+ 'close', (tester) async {+ await pump(tester);+ await openDetails(tester);+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {+ ...changes(cursor: 'c9', lastChangedAt: 300),+ 'head': part('head', 9, headData(projects: const [])),+ };+ await moveOn(tester);+ expect(key('swarm-project-info-close'), findsNothing);+ expect(find.byType(BottomSheet), findsNothing);+ });+ });++ group('Sharing', () {+ testWidgets('a public project: Public ticked and no one to pick; '+ 'Private lists the Swarm, its owner always in, and Save makes it '+ 'private to who is ticked', (tester) async {+ await pump(tester);+ await openSharing(tester);++ expect(find.text('Sharing'), findsOneWidget);+ expect(find.text('Everyone in this Swarm'), findsOneWidget);+ expect(+ find.text('Only people you invite to this project'),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: key('swarm-sharing-public'),+ matching: find.byIcon(LucideIcons.check300),+ ),+ findsOneWidget,+ );+ expect(+ tester.widget<Text>(key('swarm-sharing-line')).data,+ 'Everyone in this Swarm can open this project.',+ );+ expect(key('swarm-sharing-person-diego'), findsNothing);++ await tester.tap(key('swarm-sharing-private'));+ await tester.pumpAndSettle();+ expect(+ tester.widget<Text>(key('swarm-sharing-line')).data,+ 'Only the people below can open this project.',+ );+ expect(+ find.descendant(+ of: key('swarm-sharing-person-$me'),+ matching: find.text('[email protected] · Project owner'),+ ),+ findsOneWidget,+ );+ expect(ticked(tester, me), isTrue);+ expect(tickable(tester, me), isFalse, reason: 'its owner stays in');+ expect(ticked(tester, 'diego'), isFalse);+ expect(ticked(tester, 'ken'), isFalse);+ // Each by the name the Swarm shows them by, over their email: their+ // username until they set a name.+ for (final (id, shown) in [('diego', 'diego'), ('ken', 'Ken Tran')]) {+ final row = key('swarm-sharing-person-$id');+ expect(+ find.descendant(of: row, matching: find.text(shown)),+ findsOneWidget,+ reason: id,+ );+ expect(+ find.descendant(of: row, matching: find.text('[email protected]')),+ findsOneWidget,+ reason: id,+ );+ expect(+ tester.getTopLeft(find.text(shown)).dy,+ lessThan(tester.getTopLeft(find.text('[email protected]')).dy),+ reason: '$id: the name over the email',+ );+ }++ await tester.tap(key('swarm-sharing-person-diego'));+ await tester.pumpAndSettle();+ expect(ticked(tester, 'diego'), isTrue);+ await tester.tap(key('swarm-sharing-save'));+ await settle(tester);++ expect(sent('project.sharing'), [+ {+ 'type': 'project.sharing',+ 'projectId': project,+ 'visibility': 'private',+ 'memberIds': ['diego'],+ },+ ]);+ expect(key('swarm-sharing-close'), findsNothing);+ final shared = reader().snapshot!.projectById(project)!;+ expect(shared.isPrivate, isTrue);+ expect(shared.memberIds, ['diego']);+ });++ testWidgets('a private project opens as it is: who is a member ticked, '+ 'never someone who left the Swarm nor one who came back', (+ tester,+ ) async {+ await pump(+ tester,+ projectVisibility: 'private',+ projectMembers: [+ (id: 'diego', generation: 'gen-diego'),+ // Left the Swarm and joined again: not a member until ticked.+ (id: 'ken', generation: 'gen-old'),+ // No longer in the Swarm.+ (id: 'gone', generation: 'gen-gone'),+ ],+ );+ await openSharing(tester);++ expect(+ find.descendant(+ of: key('swarm-sharing-private'),+ matching: find.byIcon(LucideIcons.check300),+ ),+ findsOneWidget,+ );+ expect(ticked(tester, 'diego'), isTrue);+ expect(ticked(tester, 'ken'), isFalse);+ expect(key('swarm-sharing-person-gone'), findsNothing);++ // The checkbox itself ticks too; the list scrolls to the last one.+ await tester.tap(key('swarm-sharing-person-diego-check'));+ await tester.ensureVisible(key('swarm-sharing-person-ken-check'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-sharing-person-ken-check'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-sharing-save'));+ await settle(tester);++ expect(sent('project.sharing').single['memberIds'], ['ken']);+ });++ testWidgets('back to Public keeps its members for later', (tester) async {+ await pump(+ tester,+ projectVisibility: 'private',+ projectMembers: [(id: 'diego', generation: 'gen-diego')],+ );+ await openSharing(tester);+ await tester.tap(key('swarm-sharing-public'));+ await tester.pumpAndSettle();+ expect(key('swarm-sharing-person-diego'), findsNothing);+ await tester.tap(key('swarm-sharing-save'));+ await settle(tester);++ expect(sent('project.sharing'), [+ {+ 'type': 'project.sharing',+ 'projectId': project,+ 'visibility': 'public',+ 'memberIds': ['diego'],+ },+ ]);+ expect(reader().snapshot!.projectById(project)!.isPrivate, isFalse);+ });++ testWidgets('✕ changes nothing', (tester) async {+ await pump(tester);+ await openSharing(tester);+ await tester.tap(key('swarm-sharing-private'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-sharing-close'));+ await settle(tester);+ expect(key('swarm-sharing-close'), findsNothing);+ expect(sent('project.sharing'), isEmpty);+ expect(reader().snapshot!.projectById(project)!.isPrivate, isFalse);+ });++ testWidgets('a refusal says why over Save and stays open to try again', (+ tester,+ ) async {+ await pump(tester);+ await openSharing(tester);+ answer = () => throw const SuperTabFailure(+ 'PROJECT_OWNER_REQUIRED',+ 'Only the project owner can manage this project.',+ statusCode: 403,+ );+ await tester.tap(key('swarm-sharing-private'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-sharing-save'));+ await settle(tester);++ expect(+ tester.widget<Text>(key('swarm-sharing-error')).data,+ 'Only the project owner can manage this project.',+ );+ expect(key('swarm-sharing-close'), findsOneWidget);+ expect(reader().snapshot!.projectById(project)!.isPrivate, isFalse);++ await tester.tap(key('swarm-sharing-save'));+ await settle(tester);+ expect(sent('project.sharing'), hasLength(2));+ expect(key('swarm-sharing-close'), findsNothing);+ expect(reader().snapshot!.projectById(project)!.isPrivate, isTrue);+ });++ testWidgets('offline: a call lost on the way says so, never stays '+ 'Saving', (tester) async {+ await pump(tester);+ await openSharing(tester);+ answer = () => throw TimeoutException('no answer');+ await tester.tap(key('swarm-sharing-save'));+ await settle(tester);+ expect(find.text('Could not reach this Swarm. Try again.'), findsOne);+ expect(find.text('Saving…'), findsNothing);+ });++ testWidgets('the project made someone else\'s while it is open: it '+ 'goes, and nothing is sent', (tester) async {+ await pump(tester);+ await openSharing(tester);+ owner = 'diego';+ await moveOn(tester);+ expect(key('swarm-sharing-close'), findsNothing);+ expect(find.byType(BottomSheet), findsNothing);+ expect(sent('project.sharing'), isEmpty);+ });++ testWidgets('the project taken off the Swarm with it open: it closes', (+ tester,+ ) async {+ await pump(tester);+ await openSharing(tester);+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {+ ...changes(cursor: 'c9', lastChangedAt: 300),+ 'head': part('head', 9, headData(projects: const [])),+ };+ await moveOn(tester);+ expect(key('swarm-sharing-close'), findsNothing);+ expect(find.byType(BottomSheet), findsNothing);+ });++ testWidgets('the account signing out with it open: it closes', (+ tester,+ ) async {+ await pump(tester);+ await openSharing(tester);+ account.value = null;+ await tester.pumpAndSettle();+ expect(key('swarm-sharing-close'), findsNothing);+ expect(find.byType(BottomSheet), findsNothing);+ });++ testWidgets('the server is never asked for someone no longer in the '+ 'Swarm', (tester) async {+ await pump(tester);+ final error = await swarmShareProject(+ reader(),+ project,+ private: true,+ memberIds: ['diego', 'gone'],+ );+ expect(error, isNull);+ expect(sent('project.sharing').single['memberIds'], ['diego']);+ });++ testWidgets('nothing is sent for someone who may not manage it', (+ tester,+ ) async {+ await pump(tester, ownerId: 'diego', myRole: 'collaborator');+ expect(swarmManagesProject(reader(), project), isFalse);+ expect(+ await swarmShareProject(+ reader(),+ project,+ private: true,+ memberIds: const [],+ ),+ 'Only the project owner can manage this project.',+ );+ expect(+ await swarmRenameProject(reader(), project, 'Another'),+ 'Only the project owner can manage this project.',+ );+ expect(swarm.commands, isEmpty);+ });+ });++ group('the lock of a private project on Home', () {+ Future<void> row(+ WidgetTester tester, {+ required String visibility,+ String name = 'Mobile',+ String? swarmName,+ SwarmProjectNews news = swarmNoProjectNews,+ double width = 390,+ }) {+ final snapshot = SuperTabSnapshot.fromJson(+ SuperTabParts.firstLoad(+ firstLoad(+ head: headData(+ projects: [+ {+ 'id': project,+ 'name': name,+ 'ownerId': me,+ 'leadConversationId': leadChat,+ 'visibility': visibility,+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ ),+ ),+ ).state,+ );+ return tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Align(+ alignment: Alignment.topLeft,+ child: SizedBox(+ width: width,+ child: SwarmHomeProjectRow(+ project: SwarmHomeProject(+ swarmId: tab,+ project: snapshot.projects.single,+ news: news,+ ),+ swarmName: swarmName,+ onTap: () {},+ ),+ ),+ ),+ ),+ ),+ );+ }++ final lock = key('swarm-project-private');+ final name = key('swarm-project-name');++ testWidgets('a private project has a lock in the # mark\'s place, before '+ 'its name, heard as Private project', (tester) async {+ final semantics = tester.ensureSemantics();+ await row(tester, visibility: 'private');+ expect(lock, findsOneWidget);+ expect(tester.getTopLeft(lock).dx, AppSpace.l);+ expect(tester.getTopRight(lock).dx, lessThan(tester.getTopLeft(name).dx));+ expect(find.textContaining('#'), findsNothing);+ expect(+ tester.getCenter(lock).dy,+ moreOrLessEquals(tester.getCenter(name).dy, epsilon: 1),+ reason: 'level with the name, on the one line',+ );+ expect(+ tester.getSize(find.byType(SwarmHomeProjectRow)).height,+ minTouchTarget,+ );+ // Heard with the row's name, as one button.+ expect(+ find.bySemanticsLabel(RegExp(r'Private project\nMobile')),+ findsOneWidget,+ );+ semantics.dispose();+ });++ testWidgets('a public one has none, and keeps its #', (tester) async {+ await row(tester, visibility: 'public');+ expect(lock, findsNothing);+ expect(find.textContaining('#Mobile'), findsOneWidget);+ });++ testWidgets('the row\'s right side holds only its notifications', (+ tester,+ ) async {+ await row(+ tester,+ visibility: 'private',+ news: (bold: true, tags: 2, hasWaitingTag: true),+ );+ final tags = find.byType(SwarmTags);+ expect(tags, findsOneWidget);+ expect(tester.getTopRight(lock).dx, lessThan(tester.getTopLeft(name).dx));+ expect(tester.getTopRight(tags).dx, 390 - AppSpace.l);+ });++ testWidgets('a long name and its Swarm ellipsize and keep the lock in '+ 'sight', (tester) async {+ await row(+ tester,+ visibility: 'private',+ name: 'A project with a name far too long for one row of a phone',+ swarmName: 'Phone Swarm',+ width: 240,+ );+ expect(tester.takeException(), isNull);+ final rect = tester.getRect(lock);+ expect(rect.left, AppSpace.l);+ expect(rect.right, lessThan(tester.getTopLeft(name).dx));+ expect(tester.getTopRight(name).dx, lessThanOrEqualTo(240));+ });+ });++ // Last: the faces it loads stay loaded for every test after it. The test+ // font draws each glyph a full em wide, about twice a phone's, so across+ // is measured here only.+ group("the menu in the phone's faces", () {+ setUpAll(loadRealFonts);++ for (final (phone, size, top) in phones) {+ testWidgets('on $phone all eight rows fit across, every label whole', (+ tester,+ ) async {+ await menuFits(tester, size, top, across: true);+ });+ }+ });+}