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
Batch 10-28 d: 13 reviewed PRs (#1984)
0xken1592f47d7ac725
diff --git a/backend/integration/bench/mongo.ts b/backend/integration/bench/mongo.tsindex 05e0d87d7..dfbc0b658 100644--- a/backend/integration/bench/mongo.ts+++ b/backend/integration/bench/mongo.ts@@ -9,6 +9,8 @@ import { POOL_DEFAULTS, withPoolDefaults } from '../../src/lib/databaseUrl.js'export interface LocalDatabase {db: PrismaClient+ /** Its loopback address, for a backend process the bench starts itself (resilience.ts). */+ uri: string/** The MongoDB server version the run measured. */version: stringstop(): Promise<void>@@ -27,5 +29,5 @@ export async function localDatabase(): Promise<LocalDatabase> {})// The backend's own pool options (src/lib/prisma.ts), so the run measures the pool production has.const db = new PrismaClient({ datasources: { db: { url: withPoolDefaults(uri, POOL_DEFAULTS) } } })- return { db, version, async stop() { await db.$disconnect(); await replica.stop() } }+ return { db, uri, version, async stop() { await db.$disconnect(); await replica.stop() } }}diff --git a/backend/integration/bench/resilience.ts b/backend/integration/bench/resilience.tsnew file mode 100644index 000000000..0b8b0907d--- /dev/null+++ b/backend/integration/bench/resilience.ts@@ -0,0 +1,243 @@+import { spawn, type ChildProcess } from 'node:child_process'+import { createWriteStream } from 'node:fs'+import { mkdir, writeFile } from 'node:fs/promises'+import { createServer as createHttpServer, type Server } from 'node:http'+import { createServer as createTcpServer, connect, type AddressInfo, type Server as TcpServer } from 'node:net'+import { execFileSync } from 'node:child_process'+import { join } from 'node:path'+import { localDatabase } from './mongo.js'++/**+ * Stability 3.2 and 3.5 KPI bench: what one bad client, a slow Redis and a slow SSO do to everyone else's latency.+ *+ * It runs the real backend (`src/server.ts`, a child process) against its own loopback MongoDB, its own `redis-server`+ * behind a proxy that can delay every packet, and a fake SSO that answers the identity route after a chosen delay. It+ * never reads DATABASE_URL, REDIS_URL or any real service. Good clients sign in, register one computer each, then list+ * their machines in a loop (auth, Mongo and Redis presence on every call); a tenth of their calls carry a token the+ * backend has not seen yet, the way refreshed sign-ins arrive. Every scenario runs the same clients for the same time:+ *+ * normal nothing injected+ * bad-client one more account loads its own Swarm in full (the first load a client makes), 128 calls in flight+ * and no pause+ * redis-slow every Redis packet waits 5 s+ * sso-slow the SSO answers after 5 s+ *+ * `npx tsx integration/bench/resilience.ts [--seconds 20] [--bad-in-flight 128] [--out DIR]` from `backend/`, with `redis-server` on PATH.+ */++const GOOD_CLIENTS = 8+const THINK_MS = 100+const FRESH_TOKEN_SHARE = 0.1+const INJECTED_DELAY_MS = 5_000+const CALL_TIMEOUT_MS = 30_000++interface Sample { ms: number; status: number }+interface ScenarioResult { name: string; calls: number; p50: number; p95: number; p99: number; max: number; statuses: Record<string, number>; badCalls?: number }++function freePort(): Promise<number> {+ return new Promise((resolve, reject) => {+ const server = createTcpServer().listen(0, '127.0.0.1', () => {+ const { port } = server.address() as AddressInfo+ server.close(() => resolve(port))+ }).on('error', reject)+ })+}++/** A TCP proxy that holds every chunk, both ways, for `delayMs` (read per chunk, so it can change mid-connection). */+function delayProxy(target: number): Promise<{ port: number; setDelay(ms: number): void; close(): void }> {+ let delayMs = 0+ const relay = (from: NodeJS.ReadableStream, to: NodeJS.WritableStream) =>+ from.on('data', (chunk: Buffer) => { if (delayMs) setTimeout(() => to.write(chunk), delayMs); else to.write(chunk) })+ const server: TcpServer = createTcpServer(client => {+ const upstream = connect(target, '127.0.0.1')+ relay(client, upstream); relay(upstream, client)+ const end = () => { client.destroy(); upstream.destroy() }+ client.on('error', end).on('close', end); upstream.on('error', end).on('close', end)+ })+ return new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve({+ port: (server.address() as AddressInfo).port,+ setDelay: ms => { delayMs = ms },+ close: () => server.close(),+ })))+}++/** Answers `Bearer <user>.<anything>` as that user, after `delayMs`: the identity and profile routes share one shape. */+function fakeSso(): Promise<{ port: number; setDelay(ms: number): void; close(): void }> {+ let delayMs = 0+ const server: Server = createHttpServer((req, res) => {+ const token = /^Bearer\s+(.+)$/.exec(req.headers.authorization ?? '')?.[1] ?? ''+ const user = token.split('.')[0]+ setTimeout(() => {+ if (!user.startsWith('bench-')) { res.writeHead(401).end(); return }+ res.writeHead(200, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ status: 1, data: { id: `ext-${user}`, email: `${user}@bench.example` } }))+ }, delayMs)+ })+ return new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve({+ port: (server.address() as AddressInfo).port,+ setDelay: ms => { delayMs = ms },+ close: () => { server.closeAllConnections(); server.close() },+ })))+}++async function startRedis(): Promise<{ port: number; process: ChildProcess }> {+ const port = await freePort()+ const child = spawn('redis-server', ['--port', String(port), '--bind', '127.0.0.1', '--save', '', '--appendonly', 'no'], { stdio: 'ignore' })+ for (let i = 0; i < 100; i++) {+ try { execFileSync('redis-cli', ['-p', String(port), 'ping'], { stdio: 'pipe' }); return { port, process: child } } catch { await sleep(50) }+ }+ child.kill()+ throw new Error('redis-server did not start')+}++const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))++async function call(base: string, token: string, method: 'GET' | 'POST', path: string, body?: unknown): Promise<Sample> {+ const started = performance.now()+ try {+ const response = await fetch(`${base}${path}`, {+ method,+ headers: { authorization: `Bearer ${token}`, ...(body ? { 'content-type': 'application/json' } : {}) },+ ...(body ? { body: JSON.stringify(body) } : {}),+ signal: AbortSignal.timeout(CALL_TIMEOUT_MS),+ })+ await response.arrayBuffer()+ return { ms: performance.now() - started, status: response.status }+ } catch {+ return { ms: performance.now() - started, status: 0 }+ }+}++function percentile(sorted: number[], p: number): number {+ if (!sorted.length) return 0+ return Math.round(sorted[Math.min(sorted.length - 1, Math.ceil(p * sorted.length) - 1)])+}++function summarize(name: string, samples: Sample[], badCalls?: number): ScenarioResult {+ const sorted = samples.map(s => s.ms).sort((a, b) => a - b)+ const statuses: Record<string, number> = {}+ for (const s of samples) statuses[s.status || 'timeout'] = (statuses[s.status || 'timeout'] ?? 0) + 1+ return { name, calls: samples.length, p50: percentile(sorted, 0.5), p95: percentile(sorted, 0.95), p99: percentile(sorted, 0.99),+ max: Math.round(sorted.at(-1) ?? 0), statuses, ...(badCalls === undefined ? {} : { badCalls }) }+}++interface BadClient { user: string; path: string; inFlight: number }++async function scenario(base: string, name: string, seconds: number, users: string[], round: number, bad?: BadClient): Promise<ScenarioResult> {+ const until = Date.now() + seconds * 1000+ const samples: Sample[] = []+ let fresh = 0+ const good = users.map(async user => {+ while (Date.now() < until) {+ const token = Math.random() < FRESH_TOKEN_SHARE ? `${user}.r${round}-f${fresh++}` : `${user}.steady`+ samples.push(await call(base, token, 'GET', '/api/machines'))+ await sleep(THINK_MS)+ }+ })+ let badCalls = 0+ const flood = bad ? Array.from({ length: bad.inFlight }, async () => {+ while (Date.now() < until) { await call(base, `${bad.user}.steady`, 'GET', bad.path); badCalls++ }+ }) : []+ await Promise.all([...good, ...flood])+ return summarize(name, samples, bad ? badCalls : undefined)+}++function render(results: ScenarioResult[], revision: string, seconds: number, inFlight: number): string {+ const rows = results.map(r => `| ${r.name} | ${r.calls} | ${r.p50} | ${r.p95} | ${r.p99} | ${r.max} | ${Object.entries(r.statuses).map(([k, v]) => `${k}: ${v}`).join(', ')} | ${r.badCalls ?? ''} |`)+ const normal = results.find(r => r.name === 'normal')+ const bad = results.find(r => r.name === 'bad-client')+ const rise = normal && bad && normal.p95 ? `${Math.round((bad.p95 / normal.p95 - 1) * 100)}%` : 'n/a'+ return [+ `# Resilience bench, ${revision}`,+ '',+ `${GOOD_CLIENTS} good clients, ${seconds} s per scenario, GET /api/machines with ${THINK_MS} ms think time, ${FRESH_TOKEN_SHARE * 100}% fresh tokens. The bad client loads its Swarm in full with ${inFlight} calls in flight. Latency in ms.`,+ '',+ '| Scenario | Good calls | p50 | p95 | p99 | max | Statuses | Bad client calls |',+ '|---|---|---|---|---|---|---|---|',+ ...rows,+ '',+ `KPI 3.2, good clients' p95 rise under one bad client: ${rise} (target under 10%).`,+ `KPI 3.5, p95 with Redis 5 s slow: ${results.find(r => r.name === 'redis-slow')?.p95 ?? 'n/a'} ms; with SSO 5 s slow: ${results.find(r => r.name === 'sso-slow')?.p95 ?? 'n/a'} ms (target under 1000 ms).`,+ '',+ ].join('\n')+}++async function main() {+ const args = process.argv.slice(2)+ const seconds = Number(args[args.indexOf('--seconds') + 1]) || 20+ const inFlight = Number(args[args.indexOf('--bad-in-flight') + 1]) || 128+ const out = args.includes('--out') ? args[args.indexOf('--out') + 1] : join(process.cwd(), 'integration/bench/results')+ const revision = execFileSync('git', ['rev-parse', '--short', 'HEAD']).toString().trim()++ const database = await localDatabase()+ const redis = await startRedis()+ const proxy = await delayProxy(redis.port)+ const sso = await fakeSso()+ const port = await freePort()+ const base = `http://127.0.0.1:${port}`+ const ssoUrl = `http://127.0.0.1:${sso.port}`+ await mkdir(out, { recursive: true })+ const log = createWriteStream(join(out, `resilience-${revision}.log`))+ const backend = spawn(process.execPath, ['--import', 'tsx', 'src/server.ts'], {+ env: {+ ...process.env,+ NODE_ENV: 'test',+ HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',+ PORT: String(port),+ PORT_APP_PROXY: String(await freePort()),+ DATABASE_URL: database.uri,+ REDIS_URL: `redis://127.0.0.1:${proxy.port}`,+ SSO_IDENTITY_URL: `${ssoUrl}/identity`,+ SSO_PROFILE_URL: `${ssoUrl}/profile`,+ AUTONOMOUS_BFF_URL: ssoUrl,+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ })+ backend.stdout!.pipe(log); backend.stderr!.pipe(log)+ try {+ for (let i = 0; ; i++) {+ if ((await call(base, 'none', 'GET', '/api/health')).status === 200) break+ if (i > 600 || backend.exitCode !== null) throw new Error('backend did not start; see the log in the results folder')+ await sleep(100)+ }+ const users = Array.from({ length: GOOD_CLIENTS }, (_, i) => `bench-good${i}`)+ const badUser = 'bench-bad'+ for (const [i, user] of [...users, badUser].entries()) {+ const computerId = (i + 1).toString(16).padStart(32, '0')+ const made = await call(base, `${user}.steady`, 'POST', '/api/machines/resolve-computer', { computerId, label: 'bench' })+ if (made.status !== 200) throw new Error(`could not register a computer for ${user}: HTTP ${made.status}`)+ }+ const tab = await fetch(`${base}/api/super-tabs`, { method: 'POST', headers: { authorization: `Bearer ${badUser}.steady`, 'content-type': 'application/json' },+ body: JSON.stringify({ operationId: 'bench-bad-swarm', name: 'Bench' }) }).then(r => r.json()) as { data?: { id?: string; state?: { id?: string } } }+ const tabId = tab.data?.id ?? tab.data?.state?.id+ if (!tabId) throw new Error(`could not create the bad client's Swarm: ${JSON.stringify(tab).slice(0, 200)}`)+ const bad: BadClient = { user: badUser, path: `/api/super-tabs/${tabId}/parts`, inFlight }+ if ((await call(base, `${badUser}.steady`, 'GET', bad.path)).status !== 200) throw new Error('the bad client cannot read its Swarm')+ const results: ScenarioResult[] = []+ results.push(await scenario(base, 'normal', seconds, users, 1))+ results.push(await scenario(base, 'bad-client', seconds, users, 2, bad))+ await sleep(2_000)+ proxy.setDelay(INJECTED_DELAY_MS)+ results.push(await scenario(base, 'redis-slow', seconds, users, 3))+ proxy.setDelay(0)+ await sleep(INJECTED_DELAY_MS + 2_000)+ sso.setDelay(INJECTED_DELAY_MS)+ results.push(await scenario(base, 'sso-slow', seconds, users, 4))+ sso.setDelay(0)++ const markdown = render(results, revision, seconds, inFlight)+ const name = `resilience-${revision}-${new Date().toISOString().replaceAll(':', '-').replace(/\.\d+Z$/, 'Z')}`+ await writeFile(join(out, `${name}.json`), `${JSON.stringify({ revision, seconds, inFlight, results }, null, 2)}\n`)+ await writeFile(join(out, `${name}.md`), markdown)+ process.stdout.write(`${markdown}\nWrote ${join(out, name)}.json and .md\n`)+ } finally {+ backend.kill('SIGKILL')+ sso.close(); proxy.close(); redis.process.kill()+ await database.stop()+ }+}++main().catch(error => {+ process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`)+ process.exitCode = 1+})diff --git a/backend/integration/productUsageConflicts.test.ts b/backend/integration/productUsageConflicts.test.tsnew file mode 100644index 000000000..43f91b927--- /dev/null+++ b/backend/integration/productUsageConflicts.test.ts@@ -0,0 +1,70 @@+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, beforeAll, expect, it, vi } from 'vitest'+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import type { PrismaClient } from '@prisma/client'++// A fresh loopback replica set, created here; the app's own Prisma client is pointed at it before anything imports it.+// Production on 2026-10-28: about 190 usage reports a minute, every one adding to the same daily totals, and 1,000 of+// the CLI's 1,269 rejected reports that morning were write conflicts on them.+let replica: MongoMemoryReplSet+let db: PrismaClient+let usage: typeof import('../src/lib/productUsage.js')++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(`product_usage_${randomUUID().replaceAll('-', '_')}`)+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,+ })+ process.env.DATABASE_URL = uri+ vi.resetModules()+ db = (await import('../src/lib/prisma.js')).prisma+ usage = await import('../src/lib/productUsage.js')+}, 120000)+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})++const now = new Date('2026-10-28T06:00:00Z')+const context = { surface: 'cli', release: '0.4.92', platform: 'macos', channel: 'production' } as const+const total = async (metric: string): Promise<number | undefined> =>+ (await db.productUsageTotal.findUnique({ where: { dayUtc_metric: { dayUtc: new Date('2026-10-28'), metric } } }))?.value++it('a fleet reporting at once is counted whole, with no report refused', async () => {+ const reports = Array.from({ length: 64 }, (_, i) => ({ schemaVersion: 1 as const, revision: 0, id: randomUUID(), day: '2026-10-28',+ context, counters: { health_cli_collector_days: 1, turns_started: 2, [`turns_ended`]: i % 2 } }))+ const answers = await Promise.allSettled(reports.map((report, i) => usage.ingestProductUsage(`6a00000000000000000${String(i).padStart(5, '0')}`, report, now)))+ expect(answers.filter(a => a.status === 'rejected').map(a => (a as PromiseRejectedResult).reason?.code)).toEqual([])+ expect(answers.map(a => (a as PromiseFulfilledResult<unknown>).value)).toEqual(reports.map(() => ({ accepted: true })))+ expect(await total('health_cli_collector_days')).toBe(64)+ expect(await total('turns_started')).toBe(128)+ expect(await total('turns_ended')).toBe(32)+ expect(await total('breakdown:release:cli:0.4.92:turns_started')).toBe(128)+ expect(await db.productUsageReceipt.count()).toBe(64)+}, 60000)++it('a report sent again after its answer was lost counts once', async () => {+ const report = { schemaVersion: 1 as const, revision: 0, id: randomUUID(), day: '2026-10-28', context, counters: { launch_unobserved: 3 } }+ const answers = await Promise.all([1, 2, 3].map(() => usage.ingestProductUsage('6a0000000000000000000b01', report, now)))+ expect(answers).toEqual([{ accepted: true }, { accepted: true }, { accepted: true }])+ expect(await usage.ingestProductUsage('6a0000000000000000000b01', report, now)).toEqual({ accepted: true })+ expect(await total('launch_unobserved')).toBe(3)+}, 60000)++it('four backend processes reporting at once still count every report', async () => {+ // Each import after a reset is another process's batch writer over the same database.+ const processes = [usage]+ for (let i = 1; i < 4; i++) { vi.resetModules(); processes.push(await import('../src/lib/productUsage.js')) }+ const sent = processes.flatMap((each, p) => Array.from({ length: 48 }, (_, i) => each.ingestProductUsage(+ `6a000000000000000000${String(p * 100 + i).padStart(4, '0')}`,+ { schemaVersion: 1, revision: 0, id: randomUUID(), day: '2026-10-28', context, counters: { queue_capped: 1 } }, now)))+ const answers = await Promise.allSettled(sent)+ expect(answers.filter(a => a.status === 'rejected').map(a => (a as PromiseRejectedResult).reason?.code)).toEqual([])+ expect(await total('queue_capped')).toBe(192)+}, 60000)diff --git a/backend/integration/superTabGithub.test.ts b/backend/integration/superTabGithub.test.tsindex ca1df91af..ad2628bc1 100644--- a/backend/integration/superTabGithub.test.ts+++ b/backend/integration/superTabGithub.test.ts@@ -328,6 +328,25 @@ describe('a queued start\'s preparation token', () => {expect(env.approved).toHaveLength(1)})+ it('says nothing was approved when the person cancels GitHub\'s sign-in', async () => {+ const signIn = { authorizeUrl: (state: string) => `https://github.test/login/oauth/authorize?state=${state}`,+ permission: async () => ({ login: 'olive', push: true }) } as unknown as GitHubSignIn+ teamAccounts()+ const env = await fresh({ approveAll: false, signIn })+ const { tab } = await queued(env)+ const asked = await env.app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/projects/lead/github/approve`,+ headers: { authorization: `Bearer ${owner.sub}` }, payload: { scope: 'project' } })+ const state = new URL((asked.json().data as { authorizeUrl: string }).authorizeUrl).searchParams.get('state')!+ // GitHub sends a person who chose Cancel back with an error and no code (its web application flow).+ const cancelled = await env.app.inject({ method: 'GET',+ url: `/api/github/callback?error=access_denied&error_description=The+user+has+denied+your+application+access.&state=${encodeURIComponent(state)}` })+ expect(cancelled.statusCode).toBe(200)+ expect(cancelled.body).toContain('Sign-in was cancelled')+ expect(cancelled.body).toContain('Nothing was approved. Go back to Harness and choose Approve to try again.')+ expect(cancelled.body).not.toContain('Harness is installed')+ expect(env.approved).toEqual([])+ })+it('says when the server cannot approve, and refuses a project not on GitHub', async () => {const env = await fresh({ approveAll: false })const { tab } = await queued(env)diff --git a/backend/integration/superTabIndexes.test.ts b/backend/integration/superTabIndexes.test.tsindex f0d26ec68..6b2a184bd 100644--- a/backend/integration/superTabIndexes.test.ts+++ b/backend/integration/superTabIndexes.test.ts@@ -8,6 +8,7 @@ import { MongoMemoryReplSet } from 'mongodb-memory-server-core'import { PrismaClient } from '@prisma/client'import { pageDeliveries, pageReactions } from '../src/superTabs/pageReads.js'import { recentDecisions } from '../src/superTabs/routeDecisions.js'+import { settleStuckDeliveries } from '../src/superTabs/deliverySettle.js'import { revokeNativeContexts } from '../src/superTabs/native.js'import { outsider, peer, swarm } from '../src/superTabs/read/fixture.test-support.js'import type { SuperTabState } from '../src/superTabs/model.js'@@ -128,6 +129,27 @@ describe('message page reads', () => {})})+describe('the delivery pass', () => {+ it('reads the open deliveries through the status index, examining only those it judges, with their dates as Dates', async () => {+ const open = ['queued', 'claimed', 'uncertain'].map((status, i) => ({ _id: `A-open-${i}`, tabId: 'A', conversationId: 'g1', messageId: 'A-m900',+ agentId: `agent-${i}`, machineId: 'host', membershipGeneration: 'gen', authorKind: 'person', authorId: 'owner', authorGeneration: 'gen', status,+ ...status === 'claimed' ? { claimId: 'claim', holdReason: 'team_waiting_user', holdSince: { $date: new Date(T0 + 1000).toISOString() } } : {},+ createdAt: { $date: new Date(T0).toISOString() }, updatedAt: { $date: new Date(T0 + 2000).toISOString() } }))+ await db.$runCommandRaw({ insert: 'SuperTabDelivery', documents: open })+ const judged: Array<{ tabId: string; rows: unknown[] }> = []+ const store = { settleDeliveries: async (tabId: string, rows: unknown[]) => { judged.push({ tabId, rows }); return 0 } }+ const [, profile] = await profiled('SuperTabDelivery', () => settleStuckDeliveries(db, store, T0))+ await db.superTabDelivery.deleteMany({ where: { messageId: 'A-m900' } })+ // One scan of the index per open status, merged in id order.+ expect(profile).toEqual({ plans: [Array(3).fill('IXSCAN { status: 1, _id: 1 }').join(', ')], docsExamined: 3, returned: 3 })+ expect(judged).toEqual([{ tabId: 'A', rows: [+ expect.objectContaining({ id: 'A-open-0', status: 'queued', holdSince: null, createdAt: new Date(T0), updatedAt: new Date(T0 + 2000) }),+ expect.objectContaining({ id: 'A-open-1', status: 'claimed', holdReason: 'team_waiting_user', holdSince: new Date(T0 + 1000) }),+ expect.objectContaining({ id: 'A-open-2', status: 'uncertain', conversationId: 'g1', agentId: 'agent-2' }),+ ] }])+ })+})+describe('route decision list', () => {const prismaRead = (tabId: string, conversationIds: string[]) => db.superTabRouteDecision.findMany({ where: { tabId, conversationId: { in: conversationIds } },orderBy: { createdAt: 'desc' }, take: 100 })diff --git a/backend/integration/superTabObserver.test.ts b/backend/integration/superTabObserver.test.tsindex 196cc9859..55247692f 100644--- a/backend/integration/superTabObserver.test.ts+++ b/backend/integration/superTabObserver.test.ts@@ -100,13 +100,6 @@ describe('a terminal observer of a Swarm agent', () => {expect(ws.close).toHaveBeenCalledWith(4403, expect.any(String))})- it('closes within a second of the watched session turning confidential, here by becoming its project’s Lead', async () => {- const { tab, ws, builder } = await watching(false)- await run(tab, { type: 'conversation.agent', conversationId: 'lead', agentId: builder, present: true, lead: true })- expect(await until(() => ws.close.mock.calls.length > 0, 1_000)).toBe(true)- expect(ws.close).toHaveBeenCalledWith(4403, expect.any(String))- })-it('closes a link\'s viewer within a second of the watched session turning confidential, here by becoming its project’s Lead', async () => {const { tab, builder, harnessId } = await watching(false)const link = await database.db.harnessLink.create({ data: { id: randomUUID(), ownerId: host.sub, machineId: 'test-host', agentId: harnessId,@@ -123,10 +116,15 @@ describe('a terminal observer of a Swarm agent', () => {}})- it('stays open through a change that leaves its viewer allowed', async () => {- const { tab, ws } = await watching()+ it('stays open through a change that leaves its viewer allowed, the watched agent becoming its project’s Lead included', async () => {+ const { tab, ws, builder } = await watching(false)await run(tab, { type: 'conversation.create', title: 'Another task', brief: '', checks: [] })await run(tab, { type: 'project.sharing', projectId: 'lead', visibility: 'private', memberIds: [host.sub, peer.sub] })+ // Every member watches the current Lead, view only (Ken, 2026-10-28), the private chats it is in included.+ await run(tab, { type: 'conversation.agent', conversationId: 'lead', agentId: builder, present: true, lead: true })+ await run(tab, { type: 'conversation.create', title: 'Chat with PM', brief: '', checks: [], audience: { personIds: [peer.sub] } }, peer)+ // Told to check again, it checks the Lead and stays.+ await publishSwarmAccessChanged(tab)expect(await until(() => ws.close.mock.calls.length > 0, 500)).toBe(false)})})diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.tsindex 621e6a205..436c7a825 100644--- a/backend/integration/superTabRead.test.ts+++ b/backend/integration/superTabRead.test.ts@@ -395,9 +395,11 @@ describe('host form (design 4.10)', () => {expect(tab.lastChangedAt).toBe(MIGRATED)const rows = new Map<string, Row>(tab.roster.filter((r: Row) => r.agent).map((r: Row) => [r.agent!.id, r]))expect([...rows.keys()].sort()).toEqual([s.lead, s.worker, s.more.idle, s.more.loner].sort())- // Nobody but its machine's owner watches a Lead (final review, Critical 1); a Builder's readers still do.- expect(rows.get(s.lead)).toMatchObject({ lead: true, active: true, leadsConversationId: s.leads, lastChangedAt: MIGRATED, observers: [] })- expect(rows.get(s.worker)).toMatchObject({ observers: [{ email: peer.email, userId: peer.sub }, { email: outsider.email, userId: outsider.sub }] })+ // A Lead's readers watch it, view only (Ken, 2026-10-28), as a Builder's do; marked, its host lets nobody else.+ const readers = [{ email: peer.email, userId: peer.sub }, { email: outsider.email, userId: outsider.sub }]+ expect(rows.get(s.lead)).toMatchObject({ lead: true, active: true, leadsConversationId: s.leads, lastChangedAt: MIGRATED, observers: readers,+ confidential: true, membersWatch: true })+ expect(rows.get(s.worker)).toMatchObject({ observers: readers, confidential: false, membersWatch: false })// Its only group is finished and dormant, yet not archived: the host must not hand it to automatic cleanup.expect(rows.get(s.more.idle)).toMatchObject({ lead: false, active: true })expect(tab.pool).toMatchObject({ tabId: s.tabId, machine: { machineId: machine }, starts: [{ id: 'queued' }, { id: 'queued-in-dormant' }] })@@ -697,6 +699,37 @@ describe('decisions asked of one person (v2)', () => {expect(await decisions(s.tabId, owner, 'open', s.lead)).toEqual([expect.objectContaining({ id: second })])})+ it('leaves a decision to the PM: the recommended option, listed as the PM\'s, and the PM\'s line in the person\'s quiet Chat with PM', async () => {+ const s = await scene()+ clock = Date.now()+ const asked = await post(s.tabId, { type: 'decision.ask', conversationId: s.web, personId: peer.sub,+ questions: [{ ...question('Ship how?'), recommended: 1 }] }, owner, s.lead)+ const id = (asked.body.data.result.decisionIds as string[])[0]!+ // The person's Chat with PM went quiet: it is not in a command's usual load.+ await writeGroup(s.tabId, s.privateId, Date.now(), group => { group.dormant = true })+ const left = await post(s.tabId, { type: 'decision.answer', decisionId: id, delegate: true }, peer)+ expect(left.status, JSON.stringify(left.body)).toBe(200)+ expect(await db.superTabDecision.findUnique({ where: { id } })).toMatchObject({ choice: 1, delegated: true })+ const listed = { id, choice: 1, delegated: true, answer: 'PM decided: To everyone' }+ expect(await decisions(s.tabId, peer, 'settled')).toEqual([expect.objectContaining(listed)])+ // An older Desktop reads the person's answered decisions and labels each "You chose": it is not given this one.+ expect(await decisions(s.tabId, peer, 'answered')).toEqual([])+ // Agents read it as answered, as before, now saying who decided.+ expect(await decisions(s.tabId, owner, 'answered', s.lead)).toEqual([expect.objectContaining(listed)])+ const line = (await db.superTabMessage.findMany({ where: { tabId: s.tabId, conversationId: s.privateId } })).at(-1)+ expect(line).toMatchObject({ text: 'PM decided: To everyone — Ship how?', recipientIds: [], source: { kind: 'decision-delegated', decisionId: id } })+ expect(line!.author).toMatchObject({ kind: 'agent', id: s.lead })+ // Only the person asked may leave it to the PM, and only while it is open.+ expect((await post(s.tabId, { type: 'decision.answer', decisionId: id, delegate: true }, peer)).body.error?.code).toBe('DECISION_ANSWERED')+ expect((await post(s.tabId, { type: 'decision.answer', decisionId: id, delegate: true }, owner)).status).toBe(404)+ // A person's own answer is listed as theirs.+ const mine = ((await post(s.tabId, { type: 'decision.ask', conversationId: s.web, personId: peer.sub, questions: [question('Name it?')] }, owner, s.lead))+ .body.data.result.decisionIds as string[])[0]!+ await post(s.tabId, { type: 'decision.answer', decisionId: mine, choice: 0 }, peer)+ expect((await decisions(s.tabId, peer, 'settled')).find(d => d.id === mine)).toMatchObject({ delegated: false, answer: 'Behind a flag' })+ expect((await decisions(s.tabId, peer, 'answered')).map(d => d.id)).toEqual([mine])+ })+it('takes an answer in a conversation that went quiet and was archived, counts it on a fresh first load, and tells both agents', async () => {const s = await scene()clock = Date.now()diff --git a/backend/integration/superTabTidy.test.ts b/backend/integration/superTabTidy.test.tsindex 924a0a998..50040c968 100644--- a/backend/integration/superTabTidy.test.ts+++ b/backend/integration/superTabTidy.test.ts@@ -12,6 +12,7 @@ import type { Command } from '../src/superTabs/commands.js'import type { MachineObservation } from '../src/superTabs/machines.js'import { poolRows, rosterRows } from './hostRows.test-support.js'import { archiveFinishedGroups, markFinishedGroups, type PullRequestState } from '../src/superTabs/archive.js'+import { settleStuckDeliveries } from '../src/superTabs/deliverySettle.js'// Nobody tidies a Swarm by hand: a worker idle for 15 minutes is stopped on its Lead's poll and its host is asked to close// it. A fresh loopback replica set, created here.@@ -175,6 +176,37 @@ describe('a worker left idle', () => {})})+describe('a review the Swarm opens by itself', () => {+ it('opens on a Ready for review with a project pull request, reaches its free Reviewer, and the Lead can cancel and archive it', async () => {+ const f = await swarm()+ // The project's repository, as its Lead's start in the repository records it (agent.add with a project).+ const head = await db.swarmHead.findUniqueOrThrow({ where: { id: `${f.tab}:head` } })+ const data = head.data as { projects: Array<Record<string, unknown>> }+ data.projects[0]!.repository = { machineId: 'lead-host', cwd: '/repo', repositoryUrl: 'https://github.com/example/parser' }+ await db.swarmHead.update({ where: { id: head.id }, data: { data: data as object } })+ const reviewed = String((await f.execute({ type: 'conversation.create', title: 'Parser v2', brief: 'More parsing',+ checks: [{ description: 'Verified', independent: true }] })).result.conversationId)+ const builder = await f.add(reviewed, 'test-host', randomUUID(), 'Builder')+ const work = String((await f.execute({ type: 'work.assign', conversationId: reviewed, agentId: builder })).result.assignmentId)+ const reviewer = await f.add('lead', 'test-host', randomUUID(), 'Reviewer')+ await f.started(reviewer, { role: 'reviewer' })+ await f.delivered()+ await f.execute({ type: 'work.status', conversationId: reviewed, assignmentId: work, status: 'review',+ result: 'Ready: yes, revision abc..def. https://github.com/example/parser/pull/9' }, host, builder)+ const state = (await f.timed.read(owner, f.tab)).state+ const review = state.conversations.find(c => c.reviewOf === reviewed)!+ expect(review).toMatchObject({ title: 'Review: Parser v2', assignment: { agentId: reviewer, status: 'working' } })+ expect(state.conversations.find(c => c.id === reviewed)!.agentIds).toContain(reviewer)+ const queued = await db.superTabDelivery.findMany({ where: { tabId: f.tab, agentId: reviewer, status: 'queued' } })+ expect(queued.map(d => d.conversationId)).toContain(review.id)+ const leadLine = await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, conversationId: review.id, text: { startsWith: 'Review opened by itself' } } })+ expect(leadLine.text).toBe('Review opened by itself for #2: Reviewer reviews it. Cancel it here if it is not needed.')+ await f.execute({ type: 'work.cancel', conversationId: review.id, assignmentId: review.assignment!.id, reason: 'Not needed' })+ await f.execute({ type: 'conversation.archive', conversationId: review.id, archived: true })+ expect((await f.timed.read(owner, f.tab)).state.conversations.find(c => c.id === review.id)?.archived ?? true).toBe(true)+ })+})+describe('a finished group', () => {const PR = 'https://github.com/acme/app/pull/7'/** GitHub as the sweep reads it: each pull request's state, null when it cannot say. */@@ -264,3 +296,145 @@ describe('the archive pass', () => {expect((await db.swarmGroup.findUniqueOrThrow({ where: { id: part.id } })).archived).toBe(true)})})++// Prod watch, 2026-10-28: 9 deliveries had waited for days (uncertain since Oct 20, claimed for 71 hours, queued in archived+// groups). None belonged to a task, so nothing ended them. Each now ends as cancelled, which its sender sees as Not sent.+describe('a delivery that cannot move', () => {+ const HOUR = 60 * MINUTE+ type Fixture = Awaited<ReturnType<typeof swarm>>+ const status = async (id: string) => (await db.superTabDelivery.findUniqueOrThrow({ where: { id } })).status+ /** A person's message to the Lead in the project chat, waiting for the Lead's host. */+ const toLead = async (f: Fixture, text: string) => {+ const sent = await f.execute({ type: 'message.send', conversationId: 'lead', text, replyTo: null, recipientIds: [] })+ return (await db.superTabDelivery.findFirstOrThrow({ where: { tabId: f.tab, messageId: sent.result.messageId as string, agentId: f.lead } })).id+ }+ /** The Lead's message to its worker in the worker's group. */+ const toWorker = async (f: Fixture, text: string) => {+ const sent = await f.execute({ type: 'message.send', conversationId: f.group, text, replyTo: null, recipientIds: [f.worker] }, host, f.lead)+ return (await db.superTabDelivery.findFirstOrThrow({ where: { tabId: f.tab, messageId: sent.result.messageId as string, agentId: f.worker } })).id+ }+ /** The pass at [after] past the row's last write: a host's own writes are stamped by the database clock, not the store's. */+ const settleAfter = async (f: Fixture, id: string, after: number) =>+ settleStuckDeliveries(db, f.timed, (await db.superTabDelivery.findUniqueOrThrow({ where: { id } })).updatedAt.getTime() + after)++ it('ends as Not sent when the tidy pass archives its group', async () => {+ const f = await swarm()+ const waiting = await toWorker(f, 'One more thing.')+ f.clock.now += 40 * MINUTE+ await archiveFinishedGroups(db, f.timed, { state: async () => null, done: async () => {} }, f.clock.now)+ expect((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.group } })).archived).toBe(true)+ expect(await status(waiting)).toBe('cancelled')+ })++ it('is ended by the delivery pass once its group is archived, even asleep, while one its recipient can read waits', async () => {+ const f = await swarm()+ const old = await toWorker(f, 'Left over.')+ const readable = await toLead(f, 'Still for you.')+ await f.execute({ type: 'conversation.archive', conversationId: f.group, archived: true })+ // As a backend from before this pass left it: archived and asleep with its delivery still queued.+ await db.superTabDelivery.update({ where: { id: old }, data: { status: 'queued' } })+ const part = await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.group } })+ await db.swarmGroup.update({ where: { id: part.id }, data: { dormant: true, data: { ...part.data as object, dormant: true } } })+ await settleStuckDeliveries(db, f.timed, f.clock.now)+ expect(await status(old)).toBe('cancelled')+ expect(await status(readable)).toBe('queued')+ })++ it('ends a claim its host has not touched for 10 minutes, and keeps one its host touched since', async () => {+ const f = await swarm()+ const id = await toLead(f, 'Claimed, then the host went away.')+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'claim', claimId: 'claim' })+ await settleAfter(f, id, 9 * MINUTE)+ expect(await status(id)).toBe('claimed')+ await settleAfter(f, id, 10 * MINUTE + 1_000)+ expect(await status(id)).toBe('cancelled')+ })++ it('ends a hold after an hour, or after a day while a person owes the agent an answer, and keeps why', async () => {+ const f = await swarm()+ const busy = await toLead(f, 'Held while the Lead works.')+ const asking = await toLead(f, 'Held while the Lead waits on a person.')+ for (const id of [busy, asking]) await f.timed.delivery(host, f.tab, f.lead, id, { type: 'claim', claimId: `claim-${id}` })+ await f.timed.delivery(host, f.tab, f.lead, busy, { type: 'hold', claimId: `claim-${busy}`, reason: 'team_waiting_idle' })+ await f.timed.delivery(host, f.tab, f.lead, asking, { type: 'hold', claimId: `claim-${asking}`, reason: 'team_waiting_user' })+ const heldAt = f.clock.now+ await settleStuckDeliveries(db, f.timed, heldAt + 59 * MINUTE)+ expect([await status(busy), await status(asking)]).toEqual(['claimed', 'claimed'])+ await settleStuckDeliveries(db, f.timed, heldAt + HOUR + MINUTE)+ expect(await db.superTabDelivery.findUniqueOrThrow({ where: { id: busy } })).toMatchObject({ status: 'cancelled', holdReason: 'team_waiting_idle' })+ expect(await status(asking)).toBe('claimed')+ await settleStuckDeliveries(db, f.timed, heldAt + 23 * HOUR)+ expect(await status(asking)).toBe('claimed')+ await settleStuckDeliveries(db, f.timed, heldAt + 24 * HOUR + MINUTE)+ expect(await db.superTabDelivery.findUniqueOrThrow({ where: { id: asking } })).toMatchObject({ status: 'cancelled', holdReason: 'team_waiting_user' })+ })++ it('counts a hold the pass ended as delivered once its host confirms it typed it', async () => {+ const f = await swarm()+ const id = await toLead(f, 'Held, then typed as the pass ends it.')+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'claim', claimId: 'claim' })+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'hold', claimId: 'claim', reason: 'team_waiting_idle' })+ // An hour on, the terminal frees: the host claims it again and types it, and the pass ends it before the host confirms.+ f.clock.now += HOUR + MINUTE+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'claim', claimId: 'claim' })+ await settleStuckDeliveries(db, f.timed, f.clock.now)+ expect(await status(id)).toBe('cancelled')+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'ack', claimId: 'claim', receipt: 'Typed.', uncertain: false })+ expect(await db.superTabDelivery.findUniqueOrThrow({ where: { id } })).toMatchObject({ status: 'delivered', receipt: 'Typed.',+ deliveredAt: new Date(f.clock.now), holdReason: null })+ })++ it('never types a hold the pass ended: claiming it again is refused', async () => {+ const f = await swarm()+ const id = await toLead(f, 'Held and ended, never typed.')+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'claim', claimId: 'claim' })+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'hold', claimId: 'claim', reason: 'team_waiting_idle' })+ await settleStuckDeliveries(db, f.timed, f.clock.now + HOUR + MINUTE)+ await expect(f.timed.delivery(host, f.tab, f.lead, id, { type: 'claim', claimId: 'claim' })).rejects.toMatchObject({ code: 'DELIVERY_REVOKED' })+ await expect(f.timed.delivery(host, f.tab, f.lead, id, { type: 'ack', claimId: 'another', receipt: 'Typed.', uncertain: false }))+ .rejects.toMatchObject({ code: 'DELIVERY_REVOKED' })+ expect(await status(id)).toBe('cancelled')+ })++ it('ends an uncertain delivery nobody resolved within an hour', async () => {+ const f = await swarm()+ const id = await toLead(f, 'Maybe typed.')+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'claim', claimId: 'claim' })+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'ack', claimId: 'claim', receipt: 'Native paste was ambiguous.', uncertain: true })+ await settleAfter(f, id, 59 * MINUTE)+ expect(await status(id)).toBe('uncertain')+ await settleAfter(f, id, HOUR + MINUTE)+ expect(await status(id)).toBe('cancelled')+ // Ended for good: only a hold the pass ended comes back on its host's confirmation.+ await expect(f.timed.delivery(host, f.tab, f.lead, id, { type: 'ack', claimId: 'claim', receipt: 'Typed after all.', uncertain: false }))+ .rejects.toMatchObject({ code: 'DELIVERY_REVOKED' })+ expect(await status(id)).toBe('cancelled')+ })++ it('leaves a delivery its host typed or claimed again after the pass read it', async () => {+ const f = await swarm()+ const typed = await toLead(f, 'Typed as the pass reads it.')+ const reclaimed = await toLead(f, 'Claimed again as the pass reads it.')+ for (const id of [typed, reclaimed]) await f.timed.delivery(host, f.tab, f.lead, id, { type: 'claim', claimId: 'claim' })+ const read = await db.superTabDelivery.findMany({ where: { id: { in: [typed, reclaimed] } }, orderBy: { id: 'asc' } })+ await new Promise(resolve => setTimeout(resolve, 5))+ await f.timed.delivery(host, f.tab, f.lead, typed, { type: 'ack', claimId: 'claim', receipt: 'Typed.', uncertain: false })+ // A live host claims a claim it still holds again: that is what tells it from a claim nobody will type.+ await f.timed.delivery(host, f.tab, f.lead, reclaimed, { type: 'claim', claimId: 'claim' })+ expect(await f.timed.settleDeliveries(f.tab, read, Math.max(...read.map(r => r.updatedAt.getTime())) + HOUR)).toBe(0)+ expect([await status(typed), await status(reclaimed)]).toEqual(['delivered', 'claimed'])+ })++ it('ends a hold that is over even though its live host claimed it again after the pass read it', async () => {+ const f = await swarm()+ const id = await toLead(f, 'Held while the Lead works.')+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'claim', claimId: 'claim' })+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'hold', claimId: 'claim', reason: 'team_waiting_idle' })+ const read = await db.superTabDelivery.findUniqueOrThrow({ where: { id } })+ await new Promise(resolve => setTimeout(resolve, 5))+ // Its core refused the write while the terminal was busy, so the host claims it again on each poll (cli superTabs/host.ts).+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'claim', claimId: 'claim' })+ expect(await f.timed.settleDeliveries(f.tab, [read], f.clock.now + HOUR + MINUTE)).toBe(1)+ expect(await db.superTabDelivery.findUniqueOrThrow({ where: { id } })).toMatchObject({ status: 'cancelled', holdReason: 'team_waiting_idle' })+ })+})diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 3d5b6491d..a48873c64 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -1079,10 +1079,12 @@ describe('Super Tabs on a real Mongo replica set', () => {}expect((await store.read(owner, tab)).state.conversations.find(c => c.id === 'lead')!.lastMessageSequence).toBe(before)expect((await store.messages(host, tab, 'lead', {}, lead)).messages.map(m => m.text)).toEqual(['Harness updated your built-in swarm-lead skill.'])- // Typed through the normal claim; a hold while the input box is busy writes no row people would see.+ // Typed through the normal claim; a hold while the input box is busy is recorded on the delivery, so the delivery pass+ // knows its host still holds it (deliverySettle.ts), and writes no row people would see.const claimed = await store.delivery(host, tab, lead, deliveries[0]!.id, { type: 'claim', claimId: 'claim' })expect(claimed.message).toMatchObject({ text: 'Harness updated your built-in swarm-lead skill.', source: { kind: 'agent-only' } })- expect(await store.delivery(host, tab, lead, deliveries[0]!.id, { type: 'hold', claimId: 'claim', reason: 'team_waiting_draft' })).toEqual({ held: false })+ expect(await store.delivery(host, tab, lead, deliveries[0]!.id, { type: 'hold', claimId: 'claim', reason: 'team_waiting_draft' })).toEqual({ held: true })+ expect(await db.superTabDelivery.findUniqueOrThrow({ where: { id: deliveries[0]!.id } })).toMatchObject({ holdReason: 'team_waiting_draft' })expect((await store.messages(owner, tab, 'lead', {})).messages).toEqual([])})@@ -3266,11 +3268,28 @@ describe('the PM\'s terminal after a private chat (final review, Critical 1)', (await expect(opened(host)).resolves.toMatchObject({ contextId: expect.any(String) })})- it('lets nobody but its machine\'s owner watch it: not a reader outside the chat, not the Swarm owner, not with an earlier share', async () => {- const { tab, lead, harnessId } = await privateChat()+ it('lets every reader watch it while it is the Lead, view only: not through an ordinary share, and not once it is no longer the Lead', async () => {+ const { tab, lead, harnessId, swarmShare, ordinaryShare } = await privateChat()+ // Ken, 2026-10-28: a member watching the Product Manager reads the private chats it is in, and every member may.+ expect(await observers(lead)).toEqual(expect.arrayContaining([bob.sub, owner.sub, peer.sub]))+ const row = (await rosterRows(store, host, 'test-host')).find(t => t.tabId === tab && t.agent?.id === lead)!+ expect(row).toMatchObject({ confidential: true, membersWatch: true })+ for (const user of [bob, owner, peer]) expect(await store.mayObserve(user, tab, 'test-host', harnessId, host.sub)).toBe(true)+ expect(await recipientShare(swarmShare, bob, db)).not.toBeNull()+ // Outside the Swarm it is still its machine's person's alone.+ expect(await recipientShare(ordinaryShare, carol, db)).toBeNull()+ // A Lead leaves only with its project, but a state from before that rule can hold a former Lead still in the private chat.+ const state = await storedState(tab)+ state.conversations.find(c => c.id === 'lead')!.leadId = null+ await saveState(tab, state)expect(await observers(lead)).toEqual([])for (const user of [bob, owner, peer]) expect(await store.mayObserve(user, tab, 'test-host', harnessId, host.sub)).toBe(false)- // A Builder's terminal stays watchable by the project's readers.+ expect(await recipientShare(swarmShare, bob, db)).toBeNull()+ expect(await store.mayObserve(host, tab, 'test-host', harnessId, host.sub)).toBe(true)+ })++ it('leaves a Builder\'s terminal to the project\'s readers', async () => {+ const { tab } = await privateChat()const workerHarness = randomUUID()const worker = String((await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: workerHarness,name: 'Worker', configuration: config, lead: false })).result.agentId)@@ -3366,8 +3385,9 @@ describe('the PM\'s terminal after a private chat (final review, Critical 1)', (// Swarm B's Lead cannot read or type into its Builder alias of Swarm A's PM.await expect(run(other, { type: 'agent.screen', agentId: lead }, host, otherLead)).rejects.toMatchObject({ code: 'TERMINAL_PRIVATE' })await expect(run(other, { type: 'agent.input', agentId: lead, keys: ['Enter'] }, host, otherLead)).rejects.toMatchObject({ code: 'TERMINAL_PRIVATE' })- // Shares made before the chat, opened as the observer relay opens them.- expect(await recipientShare(swarmShare, bob, db)).toBeNull()+ // Shares made before the chat, opened as the observer relay opens them: Swarm A's opens for its member while the session+ // is A's Lead (Ken, 2026-10-28); Swarm B's and the ordinary one stay closed.+ expect(await recipientShare(swarmShare, bob, db)).not.toBeNull()expect(await recipientShare(ordinaryShare, carol, db)).toBeNull()await db.harnessShare.update({ where: { id: swarmShare }, data: { superTabId: other } })expect(await recipientShare(swarmShare, bob, db)).toBeNull()@@ -3734,7 +3754,7 @@ describe('Swarm parts under concurrent writes', () => {expect((await db.superTabDelivery.findUniqueOrThrow({ where: { id: delivery.id } })).status).toBe('cancelled')})- it('writes the waiting delivery rows of a conversation archived or left by their receiver, so a claim in flight conflicts', async () => {+ it('ends the waiting delivery rows of a conversation archived or left by their receiver, so a claim in flight conflicts', async () => {const { tab, lead } = await fixture()const { group, worker } = await workGroup(tab, 'Rows')const assignmentId = (await store.read(owner, tab)).state.conversations.find(c => c.id === group)!.assignment!.id@@ -3746,13 +3766,17 @@ describe('Swarm parts under concurrent writes', () => {await run(tab, { type: 'conversation.agent', conversationId: group, agentId: worker, present: false, lead: false })const left = await row()expect(left.updatedAt.getTime()).toBeGreaterThan(before.updatedAt.getTime())- expect(left.status).toBe(before.status)+ // Its receiver can no longer read it there: it ends now, rather than waiting unseen for good (prod watch, 2026-10-28).+ expect(left.status).toBe('cancelled')+ const kept = await run(tab, { type: 'message.send', conversationId: group, text: 'For the Lead.', replyTo: null, recipientIds: [] })+ const toLead = async () => db.superTabDelivery.findFirstOrThrow({ where: { tabId: tab, messageId: kept.result.messageId as string } })+ const open = await toLead()await new Promise(resolve => setTimeout(resolve, 5))await run(tab, { type: 'conversation.archive', conversationId: group, archived: true })- const archived = await row()- expect(archived.updatedAt.getTime()).toBeGreaterThan(left.updatedAt.getTime())- // Archiving keeps them for when the conversation reopens, as before.- expect(archived.status).toBe(before.status)+ const archived = await toLead()+ expect(archived.updatedAt.getTime()).toBeGreaterThan(open.updatedAt.getTime())+ // Archiving ends them too: 6 of 9 deliveries stuck for days in prod were in archived groups.+ expect(archived.status).toBe('cancelled')})it('assigns the routed agent through its finished start, without an override reason', async () => {diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 78c8bd0ce..39227705f 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1123,6 +1123,8 @@ model SuperTabDecision {answeredAt DateTime?choice Int?note String?+ /// The person asked left it to the PM, who took the recommended option: never shown as their own choice.+ delegated Boolean?@@index([tabId, personId, createdAt])@@index([tabId, askerAgentId, createdAt])@@ -1209,6 +1211,8 @@ model SuperTabDelivery {@@index([machineId, status])// A page of messages reads its deliveries by message (pageReads.ts).@@index([tabId, messageId])+ // The delivery pass reads only the open ones (superTabs/deliverySettle.ts).+ @@index([status, id])/// A Swarm's open deliveries, whoever they are for (the Lead's poll, store.ts fullDeliveries).@@index([tabId, status])/// An ended task's open deliveries, cancelled with it (store.ts releaseRuns and stopped): by [tabId, status] alone thediff --git a/backend/src/config/env.ts b/backend/src/config/env.tsindex a2a1e2ac8..b74888c2b 100644--- a/backend/src/config/env.ts+++ b/backend/src/config/env.ts@@ -22,6 +22,20 @@ const envSchema = z.object({// manager socket may land on different backend instances; Redis pub/sub bridges them// (channels up:{machineId} / down:{machineId}) plus an agent→manager presence key. See lib/bus.ts.REDIS_URL: z.string().default('redis://localhost:6379'),+ // The longest one Redis command may take on the shared command connection (lib/bus.ts). Redis answers in well under a+ // millisecond; past this it is stuck, and a request should not wait on it (Stability 3.5).+ REDIS_COMMAND_TIMEOUT_MS: z.coerce.number().int().positive().default(1_000),+ // Signed-in requests per route, across every pod (middlewares/routeRateLimit.ts). Far above what a working client+ // sends, so only a loop meets them. 0 turns one off. Revisit with per-route counts from the ingress logs.+ // Per caller and second: the agent or machine the route names (with its person), else the person.+ ROUTE_RATE_LIMIT_PER_CALLER_SECOND: z.coerce.number().int().min(0).default(50),+ // Per person and minute, whatever agents or machines the calls name. The busiest working client is an older CLI's+ // delivery poll, one call a second per running agent. A late poll can land in the next minute, so a minute can see an+ // agent 61 times: 200 agents are 12200. 15000 leaves room above that.+ ROUTE_RATE_LIMIT_PER_PERSON_MINUTE: z.coerce.number().int().min(0).default(15_000),+ // Per person and second, whatever agents or machines the calls name, so made-up ids cannot spend the minute's budget+ // at once. 200 agents polling once a second can land up to 400 in one second when polls arrive late: 500 is above it.+ ROUTE_RATE_LIMIT_PER_PERSON_SECOND: z.coerce.number().int().min(0).default(500),// What each process keeps of the Swarms it read, by their stamps in Redis (superTabs/cache.ts). 'off' is the kill switch:// every read goes to Mongo again, while writes still bump the stamps, so processes that keep theirs on stay right.SWARM_READ_CACHE: z.enum(['on', 'off']).default('on'),@@ -126,6 +140,11 @@ const envSchema = z.object({// How long a token the profile API just accepted is trusted without asking again (0 = ask every// time). This is also the longest a token revoked at the SSO keeps working here.SSO_PROFILE_CACHE_TTL_MS: z.coerce.number().int().min(0).default(60_000),+ // While the profile service cannot answer (down, slow, circuit open), a token this process validated up to this long+ // past its TTL keeps working, so an SSO outage does not sign out people who are working (lib/ssoProfileCache.ts).+ // Never past the token's own expiry, never for a token the service rejected. The cost: during an outage a token revoked+ // at the SSO keeps working this long. Off (0) until the owner decides; 600000 (10 min) is the value it was built for.+ SSO_PROFILE_STALE_GRACE_MS: z.coerce.number().int().min(0).default(0),// Forces the SSO account picker so users can switch accounts (not silently auto-login the last one).// Set to '' to disable, or 'login' to force re-entering credentials.SSO_PROMPT: z.string().default('select_account'),diff --git a/backend/src/lib/adapterShortTurns.test.ts b/backend/src/lib/adapterShortTurns.test.tsnew file mode 100644index 000000000..10e3ea3c7--- /dev/null+++ b/backend/src/lib/adapterShortTurns.test.ts@@ -0,0 +1,92 @@+import { EventEmitter } from 'node:events'+import { beforeEach, describe, expect, it, vi } from 'vitest'++// The machine socket's short-turn cap (lib/shortTurnGuard.ts) on the real handler. The socket harness is the one in+// teamSessionSockets.test.ts: authentication, the machine row, the bus and the hub are faked.+const m = vi.hoisted(() => ({+ auth: vi.fn(), upgrade: vi.fn(), resolve: vi.fn(), publishUp: vi.fn(), recordTurn: vi.fn(), nodeRole: vi.fn(), warn: vi.fn(),+}))+vi.mock('./ssoAuth.js', async original => ({ ...await original<typeof import('./ssoAuth.js')>(), authenticateAccessToken: m.auth }))+vi.mock('./wsServer.js', async original => ({ ...await original<typeof import('./wsServer.js')>(), createWss: () => ({ handleUpgrade: m.upgrade }) }))+vi.mock('../services/MachineService.js', () => ({ machineService: { resolveOrCreateForComputer: m.resolve } }))+vi.mock('./prisma.js', () => ({+ prisma: { machine: { update: vi.fn(async () => ({})), findUnique: vi.fn(async () => null) }, user: { findUnique: vi.fn(async () => null) } },+ machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] },+}))+vi.mock('./bus.js', () => ({+ publishUp: m.publishUp, claimMachineOwner: vi.fn(async () => true), releaseMachineOwner: vi.fn(), publishDeviceE2eePair: vi.fn(),+ publishTerminalUp: vi.fn(), subscribeTerminalDown: vi.fn(async () => () => {}), setMachineAppState: vi.fn(), clearMachineAppState: vi.fn(),+}))+vi.mock('./adapterAccountPushes.js', () => ({ relayAccountPushes: vi.fn(async () => () => {}) }))+vi.mock('./deviceKeyLog.js', () => ({ appendDeviceKey: vi.fn(), touchDeviceKey: vi.fn() }))+vi.mock('./nodeRole.js', () => ({ attachNodeRole: m.nodeRole, PRESENCE_TTL_SEC: 30 }))+vi.mock('./hub.js', () => ({+ CLIENTS_FRAME: '__clients', CLIENTS_DIRTY: '__clients_dirty', LIVENESS_TICK_MS: 5_000, CLIENT_IDLE_DEADLINE_MS: 75_000,+ DEVICE_IDLE_DEADLINE_MS: 35_000, CLIENT_HEARTBEAT_MS: 25_000, deliverTerminalUpLocal: vi.fn(), deliverUpLocal: vi.fn(),+ pushDeviceRevoked: vi.fn(), sendClientsControl: vi.fn(), recomputeAndSendClients: vi.fn(), attachHubClient: vi.fn(),+ trackSocketLiveness: () => () => {},+}))+vi.mock('./dailyTracking.js', async original => ({ ...await original<typeof import('./dailyTracking.js')>(),+ touchMachineOnlineDay: vi.fn(async () => {}), touchUserOnlineDay: vi.fn(async () => {}), touchClientOnlineDay: vi.fn(async () => {}),+ recordTurnStarted: m.recordTurn }))+vi.mock('../utils/logger.js', () => ({ logger: { warn: m.warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() } }))++import { handleAdapterUpgrade } from './adapterWs.js'++const flush = async () => { for (let i = 0; i < 400; i++) await Promise.resolve() }++class Socket extends EventEmitter {+ readyState = 1; bufferedAmount = 0+ send = vi.fn()+ close = vi.fn(() => { this.readyState = 3; this.emit('close') })+ terminate = vi.fn(() => this.close())+ frame(body: unknown) { this.emit('message', Buffer.from(JSON.stringify(body)), false) }+}++async function machineSocket(): Promise<Socket> {+ const ws = new Socket()+ m.upgrade.mockImplementation((_r, _s, _h, done) => done(ws))+ handleAdapterUpgrade({ url: '/api/adapter-ws?computer=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&label=Mac&autonomousEnv=prod',+ headers: { 'sec-websocket-protocol': 'access-token' } } as never,+ { write: vi.fn(), destroy: vi.fn(), destroyed: false, on: vi.fn(), once: vi.fn() } as never, Buffer.alloc(0))+ await flush()+ return ws+}+const turnsRelayed = () => m.publishUp.mock.calls.filter(([, msg]) => (msg as { frame: { type: string } }).frame.type === 'turn_started').length++beforeEach(() => {+ vi.clearAllMocks()+ m.auth.mockResolvedValue({ sub: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' })+ m.resolve.mockResolvedValue({ machine: { machineId: 'looping-mac', userId: 'owner', name: 'Mac', billingStatus: 'not_required', sessionKind: null }, created: false })+ m.publishUp.mockResolvedValue(1)+ m.recordTurn.mockResolvedValue(undefined)+ m.nodeRole.mockResolvedValue({ touch: vi.fn(), detach: vi.fn(async () => {}) })+})++describe('a machine starting turns in a loop', () => {+ it('has its turn starts counted and relayed 21 times in a row, then neither, and is logged once', async () => {+ const ws = await machineSocket()++ for (let i = 0; i < 30; i++) ws.frame({ t: 'up', frame: { type: 'turn_started', agentId: 'agent-1', payload: { __e2e: 'x' } } })+ await flush()++ expect(turnsRelayed()).toBe(21)+ expect(m.recordTurn).toHaveBeenCalledTimes(21)+ expect(m.warn.mock.calls.filter(([message]) => String(message).includes('turn starts'))).toEqual([+ [expect.stringContaining('turn starts'), expect.objectContaining({ machineId: 'looping-mac' })],+ ])+ })++ it('still relays everything else while its turn starts are held', async () => {+ const ws = await machineSocket()+ for (let i = 0; i < 30; i++) ws.frame({ t: 'up', frame: { type: 'turn_started', agentId: 'agent-1' } })++ ws.frame({ t: 'up', frame: { type: 'text_delta', payload: { __e2e: 'y' } } })+ ws.frame({ t: 'up', frame: { type: 'turn_started', agentId: 'agent-1', replay: true } })+ await flush()++ const types = m.publishUp.mock.calls.map(([, msg]) => (msg as { frame: { type: string; replay?: boolean } }).frame)+ expect(types.at(-2)?.type).toBe('text_delta')+ expect(types.at(-1)).toMatchObject({ type: 'turn_started', replay: true })+ })+})diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.tsindex 7d02e5e6c..3385ccd06 100644--- a/backend/src/lib/adapterWs.ts+++ b/backend/src/lib/adapterWs.ts@@ -63,6 +63,7 @@ import {P2pSignalRateGuard,terminalP2pPolicy,} from './p2pSignaling.js'+import { ShortTurnGuard } from './shortTurnGuard.js'const wss = createWss(WS_LIMITS.adapter, { echoFirstProtocol: true })@@ -249,6 +250,7 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, cif (nowMs - turnWindowStart >= 60_000) { turnWindowStart = nowMs; turnWindowCount = 0 }return ++turnWindowCount <= TURN_WRITES_PER_MINUTE}+ const shortTurns = new ShortTurnGuard()const p2pSignalRate = new P2pSignalRateGuard()// A machine appends its own key once per sign-in, a removal when someone asks for one: a few a minute// is generous, and it keeps a looping daemon from rebuilding the log on every frame.@@ -528,6 +530,13 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c// (measured 2026-09-17: 42 such frames in one second credited to one agent). It still relays,// it is just not a turn today. A frame with no (or a malformed) agentId has nothing to// attribute the turn to and is not counted.+ // A machine starting turns in a loop (lib/shortTurnGuard.ts): past the cap its turn starts are neither counted+ // nor relayed for a while. Everything else it sends still is.+ const verdict = shortTurns.admit()+ if (verdict !== 'relay') {+ if (verdict === 'pause_started') logger.warn('machine is starting turns in a loop; holding its turn starts for 60 s', { machineId, userId })+ return+ }const now = new Date()const agentId = typeof f.agentId === 'string' && TURN_AGENT_ID_RE.test(f.agentId) ? f.agentId : undefinedif (agentId && allowTurnWrite(now.getTime())) {diff --git a/backend/src/lib/autonomousBff.test.ts b/backend/src/lib/autonomousBff.test.tsindex d273eee9b..a440bb8c3 100644--- a/backend/src/lib/autonomousBff.test.ts+++ b/backend/src/lib/autonomousBff.test.ts@@ -21,9 +21,13 @@ import {fireCampaignDevice,getCampaignDevice,listCampaignSubscriptions,+ resetBffBreakers,} from './autonomousBff.js'-afterEach(() => vi.unstubAllGlobals())+afterEach(() => {+ vi.unstubAllGlobals()+ resetBffBreakers()+})describe('Autonomous campaign catalog', () => {it('reads billable ids and prices from each monthly frequencies entry', async () => {@@ -244,3 +248,34 @@ describe('Autonomous campaign catalog', () => {expect(fetchMock).toHaveBeenCalledOnce()})})++describe('a billing service that keeps failing', () => {+ it('is answered for at once instead of waiting out its timeout on every call', async () => {+ const fetchMock = vi.fn(async () => { throw new Error('connect ETIMEDOUT') })+ vi.stubGlobal('fetch', fetchMock)+ for (let i = 0; i < 5; i++) await expect(fetchCampaignPlans('prod')).rejects.toMatchObject({ statusCode: 503, code: 'BILLING_SERVICE_UNAVAILABLE' })+ const asked = fetchMock.mock.calls.length++ await expect(getCampaignDevice('prod', 'sso-access', 'device-1')).rejects.toMatchObject({ statusCode: 503, code: 'BILLING_SERVICE_UNAVAILABLE' })++ expect(fetchMock.mock.calls.length).toBe(asked)+ })++ it('keeps staging and production apart', async () => {+ vi.stubGlobal('fetch', vi.fn(async (url: URL) => {+ if (String(url).startsWith('https://bff.example')) throw new Error('connect ETIMEDOUT')+ return new Response(JSON.stringify({ data: [] }), { status: 200 })+ }))+ for (let i = 0; i < 5; i++) await expect(fetchCampaignPlans('prod')).rejects.toMatchObject({ code: 'BILLING_SERVICE_UNAVAILABLE' })++ await expect(fetchCampaignPlans('stag')).resolves.toEqual([])+ })++ it('does not take answers it gave for an outage', async () => {+ const fetchMock = vi.fn(async () => new Response('{}', { status: 404 }))+ vi.stubGlobal('fetch', fetchMock)+ for (let i = 0; i < 10; i++) await expect(getCampaignDevice('prod', 'sso-access', 'device-1')).rejects.toMatchObject({ code: 'BILLING_DEVICE_NOT_FOUND' })++ expect(fetchMock).toHaveBeenCalledTimes(10)+ })+})diff --git a/backend/src/lib/autonomousBff.ts b/backend/src/lib/autonomousBff.tsindex df604c3a7..8a80a65e3 100644--- a/backend/src/lib/autonomousBff.ts+++ b/backend/src/lib/autonomousBff.ts@@ -1,6 +1,8 @@import { env } from '../config/env.js'import { AppError } from '../errors/index.js'import { autonomousEnvironmentConfig, type AutonomousEnvironment } from './autonomousEnvironment.js'+import { createCircuitBreaker, CircuitOpenError, type CircuitBreaker } from './circuitBreaker.js'+import { logger } from '../utils/logger.js'type JsonObject = Record<string, unknown>@@ -122,10 +124,48 @@ export function parseSubscription(subscription: JsonObject): CampaignSubscriptio}}+// Per account plane: a billing service that keeps failing is answered for at once, not after its timeout on every call.+const UNAVAILABLE_CODES = new Set(['BILLING_SERVICE_UNAVAILABLE', 'BILLING_UPSTREAM_ERROR'])+const breakers = new Map<AutonomousEnvironment, CircuitBreaker>()++function bffBreaker(autonomousEnv: AutonomousEnvironment): CircuitBreaker {+ let breaker = breakers.get(autonomousEnv)+ if (!breaker) {+ breaker = createCircuitBreaker({+ name: `autonomous-bff:${autonomousEnv}`,+ isFailure: (err) => !(err instanceof AppError) || UNAVAILABLE_CODES.has(err.code ?? ''),+ onStateChange: (state) => {+ if (state === 'open') logger.warn('[bff] billing service unreachable; failing fast', { autonomousEnv })+ else logger.info('[bff] billing service circuit', { autonomousEnv, state })+ },+ })+ breakers.set(autonomousEnv, breaker)+ }+ return breaker+}++/** Test seam. */+export function resetBffBreakers(): void {+ breakers.clear()+}+async function request(autonomousEnv: AutonomousEnvironment,path: string,opts: { token?: string; method?: string; body?: unknown; origin?: string } = {},+): Promise<unknown> {+ try {+ return await bffBreaker(autonomousEnv).run(() => send(autonomousEnv, path, opts))+ } catch (err) {+ if (err instanceof CircuitOpenError) throw new AppError('Autonomous billing service unavailable', 503, 'BILLING_SERVICE_UNAVAILABLE')+ throw err+ }+}++async function send(+ autonomousEnv: AutonomousEnvironment,+ path: string,+ opts: { token?: string; method?: string; body?: unknown; origin?: string },): Promise<unknown> {let response: Responsetry {diff --git a/backend/src/lib/bus.test.ts b/backend/src/lib/bus.test.tsindex b8bdde064..a35c44167 100644--- a/backend/src/lib/bus.test.ts+++ b/backend/src/lib/bus.test.ts@@ -30,6 +30,8 @@ vi.mock('ioredis', () => {exec = vi.fn(async () => this.results)}class FakeRedis {+ // The bus guards its command connection at ioredis' single send point (lib/redisGuard.ts).+ sendCommand = vi.fn()publish = vi.fn(async () => 1)subscribe = vi.fn(async () => 1)unsubscribe = vi.fn(async () => 1)@@ -107,6 +109,103 @@ describe('publishUp', () => {})})+const NOT_WRITABLE = "Stream isn't writeable and enableOfflineQueue options is false"+type Listener = (...args: unknown[]) => void+/** What the subscriber connection hands the bus when Redis delivers `payload` on `channel`. */+function deliverFromRedis(instance: number, event: 'message' | 'messageBuffer', channel: string | Buffer, payload: string | Buffer) {+ const conn = state.instances[instance] as { on: MockFn }+ for (const [name, listener] of conn.on.mock.calls as Array<[string, Listener]>) if (name === event) listener(channel, payload)+}++describe('single-pod mode: Redis cannot take a publish', () => {+ beforeEach(() => { pub.publish.mockReset(); pub.publish.mockResolvedValue(1) })++ it('still delivers to this pod\'s own subscribers, once', async () => {+ const got: unknown[] = []+ await bus.subscribeShareChanged('share-1', () => got.push('changed'))+ pub.publish.mockRejectedValueOnce(new Error(NOT_WRITABLE))++ await expect(bus.publishShareChanged('share-1')).resolves.toBe(1)+ await vi.waitFor(() => expect(got).toEqual(['changed']))+ })++ it('delivers a frame for a machine whose socket is on this pod', async () => {+ const got: unknown[] = []+ await bus.subscribeDown('m-local', (msg) => got.push(msg))+ pub.publish.mockRejectedValueOnce(new Error(NOT_WRITABLE))++ await bus.publishDown('m-local', { connId: 'c1', frame: { type: 'message', payload: { text: 'hi' } } })++ await vi.waitFor(() => expect(got).toEqual([{ connId: 'c1', frame: { type: 'message', payload: { text: 'hi' } } }]))+ })++ it('delivers terminal bytes locally too', async () => {+ const got: Buffer[] = []+ await bus.subscribeTerminalUp('m-term', (payload) => got.push(payload))+ pub.publish.mockRejectedValueOnce(new Error(NOT_WRITABLE))++ await bus.publishTerminalUp('m-term', new Uint8Array([1, 2, 3]))++ await vi.waitFor(() => expect(got.map((b) => [...b])).toEqual([[1, 2, 3]]))+ })++ it('does not deliver a publish that timed out, which Redis may still deliver itself', async () => {+ const got: unknown[] = []+ await bus.subscribeShareChanged('share-2', () => got.push('changed'))+ pub.publish.mockRejectedValueOnce(new Error('Command timed out'))++ await expect(bus.publishShareChanged('share-2')).resolves.toBe(0)+ await new Promise((resolve) => setTimeout(resolve, 10))+ expect(got).toEqual([])+ })++ it('says 0 when nobody on this pod listens, as Redis would', async () => {+ pub.publish.mockRejectedValueOnce(new Error(NOT_WRITABLE))+ await expect(bus.publishShareChanged('nobody')).resolves.toBe(0)+ })++ it('warns once on entering it and says once when it is over', async () => {+ const { logger } = await import('../utils/logger.js')+ const warn = vi.mocked(logger.warn), info = vi.mocked(logger.info)+ await bus.publishShareChanged('settle') // out of single-pod mode, whatever an earlier test left+ warn.mockClear(); info.mockClear()+ pub.publish.mockRejectedValue(new Error(NOT_WRITABLE))+ await bus.publishShareChanged('a'); await bus.publishShareChanged('b')+ pub.publish.mockResolvedValue(1)+ await bus.publishShareChanged('c'); await bus.publishShareChanged('d')++ expect(warn.mock.calls.filter(([m]) => String(m).includes('single-pod mode'))).toHaveLength(1)+ expect(info.mock.calls.filter(([m]) => String(m).includes('single-pod mode'))).toHaveLength(1)+ })+})++describe('subscribing while Redis is away', () => {+ it('does not hold the caller until Redis comes back, and the subscription still works when it does', async () => {+ const mainSub = state.instances[1] as { subscribe: MockFn }+ let subscribed!: () => void+ mainSub.subscribe.mockImplementationOnce(() => new Promise<void>((resolve) => { subscribed = resolve }))+ const got: unknown[] = []++ const started = Date.now()+ await bus.subscribeShareChanged('share-away', () => got.push('changed'))+ expect(Date.now() - started).toBeLessThan(2_000)++ subscribed()+ deliverFromRedis(1, 'message', 'harness-share:share-away', '{}')+ expect(got).toEqual(['changed'])+ })++ it('does not hold a terminal subscriber either', async () => {+ const terminalSub = state.instances[2] as { subscribe: MockFn }+ terminalSub.subscribe.mockImplementationOnce(() => new Promise<void>(() => {}))+ const started = Date.now()++ await bus.subscribeTerminalDown('m-away', () => undefined)++ expect(Date.now() - started).toBeLessThan(2_000)+ })+})+describe('subscribeAppUp', () => {it('rides its own subscriber connection, not the main one', async () => {const [, mainSub, , appSub] = state.instances as Array<{ subscribe: MockFn }>diff --git a/backend/src/lib/bus.ts b/backend/src/lib/bus.tsindex e20c08189..4f025d2ec 100644--- a/backend/src/lib/bus.ts+++ b/backend/src/lib/bus.ts@@ -18,6 +18,8 @@import { Redis } from 'ioredis'import { env } from '../config/env.js'import { logger } from '../utils/logger.js'+import { createCircuitBreaker } from './circuitBreaker.js'+import { guardRedisCommands, isRedisFailure, wasNotSent } from './redisGuard.js'import type { Frame, UpBusMsg, DownBusMsg } from './tunnel.js'import { redisStamps, type SwarmStamps } from '../superTabs/cache.js'@@ -28,14 +30,26 @@ const subOpts = { maxRetriesPerRequest: null as null, lazyConnect: false }// default offline queue, every `publish` issued during a Redis outage (every up-frame from every manager// socket, every terminal packet) was stringified and parked in this process' heap until reconnect, and// every `await pub.set(...)` in an attach path hung — pinning its closure — for the whole outage.+// A Redis that is up but stuck is the other half: each command waits out `commandTimeout`, so it is short, and a circuit+// breaker (lib/redisGuard.ts) refuses commands outright after a few in a row have failed (Stability 3.5).const pubOpts = {maxRetriesPerRequest: 1,enableOfflineQueue: false,- commandTimeout: 5_000,+ commandTimeout: env.REDIS_COMMAND_TIMEOUT_MS,lazyConnect: false,}export const pub = new Redis(env.REDIS_URL, pubOpts)+guardRedisCommands(pub, createCircuitBreaker({+ name: 'redis',+ failureThreshold: 5,+ openMs: 5_000,+ isFailure: isRedisFailure,+ onStateChange: (state) => {+ if (state === 'open') logger.warn('[bus] Redis commands failing; refusing them for 5 s')+ else logger.info('[bus] Redis commands', { state })+ },+}))const sub = new Redis(env.REDIS_URL, subOpts)const terminalSub = new Redis(env.REDIS_URL, subOpts)// App-proxy replies (`appup:{streamId}`) can be multi-MiB base64 bodies. Redis cuts a subscriber that@@ -44,15 +58,63 @@ const terminalSub = new Redis(env.REDIS_URL, subOpts)// Isolated here, a heavy app stream can only hurt app streams.const appSub = new Redis(env.REDIS_URL, subOpts)-/** Every fan-out publish is best-effort: Redis unreachable → dropped with a warning, 0 subscribers.- * Callers already read 0 as "nobody holds this machine right now", which is exactly the truth. */+/**+ * Every fan-out publish is best-effort. Callers read 0 as "nobody holds this machine right now".+ *+ * Single-pod mode: while Redis cannot take a publish at all (no connection, or its circuit is open), the publish goes+ * straight to this pod's own subscribers, so everything whose two ends share a pod keeps working; that is the whole+ * deployment when it runs one pod. Only a publish that certainly never reached Redis is delivered here: one that timed+ * out may still be delivered by Redis, and a terminal keystroke must not arrive twice. That one is dropped, as before.+ */+let singlePod = falseasync function safePublish(channel: string, payload: string | Buffer): Promise<number> {try {- return await pub.publish(channel, payload)+ const receivers = await pub.publish(channel, payload)+ if (singlePod) {+ singlePod = false+ logger.info('[bus] Redis takes publishes again; single-pod mode is over')+ }+ return receivers} catch (err) {- logger.warn('[bus] publish dropped', { channel, error: err instanceof Error ? err.message : String(err) })- return 0+ const error = err instanceof Error ? err.message : String(err)+ if (!wasNotSent(err)) {+ logger.warn('[bus] publish dropped', { channel, error })+ return 0+ }+ if (!singlePod) {+ singlePod = true+ logger.warn('[bus] Redis cannot take publishes; single-pod mode: they reach only this pod\'s subscribers', { error })+ }+ return deliverLocally(channel, payload)+ }+}++/** A publish handed to this pod's subscribers as Redis would hand it back: later, parsed afresh. 1 if any listen. */+function deliverLocally(channel: string, payload: string | Buffer): number {+ if (typeof payload !== 'string') {+ if (!binarySubs.get(channel)?.size) return 0+ queueMicrotask(() => dispatchBinary(channel, payload))+ return 1}+ const registry = [mainSubscriber, appSubscriber].find((r) => r.channelSubs.get(channel)?.size)+ if (!registry) return 0+ queueMicrotask(() => dispatchJson(registry, channel, payload))+ return 1+}++/** How long a new subscription waits for Redis to confirm it. Past that it is registered here anyway and Redis+ * confirms it when it can (ioredis queues it and re-subscribes on reconnect): a socket attach must not wait out an+ * outage, and in single-pod mode local publishes reach it at once. */+const SUBSCRIBE_WAIT_MS = 1_000++/** Resolves when `work` does or after `ms`, whichever is first; rejects only if `work` fails within `ms`. */+function settledWithin(work: Promise<unknown>, ms: number): Promise<void> {+ work.catch(() => { /* a late failure is logged where the subscription is made */ })+ return new Promise((resolve, reject) => {+ const timer = setTimeout(resolve, ms)+ timer.unref?.()+ work.then(() => { clearTimeout(timer); resolve() }, (err) => { clearTimeout(timer); reject(err) })+ })}pub.on('error', (err: Error) => logger.error('[bus] pub redis error', err))@@ -69,30 +131,33 @@ type Cb = (msg: unknown) => void/** One refcounted JSON subscriber registry per subscribe-mode connection. */interface JsonSubscriber {conn: Redis+ label: stringchannelSubs: Map<string, Set<Cb>>channelSubscribePromises: Map<string, Promise<void>>}-function createJsonSubscriber(conn: Redis, label: string): JsonSubscriber {- const registry: JsonSubscriber = { conn, channelSubs: new Map(), channelSubscribePromises: new Map() }- conn.on('message', (channel: string, payload: string) => {- const set = registry.channelSubs.get(channel)- if (!set || set.size === 0) return- let msg: unknown+function dispatchJson(registry: JsonSubscriber, channel: string, payload: string): void {+ const set = registry.channelSubs.get(channel)+ if (!set || set.size === 0) return+ let msg: unknown+ try {+ msg = JSON.parse(payload)+ } catch (err) {+ logger.error(`[bus] bad JSON on channel (${registry.label})`, err, { channel })+ return+ }+ for (const cb of set) {try {- msg = JSON.parse(payload)+ cb(msg)} catch (err) {- logger.error(`[bus] bad JSON on channel (${label})`, err, { channel })- return- }- for (const cb of set) {- try {- cb(msg)- } catch (err) {- logger.error(`[bus] subscriber callback threw (${label})`, err, { channel })- }+ logger.error(`[bus] subscriber callback threw (${registry.label})`, err, { channel })}- })+ }+}++function createJsonSubscriber(conn: Redis, label: string): JsonSubscriber {+ const registry: JsonSubscriber = { conn, label, channelSubs: new Map(), channelSubscribePromises: new Map() }+ conn.on('message', (channel: string, payload: string) => dispatchJson(registry, channel, payload))return registry}@@ -122,7 +187,7 @@ async function addSubOn(reg: JsonSubscriber, channel: string, cb: Cb): Promise<(set.add(cb)if (subscribePromise) {try {- await subscribePromise+ await settledWithin(subscribePromise, SUBSCRIBE_WAIT_MS)} catch (err) {const s = channelSubs.get(channel)if (s === set) {@@ -161,20 +226,23 @@ const terminalDownChannel = (machineId: string): string => `termdown:${machineIdtype BinaryCb = (payload: Buffer) => voidconst binarySubs = new Map<string, Set<BinaryCb>>()-terminalSub.on('messageBuffer', (channelRaw: Buffer, payload: Buffer) => {- const callbacks = binarySubs.get(channelRaw.toString('utf8'))+function dispatchBinary(channel: string, payload: Buffer): void {+ const callbacks = binarySubs.get(channel)if (!callbacks) returnfor (const callback of callbacks) {try { callback(Buffer.from(payload)) } catch (err) { logger.error('[bus] binary subscriber callback threw', err) }}-})+}+terminalSub.on('messageBuffer', (channelRaw: Buffer, payload: Buffer) => dispatchBinary(channelRaw.toString('utf8'), payload))async function addBinarySub(channel: string, callback: BinaryCb): Promise<() => void> {let callbacks = binarySubs.get(channel)if (!callbacks) {callbacks = new Set()binarySubs.set(channel, callbacks)- await terminalSub.subscribe(channel)+ const subscribed = terminalSub.subscribe(channel)+ subscribed.catch((err: unknown) => logger.error('[bus] terminal subscribe failed', err, { channel }))+ await settledWithin(subscribed, SUBSCRIBE_WAIT_MS)}callbacks.add(callback)return () => {diff --git a/backend/src/lib/circuitBreaker.test.ts b/backend/src/lib/circuitBreaker.test.tsnew file mode 100644index 000000000..3f8162e80--- /dev/null+++ b/backend/src/lib/circuitBreaker.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from 'vitest'+import { CircuitOpenError, createCircuitBreaker } from './circuitBreaker.js'++const fail = () => Promise.reject(new Error('down'))+const ok = () => Promise.resolve('ok')++function clock(start = 1_000) {+ let t = start+ return { now: () => t, advance: (ms: number) => { t += ms } }+}++describe('circuit breaker', () => {+ it('opens after the threshold of consecutive failures and then refuses without calling', async () => {+ const c = clock()+ const breaker = createCircuitBreaker({ name: 'sso', failureThreshold: 3, openMs: 10_000, now: c.now })+ for (let i = 0; i < 3; i++) await expect(breaker.run(fail)).rejects.toThrow('down')+ expect(breaker.state()).toBe('open')+ let called = false+ await expect(breaker.run(async () => { called = true; return 'x' })).rejects.toBeInstanceOf(CircuitOpenError)+ expect(called).toBe(false)+ })++ it('a success in between resets the count', async () => {+ const breaker = createCircuitBreaker({ name: 'sso', failureThreshold: 3, openMs: 10_000 })+ await expect(breaker.run(fail)).rejects.toThrow()+ await expect(breaker.run(fail)).rejects.toThrow()+ await expect(breaker.run(ok)).resolves.toBe('ok')+ await expect(breaker.run(fail)).rejects.toThrow()+ await expect(breaker.run(fail)).rejects.toThrow()+ expect(breaker.state()).toBe('closed')+ })++ it('after the open period lets one trial through: success closes it', async () => {+ const c = clock()+ const breaker = createCircuitBreaker({ name: 'sso', failureThreshold: 1, openMs: 10_000, now: c.now })+ await expect(breaker.run(fail)).rejects.toThrow()+ c.advance(9_999)+ await expect(breaker.run(ok)).rejects.toBeInstanceOf(CircuitOpenError)+ c.advance(1)+ let release!: (v: string) => void+ const trial = breaker.run(() => new Promise<string>(r => { release = r }))+ expect(breaker.state()).toBe('half_open')+ // Only one trial at a time: everyone else is still refused while it runs.+ await expect(breaker.run(ok)).rejects.toBeInstanceOf(CircuitOpenError)+ release('back')+ await expect(trial).resolves.toBe('back')+ expect(breaker.state()).toBe('closed')+ await expect(breaker.run(ok)).resolves.toBe('ok')+ })++ it('a failed trial opens it for another full period', async () => {+ const c = clock()+ const breaker = createCircuitBreaker({ name: 'sso', failureThreshold: 1, openMs: 10_000, now: c.now })+ await expect(breaker.run(fail)).rejects.toThrow()+ c.advance(10_000)+ await expect(breaker.run(fail)).rejects.toThrow('down')+ expect(breaker.state()).toBe('open')+ c.advance(9_999)+ await expect(breaker.run(ok)).rejects.toBeInstanceOf(CircuitOpenError)+ })++ it('times a call out, aborts its signal and counts it as a failure', async () => {+ const breaker = createCircuitBreaker({ name: 'redis', failureThreshold: 1, openMs: 10_000, timeoutMs: 20 })+ let aborted = false+ const started = Date.now()+ await expect(breaker.run(signal => new Promise(() => { signal.addEventListener('abort', () => { aborted = true }) })))+ .rejects.toThrow('redis timed out after 20 ms')+ expect(Date.now() - started).toBeLessThan(1_000)+ expect(aborted).toBe(true)+ expect(breaker.state()).toBe('open')+ })++ it('an error the caller says is not the service failing passes through and counts as the service answering', async () => {+ const breaker = createCircuitBreaker({ name: 'sso', failureThreshold: 2, openMs: 10_000,+ isFailure: err => !(err instanceof Error && err.message === 'invalid token') })+ await expect(breaker.run(fail)).rejects.toThrow()+ await expect(breaker.run(() => Promise.reject(new Error('invalid token')))).rejects.toThrow('invalid token')+ await expect(breaker.run(fail)).rejects.toThrow()+ expect(breaker.state()).toBe('closed')+ })++ it('reports each change of state once', async () => {+ const c = clock()+ const changes: string[] = []+ const breaker = createCircuitBreaker({ name: 'bff', failureThreshold: 2, openMs: 1_000, now: c.now, onStateChange: s => changes.push(s) })+ await expect(breaker.run(fail)).rejects.toThrow()+ await expect(breaker.run(fail)).rejects.toThrow()+ await expect(breaker.run(ok)).rejects.toBeInstanceOf(CircuitOpenError)+ c.advance(1_000)+ await breaker.run(ok)+ expect(changes).toEqual(['open', 'half_open', 'closed'])+ })+})diff --git a/backend/src/lib/circuitBreaker.ts b/backend/src/lib/circuitBreaker.tsnew file mode 100644index 000000000..7e4096fea--- /dev/null+++ b/backend/src/lib/circuitBreaker.ts@@ -0,0 +1,108 @@+/**+ * A circuit breaker for a dependency on the request path (SSO, the Autonomous BFF, Redis).+ *+ * A slow dependency costs every request its full timeout; a breaker lets the first few pay it, then answers at once+ * until the dependency has had time to recover. Closed: calls run, and `failureThreshold` failures in a row open it.+ * Open: calls are refused with CircuitOpenError without running. After `openMs` one trial call runs (half open) while+ * the others are still refused; its success closes the breaker and its failure opens it for another period.+ *+ * Process-local on purpose: each pod learns for itself, in a few calls, whether it can reach the dependency.+ */+export type CircuitState = 'closed' | 'open' | 'half_open'++export class CircuitOpenError extends Error {+ constructor(readonly breaker: string) {+ super(`${breaker} is unavailable (circuit open)`)+ this.name = 'CircuitOpenError'+ }+}++export class CircuitTimeoutError extends Error {+ constructor(readonly breaker: string, readonly timeoutMs: number) {+ super(`${breaker} timed out after ${timeoutMs} ms`)+ this.name = 'CircuitTimeoutError'+ }+}++export interface CircuitBreakerOptions {+ name: string+ failureThreshold?: number+ openMs?: number+ /** Per call: the call's signal aborts, and the call fails with CircuitTimeoutError even if it ignores the signal. */+ timeoutMs?: number+ /** Whether an error means the dependency failed. False for an answer it gave (a 401 is the SSO working). */+ isFailure?: (err: unknown) => boolean+ now?: () => number+ onStateChange?: (state: CircuitState) => void+}++export interface CircuitBreaker {+ run<T>(fn: (signal: AbortSignal) => Promise<T>): Promise<T>+ state(): CircuitState+}++export function createCircuitBreaker({+ name,+ failureThreshold = 5,+ openMs = 10_000,+ timeoutMs,+ isFailure = () => true,+ now = Date.now,+ onStateChange,+}: CircuitBreakerOptions): CircuitBreaker {+ let state: CircuitState = 'closed'+ let failures = 0+ let openedAt = 0+ let trialRunning = false++ const move = (next: CircuitState): void => {+ if (state === next) return+ state = next+ onStateChange?.(next)+ }++ const withTimeout = <T>(fn: (signal: AbortSignal) => Promise<T>): Promise<T> => {+ if (timeoutMs === undefined) return fn(new AbortController().signal)+ const controller = new AbortController()+ let timer: NodeJS.Timeout | undefined+ const expired = new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ const error = new CircuitTimeoutError(name, timeoutMs)+ controller.abort(error)+ reject(error)+ }, timeoutMs)+ })+ return Promise.race([fn(controller.signal), expired]).finally(() => clearTimeout(timer))+ }++ return {+ state: () => state,+ async run(fn) {+ let trial = false+ if (state !== 'closed') {+ if (trialRunning || now() - openedAt < openMs) throw new CircuitOpenError(name)+ trial = true+ trialRunning = true+ move('half_open')+ }+ try {+ const result = await withTimeout(fn)+ failures = 0+ move('closed')+ return result+ } catch (err) {+ if (!isFailure(err)) {+ failures = 0+ move('closed')+ } else if (trial || ++failures >= failureThreshold) {+ failures = 0+ openedAt = now()+ move('open')+ }+ throw err+ } finally {+ if (trial) trialRunning = false+ }+ },+ }+}diff --git a/backend/src/lib/gridProfile.ts b/backend/src/lib/gridProfile.tsindex 77f33bfe9..746d1112e 100644--- a/backend/src/lib/gridProfile.ts+++ b/backend/src/lib/gridProfile.ts@@ -3,6 +3,7 @@ import { logger } from '../utils/logger.js'import { storedAutonomousEnvironment } from './autonomousEnvironment.js'import { LiveProfileError, readLiveProfile, recordLiveProfile, type LiveProfile } from './googleSubject.js'import type { AuthUser } from './ssoAuth.js'+import { createRateLimiter } from './rateLimit.js'/*** What `GET /api/grid/profile` answers: who holds this Harness sign-in token, for the Grid control@@ -39,25 +40,12 @@ export type GridProfileAnswer =* user's token validation shares. A computer sign-in reads nothing upstream and is not counted.*/export const GRID_PROFILE_LIVE_READS_PER_MINUTE = 10-const LIVE_READ_WINDOW_MS = 60_000-const LIVE_READ_ENTRIES_MAX = 10_000-const liveReads = new Map<string, number[]>()--/** Count one live read for this account; false when it is over the limit. */-function admitLiveRead(userId: string, now = Date.now()): boolean {- const recent = (liveReads.get(userId) ?? []).filter((at) => now - at < LIVE_READ_WINDOW_MS)- if (recent.length >= GRID_PROFILE_LIVE_READS_PER_MINUTE) return false- if (!liveReads.has(userId) && liveReads.size >= LIVE_READ_ENTRIES_MAX) {- const oldest = liveReads.keys().next().value- if (oldest !== undefined) liveReads.delete(oldest)- }- liveReads.set(userId, [...recent, now])- return true-}+/** Live reads per account, counted by every pod together (lib/rateLimit.ts). */+const liveReads = createRateLimiter('grid-profile', 60_000, GRID_PROFILE_LIVE_READS_PER_MINUTE)/** Forget the per-account live read counts. Tests only. */export function resetGridProfileLimits(): void {- liveReads.clear()+ liveReads.reset()}/** Only these fields, and never a social's `token`, whatever the source held. */@@ -95,7 +83,7 @@ export async function answerGridProfile(caller: AuthUser, token: string): Promisif (!user) return UNAUTHORIZEDif (storedAutonomousEnvironment(user.autonomousEnv) !== 'prod') return STAGING_PLANE- if (!admitLiveRead(user.id)) {+ if (!(await liveReads.allows(user.id))) {return refuse(429, 'TOO_MANY_REQUESTS', 'Too many Grid profile reads for this account; try again in a minute')}diff --git a/backend/src/lib/productUsage.test.ts b/backend/src/lib/productUsage.test.tsindex c3309b9f8..02a8739e9 100644--- a/backend/src/lib/productUsage.test.ts+++ b/backend/src/lib/productUsage.test.ts@@ -5,15 +5,15 @@ import { setTimeout as delay } from 'node:timers/promises'vi.mock('node:timers/promises', () => ({ setTimeout: vi.fn(async () => {}) }))const db = vi.hoisted(() => ({- productUsagePreference: { findUnique: vi.fn(), upsert: vi.fn() },- analyticsMachineState: { findFirst: vi.fn() },- productUsageReceipt: { create: vi.fn(), findUnique: vi.fn() },+ productUsagePreference: { findUnique: vi.fn(), findMany: vi.fn(), upsert: vi.fn() },+ analyticsMachineState: { findFirst: vi.fn(), findMany: vi.fn() },+ productUsageReceipt: { findMany: vi.fn(), createMany: vi.fn() },productUsageTotal: { upsert: vi.fn(), update: vi.fn(), groupBy: vi.fn(), findMany: vi.fn(), deleteMany: vi.fn() },userDailyPresence: { deleteMany: vi.fn() }, userDailyClientPresence: { deleteMany: vi.fn() },userDailyRemoteUsage: { deleteMany: vi.fn() }, userDailyDevicePresence: { deleteMany: vi.fn() },machineDailyPresence: { deleteMany: vi.fn() }, agentDailyPresence: { deleteMany: vi.fn() },productUsageActivity: { upsert: vi.fn(), update: vi.fn(), deleteMany: vi.fn() },- user: { findUnique: vi.fn() },+ user: { findUnique: vi.fn(), findMany: vi.fn() },$transaction: vi.fn(), $runCommandRaw: vi.fn(),}))vi.mock('./prisma.js', () => ({ prisma: db }))@@ -27,7 +27,7 @@ it('commits release and platform margins under the same unlinked receipt and disexpect(await ingestProductUsage('PRIVATE_ACCOUNT', { ...report, context }, now)).toEqual({ accepted: true })expect(db.$transaction).toHaveBeenCalledOnce()expect(db.$runCommandRaw.mock.calls[0][0].updates).toHaveLength(6)- const stored = JSON.stringify([db.productUsageReceipt.create.mock.calls, db.$runCommandRaw.mock.calls])+ const stored = JSON.stringify([db.productUsageReceipt.createMany.mock.calls, db.$runCommandRaw.mock.calls])expect(stored).not.toContain('PRIVATE_ACCOUNT')expect(stored).not.toContain('1.2.73:macos')expect(stored).toContain('breakdown:release:desktop:1.2.73:turns_started')@@ -36,6 +36,12 @@ it('commits release and platform margins under the same unlinked receipt and disexpect(db.$transaction).not.toHaveBeenCalled()})+/** Every account a batch asks about has [email]. */+const accounts = (email: string) => db.user.findMany.mockImplementation(async ({ where }: { where: { id: { in: string[] } } }) =>+ where.id.in.map(id => ({ id, email })))+const choices = (...saved: Array<{ userId: string; enabled: boolean; revision: number }>) => db.productUsagePreference.findMany.mockResolvedValueOnce(saved)+const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => { resolve = r }); return { promise, resolve } }+const receipts = () => db.productUsageReceipt.createMany.mock.calls.flatMap(([{ data }]) => data.map((r: { id: string }) => r.id))const report: ProductUsageReport = { schemaVersion: 1, revision: 0, id: 'cf1c5a03-388c-4265-b5fb-a4c3d47e407f', day: '2026-10-13', counters: { turns_started: 4, turns_ended: 3 } }const now = new Date('2026-10-13T12:00:00Z')beforeEach(() => {@@ -44,6 +50,11 @@ beforeEach(() => {db.$transaction.mockImplementation((fn: (tx: typeof db) => unknown) => fn(db))db.productUsagePreference.findUnique.mockResolvedValue(null)db.analyticsMachineState.findFirst.mockResolvedValue(null)+ db.productUsagePreference.findMany.mockResolvedValue([])+ db.analyticsMachineState.findMany.mockResolvedValue([])+ db.productUsageReceipt.findMany.mockResolvedValue([])+ db.productUsageReceipt.createMany.mockImplementation(async ({ data }) => ({ count: data.length }))+ accounts('[email protected]')resetActivityMarksForTests()resetStaffAccountsForTests()db.user.findUnique.mockResolvedValue({ createdAt: new Date('2026-10-01T08:00:00Z'), email: '[email protected]' })@@ -54,7 +65,7 @@ describe('kept apart', () => {(command as { updates: Array<{ q: { metric: string } }> }).updates.map(update => update.q.metric))it('keeps the team\'s own accounts under staff:, with their margins and late marks', async () => {- db.user.findUnique.mockResolvedValue({ createdAt: new Date('2026-10-01T08:00:00Z'), email: '[email protected]' })+ accounts('[email protected]')const context = { surface: 'phone', release: '1.0.7', platform: 'ios', channel: 'production' } as constexpect(await ingestProductUsage('team-account', { ...report, day: '2026-10-12', context }, now)).toEqual({ accepted: true })expect(stored()).toEqual(expect.arrayContaining(['staff:turns_started', 'staff:breakdown:release:phone:1.0.7:turns_started',@@ -67,7 +78,7 @@ describe('kept apart', () => {expect(await ingestProductUsage('someone', { ...report, context }, now)).toEqual({ accepted: true })expect(stored()).toEqual(['testing:turns_started', 'testing:turns_ended'])// A build's channel decides it: no account is read for it.- expect(db.user.findUnique).not.toHaveBeenCalled()+ expect(db.user.findMany).not.toHaveBeenCalled()})it('leaves everyone else\'s totals as they were, and asks for an account once', async () => {@@ -76,14 +87,14 @@ describe('kept apart', () => {await ingestProductUsage('person', { ...report, id: 'cf1c5a03-388c-4265-b5fb-a4c3d47e4080', context }, now)expect(stored().filter(metric => metric.includes(':') && !metric.startsWith('breakdown:'))).toEqual([])expect(stored()).toContain('turns_started')- expect(db.user.findUnique).toHaveBeenCalledOnce()+ expect(db.user.findMany).toHaveBeenCalledOnce()})it('reads no account for signed-out setup counts', async () => {expect(await ingestSetupUsage({ id: 'cf1c5a03-388c-4265-b5fb-a4c3d47e4081', day: '2026-10-13',counters: { setup_phone_first_open: 1 } }, now)).toEqual({ accepted: true })expect(stored()).toEqual(['setup_phone_first_open'])- expect(db.user.findUnique).not.toHaveBeenCalled()+ expect(db.user.findMany).not.toHaveBeenCalled()})})@@ -154,21 +165,32 @@ describe('preference', () => {})describe('aggregate ingestion', () => {- it('rechecks permission after waiting for another report without caching an enabled choice', async () => {- let release!: () => void- const gate = new Promise<void>(resolve => { release = resolve })- // Four reports fill this process's write slots; the fifth waits for one.- for (let i = 0; i < 4; i++) db.$transaction.mockImplementationOnce(async fn => { await gate; return fn(db) })- const first = [0, 1, 2, 3].map(i => ingestProductUsage(`account-${i}`, { ...report, id: `receipt-${i}` }, now))+ it('rechecks permission inside the batch, so a choice turned off while a report waited refuses it', async () => {+ const gate = deferred()+ db.$transaction.mockImplementationOnce(async fn => { await gate.promise; return fn(db) })+ const first = ingestProductUsage('account-1', { ...report, id: 'receipt-1' }, now)+ await new Promise(resolve => setImmediate(resolve))const queued = ingestProductUsage('opted-out-while-queued', { ...report, id: 'another-receipt' }, now)- await Promise.resolve()- expect(db.$transaction).toHaveBeenCalledTimes(4)- for (let i = 0; i < 4; i++) db.productUsagePreference.findUnique.mockResolvedValueOnce({ enabled: true, revision: 0 })- db.productUsagePreference.findUnique.mockResolvedValueOnce({ enabled: false, revision: 1 })- release()- expect(await Promise.all(first)).toEqual(Array(4).fill({ accepted: true }))- expect(await queued).toMatchObject({ accepted: false, reason: 'CHOICE_CHANGED' })- expect(db.productUsageReceipt.create).toHaveBeenCalledTimes(4)+ choices()+ choices({ userId: 'opted-out-while-queued', enabled: false, revision: 1 })+ gate.resolve()+ expect(await first).toEqual({ accepted: true })+ expect(await queued).toMatchObject({ accepted: false, reason: 'CHOICE_CHANGED', enabled: false, revision: 1 })+ expect(receipts()).toEqual(['receipt-1'])+ })+ 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) })+ const first = ingestProductUsage('account-0', { ...report, id: 'receipt-0' }, now)+ await new Promise(resolve => setImmediate(resolve))+ const next = [1, 2, 3].map(i => ingestProductUsage(`account-${i}`, { ...report, id: `receipt-${i}` }, now))+ gate.resolve()+ expect(await Promise.all([first, ...next])).toEqual(Array(4).fill({ accepted: true }))+ expect(db.$transaction).toHaveBeenCalledTimes(2)+ expect(db.productUsagePreference.findMany.mock.calls[1][0].where.userId.in).toEqual(['account-1', 'account-2', 'account-3'])+ expect(receipts()).toEqual(['receipt-0', 'receipt-1', 'receipt-2', 'receipt-3'])+ expect(db.$runCommandRaw.mock.calls[1][0].updates.map((u: { q: { metric: string }; u: unknown }) => [u.q.metric, u.u]))+ .toEqual([['turns_started', { $inc: { value: 12 } }], ['turns_ended', { $inc: { value: 9 } }]])})it('stores only totals and an unlinked receipt, in one transaction', async () => {expect(await ingestProductUsage('private-account', report, now)).toEqual({ accepted: true })@@ -180,15 +202,20 @@ describe('aggregate ingestion', () => {{ q: { dayUtc: { $date: '2026-10-13T00:00:00.000Z' }, metric: 'turns_ended' }, u: { $inc: { value: 3 } }, upsert: true },],})- const stored = JSON.stringify([db.$runCommandRaw.mock.calls, db.productUsageReceipt.create.mock.calls])+ expect(db.productUsageReceipt.createMany).toHaveBeenCalledExactlyOnceWith({ data: [+ { id: report.id, expiresAt: new Date('2026-11-18T00:00:00.000Z') }] })+ const stored = JSON.stringify([db.$runCommandRaw.mock.calls, db.productUsageReceipt.createMany.mock.calls])for (const forbidden of ['private-account', 'userId', 'machineId', 'agentId', 'revision', 'counters', 'receivedAt']) expect(stored).not.toContain(forbidden)})it('rejects opted-out and stale queued uploads without receipts or counters', async () => {- db.productUsagePreference.findUnique.mockResolvedValue({ enabled: false, revision: 1 })+ choices({ userId: 'a', enabled: false, revision: 1 })expect(await ingestProductUsage('a', report, now)).toMatchObject({ accepted: false, reason: 'CHOICE_CHANGED' })- db.productUsagePreference.findUnique.mockResolvedValue({ enabled: true, revision: 2 })+ choices({ userId: 'a', enabled: true, revision: 2 })expect(await ingestProductUsage('a', report, now)).toMatchObject({ accepted: false, reason: 'CHOICE_CHANGED' })- expect(db.productUsageReceipt.create).not.toHaveBeenCalled()+ // A machine switched off before any saved choice is off too.+ db.analyticsMachineState.findMany.mockResolvedValueOnce([{ userId: 'a' }])+ expect(await ingestProductUsage('a', report, now)).toMatchObject({ accepted: false, reason: 'CHOICE_CHANGED', enabled: false })+ expect(db.productUsageReceipt.createMany).not.toHaveBeenCalled()expect(db.$runCommandRaw).not.toHaveBeenCalled()})it.each(['2026-09-08', '2026-10-14', '2026-02-30', 'bad'])('refuses expired/future/invalid day %s', async day => {@@ -196,14 +223,24 @@ describe('aggregate ingestion', () => {expect(db.$transaction).not.toHaveBeenCalled()})it('accepts a previously committed receipt without incrementing again', async () => {- db.productUsageReceipt.create.mockRejectedValue({ code: 'P2002' })- db.productUsageReceipt.findUnique.mockResolvedValue({ id: report.id })+ db.productUsageReceipt.findMany.mockResolvedValue([{ id: report.id }])expect(await ingestProductUsage('a', report, now)).toEqual({ accepted: true })+ expect(db.productUsageReceipt.createMany).not.toHaveBeenCalled()expect(db.$runCommandRaw).not.toHaveBeenCalled()})+ it('a report sent again while its first copy waits in the same batch counts once', async () => {+ const gate = deferred()+ db.$transaction.mockImplementationOnce(async fn => { await gate.promise; return fn(db) })+ const first = ingestProductUsage('a', { ...report, id: 'receipt-0' }, now)+ await new Promise(resolve => setImmediate(resolve))+ const twice = [ingestProductUsage('a', report, now), ingestProductUsage('a', report, now)]+ gate.resolve()+ expect(await Promise.all([first, ...twice])).toEqual(Array(3).fill({ accepted: true }))+ expect(receipts()).toEqual(['receipt-0', report.id])+ expect(db.$runCommandRaw.mock.calls[1][0].updates[0].u).toEqual({ $inc: { value: 4 } })+ })it('does not mistake a rolled-back aggregate creation race for a received report', async () => {db.$runCommandRaw.mockRejectedValue({ code: 'P2002' })- db.productUsageReceipt.findUnique.mockResolvedValue(null)await expect(ingestProductUsage('a', report, now)).rejects.toMatchObject({ code: 'P2002' })expect(db.$transaction).toHaveBeenCalledTimes(4)expect(delay).toHaveBeenCalledTimes(3)@@ -212,8 +249,8 @@ describe('aggregate ingestion', () => {db.$runCommandRaw.mockRejectedValueOnce({ code })expect(await ingestProductUsage('private-account', report, now)).toEqual({ accepted: true })expect(db.$transaction).toHaveBeenCalledTimes(2)- expect(db.productUsagePreference.findUnique).toHaveBeenCalledTimes(2)- expect(db.productUsageReceipt.create.mock.calls[0]).toEqual(db.productUsageReceipt.create.mock.calls[1])+ expect(db.productUsagePreference.findMany).toHaveBeenCalledTimes(2)+ expect(db.productUsageReceipt.createMany.mock.calls[0]).toEqual(db.productUsageReceipt.createMany.mock.calls[1])expect(delay).toHaveBeenCalledExactlyOnceWith(expect.any(Number))expect(vi.mocked(delay).mock.calls[0][0]).toBeGreaterThanOrEqual(25)expect(vi.mocked(delay).mock.calls[0][0]).toBeLessThan(75)@@ -222,16 +259,16 @@ describe('aggregate ingestion', () => {db.$runCommandRaw.mockRejectedValueOnce(new Error('Error code 24 (LockTimeout): Unable to acquire IX lock, labels: {"TransientTransactionError"}'))expect(await ingestProductUsage('a', report, now)).toEqual({ accepted: true })expect(db.$transaction).toHaveBeenCalledTimes(2)- expect(db.productUsageReceipt.create.mock.calls[0]).toEqual(db.productUsageReceipt.create.mock.calls[1])+ expect(db.productUsageReceipt.createMany.mock.calls[0]).toEqual(db.productUsageReceipt.createMany.mock.calls[1])expect(delay).toHaveBeenCalledOnce()})it('rechecks a sharing-off choice before retrying the transaction', async () => {db.$runCommandRaw.mockRejectedValueOnce({ code: 'P2034' })- db.productUsagePreference.findUnique.mockResolvedValueOnce({ enabled: true, revision: 0 })- .mockResolvedValueOnce({ enabled: false, revision: 1 })+ choices({ userId: 'a', enabled: true, revision: 0 })+ choices({ userId: 'a', enabled: false, revision: 1 })expect(await ingestProductUsage('a', report, now)).toMatchObject({ accepted: false, reason: 'CHOICE_CHANGED' })expect(db.$transaction).toHaveBeenCalledTimes(2)- expect(db.productUsageReceipt.create).toHaveBeenCalledOnce()+ expect(db.productUsageReceipt.createMany).toHaveBeenCalledOnce()})it('bounds persistent conflicts and does not retry unrelated storage errors', async () => {db.$transaction.mockRejectedValue({ code: 'P2034' })@@ -259,9 +296,9 @@ describe('aggregate ingestion', () => {} finally { clock.mockRestore() }})it('fails closed when the preference cannot be checked', async () => {- db.productUsagePreference.findUnique.mockRejectedValue(new Error('unavailable'))+ db.productUsagePreference.findMany.mockRejectedValue(new Error('unavailable'))await expect(ingestProductUsage('a', report, now)).rejects.toThrow()- expect(db.productUsageReceipt.create).not.toHaveBeenCalled()+ expect(db.productUsageReceipt.createMany).not.toHaveBeenCalled()})})@@ -343,9 +380,9 @@ it('bounds duplicate repair work and refuses to claim readiness without a uniqueit('setup ingestion never reads an account and expires after yesterday', async () => {const setup = { id: report.id, day: report.day, counters: { setup_desktop_sign_in_ok: 1 } }expect(await ingestSetupUsage(setup, now)).toEqual({ accepted: true })- expect(db.productUsagePreference.findUnique).not.toHaveBeenCalled()- expect(db.analyticsMachineState.findFirst).not.toHaveBeenCalled()- expect(JSON.stringify(db.productUsageReceipt.create.mock.calls)).not.toContain('setup_desktop')+ expect(db.productUsagePreference.findMany).not.toHaveBeenCalled()+ expect(db.analyticsMachineState.findMany).not.toHaveBeenCalled()+ expect(JSON.stringify(db.productUsageReceipt.createMany.mock.calls)).not.toContain('setup_desktop')expect(await ingestSetupUsage({ ...setup, day: '2026-10-11' }, now)).toMatchObject({ reason: 'EXPIRED' })expect(await ingestSetupUsage({ ...setup, day: '2026-10-12' }, now)).toMatchObject({ accepted: true })})@@ -353,14 +390,13 @@ it('setup ingestion never reads an account and expires after yesterday', async (it('Hub totals share the setup path: unlinked receipt, atomic totals, a retried receipt counts once', async () => {const hub = { id: report.id, day: report.day, counters: { hub_view_harness_visitor: 3, hub_fork: 1 } }expect(await ingestSetupUsage(hub, now)).toEqual({ accepted: true })- expect(db.productUsagePreference.findUnique).not.toHaveBeenCalled()+ expect(db.productUsagePreference.findMany).not.toHaveBeenCalled()expect(db.$runCommandRaw.mock.calls[0][0].updates).toEqual([{ q: { dayUtc: { $date: '2026-10-13T00:00:00.000Z' }, metric: 'hub_view_harness_visitor' }, u: { $inc: { value: 3 } }, upsert: true },{ q: { dayUtc: { $date: '2026-10-13T00:00:00.000Z' }, metric: 'hub_fork' }, u: { $inc: { value: 1 } }, upsert: true },])db.$runCommandRaw.mockClear()- db.productUsageReceipt.create.mockRejectedValue({ code: 'P2002' })- db.productUsageReceipt.findUnique.mockResolvedValue({ id: report.id })+ db.productUsageReceipt.findMany.mockResolvedValue([{ id: report.id }])expect(await ingestSetupUsage(hub, now)).toEqual({ accepted: true })expect(db.$runCommandRaw).not.toHaveBeenCalled()expect(await ingestSetupUsage({ ...hub, day: '2026-10-11' }, now)).toMatchObject({ reason: 'EXPIRED' })diff --git a/backend/src/lib/productUsage.ts b/backend/src/lib/productUsage.tsindex 51f9b4ff9..152479064 100644--- a/backend/src/lib/productUsage.ts+++ b/backend/src/lib/productUsage.ts@@ -8,10 +8,9 @@ import { prisma } from './prisma.js'import { PRODUCT_USAGE_DAYS, type ProductUsageChoice, type ProductUsageReport } from '../types/productUsage.js'import { ACTIVITY_DAYS, type ActivitySurface } from '../types/productUsageActivity.js'import { incrementUsageTotals, type UsageIncrement } from './productUsageWrite.js'-import { createUsageAdmission } from './productUsageAdmission.js'+import { createUsageBatch } from './productUsageBatch.js'const DAY = 86_400_000-const writeUsage = createUsageAdmission()type Db = Pick<Prisma.TransactionClient, 'productUsagePreference' | 'analyticsMachineState'>/** A pre-existing off choice wins over the new default. Never cache an enabled answer. */@@ -39,6 +38,19 @@ function validDay(day: string, now: Date): boolean {&& stamp <= today && stamp > today - PRODUCT_USAGE_DAYS * DAY}+/** [productUsageChoice] for several accounts at once, in two reads: a batch's permission checks. */+async function productUsageChoices(userIds: string[], db: Db): Promise<Map<string, ProductUsageChoice>> {+ const choices = new Map<string, ProductUsageChoice>()+ if (!userIds.length) return choices+ for (const saved of await db.productUsagePreference.findMany({ where: { userId: { in: userIds } },+ select: { userId: true, enabled: true, revision: true } })) choices.set(saved.userId, { enabled: saved.enabled, revision: saved.revision })+ const unsaved = userIds.filter(id => !choices.has(id))+ const off = new Set(unsaved.length ? (await db.analyticsMachineState.findMany({ where: { userId: { in: unsaved }, consent: 'off' },+ select: { userId: true } })).map(row => row.userId) : [])+ for (const id of unsaved) choices.set(id, { enabled: !off.has(id), revision: 0 })+ return choices+}+/** Identity is used for permission only. Neither it nor the report body reaches analytics storage. */export async function ingestProductUsage(userId: string, report: ProductUsageReport, now = new Date()) {if (!validDay(report.day, now)) return { accepted: false, reason: 'EXPIRED' }@@ -65,24 +77,25 @@ const STAFF_ACCOUNTS_MAX = 10_000* 2026 the team was 8–30% of the phone's people each day, and a TestFlight build's counts were the App Store's.* Kept, not dropped, so either can still be read on its own. Signed-out setup reports have no account to ask.*- * Read inside the admitted transaction, beside the permission check: a lookup ahead of admission would put a- * database read per report outside the bound that admission keeps on this process.+ * Read inside the batch's transaction, beside the permission check, one read for the accounts not seen yet.*/-async function apartPrefix(tx: Pick<Prisma.TransactionClient, 'user'>, context: ProductUsageContext | undefined,- userId: string | undefined): Promise<string> {- if (context?.channel === 'testing') return 'testing:'- if (!userId) return ''- let staff = staffAccounts.get(userId)- if (staff === undefined) {- const user = await tx.user.findUnique({ where: { id: userId }, select: { email: true } })- staff = !!user?.email.toLowerCase().endsWith(STAFF_EMAIL)- if (staffAccounts.size >= STAFF_ACCOUNTS_MAX) staffAccounts.clear()- staffAccounts.set(userId, staff)+async function apartPrefixes(tx: Pick<Prisma.TransactionClient, 'user'>, reports: QueuedReport[]): Promise<string[]> {+ const unknown = [...new Set(reports.filter(r => r.context?.channel !== 'testing' && r.userId && !staffAccounts.has(r.userId))+ .map(r => r.userId!))]+ if (unknown.length) {+ const emails = new Map((await tx.user.findMany({ where: { id: { in: unknown } }, select: { id: true, email: true } }))+ .map(user => [user.id, user.email]))+ if (staffAccounts.size + unknown.length > STAFF_ACCOUNTS_MAX) staffAccounts.clear()+ for (const id of unknown) staffAccounts.set(id, !!emails.get(id)?.toLowerCase().endsWith(STAFF_EMAIL))}- return staff ? 'staff:' : ''+ return reports.map(r => r.context?.channel === 'testing' ? 'testing:' : r.userId && staffAccounts.get(r.userId) ? 'staff:' : '')}export function resetStaffAccountsForTests(): void { staffAccounts.clear() }+interface QueuedReport { id: string; day: string; revision?: number; context?: ProductUsageContext; userId?: string+ increments: UsageIncrement[] }+type IngestResult = { accepted: true } | ({ accepted: false; reason: 'CHOICE_CHANGED' } & ProductUsageChoice)+async function ingestCounters(report: SetupUsageReport & { revision?: number; context?: ProductUsageContext }, userId?: string, now = new Date()) {if (report.context?.channel === 'development') return { accepted: true, reason: 'DEVELOPMENT' }const increments: UsageIncrement[] = []@@ -96,41 +109,63 @@ async function ingestCounters(report: SetupUsageReport & { revision?: number; coincrements.push({ dayUtc: new Date(Math.floor(now.getTime() / DAY) * DAY),metric: `health_${report.context.surface}_report_late`, value: 1 })}- // October's delivery audit found aggregate write conflicts. Retry the entire transaction,- // including permission, without extending a slow request or waiting a full client interval.- // At most four attempts; only fast conflicts may start another within the first second.- return writeUsage(async () => {- const started = performance.now()- for (let attempt = 0; ; attempt++) {- try {- return await prisma.$transaction(async tx => {- if (userId) {- const choice = await productUsageChoice(userId, tx)- if (!choice.enabled || choice.revision !== report.revision) return { accepted: false, reason: 'CHOICE_CHANGED', ...choice }- }- // Receipt and increments commit together; a lost HTTP response can be retried with the same id.- const apart = await apartPrefix(tx, report.context, userId)- await tx.productUsageReceipt.create({ data: {- id: report.id, expiresAt: new Date(Date.parse(report.day) + (PRODUCT_USAGE_DAYS + 1) * DAY),- } })- await incrementUsageTotals(tx, apart ? increments.map(i => ({ ...i, metric: apart + i.metric })) : increments)- return { accepted: true }+ return writeUsage({ id: report.id, day: report.day, revision: report.revision, context: report.context, userId, increments })+}++const writeUsage = createUsageBatch(commitReports)++/** One transaction for a batch: each report's permission, its receipt and the batch's summed totals commit together;+ * a lost HTTP response can be retried with the same id, and a receipt already committed counts once. Write conflicts+ * now come only from another process's batch: the whole batch is retried, permission included, at most four+ * attempts, and only fast conflicts may start another within the first second. */+async function commitReports(reports: QueuedReport[]): Promise<IngestResult[]> {+ const started = performance.now()+ for (let attempt = 0; ; attempt++) {+ try {+ return await prisma.$transaction(async tx => {+ const choices = await productUsageChoices([...new Set(reports.flatMap(r => r.userId ? [r.userId] : []))], tx)+ const results: IngestResult[] = reports.map(r => {+ const choice = r.userId ? choices.get(r.userId)! : null+ return !choice || (choice.enabled && choice.revision === r.revision) ? { accepted: true }+ : { accepted: false, reason: 'CHOICE_CHANGED', ...choice }})- } catch (error) {- // A competing first writer of a daily total is not a duplicate unless its receipt committed.- const code = (error as { code?: string } | null)?.code- if (code === 'P2002'- && await prisma.productUsageReceipt.findUnique({ where: { id: report.id }, select: { id: true } })) return { accepted: true }- const pause = 25 * 2 ** attempt + Math.floor(Math.random() * 50)- // A Mongo lock wait comes without a Prisma code, labelled transient, as Swarm's do (superTabs/store.ts).- const transient = error instanceof Error && error.message.includes('TransientTransactionError')- if ((code !== 'P2034' && code !== 'P2002' && !transient) || attempt >= 3- || performance.now() - started + pause >= 1000) throw error- await delay(pause)- if (performance.now() - started >= 1000) throw error- }+ const permitted = reports.filter((_, i) => results[i].accepted)+ const 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.+ const fresh: QueuedReport[] = []+ for (const r of permitted) if (!received.has(r.id)) { received.add(r.id); fresh.push(r) }+ if (!fresh.length) return results+ await tx.productUsageReceipt.createMany({ data: fresh.map(r => ({+ id: r.id, expiresAt: new Date(Date.parse(r.day) + (PRODUCT_USAGE_DAYS + 1) * DAY) })) })+ const apart = await apartPrefixes(tx, fresh)+ await incrementUsageTotals(tx, summed(fresh.flatMap((r, i) =>+ apart[i] ? r.increments.map(inc => ({ ...inc, metric: apart[i] + inc.metric })) : r.increments)))+ return results+ })+ } catch (error) {+ const code = (error as { code?: string } | null)?.code+ const pause = 25 * 2 ** attempt + Math.floor(Math.random() * 50)+ // A Mongo lock wait comes without a Prisma code, labelled transient, as Swarm's do (superTabs/store.ts).+ const transient = error instanceof Error && error.message.includes('TransientTransactionError')+ if ((code !== 'P2034' && code !== 'P2002' && !transient) || attempt >= 3+ || performance.now() - started + pause >= 1000) throw error+ await delay(pause)+ if (performance.now() - started >= 1000) throw error}- })+ }+}++/** One update per day and name, whichever reports added to it. */+function summed(increments: UsageIncrement[]): UsageIncrement[] {+ const totals = new Map<string, UsageIncrement>()+ for (const inc of increments) {+ const key = `${inc.dayUtc.toISOString()}|${inc.metric}`+ const seen = totals.get(key)+ if (seen) seen.value += inc.value+ else totals.set(key, { ...inc })+ }+ return [...totals.values()]}export type RelayUsageMetric = 'relay_desktop_opens' | 'relay_tui_opens' | 'relay_mobile_opens' | 'relay_web_opens'diff --git a/backend/src/lib/productUsageAdmission.test.ts b/backend/src/lib/productUsageAdmission.test.tsdeleted file mode 100644index 6cab8f362..000000000--- a/backend/src/lib/productUsageAdmission.test.ts+++ /dev/null@@ -1,58 +0,0 @@-import { afterEach, expect, it, vi } from 'vitest'-import { createUsageAdmission } from './productUsageAdmission.js'--afterEach(() => vi.useRealTimers())-const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => { resolve = r }); return { promise, resolve } }--it('runs four writes at once and admits the fifth when one finishes', async () => {- const write = createUsageAdmission(), gates = [deferred(), deferred(), deferred(), deferred()], seen: number[] = []- const running = gates.map((gate, i) => write(async () => { seen.push(i + 1); await gate.promise; return i + 1 }))- const fifth = write(async () => { seen.push(5); return 5 })- await Promise.resolve()- expect(seen).toEqual([1, 2, 3, 4])- gates[2].resolve()- expect(await running[2]).toBe(3)- await Promise.resolve()- expect(seen).toEqual([1, 2, 3, 4, 5])- expect(await fifth).toBe(5)- for (const gate of gates) gate.resolve()- expect(await Promise.all(running)).toEqual([1, 2, 3, 4])-})--it('with one slot, serializes concurrent transactions in arrival order and releases after an error', async () => {- const write = createUsageAdmission(32, 2000, 1), gate = deferred(), seen: number[] = []- const first = write(async () => { seen.push(1); await gate.promise; throw new Error('fixture failure') })- const failure = expect(first).rejects.toThrow('fixture failure')- const second = write(async () => { seen.push(2); return 'second' })- const third = write(async () => { seen.push(3); return 'third' })- await Promise.resolve()- expect(seen).toEqual([1])- gate.resolve()- await failure- expect(await Promise.all([second, third])).toEqual(['second', 'third'])- expect(seen).toEqual([1, 2, 3])-})--it('bounds waiting work behind every running slot and rejects overflow without executing it', async () => {- const write = createUsageAdmission(1, 2000, 2), gate = deferred(), skipped = vi.fn()- const running = [write(() => gate.promise), write(() => gate.promise)], queued = write(async () => 'accepted')- await expect(write(skipped)).rejects.toMatchObject({ code: 'USAGE_BUSY' })- expect(skipped).not.toHaveBeenCalled()- gate.resolve()- expect(await queued).toBe('accepted'); await Promise.all(running)-})--it('removes expired waiters; no late write, timer, or stuck admission remains', async () => {- vi.useFakeTimers()- const write = createUsageAdmission(2, 1000, 2), gate = deferred(), skipped = vi.fn()- const first = Promise.all([write(() => gate.promise), write(() => gate.promise)])- const expired = expect(write(skipped)).rejects.toMatchObject({ code: 'USAGE_BUSY' })- await vi.advanceTimersByTimeAsync(1000)- await expired- const next = write(async () => 'next')- gate.resolve(); await first- expect(await next).toBe('next')- expect(skipped).not.toHaveBeenCalled()- expect(vi.getTimerCount()).toBe(0)- expect(await write(async () => 'idle')).toBe('idle')-})diff --git a/backend/src/lib/productUsageAdmission.ts b/backend/src/lib/productUsageAdmission.tsdeleted file mode 100644index 79d66d1ae..000000000--- a/backend/src/lib/productUsageAdmission.ts+++ /dev/null@@ -1,32 +0,0 @@-/** Daily totals are shared rows. Admitting only a few of this process's report transactions at once keeps its- * own uploads from piling onto them; their write conflicts are retried by the transaction. One at a time was- * too few: a fleet's restart after each release filled the queue and refused reports with USAGE_BUSY.- * Only measurement waits here: bounded RAM, two seconds of queueing, no product traffic. */-export function createUsageAdmission(maxQueued = 32, waitMs = 2000, concurrency = 4) {- type Waiter = { ready: (release: () => void) => void; timer: ReturnType<typeof setTimeout> }- const waiting = new Set<Waiter>()- let running = 0- const unavailable = () => Object.assign(new Error('Usage measurement busy'), { code: 'USAGE_BUSY' })- function release(): void {- const next = waiting.values().next().value- if (!next) { running--; return }- waiting.delete(next)- clearTimeout(next.timer)- next.ready(release)- }- function acquire(): Promise<() => void> {- if (running < concurrency) { running++; return Promise.resolve(release) }- if (waiting.size >= maxQueued) return Promise.reject(unavailable())- return new Promise((ready, reject) => {- const waiter: Waiter = { ready, timer: setTimeout(() => {- waiting.delete(waiter)- reject(unavailable())- }, waitMs) }- waiting.add(waiter)- })- }- return async function write<T>(operation: () => Promise<T>): Promise<T> {- const done = await acquire()- try { return await operation() } finally { done() }- }-}diff --git a/backend/src/lib/productUsageBatch.test.ts b/backend/src/lib/productUsageBatch.test.tsnew file mode 100644index 000000000..598a1e2f0--- /dev/null+++ b/backend/src/lib/productUsageBatch.test.ts@@ -0,0 +1,78 @@+import { afterEach, expect, it, vi } from 'vitest'+import { createUsageBatch } from './productUsageBatch.js'++afterEach(() => vi.useRealTimers())+const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => { resolve = r }); return { promise, resolve } }+const tick = () => new Promise<void>(resolve => setImmediate(resolve))++it('commits one batch at a time, and what arrives meanwhile together in the next', async () => {+ const gate = deferred(), batches: number[][] = []+ const write = createUsageBatch<number, string>(async items => {+ batches.push(items)+ if (batches.length === 1) await gate.promise+ return items.map(item => `ok ${item}`)+ })+ const first = write(1)+ await tick()+ const rest = [2, 3, 4].map(item => write(item))+ await tick()+ expect(batches).toEqual([[1]])+ gate.resolve()+ expect(await first).toBe('ok 1')+ expect(await Promise.all(rest)).toEqual(['ok 2', 'ok 3', 'ok 4'])+ expect(batches).toEqual([[1], [2, 3, 4]])+})++it('a failed batch refuses only its own reports; the next batch still commits', async () => {+ const gate = deferred(), batches: number[][] = []+ const write = createUsageBatch<number, number>(async items => {+ batches.push(items)+ if (batches.length === 1) { await gate.promise; throw Object.assign(new Error('conflict'), { code: 'P2034' }) }+ return items+ })+ const first = write(1)+ const failed = expect(first).rejects.toMatchObject({ code: 'P2034' })+ await tick()+ const second = write(2)+ gate.resolve()+ await failed+ expect(await second).toBe(2)+ expect(batches).toEqual([[1], [2]])+})++it('splits a long queue into batches of at most the bound', async () => {+ const gate = deferred(), batches: number[][] = []+ const write = createUsageBatch<number, number>(async items => {+ batches.push(items)+ if (batches.length === 1) await gate.promise+ return items+ }, { maxBatch: 2 })+ const all = [write(0)]+ await tick()+ all.push(...[1, 2, 3, 4, 5].map(item => write(item)))+ gate.resolve()+ expect(await Promise.all(all)).toEqual([0, 1, 2, 3, 4, 5])+ expect(batches).toEqual([[0], [1, 2], [3, 4], [5]])+})++it('a full queue answers busy at once, and a report that waited too long is refused, not written', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const gate = deferred(), batches: number[][] = []+ const write = createUsageBatch<number, number>(async items => {+ batches.push(items)+ if (batches.length === 1) await gate.promise+ return items+ }, { maxQueued: 2, waitMs: 2000 })+ const first = write(0)+ await tick()+ const waited = write(1)+ vi.advanceTimersByTime(1500)+ const recent = write(2)+ await expect(write(3)).rejects.toMatchObject({ code: 'USAGE_BUSY' })+ vi.advanceTimersByTime(600)+ gate.resolve()+ expect(await first).toBe(0)+ await expect(waited).rejects.toMatchObject({ code: 'USAGE_BUSY' })+ expect(await recent).toBe(2)+ expect(batches).toEqual([[0], [2]])+})diff --git a/backend/src/lib/productUsageBatch.ts b/backend/src/lib/productUsageBatch.tsnew file mode 100644index 000000000..e827b8411--- /dev/null+++ b/backend/src/lib/productUsageBatch.ts@@ -0,0 +1,39 @@+/** Daily totals are shared rows. Every report a transaction of its own made each process's reports conflict with+ * one another on them: on 2026-10-28, 1,000 of the CLI's 1,269 rejected reports were write conflicts, and 64 reports+ * at once (a fleet after a release) refused 28. Here a process writes its reports one batch at a time: whatever+ * arrives while a batch commits goes together in the next, so its own reports never conflict, and the processes'+ * batches, a few at once, rarely do. Only measurement waits here: bounded RAM, two seconds of queueing, no product+ * traffic. A full queue or a long wait answers USAGE_BUSY, which the routes send back with a Retry-After. */+export function createUsageBatch<T, R>(commit: (items: T[]) => Promise<R[]>,+ { maxQueued = 2048, maxBatch = 256, waitMs = 2000 }: { maxQueued?: number; maxBatch?: number; waitMs?: number } = {}) {+ type Entry = { item: T; at: number; resolve: (result: R) => void; reject: (error: unknown) => void }+ const queue: Entry[] = []+ let running = false+ const busy = () => Object.assign(new Error('Usage measurement busy'), { code: 'USAGE_BUSY' })+ async function drain(): Promise<void> {+ running = true+ try {+ while (queue.length) {+ const batch: Entry[] = []+ for (const entry of queue.splice(0, maxBatch)) {+ if (Date.now() - entry.at > waitMs) entry.reject(busy())+ else batch.push(entry)+ }+ if (!batch.length) continue+ try {+ const results = await commit(batch.map(entry => entry.item))+ batch.forEach((entry, i) => entry.resolve(results[i]))+ } catch (error) {+ for (const entry of batch) entry.reject(error)+ }+ }+ } finally { running = false }+ }+ return (item: T): Promise<R> => {+ if (queue.length >= maxQueued) return Promise.reject(busy())+ return new Promise<R>((resolve, reject) => {+ queue.push({ item, at: Date.now(), resolve, reject })+ if (!running) void drain()+ })+ }+}diff --git a/backend/src/lib/rateLimit.test.ts b/backend/src/lib/rateLimit.test.tsnew file mode 100644index 000000000..8d81db05a--- /dev/null+++ b/backend/src/lib/rateLimit.test.ts@@ -0,0 +1,87 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++vi.mock('../utils/logger.js', () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn() } }))++import { createRateLimiter, useSharedRateCounter, type WindowCounter } from './rateLimit.js'+import { logger } from '../utils/logger.js'++/** What Redis is to the limiters: one fixed-window count per key, shared by every pod. */+function sharedCounter(): WindowCounter & { keys: string[] } {+ const counts = new Map<string, number>()+ const keys: string[] = []+ const counter = async (asked: Array<{ key: string; windowMs: number }>) => asked.map(({ key }) => {+ keys.push(key)+ const next = (counts.get(key) ?? 0) + 1+ counts.set(key, next)+ return next+ })+ return Object.assign(counter, { keys })+}++afterEach(() => {+ useSharedRateCounter(null)+ vi.mocked(logger.warn).mockClear()+ vi.mocked(logger.info).mockClear()+})++async function allowedOf(limiter: { allows(key: string, now?: number): Promise<boolean> }, key: string, times: number, now = 0) {+ let allowed = 0+ for (let i = 0; i < times; i++) if (await limiter.allows(key, now)) allowed+++ return allowed+}++describe('rate limiter', () => {+ it('without a shared counter, counts in this process, per key and per window', async () => {+ const limiter = createRateLimiter('route', 60_000, 3)++ expect(await allowedOf(limiter, 'user-1', 5)).toBe(3)+ expect(await allowedOf(limiter, 'user-2', 1)).toBe(1)+ expect(await allowedOf(limiter, 'user-1', 1, 60_000)).toBe(1)+ })++ it('with a shared counter, every pod spends one budget instead of each having its own', async () => {+ useSharedRateCounter(sharedCounter())+ const podA = createRateLimiter('route', 60_000, 3)+ const podB = createRateLimiter('route', 60_000, 3)++ const allowed = (await allowedOf(podA, 'user-1', 2)) + (await allowedOf(podB, 'user-1', 2)) + (await allowedOf(podA, 'user-1', 2))++ expect(allowed).toBe(3)+ })++ it('keeps limiters with different names apart and starts a new window on time', async () => {+ const counter = sharedCounter()+ useSharedRateCounter(counter)+ const route = createRateLimiter('route', 60_000, 1)+ const reports = createRateLimiter('reports', 60_000, 1)++ expect(await route.allows('user-1', 0)).toBe(true)+ expect(await reports.allows('user-1', 0)).toBe(true)+ expect(await route.allows('user-1', 59_999)).toBe(false)+ expect(await route.allows('user-1', 60_000)).toBe(true)+ expect(counter.keys).toEqual(['rl:route:user-1:0', 'rl:reports:user-1:0', 'rl:route:user-1:0', 'rl:route:user-1:1'])+ })++ it('while the shared counter fails, falls back to counting in this process, and says so once each way', async () => {+ let down = true+ const counter = sharedCounter()+ useSharedRateCounter(async (entries) => { if (down) throw new Error('redis circuit open'); return counter(entries) })+ const limiter = createRateLimiter('route', 60_000, 2)++ expect(await allowedOf(limiter, 'user-1', 4)).toBe(2)+ down = false+ await limiter.allows('user-2')+ await limiter.allows('user-2')++ expect(vi.mocked(logger.warn).mock.calls.filter(([m]) => String(m).includes('rate limits'))).toHaveLength(1)+ expect(vi.mocked(logger.info).mock.calls.filter(([m]) => String(m).includes('rate limits'))).toHaveLength(1)+ })++ it('reset forgets this process\' counts', async () => {+ const limiter = createRateLimiter('route', 60_000, 1)+ await limiter.allows('user-1')+ limiter.reset()++ expect(await limiter.allows('user-1')).toBe(true)+ })+})diff --git a/backend/src/lib/rateLimit.ts b/backend/src/lib/rateLimit.tsnew file mode 100644index 000000000..fe2892ca5--- /dev/null+++ b/backend/src/lib/rateLimit.ts@@ -0,0 +1,65 @@+import { logger } from '../utils/logger.js'+import { createWindowLimiter } from './windowLimiter.js'++/**+ * Rate limits every pod counts together (Stability 3.2).+ *+ * A process-local limit is multiplied by the number of processes and pods, and resets on every deploy: "60 a minute"+ * was 300 a minute on five pods. Here each limiter counts in a fixed window shared through Redis, keyed by its name,+ * the caller's key and the window. The server attaches that counter at startup (`useSharedRateCounter`); without it+ * (tests, scripts), and while it fails, each limiter counts in this process as before, which is the right way to fail:+ * a Redis outage must neither refuse everyone nor lift every limit.+ */++/** Counts one hit on each key, each in its own window, all at once, and returns each key's count after it. */+export type WindowCounter = (entries: Array<{ key: string; windowMs: number }>) => Promise<number[]>++let sharedCounter: WindowCounter | null = null+let sharedFailing = false++export function useSharedRateCounter(counter: WindowCounter | null): void {+ sharedCounter = counter+ sharedFailing = false+}++/** The counts after this hit on each key from the shared counter, or null when there is none or it failed. */+export async function countShared(entries: Array<{ key: string; windowMs: number }>): Promise<number[] | null> {+ const counter = sharedCounter+ if (!counter) return null+ try {+ const counts = await counter(entries)+ if (sharedFailing) {+ sharedFailing = false+ logger.info('[rate-limit] shared rate limits are back')+ }+ return counts+ } catch (err) {+ if (!sharedFailing) {+ sharedFailing = true+ logger.warn('[rate-limit] shared rate limits unavailable; counting per process', { error: err instanceof Error ? err.message : String(err) })+ }+ return null+ }+}++/** The shared key of one caller's window. */+export const windowKey = (name: string, key: string, windowMs: number, now: number): string =>+ `rl:${name}:${key}:${Math.floor(now / windowMs)}`++export interface RateLimiter {+ /** Counts one request for [key] and says whether it is within the allowance. */+ allows(key: string, now?: number): Promise<boolean>+ /** Forget this process' counts. Test seam. */+ reset(): void+}++export function createRateLimiter(name: string, windowMs: number, max: number): RateLimiter {+ const local = createWindowLimiter(windowMs, max)+ return {+ async allows(key, now = Date.now()) {+ const counts = await countShared([{ key: windowKey(name, key, windowMs, now), windowMs }])+ return counts ? counts[0] <= max : local.allows(key, now)+ },+ reset: () => local.reset(),+ }+}diff --git a/backend/src/lib/redisGuard.test.ts b/backend/src/lib/redisGuard.test.tsnew file mode 100644index 000000000..4e384abc9--- /dev/null+++ b/backend/src/lib/redisGuard.test.ts@@ -0,0 +1,133 @@+import { afterEach, describe, expect, it } from 'vitest'+import { createServer, type AddressInfo, type Server, type Socket } from 'node:net'+import { Redis } from 'ioredis'+import { createCircuitBreaker, CircuitOpenError } from './circuitBreaker.js'+import { guardRedisCommands, isRedisFailure, wasNotSent } from './redisGuard.js'++// A real ioredis client against a loopback server that speaks just enough RESP: while `answering` is false it reads+// commands and never replies (a Redis that is up but stuck); once answering it owes, and sends in order, a nil for every+// command it has read, as a Redis that comes unstuck does.+let server: Server | undefined+let client: Redis | undefined+const sockets = new Set<Socket>()+afterEach(async () => {+ client?.disconnect()+ for (const socket of sockets) socket.destroy()+ sockets.clear()+ await new Promise<void>(resolve => server ? server.close(() => resolve()) : resolve())+ server = client = undefined+})++async function stuckRedis(): Promise<{ client: Redis; answer: (on: boolean, reply?: string) => void; commands: () => number }> {+ let answering = false+ let reply = '$-1\r\n'+ let commands = 0+ const owed = new Map<Socket, number>()+ server = createServer(socket => {+ sockets.add(socket)+ owed.set(socket, 0)+ socket.on('data', (chunk: Buffer) => {+ const count = chunk.toString('utf8').split('\r\n').filter(line => line.startsWith('*')).length+ commands += count+ if (answering) socket.write(reply.repeat(count))+ else owed.set(socket, owed.get(socket)! + count)+ })+ })+ await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve))+ client = new Redis({ port: (server.address() as AddressInfo).port, host: '127.0.0.1', enableReadyCheck: false,+ enableOfflineQueue: false, maxRetriesPerRequest: 1, commandTimeout: 50, lazyConnect: true })+ await client.connect()+ const answer = (on: boolean, with_ = '$-1\r\n') => {+ answering = on+ reply = with_+ if (!on) return+ for (const [socket, count] of owed) { socket.write(reply.repeat(count)); owed.set(socket, 0) }+ }+ return { client, answer, commands: () => commands }+}++describe('guarded Redis commands', () => {+ it('a stuck Redis costs the command timeout a few times, then commands fail at once without being sent', async () => {+ const redis = await stuckRedis()+ guardRedisCommands(redis.client, createCircuitBreaker({ name: 'redis', failureThreshold: 3, openMs: 60_000 }))+ for (let i = 0; i < 3; i++) await expect(redis.client.get('k')).rejects.toThrow(/timed out/i)+ const sent = redis.commands()++ const started = Date.now()+ const refused = await redis.client.get('k').catch((err: unknown) => err)++ expect(refused).toBeInstanceOf(CircuitOpenError)+ expect(wasNotSent(refused)).toBe(true)+ expect(Date.now() - started).toBeLessThan(40)+ expect(redis.commands()).toBe(sent)+ })++ it('tries again after the open period and closes on an answer', async () => {+ let now = 0+ const redis = await stuckRedis()+ const breaker = createCircuitBreaker({ name: 'redis', failureThreshold: 1, openMs: 1_000, now: () => now })+ guardRedisCommands(redis.client, breaker)+ await expect(redis.client.get('k')).rejects.toThrow(/timed out/i)+ redis.answer(true)+ await expect(redis.client.get('k')).rejects.toBeInstanceOf(CircuitOpenError)++ now += 1_000+ await expect(redis.client.get('k')).resolves.toBeNull()++ expect(breaker.state()).toBe('closed')+ await expect(redis.client.set('k', 'v')).resolves.toBeNull()+ })++ it('leaves transactions and pipelines to the command timeout alone, so their batch is never split', async () => {+ const redis = await stuckRedis()+ guardRedisCommands(redis.client, createCircuitBreaker({ name: 'redis', failureThreshold: 1, openMs: 60_000 }))+ await expect(redis.client.get('k')).rejects.toThrow(/timed out/i)+ redis.answer(true)++ const results = await redis.client.pipeline().get('a').get('b').exec()++ expect(results).toEqual([[null, null], [null, null]])+ })++ it('a command that could not be written because Redis is away was not sent', async () => {+ const offline = new Redis({ lazyConnect: true, enableOfflineQueue: false })+ const error = await offline.get('k').catch((err: unknown) => err)++ expect(wasNotSent(error)).toBe(true)+ expect(wasNotSent(new Error('Command timed out'))).toBe(false)+ offline.disconnect()+ })++ it('an error Redis answers with is Redis working, not failing', async () => {+ const redis = await stuckRedis()+ const breaker = createCircuitBreaker({ name: 'redis', failureThreshold: 2, openMs: 60_000, isFailure: isRedisFailure })+ guardRedisCommands(redis.client, breaker)+ redis.answer(true, '-WRONGTYPE Operation against a key holding the wrong kind of value\r\n')+ for (let i = 0; i < 5; i++) await expect(redis.client.get('k')).rejects.toThrow(/WRONGTYPE/)++ expect(breaker.state()).toBe('closed')+ })++ it('lets a connection that is not ready yet send its own setup, so it can come back while the circuit is open', async () => {+ // A Redis that answers, including the INFO that ioredis' ready check sends before the connection is ready.+ server = createServer(socket => {+ sockets.add(socket)+ socket.on('data', (chunk: Buffer) => {+ // One answer per command in the chunk: a command starts with its `*` count, and INFO is the only one named alone.+ for (const command of chunk.toString('utf8').split(/(?=\*\d+\r\n)/)) {+ if (command) socket.write(/^\*1\r\n\$4\r\ninfo\r\n$/i.test(command) ? '$9\r\nloading:0\r\n' : '$-1\r\n')+ }+ })+ })+ await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve))+ client = new Redis({ port: (server.address() as AddressInfo).port, host: '127.0.0.1', enableOfflineQueue: false, lazyConnect: true })+ const breaker = createCircuitBreaker({ name: 'redis', failureThreshold: 1, openMs: 60_000 })+ await breaker.run(() => Promise.reject(new Error('Command timed out'))).catch(() => {})+ guardRedisCommands(client, breaker)++ await client.connect()++ expect(client.status).toBe('ready')+ await expect(client.get('k')).rejects.toBeInstanceOf(CircuitOpenError)+ })+})diff --git a/backend/src/lib/redisGuard.ts b/backend/src/lib/redisGuard.tsnew file mode 100644index 000000000..6ddbb7445--- /dev/null+++ b/backend/src/lib/redisGuard.ts@@ -0,0 +1,38 @@+import { ReplyError, type Command, type Redis } from 'ioredis'+import { CircuitOpenError, type CircuitBreaker } from './circuitBreaker.js'++/**+ * Puts a circuit breaker in front of every command a Redis connection sends (Stability 3.5).+ *+ * The bus' command connection already fails fast while Redis is away (no offline queue). A Redis that is up but stuck+ * is worse: each command waits out the command timeout. Through the breaker the first few do, then commands are refused+ * before they are written until Redis has had time to recover. Callers already treat a failed command as "unknown".+ *+ * Every command goes through `sendCommand`, so this one place covers the bus and every module that borrows its+ * connection. A transaction or pipeline (`sendCommand` with a stream) passes untouched: refusing one of its commands+ * would split the batch it writes at once. It still has the command timeout. So do the commands ioredis sends while it+ * (re)connects (its ready check, SELECT): refusing those would keep a recovered Redis from ever becoming ready. A+ * command of ours on a connection that is not ready fails at once anyway, with no offline queue.+ */+export function guardRedisCommands(redis: Redis, breaker: CircuitBreaker): void {+ const send = redis.sendCommand.bind(redis)+ redis.sendCommand = ((command: Command, stream?: unknown, node?: unknown) => {+ if (stream || redis.status !== 'ready') return (send as (c: Command, s?: unknown, n?: unknown) => unknown)(command, stream, node)+ breaker.run(() => {+ send(command)+ return command.promise+ }).catch((err: unknown) => {+ if (err instanceof CircuitOpenError) command.reject(err)+ })+ return command.promise+ }) as Redis['sendCommand']+}++/** Whether a Redis command failed for the connection, not with an answer: a reply error is Redis working. */+export const isRedisFailure = (err: unknown): boolean => !(err instanceof ReplyError)++/** True only when the command certainly never reached Redis, so doing its work another way cannot do it twice. A+ * timed-out command may still have been delivered. */+export function wasNotSent(err: unknown): boolean {+ return err instanceof CircuitOpenError || (err instanceof Error && err.message.startsWith("Stream isn't writeable"))+}diff --git a/backend/src/lib/redisRateCounter.test.ts b/backend/src/lib/redisRateCounter.test.tsnew file mode 100644index 000000000..0062c4564--- /dev/null+++ b/backend/src/lib/redisRateCounter.test.ts@@ -0,0 +1,44 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { execFileSync, spawn, type ChildProcess } from 'node:child_process'+import { createServer, type AddressInfo } from 'node:net'+import { Redis } from 'ioredis'+import { redisWindowCounter } from './redisRateCounter.js'++// Against a real redis-server, so the script is what is tested. Skipped where none is installed (CI's Linux runners).+const hasRedis = (() => { try { execFileSync('redis-server', ['--version'], { stdio: 'pipe' }); return true } catch { return false } })()++describe.skipIf(!hasRedis)('Redis window counter', () => {+ let server: ChildProcess+ let redis: Redis++ beforeAll(async () => {+ const port = await new Promise<number>((resolve) => {+ const probe = createServer().listen(0, '127.0.0.1', () => { const { port } = probe.address() as AddressInfo; probe.close(() => resolve(port)) })+ })+ server = spawn('redis-server', ['--port', String(port), '--bind', '127.0.0.1', '--save', '', '--appendonly', 'no'], { stdio: 'ignore' })+ redis = new Redis({ port, host: '127.0.0.1', lazyConnect: true, retryStrategy: () => 50 })+ for (let i = 0; i < 100; i++) { try { await redis.connect(); break } catch { await new Promise((r) => setTimeout(r, 50)) } }+ })+ afterAll(() => { redis?.disconnect(); server?.kill() })++ it('counts each key in one round trip and returns the counts after this hit', async () => {+ const count = redisWindowCounter(redis)++ const both = [{ key: 'rl:t:a:1', windowMs: 60_000 }, { key: 'rl:t:b:1', windowMs: 1_000 }]+ expect(await count(both)).toEqual([1, 1])+ expect(await count(both)).toEqual([2, 2])+ expect(await count([{ key: 'rl:t:a:1', windowMs: 60_000 }])).toEqual([3])+ })++ it('lets each key expire with its own window, so nothing is left behind', async () => {+ const count = redisWindowCounter(redis)+ await count([{ key: 'rl:t:minute:1', windowMs: 60_000 }, { key: 'rl:t:second:1', windowMs: 1_000 }])++ const [minute, second] = [await redis.pttl('rl:t:minute:1'), await redis.pttl('rl:t:second:1')]++ expect(minute).toBeGreaterThan(59_000)+ expect(minute).toBeLessThanOrEqual(60_000)+ expect(second).toBeGreaterThan(0)+ expect(second).toBeLessThanOrEqual(1_000)+ })+})diff --git a/backend/src/lib/redisRateCounter.ts b/backend/src/lib/redisRateCounter.tsnew file mode 100644index 000000000..8e6d4d03b--- /dev/null+++ b/backend/src/lib/redisRateCounter.ts@@ -0,0 +1,24 @@+import type { Redis } from 'ioredis'+import type { WindowCounter } from './rateLimit.js'++// One INCR per key, and its expiry (ARGV, one per key) set with the window's first hit: the window is in the key, so+// the expiry only cleans up. A single EVAL, not a MULTI, so it rides the command circuit breaker (lib/redisGuard.ts) and a stuck Redis+// costs a request nothing once the breaker is open.+const COUNT_SCRIPT = `+local counts = {}+for i, key in ipairs(KEYS) do+ local n = redis.call('INCR', key)+ if n == 1 then redis.call('PEXPIRE', key, ARGV[i]) end+ counts[i] = n+end+return counts`++/** The shared counter for lib/rateLimit.ts over a Redis connection. */+export function redisWindowCounter(redis: Pick<Redis, 'eval'>): WindowCounter {+ return async (entries) => {+ const keys = entries.map((e) => e.key)+ const windows = entries.map((e) => Math.max(1, Math.floor(e.windowMs)))+ const counts = await redis.eval(COUNT_SCRIPT, keys.length, ...keys, ...windows) as number[]+ return counts.map(Number)+ }+}diff --git a/backend/src/lib/shortTurnGuard.test.ts b/backend/src/lib/shortTurnGuard.test.tsnew file mode 100644index 000000000..ef02bdb3f--- /dev/null+++ b/backend/src/lib/shortTurnGuard.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest'+import { ShortTurnGuard } from './shortTurnGuard.js'++/** Turn starts `gapMs` apart, starting at the clock's current time; the guard's verdict for each. */+function starts(guard: ShortTurnGuard, clock: { now: number }, count: number, gapMs: number): string[] {+ const verdicts: string[] = []+ for (let i = 0; i < count; i++) {+ verdicts.push(guard.admit())+ clock.now += gapMs+ }+ return verdicts+}++describe('short turn guard', () => {+ it('relays 20 turn starts in a row under 10 s apart, then holds the next for 60 s, saying so once', () => {+ const clock = { now: 1_000_000 }+ const guard = new ShortTurnGuard(() => clock.now)++ const verdicts = starts(guard, clock, 25, 2_000)++ // The first start has no previous one; the 20 short gaps after it are relayed, the 21st is not.+ expect(verdicts.slice(0, 21)).toEqual(Array(21).fill('relay'))+ expect(verdicts.slice(21)).toEqual(['pause_started', 'paused', 'paused', 'paused'])+ })++ it('a gap of 10 s or more ends the run', () => {+ const clock = { now: 0 }+ const guard = new ShortTurnGuard(() => clock.now)+ starts(guard, clock, 20, 9_999)+ clock.now += 1 // this gap is exactly 10 s++ expect(starts(guard, clock, 21, 9_999)).toEqual(Array(21).fill('relay'))+ })++ it('relays again once the 60 s are over, and holds a loop that goes on again after another 20', () => {+ const clock = { now: 0 }+ const guard = new ShortTurnGuard(() => clock.now)+ starts(guard, clock, 22, 1_000)+ expect(guard.admit()).toBe('paused')+ clock.now += 60_000++ expect(starts(guard, clock, 21, 1_000)).toEqual(Array(21).fill('relay'))+ expect(guard.admit()).toBe('pause_started')+ })+})diff --git a/backend/src/lib/shortTurnGuard.ts b/backend/src/lib/shortTurnGuard.tsnew file mode 100644index 000000000..ffbf072ed--- /dev/null+++ b/backend/src/lib/shortTurnGuard.ts@@ -0,0 +1,37 @@+/**+ * A ceiling on a machine starting turns in a loop (Stability 3.2).+ *+ * A person starts a turn, reads the answer and starts another: seconds to minutes apart. An older CLI was measured+ * sending 106k turn-start signals a day, each one counted and relayed to every app watching. After+ * SHORT_TURN_RUN_MAX turn starts in a row each under SHORT_TURN_GAP_MS after the one before, the next ones are neither+ * counted nor relayed for SHORT_TURN_PAUSE_MS; the run starts again after that. The turns themselves run on the+ * machine, untouched; only the server's work for each signal stops.+ */+export const SHORT_TURN_GAP_MS = 10_000+export const SHORT_TURN_RUN_MAX = 20+export const SHORT_TURN_PAUSE_MS = 60_000++export type ShortTurnVerdict = 'relay' | 'pause_started' | 'paused'++export class ShortTurnGuard {+ private lastAt: number | undefined+ private run = 0+ private pausedUntil = 0++ constructor(private readonly now: () => number = () => Date.now()) {}++ admit(): ShortTurnVerdict {+ const at = this.now()+ if (at < this.pausedUntil) return 'paused'+ if (this.pausedUntil) {+ this.pausedUntil = 0+ this.lastAt = undefined+ this.run = 0+ }+ this.run = this.lastAt !== undefined && at - this.lastAt < SHORT_TURN_GAP_MS ? this.run + 1 : 0+ this.lastAt = at+ if (this.run <= SHORT_TURN_RUN_MAX) return 'relay'+ this.pausedUntil = at + SHORT_TURN_PAUSE_MS+ return 'pause_started'+ }+}diff --git a/backend/src/lib/sso.test.ts b/backend/src/lib/sso.test.tsindex 537045b42..da553fb09 100644--- a/backend/src/lib/sso.test.ts+++ b/backend/src/lib/sso.test.ts@@ -7,7 +7,7 @@ const state = vi.hoisted(() => ({vi.mock('./bus.js', () => ({ pub: state }))-import { consumeTx, createTx, exchangeCode, refreshAccessToken, SsoTokenError, type SsoTx } from './sso.js'+import { consumeTx, createTx, exchangeCode, refreshAccessToken, resetSsoTokenBreakers, SsoTokenError, type SsoTx } from './sso.js'const tx: SsoTx = {verifier: 'verifier',@@ -26,6 +26,7 @@ describe('SSO PKCE transaction store', () => {afterEach(() => {vi.unstubAllGlobals()+ resetSsoTokenBreakers()})it('stores an opaque one-time id in Redis for ten minutes', async () => {@@ -116,4 +117,23 @@ describe('SSO PKCE transaction store', () => {code: 'TOKEN_SERVICE_UNAVAILABLE',} satisfies Partial<SsoTokenError>)})++ it('stops asking a token service that keeps failing, and answers at once that it is unavailable', async () => {+ const fetchMock = vi.fn<typeof fetch>().mockRejectedValue(new Error('connect ETIMEDOUT'))+ vi.stubGlobal('fetch', fetchMock)+ for (let i = 0; i < 5; i++) await expect(refreshAccessToken(`refresh-${i}`, 'prod')).rejects.toMatchObject({ code: 'TOKEN_SERVICE_UNAVAILABLE' })+ const asked = fetchMock.mock.calls.length++ await expect(exchangeCode('code', 'verifier', 'http://127.0.0.1:5000/callback', 'prod')).rejects.toMatchObject({ code: 'TOKEN_SERVICE_UNAVAILABLE' })++ expect(fetchMock.mock.calls.length).toBe(asked)+ })++ it('does not take refused refresh tokens for an outage', async () => {+ const fetchMock = vi.fn<typeof fetch>().mockImplementation(async () => new Response(JSON.stringify({ error: 'invalid_grant' }), { status: 400 }))+ vi.stubGlobal('fetch', fetchMock)+ for (let i = 0; i < 10; i++) await expect(refreshAccessToken(`expired-${i}`, 'prod')).rejects.toMatchObject({ code: 'INVALID_GRANT' })++ expect(fetchMock).toHaveBeenCalledTimes(10)+ })})diff --git a/backend/src/lib/sso.ts b/backend/src/lib/sso.tsindex b304d7006..2c4fef421 100644--- a/backend/src/lib/sso.ts+++ b/backend/src/lib/sso.ts@@ -8,6 +8,8 @@import { createHash, randomBytes } from 'crypto'import { env } from '../config/env.js'import { pub } from './bus.js'+import { createCircuitBreaker, CircuitOpenError, type CircuitBreaker } from './circuitBreaker.js'+import { logger } from '../utils/logger.js'import {autonomousEnvironmentConfig,isAutonomousEnvironment,@@ -247,10 +249,47 @@ export class SsoTokenError extends Error {}}+// Per account plane, like the profile check (lib/ssoAuth.ts): a token service that keeps failing is answered for at once.+const tokenBreakers = new Map<AutonomousEnvironment, CircuitBreaker>()++function tokenBreaker(autonomousEnv: AutonomousEnvironment): CircuitBreaker {+ let breaker = tokenBreakers.get(autonomousEnv)+ if (!breaker) {+ breaker = createCircuitBreaker({+ name: `sso-token:${autonomousEnv}`,+ isFailure: (err) => !(err instanceof SsoTokenError) || err.code === 'TOKEN_SERVICE_UNAVAILABLE',+ onStateChange: (state) => {+ if (state === 'open') logger.warn('[sso] token service unreachable; failing fast', { autonomousEnv })+ else logger.info('[sso] token service circuit', { autonomousEnv, state })+ },+ })+ tokenBreakers.set(autonomousEnv, breaker)+ }+ return breaker+}++/** Test seam. */+export function resetSsoTokenBreakers(): void {+ tokenBreakers.clear()+}+async function requestTokens(grant: Record<string, string>,autonomousEnv: AutonomousEnvironment,clientId?: SsoClientId,+): Promise<SsoTokens> {+ try {+ return await tokenBreaker(autonomousEnv).run(() => postTokenRequest(grant, autonomousEnv, clientId))+ } catch (err) {+ if (err instanceof CircuitOpenError) throw new SsoTokenError('SSO token service unavailable', 'TOKEN_SERVICE_UNAVAILABLE')+ throw err+ }+}++async function postTokenRequest(+ grant: Record<string, string>,+ autonomousEnv: AutonomousEnvironment,+ clientId?: SsoClientId,): Promise<SsoTokens> {const config = autonomousEnvironmentConfig(autonomousEnv)const client = ssoClient(autonomousEnv, clientId)diff --git a/backend/src/lib/ssoAuth.resilience.test.ts b/backend/src/lib/ssoAuth.resilience.test.tsnew file mode 100644index 000000000..351d7e513--- /dev/null+++ b/backend/src/lib/ssoAuth.resilience.test.ts@@ -0,0 +1,86 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// Stability 3.5: a slow or down SSO must not hold every request for its full timeout.+vi.mock('../config/env.js', () => ({+ env: {+ SSO_PROFILE_URL: 'http://127.0.0.1:4010/profile',+ SSO_IDENTITY_URL: 'http://127.0.0.1:4010/identity',+ SSO_PROFILE_TIMEOUT_MS: 50,+ SSO_PROFILE_CACHE_TTL_MS: 60_000,+ SSO_PROFILE_STALE_GRACE_MS: 600_000,+ },+}))+const upsertFromSso = vi.hoisted(() => vi.fn())+vi.mock('../services/UserService.js', () => ({+ userService: { findByEmail: vi.fn(async () => null), findByExternal: vi.fn(async () => null), upsertFromSso },+ normalizeUserEmail: (email: string) => email.trim().toLowerCase(),+ isProvisionalUserEmail: () => false,+}))+vi.mock('./googleSubject.js', () => ({ scheduleGoogleSubjectFill: () => {} }))++import { authenticateAccessToken, clearSsoProfileCache, fetchSsoProfile, resetSsoBreakers } from './ssoAuth.js'++const ok = () => new Response(JSON.stringify({ status: 1, data: { id: 'external-1', email: '[email protected]' } }),+ { status: 200, headers: { 'Content-Type': 'application/json' } })+const rejected = () => new Response(JSON.stringify({ message: 'Invalid or expired JWT' }), { status: 401 })+/** An SSO that never answers: the call ends only when its signal aborts. */+const silent: typeof fetch = (_url, init) => new Promise((_, reject) => {+ init?.signal?.addEventListener('abort', () => reject(init.signal!.reason))+})++beforeEach(() => {+ upsertFromSso.mockImplementation(async ({ email }: { email: string }) => ({ id: 'user-1', email, role: 'user' }))+})+afterEach(() => {+ clearSsoProfileCache()+ resetSsoBreakers()+ vi.unstubAllGlobals()+ vi.useRealTimers()+})++describe('a slow SSO', () => {+ it('costs one timeout in all, not one per endpoint', async () => {+ const fetchMock = vi.fn<typeof fetch>(silent)+ const started = Date.now()++ await expect(fetchSsoProfile('token', fetchMock)).rejects.toMatchObject({ code: 'AUTH_SERVICE_UNAVAILABLE' })++ expect(fetchMock).toHaveBeenCalledOnce()+ expect(Date.now() - started).toBeLessThan(1_000)+ })++ it('answers at once once it is known to be down, without asking it again', async () => {+ const fetchMock = vi.fn<typeof fetch>(async () => { throw new Error('connect ECONNREFUSED') })+ vi.stubGlobal('fetch', fetchMock)+ for (let i = 0; i < 5; i++) {+ await expect(authenticateAccessToken(`token-${i}`)).rejects.toMatchObject({ code: 'AUTH_SERVICE_UNAVAILABLE' })+ }+ const asked = fetchMock.mock.calls.length++ await expect(authenticateAccessToken('token-next')).rejects.toMatchObject({ code: 'AUTH_SERVICE_UNAVAILABLE' })++ expect(fetchMock.mock.calls.length).toBe(asked)+ })++ it('is not taken for down when it rejects tokens', async () => {+ const fetchMock = vi.fn<typeof fetch>(async () => rejected())+ vi.stubGlobal('fetch', fetchMock)+ for (let i = 0; i < 10; i++) await expect(authenticateAccessToken(`bad-${i}`)).rejects.toMatchObject({ code: 'INVALID_TOKEN' })+ fetchMock.mockImplementation(async () => ok())++ await expect(authenticateAccessToken('good')).resolves.toMatchObject({ sub: 'user-1' })+ })++ it('does not sign out someone it validated a few minutes ago', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ vi.setSystemTime(1_000_000_000)+ const fetchMock = vi.fn<typeof fetch>(async () => ok())+ vi.stubGlobal('fetch', fetchMock)+ await authenticateAccessToken('working-token')+ vi.setSystemTime(1_000_000_000 + 5 * 60_000)+ fetchMock.mockImplementation(async () => { throw new Error('connect ECONNREFUSED') })++ await expect(authenticateAccessToken('working-token')).resolves.toMatchObject({ sub: 'user-1', email: '[email protected]' })+ await expect(authenticateAccessToken('never-seen')).rejects.toMatchObject({ code: 'AUTH_SERVICE_UNAVAILABLE' })+ })+})diff --git a/backend/src/lib/ssoAuth.ts b/backend/src/lib/ssoAuth.tsindex 9832e21b7..b2456defc 100644--- a/backend/src/lib/ssoAuth.ts+++ b/backend/src/lib/ssoAuth.ts@@ -10,6 +10,8 @@ import {type AutonomousEnvironment,} from './autonomousEnvironment.js'import { createSsoProfileCache, type SharedProfileStore } from './ssoProfileCache.js'+import { createCircuitBreaker, CircuitOpenError, type CircuitBreaker } from './circuitBreaker.js'+import { logger } from '../utils/logger.js'import { isHarnessAccessToken } from './harnessTokenFormat.js'import { scheduleGoogleSubjectFill } from './googleSubject.js'import type { SignInAttribution } from './signInAttribution.js'@@ -61,8 +63,48 @@ let sharedProfileStore: SharedProfileStore | null = nullconst profileCache = createSsoProfileCache({ttlMs: env.SSO_PROFILE_CACHE_TTL_MS,shared: () => sharedProfileStore,+ staleGraceMs: env.SSO_PROFILE_STALE_GRACE_MS,+ servesStale: (err) => err instanceof SsoAuthError && err.code === 'AUTH_SERVICE_UNAVAILABLE',})+// Per account plane: after a few validations in a row that the profile service could not answer, the next ones fail+// at once for a while instead of each waiting out the timeout (Stability 3.5). A rejected token is an answer.+const SSO_BREAKER_FAILURES = 5+const SSO_BREAKER_OPEN_MS = 10_000+const ssoBreakers = new Map<AutonomousEnvironment, CircuitBreaker>()++function ssoBreaker(autonomousEnv: AutonomousEnvironment): CircuitBreaker {+ let breaker = ssoBreakers.get(autonomousEnv)+ if (!breaker) {+ breaker = createCircuitBreaker({+ name: `sso-profile:${autonomousEnv}`,+ failureThreshold: SSO_BREAKER_FAILURES,+ openMs: SSO_BREAKER_OPEN_MS,+ isFailure: (err) => !(err instanceof SsoAuthError) || err.code === 'AUTH_SERVICE_UNAVAILABLE',+ onStateChange: (state) => {+ if (state === 'open') logger.warn('[sso] profile service unreachable; failing fast', { autonomousEnv })+ else logger.info('[sso] profile service circuit', { autonomousEnv, state })+ },+ })+ ssoBreakers.set(autonomousEnv, breaker)+ }+ return breaker+}++async function validateWithBreaker(token: string, autonomousEnv: AutonomousEnvironment): Promise<SsoProfile> {+ try {+ return await ssoBreaker(autonomousEnv).run(() => fetchSsoProfile(token, autonomousEnv))+ } catch (err) {+ if (err instanceof CircuitOpenError) throw new SsoAuthError('SSO profile service unavailable', 'AUTH_SERVICE_UNAVAILABLE')+ throw err+ }+}++/** Test seam. */+export function resetSsoBreakers(): void {+ ssoBreakers.clear()+}+export function useSharedSsoProfileStore(store: SharedProfileStore | null): void {sharedProfileStore = store}@@ -88,7 +130,10 @@ export async function fetchSsoProfile(const autonomousEnv = typeof autonomousEnvOrFetch === 'function' ? 'prod' : autonomousEnvOrFetchconst fetchImpl = typeof autonomousEnvOrFetch === 'function' ? autonomousEnvOrFetch : (fetchOverride ?? fetch)const { ssoProfileUrl, ssoIdentityUrl } = autonomousEnvironmentConfig(autonomousEnv)+ // One deadline for the whole validation: the profile fallback gets what the identity call left, not a second timeout.+ const deadline = AbortSignal.timeout(env.SSO_PROFILE_TIMEOUT_MS)const ask = async (url: string): Promise<Response> => {+ if (deadline.aborted) throw new SsoAuthError('SSO profile service unavailable', 'AUTH_SERVICE_UNAVAILABLE')try {return await fetchImpl(url, {method: 'GET',@@ -98,7 +143,7 @@ export async function fetchSsoProfile(Location: 'en-US',Authorization: `Bearer ${token}`,},- signal: AbortSignal.timeout(env.SSO_PROFILE_TIMEOUT_MS),+ signal: deadline,})} catch {throw new SsoAuthError('SSO profile service unavailable', 'AUTH_SERVICE_UNAVAILABLE')@@ -233,7 +278,7 @@ export async function authenticateAccessToken(}return user}- const profile = await profileCache.resolve(token, autonomousEnv, () => fetchSsoProfile(token, autonomousEnv))+ const profile = await profileCache.resolve(token, autonomousEnv, () => validateWithBreaker(token, autonomousEnv))const metadata = accessTokenMetadata(token)const email = normalizeUserEmail(profile.email)if (!email) throw new SsoAuthError('SSO profile service returned an invalid profile', 'AUTH_SERVICE_UNAVAILABLE')diff --git a/backend/src/lib/ssoProfileCache.test.ts b/backend/src/lib/ssoProfileCache.test.tsindex 47239a930..50941ec61 100644--- a/backend/src/lib/ssoProfileCache.test.ts+++ b/backend/src/lib/ssoProfileCache.test.ts@@ -230,3 +230,66 @@ describe('SSO profile cache', () => {expect(state.calls).toBe(2)})})++describe('while the profile service is unavailable', () => {+ const unavailable = Object.assign(new Error('SSO profile service unavailable'), { unavailable: true })+ const rejected = new Error('Invalid or expired SSO access token')+ const servesStale = (err: unknown) => (err as { unavailable?: boolean }).unavailable === true++ /** A cache that validated `token` once at `start`, then the clock moved on by `elapsed`. */+ async function validatedThen(elapsed: number, token = 'opaque-token') {+ let now = 1_000_000+ const cache = createSsoProfileCache({ ttlMs: 60_000, staleGraceMs: 600_000, servesStale, now: () => now })+ await cache.resolve(token, 'prod', loader().load)+ now += elapsed+ return cache+ }++ it('keeps a token it validated recently working, rather than signing everyone out', async () => {+ const cache = await validatedThen(60_000 + 599_000)+ const down = loader(unavailable)++ await expect(cache.resolve('opaque-token', 'prod', down.load)).resolves.toEqual(profile)++ expect(down.state.calls).toBe(1)+ })++ it('still asks the profile service first, and uses its answer when it has one', async () => {+ const cache = await validatedThen(60_001)+ const fresh = loader({ id: 'external-1', email: '[email protected]' })++ await expect(cache.resolve('opaque-token', 'prod', fresh.load)).resolves.toEqual({ id: 'external-1', email: '[email protected]' })+ })++ it('stops after the grace period', async () => {+ const cache = await validatedThen(60_000 + 600_001)++ await expect(cache.resolve('opaque-token', 'prod', loader(unavailable).load)).rejects.toBe(unavailable)+ })++ it('never keeps a token the profile service rejected, even within the grace period', async () => {+ const cache = await validatedThen(60_001)++ await expect(cache.resolve('opaque-token', 'prod', loader(rejected).load)).rejects.toBe(rejected)+ await expect(cache.resolve('opaque-token', 'prod', loader(unavailable).load)).rejects.toBe(unavailable)+ })++ it('never keeps a token past its own expiry', async () => {+ let now = 1_000_000+ const cache = createSsoProfileCache({ ttlMs: 60_000, staleGraceMs: 600_000, servesStale, now: () => now })+ const token = tokenExpiringAt(now + 120_000)+ await cache.resolve(token, 'prod', loader().load)+ now += 120_001++ await expect(cache.resolve(token, 'prod', loader(unavailable).load)).rejects.toBe(unavailable)+ })++ it('serves nothing stale when no grace period is set', async () => {+ let now = 1_000_000+ const cache = createSsoProfileCache({ ttlMs: 60_000, servesStale, now: () => now })+ await cache.resolve('opaque-token', 'prod', loader().load)+ now += 60_001++ await expect(cache.resolve('opaque-token', 'prod', loader(unavailable).load)).rejects.toBe(unavailable)+ })+})diff --git a/backend/src/lib/ssoProfileCache.ts b/backend/src/lib/ssoProfileCache.tsindex 7ba3b1683..4a51f6ddc 100644--- a/backend/src/lib/ssoProfileCache.ts+++ b/backend/src/lib/ssoProfileCache.ts@@ -17,6 +17,11 @@ import { createHash } from 'node:crypto'* What the TTL costs: a token revoked at the SSO keeps working HERE for at most that long. Only a* positive answer is remembered — a rejected token is asked about again every time — and an entry* never outlives the token's own `exp`.+ *+ * While the profile service cannot answer (down, slow, its circuit open), a token this process validated within+ * `staleGraceMs` past its TTL keeps working, so an SSO outage does not sign out everyone who is already working. Only+ * this process' own entries, only for errors `servesStale` accepts, never past the token's `exp`, and a token the+ * service rejects is forgotten at once.*/export interface CachedSsoProfile {@@ -47,11 +52,17 @@ interface Options {* seconds; nobody signing in should wait that long for a cache. */sharedReadTimeoutMs?: numbermaxEntries?: number+ /** How long past its TTL an entry may still answer while the profile service is unavailable. 0: never. */+ staleGraceMs?: number+ /** Whether a load error means the service could not answer (serve stale), not that it refused the token. */+ servesStale?: (err: unknown) => boolean}interface Entry {profile: CachedSsoProfileexpiresAt: number+ /** The last moment it may answer while the profile service is unavailable. */+ staleUntil?: number}/** The token's own expiry in ms, if it is a JWT that states one. Unverified: it can only SHORTEN the TTL. */@@ -88,7 +99,9 @@ function promptly<T>(work: Promise<T>, ms: number): Promise<T | null> {})}-export function createSsoProfileCache({ ttlMs, now = Date.now, shared = () => null, sharedReadTimeoutMs = 250, maxEntries = 50_000 }: Options): SsoProfileCache {+export function createSsoProfileCache({+ ttlMs, now = Date.now, shared = () => null, sharedReadTimeoutMs = 250, maxEntries = 50_000, staleGraceMs = 0, servesStale = () => false,+}: Options): SsoProfileCache {const entries = new Map<string, Entry>()const inFlight = new Map<string, Promise<CachedSsoProfile>>()@@ -96,26 +109,34 @@ export function createSsoProfileCache({ ttlMs, now = Date.now, shared = () => nuconst keyOf = (token: string, autonomousEnv: string): string =>`sso:profile:${createHash('sha256').update(`${autonomousEnv}:${token}`).digest('hex')}`- const remember = (key: string, profile: CachedSsoProfile, expiresAt: number): void => {+ const remember = (key: string, profile: CachedSsoProfile, expiresAt: number, tokenExpiry: number): void => {if (entries.size >= maxEntries && !entries.has(key)) {const oldest = entries.keys().next().valueif (oldest !== undefined) entries.delete(oldest)}- entries.set(key, { profile, expiresAt })+ const staleUntil = staleGraceMs > 0 ? Math.min(expiresAt + staleGraceMs, tokenExpiry) : undefined+ entries.set(key, { profile, expiresAt, ...(staleUntil !== undefined && staleUntil > expiresAt ? { staleUntil } : {}) })}- const fill = async (key: string, expiresAt: number, load: () => Promise<CachedSsoProfile>): Promise<CachedSsoProfile> => {+ const fill = async (key: string, expiresAt: number, tokenExpiry: number, load: () => Promise<CachedSsoProfile>, stale?: Entry): Promise<CachedSsoProfile> => {const store = shared()if (store) {// A store that is down — or merely slow — is a cache miss, not an authentication failure.const hit = parseEntry(await promptly(store.get(key), sharedReadTimeoutMs))if (hit && hit.expiresAt > now()) {- remember(key, hit.profile, Math.min(hit.expiresAt, expiresAt))+ remember(key, hit.profile, Math.min(hit.expiresAt, expiresAt), tokenExpiry)return hit.profile}}- const profile = await load()- remember(key, profile, expiresAt)+ let profile: CachedSsoProfile+ try {+ profile = await load()+ } catch (err) {+ if (stale?.staleUntil !== undefined && stale.staleUntil > now() && servesStale(err)) return stale.profile+ entries.delete(key)+ throw err+ }+ remember(key, profile, expiresAt, tokenExpiry)// Not awaited: the token is already proved, and a hung store must not hold the answer hostage.if (store) void Promise.resolve().then(() => store.set(key, JSON.stringify({ ...profile, expiresAt }), expiresAt - now())).catch(() => { /* best effort */ })return profile@@ -123,17 +144,20 @@ export function createSsoProfileCache({ ttlMs, now = Date.now, shared = () => nureturn {resolve(token, autonomousEnv, load) {- const expiresAt = Math.min(now() + ttlMs, tokenExpiresAt(token) ?? Infinity)+ const tokenExpiry = tokenExpiresAt(token) ?? Infinity+ const expiresAt = Math.min(now() + ttlMs, tokenExpiry)if (expiresAt <= now()) return load()const key = keyOf(token, autonomousEnv)const entry = entries.get(key)if (entry && entry.expiresAt > now()) return Promise.resolve(entry.profile)- if (entry) entries.delete(key)+ // An expired entry stays only as long as it could still answer during an outage.+ const stale = entry?.staleUntil !== undefined && entry.staleUntil > now() ? entry : undefined+ if (entry && !stale) entries.delete(key)const pending = inFlight.get(key)if (pending) return pending- const filling = fill(key, expiresAt, load).finally(() => { inFlight.delete(key) })+ const filling = fill(key, expiresAt, tokenExpiry, load, stale).finally(() => { inFlight.delete(key) })inFlight.set(key, filling)return filling},diff --git a/backend/src/lib/windowLimiter.ts b/backend/src/lib/windowLimiter.tsindex ed11a99ec..efcdee68c 100644--- a/backend/src/lib/windowLimiter.ts+++ b/backend/src/lib/windowLimiter.ts@@ -1,6 +1,6 @@/**- * A per-account fixed-window limiter, process-local by design: it spreads a route's budget, it is not- * the budget (the provider's own credit limit is).+ * A fixed-window limiter in this process. Routes use lib/rateLimit.ts, which counts across every pod and falls back to+ * this while the shared counter is unavailable.*/export interface WindowLimiter {/** Counts one request for [key] and says whether it is within the window's allowance. */diff --git a/backend/src/middlewares/routeRateLimit.test.ts b/backend/src/middlewares/routeRateLimit.test.tsnew file mode 100644index 000000000..cfbd630bc--- /dev/null+++ b/backend/src/middlewares/routeRateLimit.test.ts@@ -0,0 +1,266 @@+import Fastify, { type FastifyInstance } from 'fastify'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { env } from '../config/env.js'+import type { AuthUser } from '../lib/ssoAuth.js'+import { useSharedRateCounter } from '../lib/rateLimit.js'+import { createRouteRateLimit } from './routeRateLimit.js'++const user = (sub: string, extra: Partial<AuthUser> = {}): AuthUser => ({ sub, email: `${sub}@example.com`, role: 'user', autonomousEnv: 'prod', ...extra })++let app: FastifyInstance | undefined+afterEach(async () => {+ await app?.close()+ app = undefined+ useSharedRateCounter(null)+})++let signIns = 0++/** An app whose requests sign in with `Bearer <user>` (none: anonymous), between the limit's two hooks, as in server.ts. */+async function appWith(limits: { perPersonPerMinute: number; perCallerPerSecond: number; perPersonPerSecond?: number; refusalDelayMs?: number; maxHeldRefusals?: number }, now?: () => number) {+ app = Fastify({ forceCloseConnections: true })+ signIns = 0+ const limit = createRouteRateLimit({ refusalDelayMs: 0, ...limits, ...(now ? { now } : {}) })+ app.addHook('onRequest', limit.beforeSignIn)+ app.addHook('onRequest', async (request) => {+ const sub = /^Bearer (.+)$/.exec(request.headers.authorization ?? '')?.[1]+ if (sub) { signIns++; request.user = user(sub) }+ })+ app.addHook('onRequest', limit.afterSignIn)+ app.get('/api/things', async () => ({ ok: true }))+ app.get('/api/other', async () => ({ ok: true }))+ app.get('/api/tabs/:tabId/changes', async () => ({ ok: true }))+ app.get('/api/hosts/:machineId/changes', async () => ({ ok: true }))+ app.get('/api/tabs/:tabId/agents/:agentId/deliveries', async () => ({ ok: true }))+ app.get('/api/public', async () => ({ ok: true }))+ await app.ready()+ return (url: string, sub?: string) => app!.inject({ method: 'GET', url, headers: sub ? { authorization: `Bearer ${sub}` } : {} })+}++describe('per-route rate limit', () => {+ it('refuses a person past a route\'s per-second budget with 429 and when to come back, and only on that route', async () => {+ const get = await appWith({ perPersonPerMinute: 100, perCallerPerSecond: 3 }, () => 15_400)+ for (let i = 0; i < 3; i++) expect((await get('/api/things', 'loop')).statusCode).toBe(200)++ const refused = await get('/api/things', 'loop')++ expect(refused.statusCode).toBe(429)+ expect(refused.headers['retry-after']).toBe('1')+ expect(refused.json()).toMatchObject({ success: false, error: { code: 'RATE_LIMITED' } })+ expect((await get('/api/other', 'loop')).statusCode).toBe(200)+ expect((await get('/api/things', 'someone-else')).statusCode).toBe(200)+ })++ it('counts a route by its pattern, so changing an id does not buy a new budget', async () => {+ const get = await appWith({ perPersonPerMinute: 100, perCallerPerSecond: 2 }, () => 0)+ expect((await get('/api/tabs/t1/changes', 'loop')).statusCode).toBe(200)+ expect((await get('/api/tabs/t2/changes', 'loop')).statusCode).toBe(200)++ expect((await get('/api/tabs/t3/changes', 'loop')).statusCode).toBe(429)+ })++ it('someone else naming my machine does not spend my machine\'s budget', async () => {+ const get = await appWith({ perPersonPerMinute: 100, perCallerPerSecond: 2 }, () => 0)+ for (let i = 0; i < 5; i++) await get('/api/hosts/m1/changes', 'intruder')+ expect((await get('/api/hosts/m1/changes', 'intruder')).statusCode).toBe(429)++ expect((await get('/api/hosts/m1/changes', 'owner')).statusCode).toBe(200)+ expect((await get('/api/hosts/m1/changes', 'owner')).statusCode).toBe(200)+ })++ it('holds one machine to its own budget without spending its owner\'s other machines', async () => {+ const get = await appWith({ perPersonPerMinute: 100, perCallerPerSecond: 2 }, () => 0)+ await get('/api/hosts/m1/changes', 'owner'); await get('/api/hosts/m1/changes', 'owner')++ expect((await get('/api/hosts/m1/changes', 'owner')).statusCode).toBe(429)+ expect((await get('/api/hosts/m2/changes', 'owner')).statusCode).toBe(200)+ })++ it('gives each agent the route names its own budget, so a person\'s agents polling in the same second all get through', async () => {+ const get = await appWith({ perPersonPerMinute: 100, perCallerPerSecond: 2 }, () => 0)+ const statuses: number[] = []+ for (let agent = 0; agent < 10; agent++) {+ for (let poll = 0; poll < 2; poll++) statuses.push((await get(`/api/tabs/t1/agents/a${agent}/deliveries`, 'owner')).statusCode)+ }++ expect(statuses).toEqual(Array(20).fill(200))+ expect((await get('/api/tabs/t1/agents/a0/deliveries', 'owner')).statusCode).toBe(429)+ })++ it('still counts every call toward the person\'s per-minute ceiling, so new agent or machine ids buy nothing past it', async () => {+ let at = 0+ const get = await appWith({ perPersonPerMinute: 5, perCallerPerSecond: 100 }, () => at)+ for (let agent = 0; agent < 5; agent++) expect((await get(`/api/tabs/t1/agents/a${agent}/deliveries`, 'owner')).statusCode).toBe(200)++ const refused = await get('/api/tabs/t1/agents/a5/deliveries', 'owner')+ expect(refused.statusCode).toBe(429)+ expect(refused.headers['retry-after']).toBe('60')+ expect((await get('/api/hosts/m9/changes', 'owner')).statusCode).toBe(200)++ at = 60_000+ expect((await get('/api/tabs/t1/agents/a5/deliveries', 'owner')).statusCode).toBe(200)+ })++ it('caps a person per route and second however many agent ids they name, so made-up ids cannot burst the minute\'s budget', async () => {+ const get = await appWith({ perPersonPerMinute: 12_000, perCallerPerSecond: 50, perPersonPerSecond: 5 }, () => 0)+ for (let agent = 0; agent < 5; agent++) expect((await get(`/api/tabs/t1/agents/made-up-${agent}/deliveries`, 'loop')).statusCode).toBe(200)++ const refused = await get('/api/tabs/t1/agents/made-up-5/deliveries', 'loop')+ expect(refused.statusCode).toBe(429)+ expect(refused.headers['retry-after']).toBe('1')+ expect((await get('/api/hosts/m1/changes', 'loop')).statusCode).toBe(200)+ expect((await get('/api/tabs/t1/agents/a0/deliveries', 'someone-else')).statusCode).toBe(200)+ })++ it.each([+ ['across pods, through the shared counter', true],+ ['in one process, while the shared counter is unavailable', false],+ ])('never refuses 200 agents of one person each polling once a second, late polls and minute boundaries included, at the server\'s default limits (%s)', async (_, shared) => {+ if (shared) {+ const counts = new Map<string, number>()+ useSharedRateCounter(async (entries) => entries.map(({ key }) => { counts.set(key, (counts.get(key) ?? 0) + 1); return counts.get(key)! }))+ }+ let at = 0+ const get = await appWith({+ perPersonPerMinute: env.ROUTE_RATE_LIMIT_PER_PERSON_MINUTE,+ perCallerPerSecond: env.ROUTE_RATE_LIMIT_PER_CALLER_SECOND,+ perPersonPerSecond: env.ROUTE_RATE_LIMIT_PER_PERSON_SECOND,+ }, () => at)+ // Each agent polls on its own phase, for a little over three minutes. Odd rounds arrive 299 ms late, so one second's+ // window can see an agent twice. The rounds just before the minute boundaries are late (59: 299 ms, 179: 999 ms) and+ // round 119 is on time, so the second and fourth minutes see some agents 61 times.+ const lateMs = (round: number) => (round === 179 ? 999 : round === 119 ? 0 : round % 2 ? 299 : 0)+ const polls: Array<{ at: number; agent: number }> = []+ for (let agent = 0; agent < 200; agent++) {+ for (let round = 0; round < 190; round++) polls.push({ at: (agent * 5) % 1_000 + round * 1_000 + lateMs(round), agent })+ }+ polls.sort((a, b) => a.at - b.at)++ const refused: Array<{ at: number; agent: number }> = []+ for (const poll of polls) {+ at = poll.at+ if ((await get(`/api/tabs/t1/agents/a${poll.agent}/deliveries`, 'owner')).statusCode !== 200) refused.push(poll)+ }+ expect(refused.slice(0, 3)).toEqual([])+ }, 30_000) // 38,000 calls through Fastify: about a second on an idle machine++ it.each([+ ['per second', { perPersonPerMinute: 1_000, perCallerPerSecond: 50, perPersonPerSecond: 5 }, 1_000],+ ['per minute', { perPersonPerMinute: 5, perCallerPerSecond: 50, perPersonPerSecond: 500 }, 60_000],+ ])('once a person is over a route\'s ceiling %s, new agent ids are refused before sign-in and before the shared counter', async (_, limits, resetAt) => {+ let counted = 0+ const counts = new Map<string, number>()+ useSharedRateCounter(async (entries) => {+ counted+++ return entries.map(({ key }) => { counts.set(key, (counts.get(key) ?? 0) + 1); return counts.get(key)! })+ })+ let at = 0+ const get = await appWith(limits, () => at)+ for (let agent = 0; agent < 5; agent++) expect((await get(`/api/tabs/t1/agents/made-up-${agent}/deliveries`, 'loop')).statusCode).toBe(200)+ expect((await get('/api/tabs/t1/agents/made-up-5/deliveries', 'loop')).statusCode).toBe(429)+ const [signedIn, countedSoFar] = [signIns, counted]++ for (let agent = 6; agent < 100; agent++) expect((await get(`/api/tabs/t1/agents/made-up-${agent}/deliveries`, 'loop')).statusCode).toBe(429)+ expect([signIns, counted]).toEqual([signedIn, countedSoFar])+ expect((await get('/api/tabs/t1/agents/a0/deliveries', 'someone-else')).statusCode).toBe(200)++ at = resetAt+ expect((await get('/api/tabs/t1/agents/made-up-100/deliveries', 'loop')).statusCode).toBe(200)+ })++ it('holds at most so many refusals at once; past that each is answered at once', async () => {+ const get = await appWith({ perPersonPerMinute: 100, perCallerPerSecond: 1, refusalDelayMs: 200, maxHeldRefusals: 2 }, () => 0)+ expect((await get('/api/things', 'loop')).statusCode).toBe(200)++ const started = Date.now()+ const answeredAfter = await Promise.all(Array.from({ length: 5 }, async () => {+ expect((await get('/api/things', 'loop')).statusCode).toBe(429)+ return Date.now() - started+ }))+ answeredAfter.sort((a, b) => a - b)+ expect(answeredAfter.slice(0, 3).every((ms) => ms < 150)).toBe(true)+ expect(answeredAfter.slice(3).every((ms) => ms >= 190)).toBe(true)+ })++ it('over real connections, keeps at most the bound open on held refusals and answers someone else at once', async () => {+ await appWith({ perPersonPerMinute: 100_000, perCallerPerSecond: 1, refusalDelayMs: 1_000, maxHeldRefusals: 40 }, () => 0)+ const address = await app!.listen({ port: 0, host: '127.0.0.1' })+ const call = async (sub: string) => (await fetch(`${address}/api/things`, { headers: { authorization: `Bearer ${sub}` } })).status+ expect(await call('loop')).toBe(200)++ const started = Date.now()+ let answered = 0+ const loop = Array.from({ length: 100 }, () => call('loop').then((status) => { answered++; return status }))+ expect(await call('someone-else')).toBe(200)+ expect(Date.now() - started).toBeLessThan(900)+ // The 60 past the bound are answered before the first held one is due, a second after they started.+ await vi.waitFor(() => expect(answered).toBe(60), { timeout: 900, interval: 10 })+ expect(answered).toBe(60)++ expect(await Promise.all(loop)).toEqual(Array(100).fill(429))+ expect(Date.now() - started).toBeGreaterThanOrEqual(1_000)+ })++ it('does not count requests nobody signed in for', async () => {+ const get = await appWith({ perPersonPerMinute: 1, perCallerPerSecond: 1 })+ for (let i = 0; i < 5; i++) expect((await get('/api/public')).statusCode).toBe(200)+ })++ it('a limit of 0 is off', async () => {+ const get = await appWith({ perPersonPerMinute: 0, perCallerPerSecond: 0 })+ for (let i = 0; i < 5; i++) expect((await get('/api/hosts/m1/changes', 'owner')).statusCode).toBe(200)+ })++ it('counts every pod together through the shared counter, in one call per request, each count in its own window', async () => {+ const calls: Array<Array<{ key: string; windowMs: number }>> = []+ const counts = new Map<string, number>()+ useSharedRateCounter(async (entries) => {+ calls.push(entries)+ return entries.map(({ key }) => { counts.set(key, (counts.get(key) ?? 0) + 1); return counts.get(key)! })+ })+ const get = await appWith({ perPersonPerMinute: 100, perCallerPerSecond: 2 }, () => 0)+ await get('/api/hosts/m1/changes', 'owner')+ counts.set('rl:route-caller:GET /api/hosts/:machineId/changes:owner:m:m1:0', 2) // another pod spent the rest++ expect((await get('/api/hosts/m1/changes', 'owner')).statusCode).toBe(429)+ expect(calls[0]).toEqual([+ { key: 'rl:route-person:GET /api/hosts/:machineId/changes:owner:0', windowMs: 60_000 },+ { key: 'rl:route-caller:GET /api/hosts/:machineId/changes:owner:m:m1:0', windowMs: 1_000 },+ ])+ })++ it('refuses a token it has already refused in this window before signing it in, so a loop costs no sign-in', async () => {+ let at = 0+ const get = await appWith({ perPersonPerMinute: 100, perCallerPerSecond: 2 }, () => at)+ await get('/api/things', 'loop'); await get('/api/things', 'loop'); await get('/api/things', 'loop')+ const signedIn = signIns++ for (let i = 0; i < 5; i++) expect((await get('/api/things', 'loop')).statusCode).toBe(429)+ expect(signIns).toBe(signedIn)+ expect((await get('/api/other', 'loop')).statusCode).toBe(200)++ at = 1_000+ expect((await get('/api/things', 'loop')).statusCode).toBe(200)+ })++ it('remembers a machine\'s refusal for that machine only', async () => {+ const get = await appWith({ perPersonPerMinute: 100, perCallerPerSecond: 1 }, () => 0)+ await get('/api/hosts/m1/changes', 'owner'); await get('/api/hosts/m1/changes', 'owner')++ expect((await get('/api/hosts/m1/changes', 'owner')).statusCode).toBe(429)+ expect((await get('/api/hosts/m2/changes', 'owner')).statusCode).toBe(200)+ })++ it('holds each refusal a moment, so a client that ignores it cannot loop faster than that', async () => {+ const get = await appWith({ perPersonPerMinute: 100, perCallerPerSecond: 1, refusalDelayMs: 60 })+ let started = Date.now()+ expect((await get('/api/things', 'loop')).statusCode).toBe(200)+ expect(Date.now() - started).toBeLessThan(50)++ for (const remembered of [false, true]) {+ started = Date.now()+ expect((await get('/api/things', 'loop')).statusCode, `remembered: ${remembered}`).toBe(429)+ expect(Date.now() - started).toBeGreaterThanOrEqual(55)+ }+ })+})diff --git a/backend/src/middlewares/routeRateLimit.ts b/backend/src/middlewares/routeRateLimit.tsnew file mode 100644index 000000000..726a90cc6--- /dev/null+++ b/backend/src/middlewares/routeRateLimit.ts@@ -0,0 +1,133 @@+import { createHash } from 'node:crypto'+import type { FastifyReply, FastifyRequest } from 'fastify'+import { countShared, windowKey } from '../lib/rateLimit.js'+import { createWindowLimiter } from '../lib/windowLimiter.js'++/**+ * Ceilings on every signed-in request, per route (Stability 3.2): one person's looping client, or one machine's or+ * agent's, must not take the server from everyone else.+ *+ * A route is its method and pattern, so changing an id does not buy a new budget. Each request counts three times, in one+ * call to the shared counter, so every pod spends one budget (lib/rateLimit.ts):+ * - for its caller, per second: the agent the route names (`:agentId`), else the machine it names (`:machineId`), each+ * counted together with the person, else the person alone. With the person in the key, naming someone else's+ * machine spends only your own budget; per agent, a person's agents polling in the same second do not crowd out one+ * another. A second is short enough that a loop cannot spend a minute's worth at once.+ * - for the person, per second and per minute, whatever agent or machine ids the calls name: so new ids, real or made+ * up, buy nothing past either. Without the per-second one, each made-up id's fresh per-second budget would let a loop+ * spend the whole minute's in a second.+ * The limits are far above any client that works as designed, late polls included, and are set by the environment; 0+ * turns one off.+ * Requests nobody signed in for are not counted here. Clients already back off on 429; Retry-After says when the+ * window that refused ends.+ *+ * Two hooks around the sign-in gate. Counting needs the person, so it runs after sign-in (`afterSignIn`); but signing in+ * reads the account, and a loop that is already refused should not cost that on every call. A count only grows within+ * its window, so a refusal holds until that window ends: this pod remembers it by the sign-in token's digest, and+ * `beforeSignIn` answers that token's next calls at once. A person's ceiling refuses the token on the whole route, so new+ * agent or machine ids do not get past it to the sign-in and the counter; the caller's ceiling only that agent or machine.+ *+ * Each refusal is held `refusalDelayMs` before it is sent. A client that honours Retry-After never sees it; one that+ * ignores it and keeps N calls in flight is slowed to N calls a second, where a refusal sent at once would let it loop+ * as fast as the event loop can answer, at everyone else's expense. The hold is a timer, not work, and at most+ * `maxHeldRefusals` are held at once in a process: past that a refusal is sent at once, so held refusals never keep more+ * than that many connections open.+ */+export interface RouteRateLimits {+ perPersonPerMinute: number+ perCallerPerSecond: number+ perPersonPerSecond?: number+ refusalDelayMs?: number+ maxHeldRefusals?: number+ now?: () => number+}++type Hook = (request: FastifyRequest, reply: FastifyReply) => Promise<unknown>++const MINUTE_MS = 60_000+const SECOND_MS = 1_000+const REMEMBERED_REFUSALS_MAX = 50_000++export function createRouteRateLimit({ perPersonPerMinute, perCallerPerSecond, perPersonPerSecond = 0, refusalDelayMs = 1_000, maxHeldRefusals = 1_000, now = Date.now }: RouteRateLimits): { beforeSignIn: Hook; afterSignIn: Hook } {+ if (perPersonPerMinute <= 0 && perCallerPerSecond <= 0 && perPersonPerSecond <= 0) return { beforeSignIn: async () => {}, afterSignIn: async () => {} }+ const localPerson = createWindowLimiter(MINUTE_MS, perPersonPerMinute)+ const localPersonSecond = createWindowLimiter(SECOND_MS, perPersonPerSecond)+ const localCaller = createWindowLimiter(SECOND_MS, perCallerPerSecond)+ const refusedUntil = new Map<string, number>()+ let held = 0++ const routeOf = (request: FastifyRequest): string | undefined =>+ request.routeOptions.url ? `${request.method} ${request.routeOptions.url}` : undefined+ /** The agent or machine the route names, as a key suffix; '' when it names neither. */+ const namedCaller = (request: FastifyRequest): string => {+ const params = request.params as { agentId?: unknown; machineId?: unknown } | undefined+ if (typeof params?.agentId === 'string' && params.agentId) return `a:${params.agentId}`+ if (typeof params?.machineId === 'string' && params.machineId) return `m:${params.machineId}`+ return ''+ }+ /** The remembered-refusal keys of this call: its token on the route, and on the agent or machine the route names. */+ const refusalKeys = (request: FastifyRequest, route: string): { person: string; caller: string } | undefined => {+ const token = /^Bearer\s+(.+)$/i.exec(request.headers.authorization ?? '')?.[1]+ if (!token) return undefined+ const person = `${route}\n${createHash('sha256').update(token).digest('hex')}\n`+ return { person, caller: person + namedCaller(request) }+ }+ const refuse = async (reply: FastifyReply, until: number, at: number) => {+ if (refusalDelayMs > 0 && held < maxHeldRefusals) {+ held+++ try { await new Promise((resolve) => setTimeout(resolve, refusalDelayMs)) } finally { held-- }+ }+ return reply.code(429).header('Retry-After', String(Math.max(1, Math.ceil((until - at) / 1000)))).send({+ success: false,+ error: { code: 'RATE_LIMITED', message: 'Too many requests. Try again in a minute.' },+ })+ }+ const remember = (key: string, until: number, at: number): void => {+ if (refusedUntil.size >= REMEMBERED_REFUSALS_MAX) {+ for (const [k, end] of refusedUntil) if (end <= at) refusedUntil.delete(k)+ if (refusedUntil.size >= REMEMBERED_REFUSALS_MAX) refusedUntil.clear()+ }+ refusedUntil.set(key, until)+ }++ return {+ async beforeSignIn(request, reply) {+ if (refusedUntil.size === 0) return+ const route = routeOf(request)+ const keys = route && refusalKeys(request, route)+ if (!keys) return+ const at = now()+ for (const key of new Set([keys.person, keys.caller])) {+ const until = refusedUntil.get(key)+ if (until === undefined) continue+ if (until > at) return refuse(reply, until, at)+ refusedUntil.delete(key)+ }+ },++ async afterSignIn(request, reply) {+ const person = request.user?.sub+ const route = routeOf(request)+ if (!person || !route) return+ const named = namedCaller(request)+ const at = now()++ const checks: Array<{ name: string; key: string; windowMs: number; max: number; local: ReturnType<typeof createWindowLimiter>; personWide: boolean }> = []+ if (perPersonPerMinute > 0) checks.push({ name: 'route-person', key: `${route}:${person}`, windowMs: MINUTE_MS, max: perPersonPerMinute, local: localPerson, personWide: true })+ if (perPersonPerSecond > 0) checks.push({ name: 'route-person-second', key: `${route}:${person}`, windowMs: SECOND_MS, max: perPersonPerSecond, local: localPersonSecond, personWide: true })+ if (perCallerPerSecond > 0) {+ checks.push({ name: 'route-caller', key: `${route}:${person}${named ? `:${named}` : ''}`, windowMs: SECOND_MS, max: perCallerPerSecond, local: localCaller, personWide: !named })+ }++ const counts = await countShared(checks.map((c) => ({ key: windowKey(c.name, c.key, c.windowMs, at), windowMs: c.windowMs })))+ const over = checks.filter((c, i) => (counts ? counts[i] > c.max : !c.local.allows(c.key, at)))+ if (!over.length) return+ const untilOf = (cs: typeof over) => Math.max(...cs.map((c) => (Math.floor(at / c.windowMs) + 1) * c.windowMs))+ const keys = refusalKeys(request, route)+ const personWide = over.filter((c) => c.personWide)+ if (keys && personWide.length) remember(keys.person, untilOf(personWide), at)+ if (keys && personWide.length < over.length) remember(keys.caller, untilOf(over.filter((c) => !c.personWide)), at)+ return refuse(reply, untilOf(over), at)+ },+ }+}diff --git a/backend/src/routes/agentRoute.ts b/backend/src/routes/agentRoute.tsindex 3223a1f9c..168bddf4f 100644--- a/backend/src/routes/agentRoute.ts+++ b/backend/src/routes/agentRoute.ts@@ -24,7 +24,7 @@ import { validateBody } from '../middlewares/validation.js'import { sendSuccess, sendError } from '../utils/response.js'import { logger } from '../utils/logger.js'import { callHarnessLlm, harnessLlmConfigured, replyJson } from '../lib/harnessLlm.js'-import { createWindowLimiter } from '../lib/windowLimiter.js'+import { createRateLimiter } from '../lib/rateLimit.js'export const AGENT_ROUTE_PATH = '/api/route/agents'@@ -53,11 +53,11 @@ const BUDGET_MS_RANGE = { min: 3_000, max: 20_000, fallback: 10_000 } as constconst RATE_LIMIT_WINDOW_MS = 60_000const RATE_LIMIT_MAX = 60-const rateLimiter = createWindowLimiter(RATE_LIMIT_WINDOW_MS, RATE_LIMIT_MAX)+const rateLimiter = createRateLimiter('agent-route', RATE_LIMIT_WINDOW_MS, RATE_LIMIT_MAX)-export const routeRateLimitAllows = (userId: string, now = Date.now()): boolean => rateLimiter.allows(userId, now)+export const routeRateLimitAllows = (userId: string, now = Date.now()): Promise<boolean> => rateLimiter.allows(userId, now)-/** Test seam: process-local by design, like the analytics limiter it copies. */+/** Test seam: forgets this process' counts (lib/rateLimit.ts). */export const resetRouteRateLimits = (): void => rateLimiter.reset()const agentSchema = z.object({@@ -224,7 +224,7 @@ export async function agentRouteRoutes(app: FastifyInstance): Promise<void> {const body = req.bodyconst userId = req.user?.sub ?? ''- if (!routeRateLimitAllows(userId)) {+ if (!(await routeRateLimitAllows(userId))) {sendError(reply, 'Too many routing requests', 'RATE_LIMITED', 429)return}diff --git a/backend/src/routes/analytics.ts b/backend/src/routes/analytics.tsindex 5f196d110..a4f37cba0 100644--- a/backend/src/routes/analytics.ts+++ b/backend/src/routes/analytics.ts@@ -21,6 +21,7 @@ import { sendSuccess, sendError } from '../utils/response.js'import { logger } from '../utils/logger.js'import { analyticsOverview, buildConsentView } from '../lib/analyticsQuery.js'import { deleteLegacyProductUsage, setProductUsageChoice } from '../lib/productUsage.js'+import { createRateLimiter } from '../lib/rateLimit.js'import {ANALYTICS_SCHEMA_VERSION,CONSENT_STATES,@@ -39,22 +40,13 @@ const REPORT_BODY_LIMIT = 512 * 1024const RATE_LIMIT_WINDOW_MS = 60_000const RATE_LIMIT_MAX = 30-const rateBuckets = new Map<string, { count: number; resetAt: number }>()+const rateLimiter = createRateLimiter('analytics-report', RATE_LIMIT_WINDOW_MS, RATE_LIMIT_MAX)-export function rateLimitAllows(machineId: string, now = Date.now()): boolean {- const bucket = rateBuckets.get(machineId)- if (!bucket || now >= bucket.resetAt) {- rateBuckets.set(machineId, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS })- return true- }- if (bucket.count >= RATE_LIMIT_MAX) return false- bucket.count++- return true-}+export const rateLimitAllows = (machineId: string, now = Date.now()): Promise<boolean> => rateLimiter.allows(machineId, now)-/** Test seam: the limiter is process-local by design (one more report is not worth a Redis hop). */+/** Test seam: forgets this process' counts (lib/rateLimit.ts). */export function resetRateLimits(): void {- rateBuckets.clear()+ rateLimiter.reset()}const engineEnum = z.enum(ENGINES)@@ -125,7 +117,7 @@ async function machineAuth(req: FastifyRequest, reply: FastifyReply): Promise<vosendError(reply, 'Unknown machine', 'NO_MACHINE', 404)return}- if (!rateLimitAllows(machineId)) {+ if (!(await rateLimitAllows(machineId))) {sendError(reply, 'Too many analytics reports', 'RATE_LIMITED', 429)return}diff --git a/backend/src/routes/communityEdit.ts b/backend/src/routes/communityEdit.tsindex f4e2cc836..b5ea2a43c 100644--- a/backend/src/routes/communityEdit.ts+++ b/backend/src/routes/communityEdit.ts@@ -9,13 +9,13 @@ import type { FastifyInstance } from 'fastify'import { z } from 'zod'import { prisma } from '../lib/prisma.js'import { acceptGzipJson } from '../lib/gzipJson.js'-import { createWindowLimiter } from '../lib/windowLimiter.js'+import { createRateLimiter } from '../lib/rateLimit.js'import { validateBody, validateParams } from '../middlewares/validation.js'import { sendError, sendSuccess } from '../utils/response.js'import { environment, publicationEditSchema } from './community.js'const params = z.object({ id: z.string().uuid() })-const limiter = createWindowLimiter(10 * 60_000, 20)+const limiter = createRateLimiter('community-edit', 10 * 60_000, 20)export const resetEditRateLimits = (): void => limiter.reset()export async function communityEditRoutes(app: FastifyInstance): Promise<void> {@@ -25,7 +25,7 @@ export async function communityEditRoutes(app: FastifyInstance): Promise<void> {const post = await prisma.communityHarness.findFirst({ where: { id: req.params.id, autonomousEnv, deletedAt: null }, select: { authorId: true } })if (!post) return sendError(reply, 'This harness is unavailable.', 'NOT_FOUND', 404)if (post.authorId !== userId) return sendError(reply, 'Only its author can edit this harness.', 'FORBIDDEN', 403)- if (!limiter.allows(userId)) return sendError(reply, 'Please wait before saving again.', 'RATE_LIMITED', 429)+ if (!(await limiter.allows(userId))) return sendError(reply, 'Please wait before saving again.', 'RATE_LIMITED', 429)const { confirmed: _confirmed, license: _license, cover, harnessId, ...snapshot } = req.bodyawait prisma.communityHarness.updateMany({where: { id: req.params.id, autonomousEnv, authorId: userId, deletedAt: null },diff --git a/backend/src/routes/communityReports.ts b/backend/src/routes/communityReports.tsindex 171118594..85e20c8da 100644--- a/backend/src/routes/communityReports.ts+++ b/backend/src/routes/communityReports.ts@@ -13,7 +13,7 @@ import { z } from 'zod'import { communityStarters } from '../lib/communityAccess.js'import { communityReportReasons, communityReportTargets, fileReport, type ReportTarget } from '../lib/communityReports.js'import { prisma } from '../lib/prisma.js'-import { createWindowLimiter } from '../lib/windowLimiter.js'+import { createRateLimiter } from '../lib/rateLimit.js'import { requireAdmin } from '../middlewares/authMiddleware.js'import { validateBody } from '../middlewares/validation.js'import { sendError, sendSuccess } from '../utils/response.js'@@ -22,7 +22,7 @@ import { environment, publication } from './community.js'const target = { targetType: z.enum(communityReportTargets), targetId: z.string().regex(/^[a-z0-9-]{1,80}$/) }const reportBody = z.object({ ...target, reason: z.enum(communityReportReasons) }).strict()const reviewBody = z.object({ ...target, decision: z.enum(['restore', 'remove']) }).strict()-const limiter = createWindowLimiter(10 * 60_000, 20)+const limiter = createRateLimiter('community-report', 10 * 60_000, 20)export const resetReportRateLimits = (): void => limiter.reset()/** What a report is about: the publication it is on, and who made it (who may not report it). */@@ -68,7 +68,7 @@ export async function communityReportRoutes(app: FastifyInstance): Promise<void>const about = await reported(targetType, targetId, autonomousEnv)if (!about) return sendError(reply, 'This is no longer available.', 'NOT_FOUND', 404)if (about.authorId === userId) return sendError(reply, 'You cannot report your own work.', 'INVALID_REPORT', 400)- if (!limiter.allows(userId)) return sendError(reply, 'Please wait before reporting again.', 'RATE_LIMITED', 429)+ if (!(await limiter.allows(userId))) return sendError(reply, 'Please wait before reporting again.', 'RATE_LIMITED', 429)await fileReport({ autonomousEnv, targetType, targetId, harnessId: about.harnessId, userId, reason })sendSuccess(reply, { reported: true })})diff --git a/backend/src/routes/communityTranslate.ts b/backend/src/routes/communityTranslate.tsindex 8f2144000..bf6d89651 100644--- a/backend/src/routes/communityTranslate.ts+++ b/backend/src/routes/communityTranslate.ts@@ -11,7 +11,7 @@ import { communityLimits } from '../lib/communityContract.js'import { translateDraft, TranslationTooLong } from '../lib/communityTranslate.js'import { acceptGzipJson } from '../lib/gzipJson.js'import { harnessLlmConfigured } from '../lib/harnessLlm.js'-import { createWindowLimiter } from '../lib/windowLimiter.js'+import { createRateLimiter } from '../lib/rateLimit.js'import { validateBody } from '../middlewares/validation.js'import { sendError, sendSuccess } from '../utils/response.js'import { logger } from '../utils/logger.js'@@ -19,7 +19,7 @@ import { logger } from '../utils/logger.js'export const COMMUNITY_TRANSLATE_PATH = '/api/community/translate'/** A draft is translated once as it arrives, and again only when its author asks. */-const limiter = createWindowLimiter(10 * 60_000, 10)+const limiter = createRateLimiter('community-translate', 10 * 60_000, 10)export const resetTranslateRateLimits = (): void => limiter.reset()const bodySchema = z.object({@@ -36,7 +36,7 @@ export async function communityTranslateRoutes(app: FastifyInstance): Promise<voreturn sendError(reply, 'Translation is not available right now.', 'LLM_NOT_CONFIGURED', 503)}const userId = req.user!.sub- if (!limiter.allows(userId)) return sendError(reply, 'Please wait before translating again.', 'RATE_LIMITED', 429)+ if (!(await limiter.allows(userId))) return sendError(reply, 'Please wait before translating again.', 'RATE_LIMITED', 429)const started = Date.now()try {const result = await translateDraft(req.body)diff --git a/backend/src/routes/deviceKeys.ts b/backend/src/routes/deviceKeys.tsindex 35da5efa1..02758057d 100644--- a/backend/src/routes/deviceKeys.ts+++ b/backend/src/routes/deviceKeys.ts@@ -4,6 +4,7 @@ import { appendDeviceAck, appendDeviceKey, deviceKeysSeen, readDeviceAcks, readDimport { validateBody, validateQuery } from '../middlewares/validation.js'import { sendError, sendSuccess } from '../utils/response.js'import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'+import { createRateLimiter } from '../lib/rateLimit.js'const query = z.object({since: z.coerce.number().int().min(0).default(0),@@ -17,22 +18,10 @@ const query = z.object({* removal when someone asks. Generous for that; a loop cannot rebuild the log on every request. */const APPENDS_PER_MINUTE = 20/** At most [perMinute] calls per account per minute, per process. */-function limiter(perMinute: number): (userId: string, now?: number) => boolean {- const windows = new Map<string, { start: number; count: number }>()- return (userId, now = Date.now()) => {- const w = windows.get(userId)- if (!w || now - w.start >= 60_000) {- if (windows.size >= 10_000) windows.clear()- windows.set(userId, { start: now, count: 1 })- return true- }- return ++w.count <= perMinute- }-}-const allowAppend = limiter(APPENDS_PER_MINUTE)+const allowAppend = createRateLimiter('device-keys-append', 60_000, APPENDS_PER_MINUTE)// An acknowledgement is one "It's mine" a person pressed, on one device: the same budget, kept apart so// confirming devices never costs the log its appends. Each one replays the log to check it.-const allowAck = limiter(APPENDS_PER_MINUTE)+const allowAck = createRateLimiter('device-keys-ack', 60_000, APPENDS_PER_MINUTE)const body = z.object({ entry: z.record(z.string(), z.unknown()) }).strict()const acksQuery = z.object({ since: z.coerce.number().int().min(0).default(0) })const ackBody = z.object({ ack: z.record(z.string(), z.unknown()) }).strict()@@ -71,7 +60,7 @@ export async function deviceKeyRoutes(app: FastifyInstance): Promise<void> {// A key added here is one the account's machines let in as an app: never a team account's (lib/teamSession.ts),// whichever gate it came through. Its machine key goes over its own socket, which keeps it to that machine.if (isTeamSession(user)) return sendError(reply, TEAM_SESSION_MESSAGE, TEAM_SESSION_LIMITED, 403)- if (!allowAppend(user.sub)) return sendError(reply, 'Too many changes to your devices. Try again in a minute.', 'RATE_LIMITED', 429)+ if (!(await allowAppend.allows(user.sub))) return sendError(reply, 'Too many changes to your devices. Try again in a minute.', 'RATE_LIMITED', 429)const result = await appendDeviceKey(user.sub, req.body.entry, { kind: 'viewer', harnessSessionId: user.harnessSessionId })if (result.ok) return sendSuccess(reply, { head: result.head })if (result.status === 409) {@@ -95,7 +84,7 @@ export async function deviceKeyRoutes(app: FastifyInstance): Promise<void> {const user = req.user!// "It's mine" is the person's word: a team account never vouches for a key on the person's devices.if (isTeamSession(user)) return sendError(reply, TEAM_SESSION_MESSAGE, TEAM_SESSION_LIMITED, 403)- if (!allowAck(user.sub)) return sendError(reply, 'Too many changes to your devices. Try again in a minute.', 'RATE_LIMITED', 429)+ if (!(await allowAck.allows(user.sub))) return sendError(reply, 'Too many changes to your devices. Try again in a minute.', 'RATE_LIMITED', 429)const result = await appendDeviceAck(user.sub, req.body.ack)if (result.ok) return sendSuccess(reply, { created: result.created })sendError(reply, 'This acknowledgement was refused.', result.code, result.status)diff --git a/backend/src/routes/qrSignIn.ts b/backend/src/routes/qrSignIn.tsindex b86b0f1e4..607ea0b19 100644--- a/backend/src/routes/qrSignIn.ts+++ b/backend/src/routes/qrSignIn.ts@@ -8,6 +8,8 @@ import { clientIpFromHeaders, countryCodeFromHeaders } from '../lib/clientGeo.jsimport { validateBody } from '../middlewares/validation.js'import { sendError, sendSuccess } from '../utils/response.js'import { logger } from '../utils/logger.js'+import { createHash } from 'node:crypto'+import { createRateLimiter } from '../lib/rateLimit.js'/*** Sign a computer in by scanning its QR with a signed-in phone (lib/harnessSession.ts has the flow).@@ -27,23 +29,13 @@ const byCode = z.object({ code: z.string().min(1).max(128) }).strict()const byPoll = z.object({ pollToken: z.string().min(1).max(128) }).strict()const noBody = z.object({}).strict()-/** Per-process fixed windows: generous for a person, a wall for a loop. */-function limiter(perMinute: number) {- const windows = new Map<string, { start: number; count: number }>()- return (key: string, now = Date.now()): boolean => {- const w = windows.get(key)- if (!w || now - w.start >= 60_000) {- if (windows.size >= 20_000) windows.clear()- windows.set(key, { start: now, count: 1 })- return true- }- return ++w.count <= perMinute- }-}-const startLimit = limiter(10)-const pollLimit = limiter(90)-const answerLimit = limiter(20)-const ticketLimit = limiter(10)+/** Fixed windows every pod counts together (lib/rateLimit.ts): generous for a person, a wall for a loop. */+const startLimit = createRateLimiter('qr-start', 60_000, 10)+const pollLimit = createRateLimiter('qr-poll', 60_000, 90)+const answerLimit = createRateLimiter('qr-answer', 60_000, 20)+const ticketLimit = createRateLimiter('qr-ticket', 60_000, 10)+/** A poll token is a credential: it is counted by its digest, never written into a shared key. */+const pollKey = (pollToken: string): string => createHash('sha256').update(pollToken).digest('hex').slice(0, 32)const unavailable = (reply: FastifyReply, e: unknown, what: string) => {logger.error(`qr sign-in ${what} failed`, e)@@ -62,7 +54,7 @@ const noSuchCode = async (reply: FastifyReply, userId: string, code: string) =>export async function qrSignInRoutes(app: FastifyInstance): Promise<void> {app.post<{ Body: z.infer<typeof start> }>('/api/auth/qr/start', { preHandler: validateBody(start) }, async (req, reply) => {const ip = clientIpFromHeaders(req.headers, req.socket.remoteAddress)- if (!startLimit(ip ?? 'unknown')) return tooMany(reply)+ if (!(await startLimit.allows(ip ?? 'unknown'))) return tooMany(reply)if (req.body.kind === 'computer' && !req.body.computerId) {return sendError(reply, 'A computer names itself to sign in.', 'COMPUTER_ID_REQUIRED', 400)}@@ -76,12 +68,12 @@ export async function qrSignInRoutes(app: FastifyInstance): Promise<void> {})app.post<{ Body: z.infer<typeof byPoll> }>('/api/auth/qr/poll', { preHandler: validateBody(byPoll) }, async (req, reply) => {- if (!pollLimit(req.body.pollToken)) return tooMany(reply)+ if (!(await pollLimit.allows(pollKey(req.body.pollToken)))) return tooMany(reply)try { return sendSuccess(reply, await pollQrSignIn(req.body.pollToken)) } catch (e) { return unavailable(reply, e, 'poll') }})app.post<{ Body: z.infer<typeof byPoll> }>('/api/auth/qr/extend', { preHandler: validateBody(byPoll) }, async (req, reply) => {- if (!pollLimit(req.body.pollToken)) return tooMany(reply)+ if (!(await pollLimit.allows(pollKey(req.body.pollToken)))) return tooMany(reply)try {const expiresIn = await extendQrSignIn(req.body.pollToken)if (expiresIn === null) return sendError(reply, 'This code has expired.', 'QR_EXPIRED', 410)@@ -90,7 +82,7 @@ export async function qrSignInRoutes(app: FastifyInstance): Promise<void> {})app.post<{ Body: z.infer<typeof byPoll> }>('/api/auth/qr/claim', { preHandler: validateBody(byPoll) }, async (req, reply) => {- if (!pollLimit(req.body.pollToken)) return tooMany(reply)+ if (!(await pollLimit.allows(pollKey(req.body.pollToken)))) return tooMany(reply)try {const tokens = await claimQrSignIn(req.body.pollToken)if (!tokens) return sendError(reply, 'Nothing to claim: scan again.', 'QR_INVALID', 401)@@ -106,7 +98,7 @@ export async function qrSignInRoutes(app: FastifyInstance): Promise<void> {// The phone's half.app.post<{ Body: z.infer<typeof byCode> }>('/api/auth/qr/lookup', { preHandler: validateBody(byCode) }, async (req, reply) => {const userId = req.user!.sub- if (!answerLimit(userId)) return tooMany(reply)+ if (!(await answerLimit.allows(userId))) return tooMany(reply)try {if (isSpokenCode(req.body.code) && !(await spokenCodeGuessesLeft(userId))) return tooManyWrongCodes(reply)const ip = clientIpFromHeaders(req.headers, req.socket.remoteAddress)@@ -118,7 +110,7 @@ export async function qrSignInRoutes(app: FastifyInstance): Promise<void> {const answer = (approve: boolean) => async (req: { body: z.infer<typeof byCode>; user?: { sub: string; email: string } }, reply: FastifyReply) => {const user = req.user!- if (!answerLimit(user.sub)) return tooMany(reply)+ if (!(await answerLimit.allows(user.sub))) return tooMany(reply)try {if (isSpokenCode(req.body.code) && !(await spokenCodeGuessesLeft(user.sub))) return tooManyWrongCodes(reply)const out = await answerQrSignIn(req.body.code, approve ? { approve: true, userId: user.sub, email: user.email } : { approve: false })@@ -134,7 +126,7 @@ export async function qrSignInRoutes(app: FastifyInstance): Promise<void> {// A headless box: the phone approves before there is a code to scan, and hands the box the ticket.app.post('/api/auth/box/ticket', { preHandler: validateBody(noBody) }, async (req, reply) => {const user = req.user!- if (!ticketLimit(user.sub)) return tooMany(reply)+ if (!(await ticketLimit.allows(user.sub))) return tooMany(reply)try {const out = await issueBoxTicket(user.sub, user.email)logger.info('box ticket issued', { userId: user.sub })diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 3d5333134..881e314ac 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -75,7 +75,7 @@ const projectParams = tabParams.extend({ projectId: id })const refreshQuery = z.object({ refresh: z.literal('1').optional() })const approveBody = z.object({ scope: z.enum(['project', 'swarm']) }).strict()// What GitHub sends back: a sign-in's code and our state, and after an installation its id and action.-const callbackQuery = z.object({ code: z.string().max(512).optional(), state: z.string().max(4096).optional(),+const callbackQuery = z.object({ code: z.string().max(512).optional(), state: z.string().max(4096).optional(), error: z.string().max(128).optional(),installation_id: z.string().max(32).optional(), setup_action: z.string().max(32).optional() })const escapeHtml = (text: string) => text.replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!)@@ -94,7 +94,7 @@ const deliveryAction = z.discriminatedUnion('type', [z.object({ type: z.literal('hold'), claimId: id, reason: holdReason }).strict(),])const mentionQuery = z.object({ state: z.enum(['waiting', 'earlier']) }).strict()-const personDecisionQuery = agentQuery.extend({ state: z.enum(['open', 'answered']) }).strict()+const personDecisionQuery = agentQuery.extend({ state: z.enum(['open', 'answered', 'settled']) }).strict()const savePolicy = z.object({ revision: z.number().int().nonnegative().safe(), policy: routingPolicySchema }).strict()const stop = z.object({ assignmentId: id, receipt: z.string().min(1).max(2000) }).strict()const githubToken = z.object({ machineId: id }).strict()@@ -239,6 +239,9 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suconst request = approvalSecret && req.query.state ? readState(approvalSecret, req.query.state, Date.now()) : nullif (!request) return page('This link has expired', 'Go back to Harness and choose Approve again.', 400)const named = githubRepository(`https://github.com/${request.repository}`)+ // Cancel on GitHub's sign-in sends the person back with `error` and no code: they were told Harness was installed+ // (local Team account run, 2026-10-28).+ if (req.query.error) return page('Sign-in was cancelled', 'Nothing was approved. Go back to Harness and choose Approve to try again.')if (!req.query.code || !signIn || !named) {return page('Harness is installed', 'Go back to Harness and choose Approve, so this project can use it.')}diff --git a/backend/src/server.ts b/backend/src/server.tsindex 8ed6b7ce4..843023de0 100644--- a/backend/src/server.ts+++ b/backend/src/server.ts@@ -24,6 +24,9 @@ import { prisma } from './lib/prisma.js'import { backendReadinessChecks, createReadiness, drainBeforeClosing, processDrain } from './lib/readiness.js'import { configureSwarmStamps } from './superTabs/cache.js'import { useSharedSsoProfileStore } from './lib/ssoAuth.js'+import { useSharedRateCounter } from './lib/rateLimit.js'+import { createRouteRateLimit } from './middlewares/routeRateLimit.js'+import { redisWindowCounter } from './lib/redisRateCounter.js'import { selfProfileFromEnv } from './lib/selfProfile.js'import { drainAllSockets, openSocketCount, RELEASE_UPGRADE_SLOT, type SlotSocket } from './lib/wsServer.js'@@ -144,10 +147,21 @@ async function start(): Promise<void> {// Every process shares one memory of validated tokens; without it each worker asks the profile API// for itself. Attached before anything can authenticate — the REST gate below and the socket upgrades.useSharedSsoProfileStore(redisSsoProfileStore)+ // Rate limits count across every process and pod (lib/rateLimit.ts), not once per process.+ useSharedRateCounter(redisWindowCounter(pub))configureSwarmStamps(redisSwarmStamps(), { reads: env.SWARM_READ_CACHE === 'on', maxBytes: env.SWARM_CACHE_MB * 2 ** 20 })- // SSO access-token gate for the control API (data-plane auth happens before Fastify).+ // SSO access-token gate for the control API (data-plane auth happens before Fastify), inside the per-route limit+ // (Stability 3.2): a request counts for the person it signed in as, and a token already refused this window is+ // answered before it costs a sign-in.+ const routeLimit = createRouteRateLimit({+ perPersonPerMinute: env.ROUTE_RATE_LIMIT_PER_PERSON_MINUTE,+ perCallerPerSecond: env.ROUTE_RATE_LIMIT_PER_CALLER_SECOND,+ perPersonPerSecond: env.ROUTE_RATE_LIMIT_PER_PERSON_SECOND,+ })+ app.addHook('onRequest', routeLimit.beforeSignIn)registerAuthMiddleware(app)+ app.addHook('onRequest', routeLimit.afterSignIn)// Mongo always; Redis where one is configured. Each answers within 1 s or counts as down (lib/readiness.ts).const readiness = createReadiness(backendReadinessChecks(process.env, {diff --git a/backend/src/superTabs/autoReview.ts b/backend/src/superTabs/autoReview.tsnew file mode 100644index 000000000..73d3cbb5e--- /dev/null+++ b/backend/src/superTabs/autoReview.ts@@ -0,0 +1,135 @@+import { githubRepository } from '../github/repository.js'+import { agentDisplayName } from './agentNames.js'+import { activeWork, agentRole, nextConversationNumber, renderWorkTask, stableId, type Agent, type Author, type Conversation, type MessageDraft, type SuperTabState } from './model.js'+import { agentProjectId, groupProject, skillSetOf } from './projects.js'+import { recordAsked, recordRun } from './leaderboard/record.js'+import { renewLease } from './liveness.js'+import { downSince } from './machines.js'++// Reviews start the moment work is ready (Dee, 2026-10-28). The Lead hand-opened about 30 review groups that day, and one+// review request sat unanswered until its group was archived, so a privacy fix waited hours with no verdict. Now an+// Engineer's Ready for review that links a pull request of the project's repository opens the review in the same write,+// with a free Reviewer when there is one. Starting a new Reviewer stays with the Lead: routing reads the Lead machine's+// list and capacity (cli superTabs/routeCommand.ts), which a write here cannot (ruling in #610's plan).++/** The one check every review group carries. */+export const VERDICT_CHECK = 'Verdict with the reviewed revision'+/** Work that touches who can see or reach what is reviewed for that first. */+const PRIVACY = /\b(privacy|private|shar(e|es|ed|ing)|access|permissions?|confidential(ity)?|audiences?|visibility|credentials?|secrets?)\b/i+const PULL = /https:\/\/github\.com\/([A-Za-z0-9_-]+)\/([A-Za-z0-9_.-]+)\/pull\/[1-9][0-9]*\b/g+/** What of the Engineer's handoff a brief keeps: conversation.create takes briefs up to 8,000 characters. */+const HANDOFF_CHARS = 5000++/** The first pull request [text] links in [group]'s project repository; null when it links none there. */+export function projectPullRequest(state: SuperTabState, group: Conversation, text: string | null): string | null {+ const repository = githubRepository(groupProject(state, group).repository?.repositoryUrl)+ if (!repository || !text) return null+ for (const match of text.matchAll(PULL)) if (`${match[1]}/${match[2]}`.toLowerCase() === repository.fullName.toLowerCase()) return match[0]+ return null+}++/** Whether a Reviewer gave [group]'s verdict: one of its checks carries evidence. */+const verdictGiven = (group: Conversation): boolean => group.checks.some(c => c.evidence)++/** A review group whose Reviewer has given no verdict and that nobody cancelled. */+const verdictMissing = (group: Conversation): boolean =>+ !!group.reviewOf && group.assignment?.status !== 'cancelled' && !verdictGiven(group)++/** A review of [group] that is still open: not archived, not cancelled and with no verdict yet. A second review, by itself+ * or by hand, waits until it closes (commands.ts conversation.create). */+export const openReviewOf = (state: SuperTabState, group: Conversation): Conversation | undefined =>+ state.conversations.find(c => c.reviewOf === group.id && !c.archived && verdictMissing(c))++/** A review that may not be archived, by hand or by itself: no verdict, not cancelled, and the work it reviews still going.+ * Once that work is done or cancelled the review is moot. A review with no Reviewer has no assignment to cancel, so that+ * is its way out (ruling in #610). */+export const verdictPending = (state: SuperTabState, review: Conversation): boolean => {+ const reviewed = review.reviewOf ? state.conversations.find(c => c.id === review.reviewOf) : undefined+ return verdictMissing(review) && !!reviewed && activeWork(reviewed)+}++const free = (state: SuperTabState, agent: Agent) =>+ !state.conversations.some(c => c.leadId === agent.id || (activeWork(c) && c.assignment!.agentId === agent.id))++/**+ * The Reviewer for [group]'s review: the one that reviewed its earlier head while it is still free (a delta review), else+ * a free Reviewer of the project, one on another engine than the Engineer's first. Never one that is stopping, waiting to+ * resume a lost task, down (its session gone or its machine silent), or (`mayWork`) not allowed to take this work: on its+ * machine, or by the owner's rules (#610 review).+ */+function pickReviewer(state: SuperTabState, group: Conversation, engineer: Agent | undefined, earlier: Conversation | undefined,+ mayWork: (agent: Agent) => boolean, now: number): Agent | null {+ const projectId = groupProject(state, group).id+ const candidates = state.agents.filter(a => agentRole(a) === 'reviewer' && agentProjectId(state, a) === projectId &&+ a.workDecision !== 'stop' && !a.lostTask && !downSince(state, a, now) && free(state, a) && mayWork(a))+ const previous = candidates.find(a => a.id === earlier?.assignment?.agentId)+ return previous ?? candidates.find(a => a.configuration.engine !== engineer?.configuration.engine) ?? candidates[0] ?? null+}++function briefOf(group: Conversation, handoff: string, pullRequest: string, earlier: Conversation | undefined): string {+ const task = group.task+ const privacy = PRIVACY.test([task ? renderWorkTask(task) : group.brief, handoff].join('\n'))+ const kept = handoff.length > HANDOFF_CHARS ? `${handoff.slice(0, HANDOFF_CHARS)}… (the rest is in #${group.number})` : handoff+ return [+ ...privacy ? ['Privacy first: this work touches sharing, access or confidentiality. Check who can see or reach what before anything else.'] : [],+ `Give an independent verdict on the Engineer's revision of #${group.number} ${group.title}. Read only; do not change the code.`,+ ...earlier ? [`Delta review: #${earlier.number} reviewed the earlier head. Review only the changes since.`] : [],+ `The reviewed work:\n${task ? renderWorkTask(task) : group.brief}`,+ `Its acceptance checks:\n${group.checks.map(c => `- ${c.description}`).join('\n')}`,+ `The Engineer's handoff:\n${kept}`,+ `Pull request: ${pullRequest}`,+ `Pass #${group.number}'s independent check with your verdict and the revision you reviewed.`,+ ].join('\n\n')+}++export interface OpenedReview { review: Conversation; reviewer: Agent | null; messages: MessageDraft[] }++/**+ * Opens [group]'s review after its Engineer marked it ready with [handoff], which links [pullRequest]: a "Review: <title>"+ * group reviewing it, assigned to a free Reviewer that also joins [group] so it can pass the independent check, and one+ * line to the Lead, who can cancel it. With no free Reviewer the review waits, and the line asks the Lead to start one.+ * Its rows are the Swarm's own: written as the project's Lead with an auto-review source, as its lost-task and failed-start+ * notices are (liveness.ts), never as the Engineer (#610 review); [engineer] writes them only in a group with no Lead.+ */+export function openReview(state: SuperTabState, group: Conversation, handoff: string, pullRequest: string,+ context: { operationId: string; now: number; engineer: Author; mayWork: (agent: Agent) => boolean }): OpenedReview | null {+ const project = groupProject(state, group)+ // On Custom skills without a reviewer role there are no review groups (commands.ts requireCustomRole).+ if (state.paused || (skillSetOf(project) === 'custom' && !project.roles?.some(r => r.kind === 'reviewer'))) return null+ // Only a review that gave its verdict reviewed the earlier head: one cancelled before it reviewed nothing (#610 review).+ const earlier = state.conversations.filter(c => c.reviewOf === group.id && c.assignment && verdictGiven(c)).sort((a, b) => (b.number ?? 0) - (a.number ?? 0))[0]+ const engineer = state.agents.find(a => a.id === group.assignment?.agentId)+ const reviewer = pickReviewer(state, group, engineer, earlier, context.mayWork, context.now)+ const id = stableId(context.operationId, 'auto-review')+ const number = nextConversationNumber(state)+ state.groupCounter = number+ const brief = briefOf(group, handoff, pullRequest, earlier)+ const leadId = group.leadId+ const lead = state.agents.find(a => a.id === leadId)+ const author: Author = lead ? { kind: 'agent', id: lead.id, name: lead.name, displayName: agentDisplayName(state.agents, lead.id),+ membershipGeneration: lead.membershipGeneration } : context.engineer+ const review: Conversation = { id, ...(group.projectId ? { projectId: group.projectId } : {}), number, title: `Review: ${group.title}`.slice(0, 160),+ leadId, agentIds: leadId ? [leadId] : [], archived: false, brief, reviewOf: group.id, assignment: null, lastMessageSequence: 0,+ checks: [{ description: VERDICT_CHECK, independent: false, id: stableId(id, '0'), evidence: null, passedBy: null }] }+ state.conversations.push(review)+ recordAsked(review, group.requesterId, context.now)+ const row = (key: string, text: string, recipients: string[]): MessageDraft => ({ id: stableId(context.operationId, 'auto-review', key),+ conversationId: id, author, text, replyTo: null, recipients, source: { kind: 'auto-review', reviewOf: group.id } })+ const messages = [row('brief', brief, [])]+ if (reviewer) {+ review.agentIds.push(reviewer.id)+ if (!group.agentIds.includes(reviewer.id)) group.agentIds.push(reviewer.id)+ delete reviewer.workDecision+ delete reviewer.releaseId+ review.assignment = { id: stableId(id, 'assignment'), agentId: reviewer.id, status: 'working', configuration: structuredClone(reviewer.configuration),+ execution: { machineId: reviewer.machineId, harnessId: reviewer.harnessId, machineOwnerId: reviewer.machineOwnerId }, result: null }+ renewLease(review.assignment, context.now)+ recordRun(state, review, review.assignment, reviewer, context.now)+ messages.push(row('assign', `${brief}\n\nAcceptance checks:\n- ${VERDICT_CHECK}`, [reviewer.id]))+ }+ const name = reviewer && (reviewer.displayName ?? reviewer.name)+ if (leadId) messages.push(row('lead', reviewer+ ? `Review opened by itself for #${group.number}: ${name} reviews it. Cancel it here if it is not needed.`+ : `Review opened by itself for #${group.number}, but no Reviewer is free. Route it and start one.`, [leadId]))+ return { review, reviewer, messages }+}diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 12b7bddb6..2af9ba182 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -1190,6 +1190,184 @@ describe('Reviewer role', () => {expect(f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'review', result: 'Head 789' }, builderActor).messages[0]!.recipients).toEqual([lead])})+ describe('a review the Swarm opens by itself', () => {+ const pr = 'https://github.com/example/project/pull/42'+ /** reviewed() with the project's repository, the Builder working, and a second Reviewer `fresh` that is not in the group. */+ function ready(engine: 'claude' | 'codex' = 'claude') {+ const setup = reviewed()+ const { f, leadActor, group, builder } = setup+ f.state.projects![0]!.repository = { machineId: 'host', cwd: '/repo', repositoryUrl: 'https://github.com/Example/project.git' }+ const startId = f.run({ type: 'agent.start', request: request('lead', { role: 'reviewer', engine, name: 'Second reviewer' }), ...via } as Command, leadActor,+ { contribution, ...decisionIn('lead') }).result.startId as string+ f.run({ type: 'agent.startDispatch', startId }, leadActor, { contribution })+ const fresh = f.run({ type: 'agent.started', startId, harnessId: 'native-fresh', configuration: { ...config, engine } }, leadActor, { contribution }).result.agentId as string+ const built = f.run({ type: 'work.assign', conversationId: group, agentId: builder }).result.assignmentId as string+ const builderActor: Actor = { kind: 'agent', agentId: builder, machineOwnerId: 'host-owner' }+ const markReady = (result: string | null, actor: Actor = builderActor) =>+ f.run({ type: 'work.status', conversationId: group, assignmentId: built, status: 'review', result }, actor)+ const reviews = () => f.state.conversations.filter(c => c.reviewOf === group)+ return { ...setup, fresh, built, builderActor, markReady, reviews }+ }++ it('opens "Review: <group>" with the handoff, the checks and the link, assigns a free Reviewer and adds it to the reviewed group', () => {+ const { f, lead, group, reviewer, fresh, markReady, reviews } = ready()+ f.run({ type: 'agent.release', agentId: reviewer, decision: 'stop' }, { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' })+ const handoff = `Ready: yes. Revision a1b2c3..d4e5f6. Unverified: nothing.\n${pr}`+ const effects = markReady(handoff)+ expect(reviews()).toHaveLength(1)+ const review = reviews()[0]!+ expect(review).toMatchObject({ title: 'Review: Offline editing', number: 2, assignment: { agentId: fresh, status: 'working' },+ checks: [{ description: 'Verdict with the reviewed revision', independent: false, evidence: null, passedBy: null }] })+ expect(review.brief).toContain('Save edits while offline.')+ expect(review.brief).toContain('- Reconnect preserves the edits.')+ expect(review.brief).toContain(handoff)+ expect(review.brief).toContain(`Pull request: ${pr}`)+ expect(review.brief).not.toContain('Privacy first')+ expect(f.state.conversations.find(c => c.id === group)!.agentIds).toContain(fresh)+ const toReviewer = effects.messages.find(m => m.conversationId === review.id && m.recipients.includes(fresh))!+ expect(toReviewer.text).toBe(`${review.brief}\n\nAcceptance checks:\n- Verdict with the reviewed revision`)+ const toLead = effects.messages.filter(m => m.conversationId === review.id && m.recipients.includes(lead))+ expect(toLead.map(m => m.text)).toEqual(['Review opened by itself for #1: Second reviewer reviews it. Cancel it here if it is not needed.'])+ // Every row of it is the Swarm's own, written as the project's Lead as its other notices are, never as the Engineer.+ expect(effects.messages.filter(m => m.conversationId === review.id).map(m => [m.author.kind, m.author.id, m.source?.kind]))+ .toEqual([['agent', lead, 'auto-review'], ['agent', lead, 'auto-review'], ['agent', lead, 'auto-review']])+ })++ it('prefers a free Reviewer on another engine than the Engineer\'s', () => {+ // The Engineer runs on Codex (config). `reviewer` comes first but runs on Codex too; `fresh` runs on Claude.+ const { f, fresh, reviewer, markReady, reviews } = ready('claude')+ f.state.agents.find(a => a.id === reviewer)!.configuration.engine = 'codex'+ markReady(`Ready. ${pr}`)+ expect(reviews()[0]!.assignment!.agentId).toBe(fresh)+ })++ it('opens nothing without a link to a pull request of the project\'s repository, or when the Lead marks it ready', () => {+ const { f, lead, markReady, reviews } = ready()+ markReady('Ready. Revision abc.')+ markReady('Ready. https://github.com/example/other/pull/42')+ markReady(`Ready. ${pr}`, { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' })+ expect(reviews()).toHaveLength(0)+ f.state.projects![0]!.repository = { machineId: 'host', cwd: '/repo', repositoryUrl: null }+ markReady(`Ready again. ${pr}`)+ expect(reviews()).toHaveLength(0)+ })++ it('opens no second review while the first has no verdict, and the Reviewer is woken as before', () => {+ const { markReady, reviews, reviewer, lead } = ready()+ markReady(`Ready. ${pr}`)+ const again = markReady(`Ready, head 2. ${pr}`)+ expect(reviews()).toHaveLength(1)+ expect(again.messages.map(m => m.recipients)).toEqual([[lead, reviewer]])+ })++ it('refuses a second review by hand while the open one has no verdict, naming it, and allows one once it is cancelled', () => {+ const { f, leadActor, group, markReady, reviews } = ready()+ markReady(`Ready. ${pr}`)+ const open = reviews()[0]!+ const create = () => f.run({ type: 'conversation.create', title: 'Review: Offline editing again', brief: 'Review it.', reviewOf: group,+ checks: [{ description: 'Verdict', independent: false }] }, leadActor)+ expect(create).toThrow(`#${open.number} Review: Offline editing already reviews this work and has no verdict yet.`)+ expect(reviews()).toHaveLength(1)+ f.run({ type: 'work.cancel', conversationId: open.id, assignmentId: open.assignment!.id, reason: 'Wrong Reviewer' }, leadActor)+ create()+ expect(reviews()).toHaveLength(2)+ })++ it('puts privacy first when the task or the handoff touches sharing, access or confidentiality', () => {+ const { markReady, reviews } = ready()+ markReady(`Ready. Readers without access to the project no longer see its groups. ${pr}`)+ expect(reviews()[0]!.brief.startsWith('Privacy first:')).toBe(true)+ })++ it('keeps a review with no verdict from being archived by hand while the work it reviews is going', () => {+ const { f, leadActor, group, built, reviewer, fresh, markReady, reviews } = ready()+ for (const id of [reviewer, fresh]) f.run({ type: 'agent.release', agentId: id, decision: 'stop' }, leadActor)+ markReady(`Ready. ${pr}`)+ const review = reviews()[0]!.id+ expect(() => f.run({ type: 'conversation.archive', conversationId: review, archived: true }, leadActor)).toThrow('no verdict yet')+ expect(reviews()[0]!.archived).toBe(false)+ f.run({ type: 'work.cancel', conversationId: group, assignmentId: built, reason: 'Dropped' }, leadActor)+ f.run({ type: 'conversation.archive', conversationId: review, archived: true }, leadActor)+ expect(reviews()[0]!.archived).toBe(true)+ })++ it('waits for a Reviewer when none is free, and tells the Lead to route and start one', () => {+ const { f, lead, leadActor, reviewer, fresh, markReady, reviews } = ready()+ for (const id of [reviewer, fresh]) f.run({ type: 'agent.release', agentId: id, decision: 'stop' }, leadActor)+ const effects = markReady(`Ready. ${pr}`)+ expect(reviews()[0]!.assignment).toBeNull()+ expect(effects.messages.filter(m => m.recipients.includes(lead) && m.conversationId === reviews()[0]!.id).map(m => m.text))+ .toEqual(['Review opened by itself for #1, but no Reviewer is free. Route it and start one.'])+ })++ it('gives a delta review to the Reviewer of the earlier head while it is still free', () => {+ const { f, group, builderActor, built, reviewer, fresh, markReady, reviews } = ready('codex')+ markReady(`Ready. ${pr}`)+ const first = reviews()[0]!+ expect(first.assignment!.agentId).toBe(reviewer)+ const reviewerActor: Actor = { kind: 'agent', agentId: reviewer, machineOwnerId: 'target-owner' }+ // A verdict that asks for fixes still passes the review's own check: it says a verdict was given (swarm-review).+ f.run({ type: 'work.check', conversationId: first.id, assignmentId: first.assignment!.id, checkId: first.checks[0]!.id, passed: true,+ evidence: 'Ready: with fixes — revision d4e5f6, one Important finding.' }, reviewerActor)+ f.run({ type: 'work.status', conversationId: first.id, assignmentId: first.assignment!.id, status: 'done', result: 'Changes needed.' }, reviewerActor)+ f.run({ type: 'work.status', conversationId: group, assignmentId: built, status: 'working', result: null }, builderActor)+ // Now only `fresh` runs on another engine than the Engineer's; the earlier head's Reviewer is still preferred.+ f.state.agents.find(a => a.id === reviewer)!.configuration.engine = 'codex'+ f.state.agents.find(a => a.id === fresh)!.configuration.engine = 'claude'+ markReady(`Fixed: one finding, head 778899. ${pr}`)+ const delta = reviews().find(c => c.id !== first.id)!+ expect(delta.assignment!.agentId).toBe(reviewer)+ expect(delta.brief).toContain(`Delta review: #${first.number} reviewed the earlier head. Review only the changes since.`)+ })++ it.each([+ ['machines', { kind: 'machines', machineIds: ['elsewhere'] }],+ ['model', { kind: 'forbidModel', model: 'test-model' }],+ ['effort', { kind: 'minEffort', effort: 'max' }],+ ])('gives the review to no Reviewer the owner\'s %s rule rules out, and leaves it for the Lead', (_, rule) => {+ const { f, lead, markReady, reviews } = ready()+ f.run({ type: 'rule.set', rule, text: 'The owner\'s rule.' } as Command)+ const effects = markReady(`Ready. ${pr}`)+ expect(reviews()[0]!.assignment).toBeNull()+ expect(effects.messages.filter(m => m.recipients.includes(lead) && m.conversationId === reviews()[0]!.id).map(m => m.text))+ .toEqual(['Review opened by itself for #1, but no Reviewer is free. Route it and start one.'])+ })++ it('passes over a Reviewer the owner\'s rules rule out for one they allow', () => {+ // On Codex the Engineer's engine would make `reviewer` (Claude) the pick; only `fresh`'s machine is allowed.+ const { f, fresh, markReady, reviews } = ready('codex')+ f.state.agents.find(a => a.id === fresh)!.machineId = 'allowed'+ f.run({ type: 'rule.set', rule: { kind: 'machines', machineIds: ['allowed'] }, text: 'Only allowed.' } as Command)+ markReady(`Ready. ${pr}`)+ expect(reviews()[0]!.assignment!.agentId).toBe(fresh)+ })++ it('passes over a Reviewer that is down for one that is up, and waits when none is up', () => {+ // `reviewer` would be the pick on another engine than the Engineer's, but its session is gone.+ const { f, leadActor, lead, reviewer, fresh, markReady, reviews } = ready('codex')+ f.state.agents.find(a => a.id === reviewer)!.downSince = new Date(500).toISOString()+ markReady(`Ready. ${pr}`)+ expect(reviews()[0]!.assignment!.agentId).toBe(fresh)+ f.run({ type: 'work.cancel', conversationId: reviews()[0]!.id, assignmentId: reviews()[0]!.assignment!.id, reason: 'Again' }, leadActor)+ f.state.agents.find(a => a.id === fresh)!.downSince = new Date(500).toISOString()+ const effects = markReady(`Ready again. ${pr}`)+ const second = reviews().find(c => c.id !== reviews()[0]!.id)!+ expect(second.assignment).toBeNull()+ expect(effects.messages.filter(m => m.recipients.includes(lead) && m.conversationId === second.id).map(m => m.text))+ .toEqual(['Review opened by itself for #1, but no Reviewer is free. Route it and start one.'])+ })++ it('asks for a full review, not a delta, after a review cancelled before its verdict', () => {+ const { f, leadActor, markReady, reviews } = ready()+ markReady(`Ready. ${pr}`)+ const cancelled = reviews()[0]!+ f.run({ type: 'work.cancel', conversationId: cancelled.id, assignmentId: cancelled.assignment!.id, reason: 'Wrong Reviewer' }, leadActor)+ markReady(`Ready, same head. ${pr}`)+ const next = reviews().find(c => c.id !== cancelled.id)!+ expect(next.brief).not.toContain('Delta review')+ })+ })+it('does not wake a Reviewer that is stopping', () => {const { f, lead, leadActor, group, reviewer, builder } = reviewed()f.run({ type: 'agent.release', agentId: reviewer, decision: 'stop' }, leadActor)diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex b43f1181e..2bc9559ae 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -11,7 +11,7 @@ import { routingOverrideSchema } from './routingPolicy.js'import { agentTarget, askedInSchema, broken, MAX_RULES, RULE_MESSAGE_MS, ruleSchema, ruleTextSchema, startTarget, unmet, type RunTarget } from './rules.js'import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'import { checkMentions, MAX_MENTIONS, type MentionTarget } from './mentions.js'-import { ANSWERED_NOTICE, answerDecision, askDecisions, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'+import { ANSWERED_NOTICE, answerDecision, DELEGATED_NOTICE, askDecisions, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'import { TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, toLead, type TerminalRequest } from './terminal.js'import { loseTasks, renewLease, renewOwnTask } from './liveness.js'import { ABANDONED, failureNotice, MACHINE_REMOVED } from './startFailure.js'@@ -23,6 +23,7 @@ import { LEDGER_WEEKS, PULL_REQUEST_URL, recordAsked, recordDecision, recordMergimport { WEEK_MS } from './leaderboard/week.js'import { react, reactionSchema, type ReactionTarget } from './reactions.js'import { shipNotice, shippedAt } from './ship.js'+import { openReview, openReviewOf, projectPullRequest, verdictPending } from './autoReview.js'import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema, type AvatarUpload } from './profile.js'import { agentKind, agentProjectId, audienceOf, agentSetRole, canReadProject, deleteProject, markConfidential, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectMembers, projectOf, projectRules, projectsOf, readAgent, readConversation, readProject, roleVersion, sameProject, sharedWithLeads, SKILL_SET_NAMES, skillSetOf, type ProjectRole, type RoleKind, type SwarmProject } from './projects.js'@@ -152,7 +153,9 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('mention.done'), mentionId: id }).strict(),z.object({ type: z.literal('message.react'), conversationId: id, messageId: id, emoji: reactionSchema, on: z.boolean() }).strict(),z.object({ type: z.literal('decision.ask'), conversationId: id, personId: id, questions: z.array(decisionQuestion).min(1).max(MAX_QUESTIONS) }).strict(),- z.object({ type: z.literal('decision.answer'), decisionId: id, choice: z.number().int().min(0), note: z.string().trim().min(1).max(2000).optional() }).strict(),+ // A choice, or `delegate`: the person asked leaves it to the PM, who takes its recommended option (decisions.ts answerDecision).+ z.object({ type: z.literal('decision.answer'), decisionId: id, choice: z.number().int().min(0).optional(), note: z.string().trim().min(1).max(2000).optional(),+ delegate: z.literal(true).optional() }).strict(),z.object({ type: z.literal('delivery.resolve'), deliveryId: id, resolution: z.enum(['received', 'resend', 'cancel']) }).strict(),z.object({ type: z.literal('work.define'), conversationId: id, brief: text.optional(), task: task.optional(), checks: z.array(check).min(1).max(40) }).strict().refine(c => c.task !== undefined || c.brief !== undefined, 'Provide a task or brief.')@@ -1083,6 +1086,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commafail('REVIEW_TARGET', 'A review group reviews one build group of the same project.', 400)}requireCustomRole(project, 'reviewer')+ // One open review at a time: a Lead on the skill text from before #610 would otherwise open one beside the Swarm's.+ const pending = openReviewOf(state, reviewed)+ if (pending) fail('REVIEW_OPEN', `#${pending.number} ${pending.title} already reviews this work and has no verdict yet. Cancel it first, or wait for its verdict.`)}const requesterId = command.requesterId ? requester(state, project, command.requesterId) : actor.kind === 'person' ? actor.userId : undefinedconst number = nextConversationNumber(state)@@ -1108,10 +1114,12 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commabreak}case 'decision.answer': {- const { answer, recipients, source } = answerDecision(state, actor, context.decision, command.choice, command.note ?? null)+ const { answer, recipients, source, line } = answerDecision(state, actor, context.decision,+ { choice: command.choice, note: command.note ?? null, delegate: command.delegate === true })effects.decisionAnswer = answer- recordDecision(conversation(state, context.decision!.conversationId), context.decision!, context.now)- if (recipients.length) message(context.decision!.conversationId, ANSWERED_NOTICE, recipients, null, source)+ recordDecision(conversation(state, context.decision!.conversationId), context.decision!, context.now, answer.delegated === true)+ if (recipients.length) message(context.decision!.conversationId, answer.delegated ? DELEGATED_NOTICE : ANSWERED_NOTICE, recipients, null, source)+ if (line) effects.messages.push({ id: stableId(operationId, 'delegated'), replyTo: null, recipients: [], ...line })result.decisionId = answer.idbreak}@@ -1160,6 +1168,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst group = conversation(state, command.conversationId)if (group.id === groupProject(state, group).leadConversationId) fail('LEAD_CONVERSATION', 'The Lead conversation stays available.')if (command.archived && activeWork(group)) fail('WORK_ACTIVE', 'Resolve the active assignment before archiving this conversation.')+ if (command.archived && verdictPending(state, group)) {+ fail('REVIEW_PENDING', 'This review has no verdict yet. Cancel it, or finish the work it reviews, before archiving it.')+ }group.archived = command.archived// Archived by hand, it leaves the active set until it is reopened (spec, Archive), once its reports are acknowledged:// until then the sweep leaves it in the active set, where the report check sees it (design section 3.6).@@ -1793,6 +1804,14 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma(actor.kind !== 'agent' || id !== actor.agentId) && state.agents.some(a => a.id === id && agentRole(a) === 'reviewer' && a.workDecision !== 'stop'))const asked = !command.ask ? '' : effects.result.notAsked ? `\n\n${effects.result.notAsked}` : `\n\nAsked ${person(state, command.ask.personId).email}.`message(group.id, `${label}${command.result ? `\n\n${command.result}` : ''}${asked}`, [...(tellLead ? [lead] : []), ...reviewers], null, SYSTEM_ROW)+ // The Engineer's own Ready for review with a pull request of the project opens its review (autoReview.ts).+ const pullRequest = command.status === 'review' && actor.kind === 'agent' && actor.agentId === assignment.agentId && !group.reviewOf+ && !group.audience && !openReviewOf(state, group) ? projectPullRequest(state, group, command.result) : null+ const opened = pullRequest && openReview(state, group, command.result!, pullRequest, { operationId, now: context.now, engineer: sender,+ // The owner's hard rules hold as for work.assign; the reviewed task's own requirement is its Engineer's, not its Reviewer's.+ mayWork: a => !teamWorkCheck(state, a.machineId, a.contributorId, groupProject(state, group), context.now, context.teamMachines, context.otherWorkspaceMachines)+ && !broken(groupRules(group.id), agentTarget(state, a), machineName, macOf) })+ if (opened) effects.messages.push(...opened.messages)// Shipped before this command: the leaderboard marks this Done as shipped just above (recordStatus).if (command.status === 'done' && shippedAt(conversation(original, group.id)) == null) {appendPullRequestUrls(group, [command.result, ...group.checks.map(check => check.evidence)])diff --git a/backend/src/superTabs/confidential.ts b/backend/src/superTabs/confidential.tsindex 4700d545d..8c11c55ec 100644--- a/backend/src/superTabs/confidential.ts+++ b/backend/src/superTabs/confidential.ts@@ -8,14 +8,16 @@ type Transaction = Prisma.TransactionClient/*** The native sessions (an agent id is one machine's harness, the same in every Swarm) among `agentIds` that are confidential- * in any Swarm (Lead ruling, final review Critical 1): marked once a Lead or a private conversation's member (projects.ts- * markConfidential), or, in a part written before that mark, a Lead or private member now. A confidential session is- * watched by nobody but its machine's person, whichever Swarm or share asks.+ * in any Swarm (Lead ruling, final review Critical 1), or in any but `exceptTabId`: marked once a Lead or a private+ * conversation's member (projects.ts markConfidential), or, in a part written before that mark, a Lead or private member now.+ * A confidential session is watched by nobody but its machine's person, whichever Swarm or share asks, except by its own+ * Swarm's readers while it is that Swarm's current Lead (projects.ts watchClosed), which is why a Swarm asks about the others.*/-export async function confidentialSessions(tx: Transaction, agentIds: string[]): Promise<Set<string>> {+export async function confidentialSessions(tx: Transaction, agentIds: string[], exceptTabId?: string): Promise<Set<string>> {const found = new Set<string>()if (!agentIds.length) return found- const rows = await tx.swarmAgent.findMany({ where: { key: { in: [...new Set(agentIds)] }, deleted: false }, select: { tabId: true, key: true, data: true } })+ const rows = await tx.swarmAgent.findMany({ where: { key: { in: [...new Set(agentIds)] }, deleted: false, ...(exceptTabId ? { tabId: { not: exceptTabId } } : {}) },+ select: { tabId: true, key: true, data: true } })const unmarked = new Map<string, string[]>()for (const row of rows) {if ((row.data as unknown as Agent).confidential) found.add(row.key)diff --git a/backend/src/superTabs/decisions.test.ts b/backend/src/superTabs/decisions.test.tsindex 24651a916..25ddcd94f 100644--- a/backend/src/superTabs/decisions.test.ts+++ b/backend/src/superTabs/decisions.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'import type { Prisma } from '@prisma/client'import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'-import { waitingInProject, type DecisionTarget } from './decisions.js'+import { listDecisions, waitingInProject, type DecisionTarget } from './decisions.js'const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }@@ -77,8 +77,8 @@ describe('asking a person for decisions', () => {describe('answering a decision', () => {const open = (s: ReturnType<typeof swarm>, overrides: Partial<DecisionTarget> = {}): DecisionTarget => ({ id: 'decision-1', personId: 'peer',- conversationId: s.group, askerAgentId: s.worker, question: 'Ship how?', options: ['Behind a flag', 'To everyone'], answeredAt: null,- createdAt: 0, assignmentId: null, ...overrides })+ conversationId: s.group, projectId: 'lead', askerAgentId: s.worker, question: 'Ship how?', options: ['Behind a flag', 'To everyone'], recommended: 0,+ answeredAt: null, createdAt: 0, assignmentId: null, ...overrides })it('records the asked person\'s choice and tells the asking agent and the Lead with a notice only they read, carrying none of it', () => {const s = swarm()@@ -111,6 +111,83 @@ describe('answering a decision', () => {})})+describe('leaving a decision to the PM', () => {+ const open = (s: ReturnType<typeof swarm>, overrides: Partial<DecisionTarget> = {}): DecisionTarget => ({ id: 'decision-1', personId: 'peer',+ conversationId: s.group, projectId: 'lead', askerAgentId: s.worker, question: 'Ship how?', options: ['Behind a flag', 'To everyone'], recommended: 1,+ answeredAt: null, createdAt: 0, assignmentId: null, ...overrides })+ /** The peer's own Chat with PM in the project, as Desktop opens it. */+ const pmChat = (s: ReturnType<typeof swarm>) => s.run({ type: 'conversation.create', projectId: 'lead', title: 'peer', brief: '', checks: [],+ audience: { personIds: ['peer'] } }, peer).result.conversationId as string+ const delegate = (s: ReturnType<typeof swarm>, actor: Actor, decision: DecisionTarget | undefined) =>+ s.run({ type: 'decision.answer', decisionId: 'decision-1', delegate: true }, actor, decision ? { decision } : {})++ it('answers with the recommended option for the person asked, recorded as delegated, and the PM says so in their Chat with PM', () => {+ const s = swarm()+ const chat = pmChat(s)+ const answered = delegate(s, peer, open(s))+ expect(answered.decisionAnswer).toEqual({ id: 'decision-1', choice: 1, note: null, delegated: true })+ const [notice, line] = answered.messages+ // The asker and the Lead are told the PM decided, with none of the answer, as for any answer.+ expect(notice).toMatchObject({ conversationId: s.group, recipients: [s.worker, s.lead], source: { kind: 'agent-only', decisionId: 'decision-1' } })+ expect(notice!.text).toContain('left to the Product Manager')+ for (const text of ['Ship how?', 'To everyone']) expect(notice!.text).not.toContain(text)+ // One line from the PM in the person's own chat, which only they read, to nobody.+ expect(line).toMatchObject({ conversationId: chat, recipients: [], text: 'PM decided: To everyone — Ship how?',+ author: { kind: 'agent', id: s.lead }, source: { kind: 'decision-delegated', decisionId: 'decision-1' } })+ expect(line!.id).not.toBe(notice!.id)+ expect(answered.messages).toHaveLength(2)+ })++ it('posts no line when the person has no open Chat with PM in that project', () => {+ const s = swarm()+ const answered = delegate(s, peer, open(s))+ expect(answered.decisionAnswer).toMatchObject({ choice: 1, delegated: true })+ expect(answered.messages.map(m => m.conversationId)).toEqual([s.group])+ // An archived one refuses posts: the answer still stands, without the line.+ const chat = pmChat(s)+ s.state.conversations.find(c => c.id === chat)!.archived = true+ expect(delegate(s, peer, open(s)).messages.map(m => m.conversationId)).toEqual([s.group])+ })++ it('lets only the person asked delegate, once, and only a decision with a recommended option', () => {+ const s = swarm()+ expect(() => delegate(s, owner, open(s))).toThrow('unavailable')+ expect(() => delegate(s, peer, undefined)).toThrow('unavailable')+ expect(() => delegate(s, peer, open(s, { answeredAt: 5 }))).toThrow('already answered')+ expect(() => delegate(s, peer, open(s, { recommended: 2 }))).toThrow('no recommended option')+ })++ it('takes either a choice or a delegation, not both or neither', () => {+ const s = swarm()+ expect(() => s.run({ type: 'decision.answer', decisionId: 'decision-1', choice: 0, delegate: true }, peer, { decision: open(s) })).toThrow('or leave it to the PM')+ expect(() => s.run({ type: 'decision.answer', decisionId: 'decision-1' }, peer, { decision: open(s) })).toThrow('or leave it to the PM')+ expect(commandSchema.safeParse({ type: 'decision.answer', decisionId: 'decision-1', delegate: false }).success).toBe(false)+ })+})++describe('listing a person\'s decisions', () => {+ /** A transaction whose open decisions are [count] rows asked of the peer in the group, newest first. */+ const reading = (s: ReturnType<typeof swarm>, count: number) => {+ const asked: Array<{ take?: number }> = []+ const rows = Array.from({ length: count }, (_, i) => ({ id: `decision-${i}`, batchId: `batch-${i}`, projectId: 'lead', conversationId: s.group,+ assignmentId: null, personId: 'peer', askerAgentId: s.lead, question: `Question ${i}`, options: ['Behind a flag', 'To everyone'], recommended: 0,+ unblocks: 'The release', createdAt: new Date(1000 - i), answeredAt: null, choice: null, note: null, delegated: null }))+ const tx = { superTabDecision: { findMany: async (args: { take?: number }) => { asked.push(args); return rows.slice(0, args.take) } } }+ return { tx: tx as unknown as Prisma.TransactionClient, asked }+ }++ it('says when the newest page leaves open decisions out, so a client never takes it for all of them', async () => {+ const s = swarm()+ const full = reading(s, 201)+ const page = await listDecisions(full.tx, 'tab', s.state, peer, 'open')+ expect(page.decisions).toHaveLength(200)+ expect(page.more).toBe(true)+ const all = await listDecisions(reading(s, 3).tx, 'tab', s.state, peer, 'open')+ expect(all.decisions.map(d => d.id)).toEqual(['decision-0', 'decision-1', 'decision-2'])+ expect(all.more).toBe(false)+ })+})+// groupBy on SuperTabDecision once panicked the Prisma engine on Mongo: the digest counts the open decisions it reads instead.describe('the decisions waiting in a project', () => {it('counts each conversation and person\'s open decisions without groupBy, reading only who and where', async () => {diff --git a/backend/src/superTabs/decisions.ts b/backend/src/superTabs/decisions.tsindex ad890d2a0..6d074f0e2 100644--- a/backend/src/superTabs/decisions.ts+++ b/backend/src/superTabs/decisions.ts@@ -6,7 +6,8 @@import { createHash } from 'node:crypto'import type { Prisma } from '@prisma/client'import { z } from 'zod'-import { AGENT_ONLY, fail, isLeads, person, stableId, type Actor, type Conversation, type SuperTabState } from './model.js'+import { agentDisplayName } from './agentNames.js'+import { AGENT_ONLY, fail, isLeads, person, stableId, type Actor, type Author, type Conversation, type SuperTabState } from './model.js'import { canReadGroup, groupProject, ledProject, projectOf } from './projects.js'import { LEDGER_WEEKS } from './leaderboard/record.js'import { WEEK_MS } from './leaderboard/week.js'@@ -30,11 +31,14 @@ export interface DecisionDraft extends Question {}/** The decision `decision.answer` names, read from SuperTabDecision by the store. */export interface DecisionTarget {- id: string; personId: string; conversationId: string; askerAgentId: string; question: string; options: string[]; answeredAt: number | null+ id: string; personId: string; conversationId: string; projectId: string; askerAgentId: string; question: string; options: string[]+ /** The option Let PM decide takes; a row whose index is not one of its options has none. */+ recommended: number; answeredAt: number | null/** When it was asked, and the task whose needs_human asked it: the leaderboard credits the answer (leaderboard/record.ts). */createdAt: number; assignmentId: string | null}-export interface DecisionAnswer { id: string; choice: number; note: string | null }+/** `delegated`: the person asked left it to the PM, who took the recommended option. */+export interface DecisionAnswer { id: string; choice: number; note: string | null; delegated?: true }/** Questions for one person in one conversation they read, from `asker`. One batch: one id ties them, no ping per question. */export function askDecisions(state: SuperTabState, group: Conversation, personId: string, questions: Question[],@@ -70,15 +74,45 @@ export function answerable(state: SuperTabState, actor: Actor, decision: Decisio/** What tells the asking agent and the Lead, whichever of them is still in the conversation. A notice only they read, with* none of the answer in it: the decisions read, which checks who reads it, has the answer (review of #1753). */export const ANSWERED_NOTICE = 'A decision asked in this conversation was answered. Read the answer with: harness super-tab decisions --answered'+/** The same notice for a decision the person left to the PM, with none of the answer either. */+export const DELEGATED_NOTICE = 'A decision asked in this conversation was left to the Product Manager, who took its recommended option. '+ + 'Read it with: harness super-tab decisions --answered'-/** The asked person's one answer, and the notice for the asking agent and the Lead. */-export function answerDecision(state: SuperTabState, actor: Actor, decision: DecisionTarget | undefined, choice: number, note: string | null) {+/** How an answer reads in the decisions list: a delegated one never as the person's own choice. */+const answerText = (option: string, delegated: boolean) => delegated ? `PM decided: ${option}` : option++/** The asked person's one answer, or their leaving it to the PM (`delegate`), which takes the recommended option; the notice+ * for the asking agent and the Lead; and for a delegated one, the Lead's line in the person's own Chat with PM. */+export function answerDecision(state: SuperTabState, actor: Actor, decision: DecisionTarget | undefined,+ given: { choice?: number; note: string | null; delegate: boolean }) {+ if ((given.choice === undefined) === !given.delegate) fail('INVALID_DECISION', 'Choose one of its options, or leave it to the PM.', 400)const group = answerable(state, actor, decision)- if (decision!.answeredAt !== null) fail('DECISION_ANSWERED', 'This decision is already answered.')- if (choice >= decision!.options.length) fail('INVALID_DECISION', 'Choose one of its options.', 400)- const lead = state.conversations.find(c => c.id === groupProject(state, group).leadConversationId)?.leadId- const recipients = [...new Set([decision!.askerAgentId, ...lead ? [lead] : []])].filter(id => group.agentIds.includes(id))- return { answer: { id: decision!.id, choice, note }, recipients, source: { ...AGENT_ONLY, decisionId: decision!.id } }+ const asked = decision!+ if (asked.answeredAt !== null) fail('DECISION_ANSWERED', 'This decision is already answered.')+ if (given.delegate && !(asked.recommended >= 0 && asked.recommended < asked.options.length)) {+ fail('INVALID_DECISION', 'This decision has no recommended option to leave to the PM.', 400)+ }+ const choice = given.delegate ? asked.recommended : given.choice!+ if (choice >= asked.options.length) fail('INVALID_DECISION', 'Choose one of its options.', 400)+ const project = groupProject(state, group)+ const lead = state.conversations.find(c => c.id === project.leadConversationId)?.leadId+ const recipients = [...new Set([asked.askerAgentId, ...lead ? [lead] : []])].filter(id => group.agentIds.includes(id))+ const answer: DecisionAnswer = { id: asked.id, choice, note: given.note, ...given.delegate ? { delegated: true as const } : {} }+ const line = given.delegate && lead ? delegatedLine(state, actor, project.id, lead, asked, choice) : null+ return { answer, recipients, source: { ...AGENT_ONLY, decisionId: asked.id }, line }+}++/** The Lead's one line saying what it chose, in the person's own Chat with PM of that project: only they read it, and they+ * were asked the question. None when they have no open one with the Lead in it. */+function delegatedLine(state: SuperTabState, actor: Actor, projectId: string, leadId: string, asked: DecisionTarget, choice: number) {+ const lead = state.agents.find(a => a.id === leadId)+ const chat = state.conversations.find(c => !c.archived && c.audience?.people.length === 1 && c.audience.people[0]!.id === asked.personId+ && groupProject(state, c).id === projectId && c.agentIds.includes(leadId) && canReadGroup(state, actor, c))+ if (!lead || !chat) return null+ const author: Author = { kind: 'agent', id: lead.id, name: lead.name, displayName: agentDisplayName(state.agents, lead.id), membershipGeneration: lead.membershipGeneration }+ const question = asked.question.replace(/\s+/g, ' ')+ return { conversationId: chat.id, author, text: `${answerText(asked.options[choice]!, true)} — ${question}`,+ source: { kind: 'decision-delegated', decisionId: asked.id } }}/** Mongo omits unset fields, so `answeredAt: null` alone would miss a row written without it. */@@ -135,15 +169,15 @@ export async function fullFor(tx: Tx, tabId: string, ask: { personId: string; asexport async function readAskedDecision(tx: Tx, tabId: string, id: string): Promise<DecisionTarget | undefined> {const row = await tx.superTabDecision.findFirst({ where: { id, tabId },- select: { id: true, personId: true, conversationId: true, askerAgentId: true, question: true, options: true, answeredAt: true, createdAt: true,- assignmentId: true } })+ select: { id: true, personId: true, conversationId: true, projectId: true, askerAgentId: true, question: true, options: true, recommended: true,+ answeredAt: true, createdAt: true, assignmentId: true } })return row ? { ...row, answeredAt: row.answeredAt?.getTime() ?? null, createdAt: row.createdAt.getTime(), assignmentId: row.assignmentId ?? null } : undefined}/** Conflicts with a concurrent answer of the same decision: only the first one counts. */export async function recordAnswer(tx: Tx, tabId: string, answer: DecisionAnswer, now: number): Promise<void> {const taken = await tx.superTabDecision.updateMany({ where: { id: answer.id, tabId, ...waiting },- data: { choice: answer.choice, note: answer.note, answeredAt: new Date(now) } })+ data: { choice: answer.choice, note: answer.note, answeredAt: new Date(now), ...answer.delegated ? { delegated: true } : {} } })if (!taken.count) fail('DECISION_ANSWERED', 'This decision is already answered.')}@@ -180,15 +214,27 @@ const readableIn = (state: SuperTabState, actor: Actor, groups: Map<string, Convreturn group && canReadGroup(state, actor, group) ? group : undefined}-/** ponytail: capped at 200 per state, newest first; page it if a reader ever has more. */-async function readable(tx: Tx, tabId: string, state: SuperTabState, actor: Actor, open: boolean) {- const rows = await tx.superTabDecision.findMany({ where: { tabId, AND: [readerWhere(state, actor), open ? waiting : { answeredAt: { not: null } }] },- orderBy: { createdAt: 'desc' }, take: 200 })+/** Answered by the person themself: as `waiting`, a row written before `delegated` has no such field. */+const yours: Prisma.SuperTabDecisionWhereInput = { OR: [{ delegated: { isSet: false } }, { delegated: null }, { delegated: false }] }++/** Which decisions a list holds: those still open, or those answered. `settled` is every answered one, those left to the+ * PM included; `answered` is what an older Desktop reads and labels each "You chose", so for a person it leaves out those+ * the PM decided (their Chat with PM has the PM's line). An agent's `answered` holds them all, saying who decided. */+export type DecisionList = 'open' | 'answered' | 'settled'+const LIST_PAGE = 200++/** ponytail: the newest LIST_PAGE per list; `more` says when there are others. Page it if a reader ever has more. */+async function readable(tx: Tx, tabId: string, state: SuperTabState, actor: Actor, list: DecisionList) {+ const which = list === 'open' ? [waiting] : list === 'answered' && actor.kind === 'person'+ ? [{ answeredAt: { not: null } }, yours] : [{ answeredAt: { not: null } }]+ const read = await tx.superTabDecision.findMany({ where: { tabId, AND: [readerWhere(state, actor), ...which] },+ orderBy: { createdAt: 'desc' }, take: LIST_PAGE + 1 })+ const rows = read.slice(0, LIST_PAGE)const groups = await conversationsOf(tx, tabId, state, rows.map(r => r.conversationId))- return rows.flatMap(row => {+ return { more: read.length > LIST_PAGE, rows: rows.flatMap(row => {const group = readableIn(state, actor, groups, row.conversationId)return group ? [{ row, group }] : []- })+ }) }}/** How many of a project's open decisions wait in each conversation for each person, for its digest (digest.ts@@ -219,14 +265,19 @@ export async function decisionsWaiting(tx: Tx, tabId: string, state: SuperTabStareturn { count: ids.length, digest: createHash('sha256').update(ids.join('\n')).digest('base64url').slice(0, 16) }}-export async function listDecisions(tx: Tx, tabId: string, state: SuperTabState, actor: Actor, open: boolean) {- return (await readable(tx, tabId, state, actor, open)).map(({ row, group }) => {+/** One list of the reader's decisions, newest first, and whether it leaves older ones out (`more`): a client may take a+ * decision missing from it as answered or gone only when it does not. */+export async function listDecisions(tx: Tx, tabId: string, state: SuperTabState, actor: Actor, list: DecisionList) {+ const { more, rows } = await readable(tx, tabId, state, actor, list)+ return { more, decisions: rows.map(({ row, group }) => {const asker = state.agents.find(a => a.id === row.askerAgentId)return { id: row.id, batchId: row.batchId, projectId: row.projectId, projectName: projectOf(state, row.projectId).name,conversationId: row.conversationId, conversationTitle: group.title, assignmentId: row.assignmentId ?? null,personId: row.personId, personEmail: state.people.find(p => p.id === row.personId)?.email ?? null,askerAgentId: row.askerAgentId, askerName: asker?.displayName ?? asker?.name ?? 'Agent',question: row.question, options: row.options, recommended: row.recommended, unblocks: row.unblocks,- createdAt: row.createdAt, answeredAt: row.answeredAt ?? null, choice: row.choice ?? null, note: row.note ?? null }- })+ createdAt: row.createdAt, answeredAt: row.answeredAt ?? null, choice: row.choice ?? null, note: row.note ?? null,+ delegated: row.delegated === true,+ answer: row.choice == null || row.options[row.choice] === undefined ? null : answerText(row.options[row.choice]!, row.delegated === true) }+ }) }}diff --git a/backend/src/superTabs/deliverySettle.ts b/backend/src/superTabs/deliverySettle.tsnew file mode 100644index 000000000..2fa522273--- /dev/null+++ b/backend/src/superTabs/deliverySettle.ts@@ -0,0 +1,76 @@+import type { PrismaClient, SuperTabDelivery } from '@prisma/client'+import { ms } from './parts/light.js'+import type { SuperTabStore } from './store.js'+import { logger } from '../utils/logger.js'++// No delivery waits for good (Ken, 2026-10-28). Prod watch kept finding the same 9: uncertain since Oct 20, claimed for 71+// hours, queued in archived groups. None belonged to a task, so nothing that ends a task's deliveries ended them. This pass+// ends, as cancelled, every open delivery that can no longer move; its sender sees it as Not sent. A host's later read of a+// cancelled delivery types nothing: it leaves the host's list, and its claim path never sees it again (cli superTabs/host.ts).++/** A host that still holds a claim says so within a minute: it re-claims, types and acknowledges, or reports a hold after 30 s+ * (cli superTabs/withheld.ts). A claim nobody wrote for this long has no live claimer. */+export const CLAIM_QUIET_MS = 10 * 60_000+/** How long the host may hold a claim while the agent's terminal is busy. */+export const HOLD_LIMIT_MS = 60 * 60_000+/** How long while the terminal waits on a person's answer: that person still owes it one (Lead, 2026-10-28). */+export const WAITING_ON_PERSON_LIMIT_MS = 24 * 60 * 60_000+/** How long a person has to check a delivery its host could not confirm before it ends, as their Open terminal ends it. */+export const UNCERTAIN_LIMIT_MS = 60 * 60_000+const SETTLE_EVERY_MS = 5 * 60_000+const OPEN = ['queued', 'claimed', 'uncertain']+const BATCH = 500++/** Whether an open delivery can no longer move. [reachable]: its recipient may still read it there (store.ts deliveryAllowed). */+export function stuck(delivery: Pick<SuperTabDelivery, 'status' | 'holdReason' | 'holdSince' | 'updatedAt'>, reachable: boolean, now: number): boolean {+ if (!reachable) return true+ const since = (at: Date) => now - at.getTime()+ if (delivery.status === 'uncertain') return since(delivery.updatedAt) > UNCERTAIN_LIMIT_MS+ if (delivery.status !== 'claimed') return false+ if (!delivery.holdSince) return since(delivery.updatedAt) > CLAIM_QUIET_MS+ return since(delivery.holdSince) > (delivery.holdReason === 'team_waiting_user' ? WAITING_ON_PERSON_LIMIT_MS : HOLD_LIMIT_MS)+}++/** A page of open deliveries, by id. Read by their own index (status, id) with a plain match: Prisma sends `status in` as an+ * $expr $or that no index can bound (pageReads.ts), and a pass must not read every delivery ever sent. */+async function openDeliveries(db: PrismaClient, after: string | null): Promise<SuperTabDelivery[]> {+ const rows = await db.superTabDelivery.aggregateRaw({ pipeline: [{ $match: { status: { $in: OPEN }, ...after ? { _id: { $gt: after } } : {} } },+ { $sort: { _id: 1 } }, { $limit: BATCH }] }) as unknown as Array<Record<string, unknown>>+ const date = (value: unknown) => value == null ? null : new Date(ms(value))+ return rows.map(({ _id, ...row }) => ({ ...row, id: _id as string, holdSince: date(row.holdSince), deliveredAt: date(row.deliveredAt),+ answeredAt: date(row.answeredAt), createdAt: date(row.createdAt)!, updatedAt: date(row.updatedAt)! }) as unknown as SuperTabDelivery)+}++/** One pass: each Swarm's open deliveries are judged against that Swarm as it is now, and the stuck ones end. */+export async function settleStuckDeliveries(db: PrismaClient, store: Pick<SuperTabStore, 'settleDeliveries'>, now: number): Promise<number> {+ let settled = 0, after: string | null = null+ for (;;) {+ const rows = await openDeliveries(db, after)+ const byTab = new Map<string, SuperTabDelivery[]>()+ for (const row of rows) byTab.set(row.tabId, [...byTab.get(row.tabId) ?? [], row])+ for (const [tabId, tabRows] of byTab) {+ // One Swarm that cannot be read now (it is being migrated) never holds the others back.+ try { settled += await store.settleDeliveries(tabId, tabRows, now) } catch (error) {+ logger.warn('[swarm-deliveries] could not settle', { tabId, error: error instanceof Error ? error.message : String(error) })+ }+ }+ if (rows.length < BATCH) return settled+ after = rows.at(-1)!.id+ }+}++/** Runs the pass every 5 minutes in the singleton worker. */+export function startDeliverySettle(db: PrismaClient, store: Pick<SuperTabStore, 'settleDeliveries'>, everyMs = SETTLE_EVERY_MS): () => void {+ let running = false+ const run = () => {+ if (running) return+ running = true+ void settleStuckDeliveries(db, store, Date.now()).then(count => { if (count) logger.info('[swarm-deliveries] settled', { count }) })+ .catch(error => logger.warn('[swarm-deliveries] failed', { error: error instanceof Error ? error.message : String(error) }))+ .finally(() => { running = false })+ }+ run()+ const timer = setInterval(run, everyMs)+ timer.unref()+ return () => clearInterval(timer)+}diff --git a/backend/src/superTabs/leaderboard/record.test.ts b/backend/src/superTabs/leaderboard/record.test.tsindex 4a8ecd29a..cddac3225 100644--- a/backend/src/superTabs/leaderboard/record.test.ts+++ b/backend/src/superTabs/leaderboard/record.test.ts@@ -388,7 +388,8 @@ describe('who unblocks waiting work', () => {describe('other ways a person unblocks work: decisions, approvals and tags', () => {const HOUR = 3_600_000const decision = (conversationId: string, extra: Partial<DecisionTarget> = {}): DecisionTarget => ({ id: 'decision-1', personId: 'owner', conversationId,- askerAgentId: 'gone', question: 'Ship how?', options: ['Behind a flag', 'To everyone'], answeredAt: null, createdAt: 2 * HOUR, assignmentId: null, ...extra })+ projectId: 'lead', askerAgentId: 'gone', question: 'Ship how?', options: ['Behind a flag', 'To everyone'], recommended: 0, answeredAt: null,+ createdAt: 2 * HOUR, assignmentId: null, ...extra })/** The project's Lead asks in its own conversation at [askedAt], returning what a reply to it carries. */const leadAsk = (f: ReturnType<typeof fixture>, askedAt = HOUR) => {const lead = f.add('lead', 'lead', true)@@ -417,6 +418,16 @@ describe('other ways a person unblocks work: decisions, approvals and tags', ()expect(f.group(id).ledger?.waiting?.answeredAt).toBe(2 * HOUR)})+ it('closes the wait of a decision left to the PM, but credits the person nothing: they did not choose', () => {+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)+ f.at(HOUR)+ f.status(id, assignmentId, worker, 'needs_human', 'Flag?')+ f.at(2 * HOUR)+ f.run({ type: 'decision.answer', decisionId: 'decision-1', delegate: true }, owner, { decision: decision(id, { createdAt: HOUR, assignmentId }) })+ expect(f.group(id).ledger?.waiting?.answeredAt).toBe(2 * HOUR)+ expect(f.group(id).ledger?.unblocks ?? []).toEqual([])+ })+it('counts a needs-human ask once when its person posts an answer before answering its decision', () => {const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)f.at(HOUR)diff --git a/backend/src/superTabs/leaderboard/record.ts b/backend/src/superTabs/leaderboard/record.tsindex e6cf63af4..f4157ba5a 100644--- a/backend/src/superTabs/leaderboard/record.ts+++ b/backend/src/superTabs/leaderboard/record.ts@@ -106,8 +106,10 @@ export function approves(text: string): boolean {/** The person asked answered a decision: credited from when it was asked. A decision a worker asked through needs_human is* that wait's question, named by the wait, also when the worker asked it again after moving on: answering it answers the* wait, and once the wait is answered, by a post or this decision, the other earns nothing more. A wait from before- * decisions were named is matched by its time, as it was asked in the same command. */-export function recordDecision(group: Conversation, decision: { id: string; personId: string; createdAt: number; assignmentId: string | null }, now: number): void {+ * decisions were named is matched by its time, as it was asked in the same command. A decision left to the PM closes its+ * wait and is credited to nobody. */+export function recordDecision(group: Conversation, decision: { id: string; personId: string; createdAt: number; assignmentId: string | null }, now: number,+ delegated = false): void {if (group.audience || isLeads(group)) returnconst waiting = group.ledger?.waitingif (waiting && (waiting.decisionId ? waiting.decisionId === decision.id@@ -115,6 +117,8 @@ export function recordDecision(group: Conversation, decision: { id: string; persif (waiting.answeredAt != null) returnwaiting.answeredAt = now}+ // Left to the PM: the wait is over, but the person did not choose, so it earns them nothing.+ if (delegated) returncredit(group, { personId: decision.personId, at: now, waitedMs: now - decision.createdAt, kind: 'decision', item: decision.id })}diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex 73284de31..941636750 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -205,6 +205,10 @@ export function teamAccountSwarm(state?: Pick<SuperTabState, 'ownerId' | 'people* runs every teammate's work as one macOS user, so it serves one Workspace's teammates at a time (swarm-workspaces design). */export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow = false, required = teamAccountRequired(), otherWorkspace = false): TeamWorkRefusal | null {const reading = pool.observation, name = pool.name+ // A Mac's Harness Team account whose machine is no longer a Team machine was removed (`harness team remove` deletes it).+ // Its last reading stays fresh for a minute, and in that minute it read as taking teammates' work and a Lead's route+ // named it (local Team account run, 2026-10-28).+ if (pool.hostMachineId && !teamRow) return { code: 'TEAM_ACCOUNT_REQUIRED', reason: `The Harness Team account on ${name} was removed, ${ONLY_OWN}.` }if (!teamRow && reading?.sessionKind !== 'team' && !required) return nullif (otherWorkspace) return { code: 'MACHINE_IN_OTHER_WORKSPACE', reason: `The Harness Team account on ${name} also serves another ${WORKSPACE_LABEL}'s Swarms, ${ONLY_OWN} here.` }if (!reading || now - reading.receivedAt > MACHINE_FRESH_MS) {diff --git a/backend/src/superTabs/parts/touches.test.ts b/backend/src/superTabs/parts/touches.test.tsindex 790389a39..864f18091 100644--- a/backend/src/superTabs/parts/touches.test.ts+++ b/backend/src/superTabs/parts/touches.test.ts@@ -52,6 +52,23 @@ describe('the parts a command touches (design section 1.2, column T)', () => {expect(has(touches, 'agent', f.lead)).toBe(false)})+ it('makes two reviews the Swarm opens at once meet on the Reviewer both would take, and on the head that numbers them', () => {+ const f = swarm(), a = f.group('A')+ const reviewer = f.run({ type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: 'reviewer', name: 'Reviewer', configuration: config, lead: false },+ owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).effects.result.agentId as string+ f.state.agents.find(x => x.id === reviewer)!.role = 'reviewer'+ f.state.projects![0]!.repository = { machineId: 'host', cwd: '/repo', repositoryUrl: 'https://github.com/example/project' }+ const ready = f.run({ type: 'work.status', conversationId: a.id, assignmentId: a.assignmentId, status: 'review',+ result: 'Ready. https://github.com/example/project/pull/7' }, f.agentActor(a.worker))+ expect(ready.effects.state.conversations.find(c => c.reviewOf === a.id)!.assignment!.agentId).toBe(reviewer)+ expect(has(ready.touches, 'agent', reviewer)).toBe(true)+ expect(has(ready.touches, 'head', 'head')).toBe(true)+ expect(has(ready.touches, 'group', 'lead')).toBe(true)+ // A Ready for review that opens nothing touches none of them.+ const again = f.run({ type: 'work.status', conversationId: a.id, assignmentId: a.assignmentId, status: 'review', result: 'Ready, head 2.' }, f.agentActor(a.worker))+ expect(has(again.touches, 'agent', reviewer) || has(again.touches, 'head', 'head')).toBe(false)+ })+it('makes finishing work and the Lead\'s next start or assignment meet on the project\'s progress part', () => {const f = swarm(), a = f.group('A')f.run({ type: 'work.check', conversationId: a.id, assignmentId: a.assignmentId, checkId: f.state.conversations.find(c => c.id === a.id)!.checks[0]!.id,diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.tsindex 48579621d..558968591 100644--- a/backend/src/superTabs/parts/touches.ts+++ b/backend/src/superTabs/parts/touches.ts@@ -146,6 +146,17 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState// Finished work puts its worker's decision before the Lead (finishWorker): the Lead's next start, assignment or// route touches the same part, so it cannot pass over that decision on a stale read (design ruling R5).if (command.status === 'done' || command.status === 'stopped') progress(projectOfGroup(command.conversationId)?.id)+ if (command.status === 'review') {+ // A review the Swarm opened by itself (autoReview.ts) reads whether its Reviewer is free and numbers the new group,+ // as conversation.create and work.assign do: two opened at once meet on that Reviewer and on the head.+ const opened = effects.state.conversations.find(c => c.reviewOf === command.conversationId && !before.conversations.some(b => b.id === c.id))+ if (opened) {+ head()+ group(leadGroupOf(projectOfGroup(command.conversationId)?.id))+ agent(opened.assignment?.agentId)+ progress(projectOfGroup(command.conversationId)?.id)+ }+ }breakcase 'work.define':if (before.conversations.find(c => c.id === command.conversationId)?.assignment) progress(projectOfGroup(command.conversationId)?.id)diff --git a/backend/src/superTabs/projects.test.ts b/backend/src/superTabs/projects.test.tsindex 44ec56b3c..b495077c5 100644--- a/backend/src/superTabs/projects.test.ts+++ b/backend/src/superTabs/projects.test.ts@@ -1,8 +1,9 @@import { createHash } from 'node:crypto'import { describe, expect, it } from 'vitest'import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'-import { createSuperTab, visibleState, type Actor, type MessageDraft } from './model.js'+import { createSuperTab, SuperTabError, visibleState, type Actor, type MessageDraft } from './model.js'import { canReadAgent, canWatchAgent, markConfidential, projectOf, projectsOf, readConversation, skillModeOf, skillSetOf, watchersLost, watchingNarrowed } from './projects.js'+import { mayDrive } from './terminal.js'const owner: Actor = { kind: 'person', userId: 'owner', email: '[email protected]' }const peer: Actor = { kind: 'person', userId: 'peer', email: '[email protected]' }@@ -533,6 +534,29 @@ describe('who may watch an agent\'s terminal (final review, Critical 1)', () =>expect(canWatchAgent(f.state, host, target(former))).toBe(true)})+ it('lets every reader watch the project\'s current Lead, private chats included, but only its machine\'s person type or read it on request', () => {+ const f = setup()+ const host: Actor = { kind: 'person', userId: 'host', email: '[email protected]' }+ f.state.people.push({ id: 'host', email: '[email protected]', role: 'collaborator', generation: 'first' })+ const pm = f.add('lead', 'pm')+ f.run({ type: 'conversation.create', title: 'Chat with PM', brief: '', checks: [], audience: { personIds: ['peer'] } }, peer)+ const target = () => f.state.agents.find(a => a.id === pm)!+ // Marked as any Lead is, so that it stays closed once it is no longer the Lead, and to other Swarms and ordinary shares.+ expect(target().confidential).toBe(true)+ // Ken, 2026-10-28: a member watching the Product Manager reads the private chats it is in, and every member may.+ for (const reader of [owner, peer, host]) expect(canWatchAgent(f.state, reader, target())).toBe(true)+ // Confidential in another Swarm too: that Swarm's chats are not this one's members' to read.+ expect(canWatchAgent(f.state, peer, target(), true)).toBe(false)+ const refusal = (actor: Actor) => { try { mayDrive(f.state, actor, target()); return null } catch (error) { if (error instanceof SuperTabError) return error.code; throw error } }+ expect(refusal(owner)).toBe('TERMINAL_PRIVATE')+ expect(refusal(peer)).toBe('TERMINAL_PRIVATE')+ expect(refusal(host)).toBeNull()+ // A Lead leaves only with its project, but a state from before that rule can hold a former one: its mark keeps it closed.+ f.state.conversations.find(c => c.id === 'lead')!.leadId = null+ expect(canWatchAgent(f.state, peer, target())).toBe(false)+ expect(canWatchAgent(f.state, host, target())).toBe(true)+ })+it('keeps a session confidential once marked, after its private membership ends, until it leaves', () => {const f = setup()const former = f.add('lead', 'former', false)@@ -559,11 +583,14 @@ describe('whether a commit narrows who may watch a terminal', () => {return { f, builder, before, narrowed: () => watchingNarrowed(before, f.state) }}- it('is narrowed when a session turns confidential, whatever the command: here made its project’s Lead', () => {+ it('is narrowed when a session turns confidential, whatever the command, and not when it becomes its project’s Lead', () => {const { f, builder, narrowed } = watched()f.run({ type: 'conversation.create', title: 'Private', brief: '', checks: [], audience: { personIds: ['owner'] } })expect(narrowed()).toBe(false)+ // The current Lead is every reader's to watch (Ken, 2026-10-28), and marked: no longer the Lead, it is nobody's.f.run({ type: 'conversation.agent', conversationId: 'lead', agentId: builder, present: true, lead: true })+ expect(narrowed()).toBe(false)+ f.state.conversations.find(c => c.id === 'lead')!.leadId = nullexpect(narrowed()).toBe(true)})@@ -587,7 +614,14 @@ describe('whether a commit narrows who may watch a terminal', () => {f.state.people.push({ id: 'host', email: '[email protected]', role: 'collaborator', generation: 'first' })before.people.push({ id: 'host', email: '[email protected]', role: 'collaborator', generation: 'first' })expect(watchersLost(before, f.state)).toEqual([])+ // Made Lead and joined to a private chat, it is still every reader's to watch (Ken, 2026-10-28).f.run({ type: 'conversation.agent', conversationId: 'lead', agentId: builder, present: true, lead: true })+ const chat = String(f.run({ type: 'conversation.create', title: 'Private', brief: '', checks: [], audience: { personIds: ['owner'] } }).conversationId)+ f.run({ type: 'conversation.agent', conversationId: chat, agentId: builder, present: true, lead: false })+ expect(watchersLost(before, f.state)).toEqual([])+ // A Lead leaves only with its project, but a state from before that rule can hold a former Lead still in the private chat:+ // marked, it is closed to everyone but its machine's owner, the chat's member too.+ f.state.conversations.find(c => c.id === 'lead')!.leadId = nullexpect(watchersLost(before, f.state)).toEqual([{ agentId: builder, personIds: ['owner', 'peer'] }])})diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.tsindex 384d708bb..ff311b8de 100644--- a/backend/src/superTabs/projects.ts+++ b/backend/src/superTabs/projects.ts@@ -183,11 +183,18 @@ export function markConfidential(state: SuperTabState): void {for (const target of state.agents) if (!target.confidential && confidentialSession(state, target)) target.confidential = true}-/** Who may watch an agent's terminal: observe it, hold a share of it, read or type in it. A confidential session's screen and- * scrollback hold people's private chats, so only the person whose machine runs it may, owners included. `elsewhere`: the- * same session is confidential in another Swarm (confidential.ts). Any other agent: every reader of its project, as before. */+/** Whether a session's terminal is closed to watching in this Swarm. A confidential session's screen and scrollback hold+ * people's private chats, so only the person whose machine runs it watches it, owners included. The project's current Lead is+ * the exception, view only (Ken, 2026-10-28): every reader of its project watches it, the private chats it is in included.+ * It stays marked, so a former Lead, another Swarm and an ordinary share still find it closed. `elsewhere`: the session is+ * confidential in another Swarm (confidential.ts), whose chats are not this Swarm's to read. */+export const watchClosed = (state: SuperTabState, target: Agent, elsewhere = false): boolean =>+ elsewhere || (isConfidential(state, target) && !ledProject(state, target.id))++/** Who may watch an agent's terminal: observe it or hold a share of it. Reading or typing in it on request is closed by+ * `isConfidential` alone (terminal.ts mayDrive). Any other agent: every reader of its project, as before. */export function canWatchAgent(state: SuperTabState, actor: Actor, target: Agent, elsewhere = false): boolean {- return canReadAgent(state, actor, target) && (!isConfidential(state, target, elsewhere) || ownSession(actor, target))+ return canReadAgent(state, actor, target) && (!watchClosed(state, target, elsewhere) || ownSession(actor, target))}/** Who could watch an agent's terminal before a commit and cannot after it (canWatchAgent, by the session the observer relay@@ -197,11 +204,11 @@ export function canWatchAgent(state: SuperTabState, actor: Actor, target: Agent,export function watchersLost(before: SuperTabState, after: SuperTabState): Array<{ agentId: string; personIds: string[] }> {const session = (a: Agent) => `${a.machineId}\n${a.harnessId}\n${a.machineOwnerId}`const now = new Map(after.agents.map(a => [session(a), a]))- // canWatchAgent per person, with the agent's confidentiality read once per state.+ // canWatchAgent per person, with whether the agent is closed read once per state.const watchers = (state: SuperTabState, target: Agent) => {- const confidential = isConfidential(state, target)+ const closed = watchClosed(state, target)return state.people.map(p => ({ kind: 'person' as const, userId: p.id, email: p.email }))- .filter(actor => canReadAgent(state, actor, target) && (!confidential || ownSession(actor, target)))+ .filter(actor => canReadAgent(state, actor, target) && (!closed || ownSession(actor, target)))}return before.agents.flatMap(target => {const was = watchers(before, target)diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex 48beee31c..821f33515 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -214,6 +214,9 @@ export interface HostAgentRow {observers: Array<{ email: string; userId: string }>/** Its session is confidential in some Swarm: the host refuses every share of it, ordinary ones too (Critical 1). */confidential: boolean+ /** Confidential, but this Swarm's current Lead: the host lets `observers` watch it through this Swarm's shares while this+ * row is in force, and nobody else (Ken, 2026-10-28). An older host ignores it and refuses them, which errs closed. */+ membersWatch: boolean}export interface HostPool {tabId: stringdiff --git a/backend/src/superTabs/read/host.ts b/backend/src/superTabs/read/host.tsindex ee931db51..1ea820f70 100644--- a/backend/src/superTabs/read/host.ts+++ b/backend/src/superTabs/read/host.ts@@ -161,7 +161,7 @@ export class HostReads {private async lookups(tx: Transaction, state: SuperTabState, teams: Array<{ machineId: string }>): Promise<HostLookups> {const people = await tx.user.findMany({ where: { id: { in: state.people.map(p => p.id) }, autonomousEnv: state.environment }, select: { id: true, email: true } })- const confidential = await confidentialSessions(tx, state.agents.map(a => a.id))+ const confidential = await confidentialSessions(tx, state.agents.map(a => a.id), state.id)return { people, confidential, teams, githubApp: !!this.options.githubApp, agentGrant: target => this.store.agentGrant(tx, state, target) }}diff --git a/backend/src/superTabs/read/hostRows.ts b/backend/src/superTabs/read/hostRows.tsindex b39db0c8d..155105d46 100644--- a/backend/src/superTabs/read/hostRows.ts+++ b/backend/src/superTabs/read/hostRows.ts@@ -6,14 +6,14 @@import type { AuthUser } from '../../lib/ssoAuth.js'import { activeWork, agent, isLeads, SuperTabError, conversation, type Agent, type SuperTabState } from '../model.js'import { hostLocalGrid, machineContribution, teamAccountSwarm, type MachineCleanup } from '../machines.js'-import { agentProjectId, agentSetRole, canWatchAgent, isConfidential, groupProject, ledProject, projectsOf, skillModeOf, skillSetOf } from '../projects.js'+import { agentProjectId, agentSetRole, canWatchAgent, isConfidential, groupProject, ledProject, projectsOf, skillModeOf, skillSetOf, watchClosed } from '../projects.js'import type { HostAgentRow, HostPool, HostRosterRow, HostTabRows } from './contract.js'import { hostEtag } from './hostEtag.js'export interface HostLookups {/** The Swarm's people with their account emails (observers). */people: Array<{ id: string; email: string }>- /** Its agents whose session is confidential in some Swarm (confidential.ts): nobody but its machine's person watches them. */+ /** Its agents whose session is confidential in another Swarm (confidential.ts): nobody but its machine's person watches them. */confidential: Set<string>/** Throws a SuperTabError when the agent's machine grant is gone (store.ts agentGrant). */agentGrant(target: Agent): Promise<void>@@ -86,6 +86,8 @@ function agentRow(tabId: string, state: SuperTabState, machineId: string, user:.map(p => ({ email: p.email, userId: p.id })),// The host refuses every share of a confidential session, ordinary ones too, and remembers it (cli observers.ts).confidential: isConfidential(state, target, closed),+ // But for this Swarm's current Lead: its listed observers watch it while this row is in force (Ken, 2026-10-28).+ membersWatch: isConfidential(state, target, closed) && !watchClosed(state, target, closed),}}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex bf918b505..144f27822 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -36,13 +36,14 @@ import {SuperTabError, isLeads, parkLaterConversations, syncLeads, type Actor, type Agent, type Assignment, type Author, type Conversation, type MessageDraft, type SuperTabState,} from './model.js'import type { HoldReason } from './holdReason.js'+import { stuck } from './deliverySettle.js'import { agentDisplayName } from './agentNames.js'import { endedHolds, HOLDING, type WorkHold } from '../github/holds.js'import { accrueLent } from './leaderboard/lent.js'import { mayDrive, TERMINAL_ANSWER_MS, TERMINAL_EXPIRY_MS, TERMINAL_PICKUP_MS, TERMINAL_RECHECK_MS, type TerminalEffect } from './terminal.js'import { closeAssignment, closeUnassignedStart, readDecision, recentDecisions, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'import { listMentions, markDone, mentionsWaiting, openTags, readMention, resolveByReply, writeMentions } from './mentions.js'-import { answerable, fullFor, listDecisions, readAskedDecision, recordAnswer, repeatOf, waitingIn, waitingInProject, writeDecisions } from './decisions.js'+import { answerable, fullFor, listDecisions, type DecisionList, readAskedDecision, recordAnswer, repeatOf, waitingIn, waitingInProject, writeDecisions } from './decisions.js'import { DEFAULT_ROUTING_POLICY, effectivePolicy, routingPolicySchema, type RoutingPolicy } from './routingPolicy.js'import { authenticatedEmail, authorizeSwarmJoin, configureSharing, joinSwarmSchema, requireSharingOwner,saveSharingSchema, sharingDetails, type JoinSwarm, type SaveSharing } from './sharing.js'@@ -464,6 +465,7 @@ export class SuperTabStore {const groupIds = [...named.groupIds ?? []], startIds = [...named.startIds ?? []], agentIds: string[] = [], startAgentIds: string[] = []const start = 'startId' in command ? state.starts?.find(s => s.id === command.startId) : undefinedif (start) groupIds.push(start.request.conversationId)+ const projectIds = [...named.projectIds ?? []]const decisionId = routeDecisionOf(command)if (decisionId) {const decision = await readDecision(tx, tabId, decisionId)@@ -474,6 +476,8 @@ export class SuperTabStore {if (command.type === 'decision.answer') {const asked = await readAskedDecision(tx, tabId, command.decisionId)if (asked) groupIds.push(asked.conversationId)+ // Left to the PM: the person's Chat with PM in that project, quiet or not, takes the PM's line.+ if (asked && command.delegate) projectIds.push(asked.projectId)}if (command.type === 'delivery.resolve') {const delivery = await tx.superTabDelivery.findFirst({ where: { id: command.deliveryId, tabId }, select: { conversationId: true } })@@ -490,7 +494,7 @@ export class SuperTabStore {const machines = new Set((state.machines ?? []).filter(m => m.contributorId === command.userId).map(m => m.machineId))agentIds.push(...state.agents.filter(a => a.contributorId === command.userId || machines.has(a.machineId)).map(a => a.id))}- return { groupIds, startIds, agentIds, startAgentIds, projectIds: named.projectIds }+ return { groupIds, startIds, agentIds, startAgentIds, projectIds }}/** Writes what changed between the loaded state and `next`, and touches the parts the change relied on. */@@ -949,7 +953,8 @@ export class SuperTabStore {const member = await activeMember(tx, original.workspaceId, actor.userId)if (member) context.workspaceRole = member.role as WorkspaceRole}- if (TEAM_WORK_COMMANDS.has(command.type)) {+ // A Ready for review may assign a Reviewer by itself (autoReview.ts), as work.assign does.+ if (TEAM_WORK_COMMANDS.has(command.type) || (command.type === 'work.status' && command.status === 'review')) {context.teamMachines = await this.teamMachines(tx, original)context.otherWorkspaceMachines = await this.otherWorkspaceMachines(tx, original)if (this.hooks.teamAccountsIdle) context.teamAccountsIdle = true@@ -1013,12 +1018,13 @@ export class SuperTabStore {}await revokeNativeContexts(tx, original, effects.state)// Rule (b) for claims (design D10): a change to who a conversation's deliveries may reach writes those delivery rows,- // so a claim of one conflicts with it. Archiving keeps them for when it reopens, as before.- const regrouped = command.type === 'conversation.archive' && command.archived || command.type === 'conversation.audience'- || command.type === 'conversation.agent' && !command.present- if (regrouped) {+ // so a claim of one conflicts with it. An archived conversation, or one its receiver left, ends them: kept for a+ // reopening, 6 of the 9 deliveries prod watch found stuck for days on 2026-10-28 waited in archived groups, unread.+ const unreadable = command.type === 'conversation.archive' && command.archived || command.type === 'conversation.agent' && !command.present+ if (unreadable || command.type === 'conversation.audience') {await tx.superTabDelivery.updateMany({ where: { tabId, conversationId: command.conversationId, status: { in: ['queued', 'claimed', 'uncertain'] },- ...(command.type === 'conversation.agent' ? { agentId: command.agentId } : {}) }, data: { updatedAt: new Date(context.now) } })+ ...(command.type === 'conversation.agent' ? { agentId: command.agentId } : {}) },+ data: unreadable ? { status: 'cancelled', holdReason: null, holdSince: null } : { updatedAt: new Date(context.now) } })}if (command.type === 'conversation.audience') {const kept = new Set(conversation(effects.state, command.conversationId).audience?.people.map(p => p.id))@@ -1659,12 +1665,12 @@ export class SuperTabStore {/** The caller's decisions in this Swarm, newest first: a person's asked of them, an agent's asked by it (a Lead's also* those asked in its project), still open or answered. A light load: the quiet conversations its decisions are in are* read with them (decisions.ts conversationsOf), never the Swarm's whole history, read again on every change. */- async decisions(user: AuthUser, tabId: string, state: 'open' | 'answered', asAgentId?: string) {+ async decisions(user: AuthUser, tabId: string, state: DecisionList, asAgentId?: string) {return transaction(this.db, async tx => {const { state: tab } = await this.load(tx, user, tabId)const actor = await this.actor(tx, user, tab, asAgentId)author(tab, actor)- return { decisions: await listDecisions(tx, tabId, tab, actor, state === 'open') }+ return await listDecisions(tx, tabId, tab, actor, state)})}@@ -1850,22 +1856,23 @@ export class SuperTabStore {const target = state.agents.find(a => a.machineId === machineId && a.harnessId === harnessId && a.machineOwnerId === machineOwnerId)if (!target) return falseagent(state, target.id)- if (!canWatchAgent(state, { kind: 'person', userId: user.sub, email: user.email }, target, await this.confidential(tx, target.id))) return false+ if (!canWatchAgent(state, { kind: 'person', userId: user.sub, email: user.email }, target, await this.confidential(tx, target.id, tabId))) return falseawait this.agentGrant(tx, state, target)return true} catch (error) { if (error instanceof SuperTabError) return false; throw error }}- /** Whether an agent's session is confidential in any Swarm (confidential.ts). */- private async confidential(tx: Transaction, agentId: string): Promise<boolean> {- return (await confidentialSessions(tx, [agentId])).has(agentId)+ /** Whether an agent's session is confidential in any Swarm, or any but `exceptTabId` (confidential.ts). */+ private async confidential(tx: Transaction, agentId: string, exceptTabId?: string): Promise<boolean> {+ return (await confidentialSessions(tx, [agentId], exceptTabId)).has(agentId)}- /** Whether a terminal share may open, wherever it came from (routes/harnessShares.ts): a confidential session's only for- * its machine's person, even an ordinary share made outside any Swarm; a Swarm's share only while that Swarm allows it. */+ /** Whether a terminal share may open, wherever it came from (routes/harnessShares.ts): a Swarm's share only while that+ * Swarm lets its recipient watch (its current Lead included, projects.ts watchClosed); an ordinary share made outside any+ * Swarm never of a confidential session, but for its machine's person. */async mayOpenShare(user: AuthUser, share: { superTabId: string | null; machineId: string; agentId: string; ownerId: string }): Promise<boolean> {- if (user.sub !== share.ownerId && await this.confidential(this.db, stableId(share.machineId, share.agentId))) return false- return !share.superTabId || this.mayObserve(user, share.superTabId, share.machineId, share.agentId, share.ownerId)+ if (share.superTabId) return this.mayObserve(user, share.superTabId, share.machineId, share.agentId, share.ownerId)+ return user.sub === share.ownerId || !await this.confidential(this.db, stableId(share.machineId, share.agentId))}private deliveryAllowed(state: SuperTabState, delivery: SuperTabDelivery): boolean {@@ -2020,7 +2027,11 @@ export class SuperTabStore {const loaded = await this.load(tx, user, tabId, { groupIds: named ? [named.conversationId] : [] }), state = loaded.stateauthor(state, await this.actor(tx, user, state, agentId), true)const delivery = await tx.superTabDelivery.findFirst({ where: { id: deliveryId, tabId, agentId } })- if (!delivery || !this.deliveryAllowed(state, delivery) || delivery.status === 'cancelled' ||+ // The delivery pass ended a hold (it keeps the hold's reason) as its host, its terminal free again, typed it: the+ // host's own confirmation counts, or the agent has it while its sender sees Not sent and sends it again (review of+ // #1941). Nothing else brings an ended delivery back.+ const typedAsEnded = delivery?.status === 'cancelled' && !!delivery.holdReason && action.type === 'ack' && delivery.claimId === action.claimId+ if (!delivery || !this.deliveryAllowed(state, delivery) || delivery.status === 'cancelled' && !typedAsEnded ||!await this.senderAllowed(tx, state, delivery)) fail('DELIVERY_REVOKED', 'This instruction is no longer authorized.', 403)if (delivery.status === 'answered') fail('DELIVERY_RESOLVED', 'This message was already answered.')if (delivery.status === 'confirmed' || delivery.status === 'superseded') {@@ -2044,10 +2055,10 @@ export class SuperTabStore {})}- /** The host cannot type a claimed instruction yet. Recorded on the delivery for logs; nothing is posted, nobody is told it waits. */+ /** The host cannot type a claimed instruction yet. Recorded on the delivery, an agent-only one's too: it is how the delivery+ * pass tells a claim its host still holds from one nobody will type (deliverySettle.ts). Nothing is posted. */private async hold(tx: Transaction, delivery: SuperTabDelivery, reason: HoldReason) {if (delivery.status !== 'claimed') return { held: false }- if (agentOnly((await tx.superTabMessage.findUnique({ where: { id: delivery.messageId }, select: { source: true } }))?.source)) return { held: false }if (delivery.holdReason !== reason || !delivery.holdSince) {await tx.superTabDelivery.update({ where: { id: delivery.id }, data: { holdReason: reason, holdSince: delivery.holdSince ?? new Date(this.now()) } })}@@ -2056,7 +2067,7 @@ export class SuperTabStore {/** Archives a finished group whose pull requests `checked` were all read merged or closed (archive.ts), only if it still* qualifies inside this write: no message since, no decision waiting and no pull request linked since the read. Its- * queued deliveries are kept for when it reopens, as a person's archive keeps them. True when it archived. */+ * waiting deliveries end, as a person's archive ends them. True when it archived. */async archiveFinished(tabId: string, groupId: string, checked: readonly string[]): Promise<boolean> {return transaction(this.db, async tx => {const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })@@ -2071,13 +2082,37 @@ export class SuperTabStore {const sequences = numberMessages(state, rows, now)if (!dirtyGroups(state, groupProject(state, group)).includes(group)) group.dormant = true// As a person's archive does (execute): a claim of a delivery here conflicts with this write.- await tx.superTabDelivery.updateMany({ where: { tabId, conversationId: groupId, status: { in: [...OPEN_DELIVERY] } }, data: { updatedAt: new Date(now) } })+ await tx.superTabDelivery.updateMany({ where: { tabId, conversationId: groupId, status: { in: [...OPEN_DELIVERY] } },+ data: { status: 'cancelled', holdReason: null, holdSince: null } })await this.save(tx, loaded, state, clock.next())await this.writeMessages(tx, tabId, state, rows, sequences)return true})}+ /** Ends, as cancelled, those of this Swarm's open deliveries `rows` (as the delivery pass read them) that can no longer move+ * (deliverySettle.ts). Each only as it was read: one its host acknowledged since, or a claim with no hold its host claimed+ * again since, is kept. A held claim its host claims again still ends once its hold is over; it keeps its hold's reason,+ * so its sender learns why, and its host's confirmation that it typed it still counts (delivery). The number ended. */+ async settleDeliveries(tabId: string, rows: SuperTabDelivery[], now: number): Promise<number> {+ return transaction(this.db, async tx => {+ const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })+ // A Swarm deleted since: nobody can read its deliveries.+ const state = row ? (await loadRow(tx, requireParts(row), { groupIds: [...new Set(rows.map(r => r.conversationId))] })).state : null+ let settled = 0+ for (const delivery of rows) {+ if (!stuck(delivery, !!state && this.deliveryAllowed(state, delivery), now)) continue+ // A held claim is the same while its claim and hold are: its live host claims it again on every poll (cli+ // superTabs/host.ts), so its write time would let it outrun the pass for good. Any other is as last written.+ const unchanged = delivery.holdSince ? { claimId: delivery.claimId, holdReason: delivery.holdReason, holdSince: delivery.holdSince }+ : { updatedAt: delivery.updatedAt }+ settled += (await tx.superTabDelivery.updateMany({ where: { id: delivery.id, tabId, status: delivery.status, ...unchanged },+ data: { status: 'cancelled' } })).count+ }+ return settled+ })+ }+/** Only the recorded execution host may attest that the actual session/attempt has stopped. */async stopped(user: AuthUser, tabId: string, assignmentId: string, receipt: string) {let ended: WorkHold[] = []diff --git a/backend/src/superTabs/teamRouting.test.ts b/backend/src/superTabs/teamRouting.test.tsindex 47489a4cf..6cb7d9763 100644--- a/backend/src/superTabs/teamRouting.test.ts+++ b/backend/src/superTabs/teamRouting.test.ts@@ -38,7 +38,10 @@ function swarm() {let state: SuperTabState = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')let sequence = 0const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {- const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, ...context })+ // As the store reads them (store.ts teamMachines): a machine reporting from a team sign-in has a team account row,+ // unless a test says which rows are.+ const teamMachines = (state.machines ?? []).filter(m => m.observation?.sessionKind === 'team').map(m => m.machineId)+ const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, teamMachines, ...context })state = effects.statereturn effects}@@ -472,6 +475,21 @@ describe('one machine: a Mac and its Harness Team account', () => {.toBe('MACHINE_OFFLINE')})+ // Local Team account run, 2026-10-28: for a minute after `harness team remove`, its last reading still read as taking+ // teammates' work, and a Lead's route named it.+ it('once the team account is removed, its pool takes nothing at once, though its last reading is still fresh', () => {+ const f = oneMachine(), group = f.group()+ f.machine('mate-team').observation = reading('team', PASSED)+ expect(machineTeamWork(f.state, f.machine('mate-team'), NOW, [])?.code).toBe('TEAM_ACCOUNT_REQUIRED')+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-team') }, owner, { ...f.pooled('mate-team'), teamMachines: [] }))?.code)+ .toBe('TEAM_ACCOUNT_REQUIRED')+ expect(f.state.starts ?? []).toEqual([])+ // Until the switch is on, the same: a removed Harness Team account is no Team machine.+ delete process.env.SWARM_TEAM_ACCOUNT_REQUIRED+ expect(machineTeamWork(f.state, f.machine('mate-team'), NOW, [])?.code).toBe('TEAM_ACCOUNT_REQUIRED')+ process.env.SWARM_TEAM_ACCOUNT_REQUIRED = '1'+ })+it('is refused with the team account\'s own reason, and never falls back to the Mac\'s owner', () => {const f = oneMachine(), group = f.group()f.machine('mate-team').observation = reading('team', FAILED)diff --git a/backend/src/superTabs/tidy.test.ts b/backend/src/superTabs/tidy.test.tsindex 58d5d249e..12ec831dd 100644--- a/backend/src/superTabs/tidy.test.ts+++ b/backend/src/superTabs/tidy.test.ts@@ -141,6 +141,20 @@ describe('which finished groups archive', () => {}})+ it('is never a review whose Reviewer gave no verdict while the work it reviews is going, unless it was cancelled', () => {+ const verdict = { id: 'v', description: 'Verdict with the reviewed revision', independent: false }+ const review = (patch: Partial<Conversation>) => group({ id: 'r1', reviewOf: 'g1', ...patch })+ // Stored as done with no verdict, as no command allows: the rule still holds.+ const state = swarm({ groups: [group({ assignment: done({ status: 'review' }) }),+ review({ checks: [{ ...verdict, evidence: null, passedBy: null }] }),+ review({ id: 'r2', checks: [{ ...verdict, evidence: 'Ready: yes — revision abc', passedBy: 'agent:w' }] }),+ review({ id: 'r3', checks: [{ ...verdict, evidence: null, passedBy: null }], assignment: done({ status: 'cancelled' }) })] })+ expect(state.conversations.slice(2).map(g => archivable(state, g, quiet))).toEqual([false, true, true])+ // Once the reviewed work is done, its review is moot.+ state.conversations[1]!.assignment = done()+ expect(archivable(state, state.conversations[2]!, quiet)).toBe(true)+ })+it('is never a Lead conversation, a private chat, the Leads conversation, an archived group, or any once tidying is off', () => {const state = swarm({ groups: [group({ audience: { people: [] } as never }), group({ id: 'leads', kind: 'leads' }), group({ id: 'old', archived: true })] })for (const g of state.conversations) expect(archivable(state, g, quiet)).toBe(false)diff --git a/backend/src/superTabs/tidy.ts b/backend/src/superTabs/tidy.tsindex 2954e8955..e1c11af34 100644--- a/backend/src/superTabs/tidy.ts+++ b/backend/src/superTabs/tidy.ts@@ -1,4 +1,5 @@import { agentDisplayName } from './agentNames.js'+import { verdictPending } from './autoReview.js'import { activeWork, agentRole, stableId, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'import { agentProjectId, groupProject, projectsOf } from './projects.js'@@ -96,12 +97,12 @@ export function stoppedMachines(state: SuperTabState, rows: MessageDraft[]): Arrexport const ARCHIVE_QUIET_MS = 30 * 60_000/** Whether a group may archive by itself, as far as the Swarm alone can tell: its task done or cancelled, quiet for- * ARCHIVE_QUIET_MS, and not a Lead conversation, a private chat with people or the Leads conversation. Its pull requests- * and decisions are checked by the caller (archive.ts). */+ * ARCHIVE_QUIET_MS, not a review still owing its verdict (autoReview.ts verdictPending), and not a Lead conversation, a+ * private chat with people or the Leads conversation. Its pull requests and decisions are checked by the caller (archive.ts). */export function archivable(state: SuperTabState, group: Conversation, now: number): boolean {if (state.tidy === false || group.archived || group.kind || group.audience) return falseif (projectsOf(state).some(p => p.leadConversationId === group.id)) return false- if (!['done', 'cancelled'].includes(group.assignment?.status ?? '')) return false+ if (!['done', 'cancelled'].includes(group.assignment?.status ?? '') || verdictPending(state, group)) return falseconst last = time(group.lastActivityAt)return last !== undefined && now - last >= ARCHIVE_QUIET_MS}diff --git a/backend/src/worker.ts b/backend/src/worker.tsindex e58acb09c..14c341b36 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -19,6 +19,7 @@ import { ensureProductUsageExpiry } from './lib/productUsage.js'import { ensureTerminalExpiry } from './superTabs/terminal.js'import { ensureMentionExpiry } from './superTabs/mentions.js'import { ensurePartExpiry, startSwarmSweeps } from './superTabs/sweeps.js'+import { startDeliverySettle } from './superTabs/deliverySettle.js'import { appPullRequests, markFinishedGroups, startSwarmArchive, unknownPullRequests } from './superTabs/archive.js'import { SuperTabStore } from './superTabs/store.js'import { announceSwarmDeliveries } from './lib/swarmDeliveryPushes.js'@@ -58,6 +59,7 @@ async function start(): Promise<void> {let stopSweeps = (): void => {}let stopArchive = (): void => {}+ let stopDeliveries = (): void => {}const shutdown = (signal: string): void => {logger.info(`Received ${signal}, stopping backend worker...`)const hardExit = setTimeout(() => process.exit(0), 5000)@@ -66,6 +68,7 @@ async function start(): Promise<void> {productUsagePeopleRollupService.stop()stopSweeps()stopArchive()+ stopDeliveries()void Promise.allSettled([prisma.$disconnect(), closeBus()]).finally(() => process.exit(0))}process.on('SIGINT', () => shutdown('SIGINT'))@@ -82,6 +85,8 @@ async function start(): Promise<void> {// link none do (superTabs/archive.ts).const githubConfig = githubAppConfig(env), githubApp = githubConfig ? new GitHubApp(githubConfig) : nullstopArchive = startSwarmArchive(prisma, swarms, () => githubApp ? appPullRequests(githubApp) : unknownPullRequests)+ // A delivery that can no longer move ends as Not sent, instead of waiting for good (superTabs/deliverySettle.ts).+ stopDeliveries = startDeliverySettle(prisma, swarms)// PM2 wait_ready gates the singleton worker's "online" state on schema/catalog/backfill startup.// Plain node/tsx runs do not provide process.send and simply continue.process.send?.('ready')diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex f45eb61ed..0bac80ecf 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -3,5 +3,5 @@ import { defineConfig } from 'vitest/config'export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts','integration/superTabRead.test.ts', 'integration/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/superTabHotReads.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabObserver.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],+ 'integration/superTabIndexes.test.ts', 'integration/superTabHotReads.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex dfa9ab33b..fb2c4b0c8 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -4082,6 +4082,36 @@ describe('machines_changed relay', () => {await socket.stop()})+ it('hands a shares notice on at a random moment within 10 s, and a burst of them once', async () => {+ // Prod 2026-10-28: one invitation told every computer of its recipient at once, and each window read the shares list+ // in the same second; across a Swarm's members those reads came in waves that held the backend at its pod limit.+ vi.useFakeTimers()+ vi.spyOn(Math, 'random').mockReturnValue(0.5)+ const socket = relaySocket('token')+ const frames: Array<Record<string, unknown>> = []+ socket.registerLocalClient('local:machines', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })+ socket.connect()+ const ws = wsMock.instances[0]+ ws.open()+ const shares = () => frames.filter((f) => f.type === 'machines_changed')+ for (let i = 0; i < 3; i++) ws.message({ t: 'down', connId: '', frame: { type: 'machines_changed', payload: { reason: 'harness_shares' } } })+ await vi.advanceTimersByTimeAsync(4_900)+ expect(shares()).toEqual([])+ await vi.advanceTimersByTimeAsync(200)+ expect(shares()).toEqual([{ type: 'machines_changed', payload: { reason: 'harness_shares' } }])+ // A notice after that one was handed on is handed on again: its read must come after the change it tells.+ ws.message({ t: 'down', connId: '', frame: { type: 'machines_changed', payload: { reason: 'harness_shares' } } })+ await vi.advanceTimersByTimeAsync(5_100)+ expect(shares()).toHaveLength(2)+ // Another reason is not held back.+ ws.message({ t: 'down', connId: '', frame: { type: 'machines_changed', payload: { reason: 'renamed' } } })+ await vi.advanceTimersByTimeAsync(0)+ expect(shares()).toHaveLength(3)+ await socket.unregisterLocalClient('local:machines')+ await socket.stop()+ vi.useRealTimers()+ })+it('relays a reason it can show and nothing else from the payload', async () => {const socket = relaySocket('token')const frames: Array<Record<string, unknown>> = []diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex f68a9ecd6..5e86c1217 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -45,6 +45,7 @@ import type { TerminalStreamManager } from './lib/terminalStreamManager.js'import { encodeTerminalLocal, TerminalBinaryKind, type TerminalBinaryClear } from './lib/terminalBinary.js'import { BACKEND_ONLY_DOWN_TYPES, GATEWAY_REQUEST_TYPES, isLocalClientId, logSafeType, PAIR_REQUESTS, PLATE_REQUEST, rpcResultType, type DownTransport } from './lib/relayFrames.js'import { sid, logFrame } from './lib/log.js'+import { spreadNotice } from './lib/spreadNotice.js'import { eventAgentId, GUEST_REFUSALS, guestVerdict } from './core/guestPolicy.js'export { isLocalClientId, type DownTransport }@@ -52,6 +53,9 @@ export { isLocalClientId, type DownTransport }/** Requests one local connection may queue before the daemon is ready (see `openRequests`). The app* sends a handful on connect; hundreds is a client looping, not a person. */const MAX_REQUESTS_BEFORE_READY = 256+/** Within how long this computer's windows hear an invitation given or taken back: the backend now answers the shares list in+ * tens of milliseconds, and 10 s spreads every member's read of it over a hundred times that. */+const SHARES_NOTICE_SPREAD_MS = 10_000/** A terminal stream's bookkeeping, handled as it arrives rather than in its connection's line — see `enqueueDown`. */const TERMINAL_BOOKKEEPING_TYPES: ReadonlySet<string> = new Set(['terminal_ack', 'terminal_alive'])/** An upload's control frames, which go in line with its chunks — see `enqueueDown`. */@@ -222,6 +226,8 @@ export class BackendSocket {/** The account's notices the backend announces (`desk_changed`, …), for the experiments that hear them* (Agent Messages reads its tabs again), as well as the windows here. */onAccountNotice: ((notice: BackendNotice) => void) | null = null+ /** An invitation given or taken back, which has the windows read the shares list (lib/spreadNotice.ts). */+ private readonly sharesNotice = spreadNotice(() => this.sendLocal({ type: 'machines_changed', payload: { reason: 'harness_shares' } }), SHARES_NOTICE_SPREAD_MS)/** What a shared tab's relay said (gateway/tabRelay.ts), for Agent Messages. */onTabFrame: ((event: TabFrame) => void) | null = null/**@@ -445,6 +451,7 @@ export class BackendSocket {this.onAccountNotice?.(notice)// Only the Swarm host acts on it (superTabs/host.ts): the windows have nothing to re-read.if (notice.type === 'super_tab_deliveries') return+ if (notice.type === 'machines_changed' && notice.reason === 'harness_shares') { this.sharesNotice.tell(); return }this.sendLocal(notice.type === 'machines_changed' ? { type: notice.type, payload: { reason: notice.reason } }: notice.type === 'device_keys_changed' ? { type: notice.type, payload: {} }: { type: notice.type, payload: { revision: notice.revision } })@@ -516,6 +523,7 @@ export class BackendSocket {async stop(): Promise<void> {this.closed = true+ this.sharesNotice.stop()this.closeAgentService?.dispose()this.viewerStreams?.closedAll(); this.ownerCommands.closeAll()await this.terminalStreams?.stop()diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.tsindex 5da52257e..7f5242296 100644--- a/cli/src/cable/cableHost.spec.ts+++ b/cli/src/cable/cableHost.spec.ts@@ -1000,17 +1000,41 @@ describe('Swarm cards', () => {expect(host.activeSwarmProject()).toEqual({ superTabId: 'st1', projectId: '', fromDevice: false })})+ it('names the conversation the window has open in the active Swarm tab, when it names one', () => {+ const host = new DaemonCableHost(wiring())+ const swarms = [+ { id: 't1', name: 'Swarm', agentIds: [], panes: 1, superTabId: 'st1', projectId: 'p1', conversationId: 'pm1' },+ { id: 't2', name: 'Swarm', agentIds: [], panes: 1, superTabId: 'st1', projectId: 'p1' },+ { id: 't3', name: 'Work', agentIds: [], panes: 0, conversationId: 'c1' },+ ]+ host.setSwarms({ active: 't1', swarms, tiles: [] })+ expect(host.activeSwarmProject()).toEqual({ superTabId: 'st1', projectId: 'p1', conversationId: 'pm1', fromDevice: false })+ host.setSwarms({ active: 't2', swarms, tiles: [] })+ expect(host.activeSwarmProject()).toEqual({ superTabId: 'st1', projectId: 'p1', fromDevice: false })+ host.setSwarms({ active: 't3', swarms, tiles: [] })+ expect(host.activeSwarmProject()).toBeNull()+ })+it('hands the wiring what a device asks, and answers nothing when the wiring has none', async () => {const w = wiring({- swarmCardsWanted: vi.fn(), swarmCardOpen: vi.fn(), superTabSelected: vi.fn(),+ swarmCardsWanted: vi.fn(), swarmCardOpen: vi.fn(), superTabSelected: vi.fn(), swarmSay: vi.fn(async () => true),swarmCardRecap: vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'hi', at: 1, none: false })),})const host = new DaemonCableHost(w)host.swarmCardsWanted(true); host.swarmCardOpen('c1', 'st1', 'l1'); host.superTabSelected('st1', 'p1')expect(w.swarmCardsWanted).toHaveBeenCalledWith(true)- expect(w.swarmCardOpen).toHaveBeenCalledWith('c1', 'st1', 'l1')+ expect(w.swarmCardOpen).toHaveBeenCalledWith('c1', 'st1', 'l1', false)expect(w.superTabSelected).toHaveBeenCalledWith('st1', 'p1')expect(await host.swarmCardRecap('st1', 'l1')).toEqual({ tabId: 'st1', leadId: 'l1', text: 'hi', at: 1, none: false })+ // A dial that speaks swarmChat asks for the chat on the face: the flag goes on to the wiring.+ host.swarmCardOpen('c1', 'st1', 'l1', true)+ expect(w.swarmCardOpen).toHaveBeenLastCalledWith('c1', 'st1', 'l1', true)+ await host.swarmCardRecap('st1', 'l1', true)+ expect(w.swarmCardRecap).toHaveBeenLastCalledWith('st1', 'l1', true)+ expect(await host.swarmSay('h1', 'ship it', true)).toBe(true)+ expect(w.swarmSay).toHaveBeenLastCalledWith('h1', 'ship it', true)+ await host.swarmSay('h1', 'ship it')+ expect(w.swarmSay).toHaveBeenLastCalledWith('h1', 'ship it', false)const bare = new DaemonCableHost(wiring())bare.swarmCardsWanted(false); bare.swarmCardOpen('c1', 'st1', null); bare.superTabSelected('st1', 'p1')expect(await bare.swarmCardRecap('st1', 'l1')).toBeNull()diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex 70276564f..fd7e16e57 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -108,11 +108,11 @@ export interface CableHostWiring {/** A Harness Pro came with Swarm cards (true) or the last one went (false): the core reads the Swarms only meanwhile. */swarmCardsWanted?: (on: boolean) => void/** One Lead's last message, read on request; null when it could not be read. */- swarmCardRecap?: (tabId: string, leadId: string) => Promise<LeadRecap | null>+ swarmCardRecap?: (tabId: string, leadId: string, chat?: boolean) => Promise<LeadRecap | null>/** The recap a device (one cable `session`) has open, or null once closed. */- swarmCardOpen?: (session: string, tabId: string, leadId: string | null) => void+ swarmCardOpen?: (session: string, tabId: string, leadId: string | null, chat?: boolean) => void/** Words for a Lead that runs here, posted as the person in its Swarm chat; false when the harness leads no project. */- swarmSay?: (harnessId: string, text: string) => Promise<boolean>+ swarmSay?: (harnessId: string, text: string, chat?: boolean) => Promise<boolean>/** A device picked a Lead: the window opens that Swarm tab and project. */superTabSelected?: (superTabId: string, projectId: string) => void/** A finger on the dial's glass, in pieces, while it is down; `superTabId` when it scrolls that Swarm's chat (a Pro's Lead view). */@@ -423,16 +423,16 @@ export class DaemonCableHost implements CableHost {this.wiring.swarmCardsWanted?.(on)}- swarmCardRecap(tabId: string, leadId: string): Promise<LeadRecap | null> {- return this.wiring.swarmCardRecap?.(tabId, leadId) ?? Promise.resolve(null)+ swarmCardRecap(tabId: string, leadId: string, chat = false): Promise<LeadRecap | null> {+ return this.wiring.swarmCardRecap?.(tabId, leadId, chat) ?? Promise.resolve(null)}- swarmCardOpen(session: string, tabId: string, leadId: string | null): void {- this.wiring.swarmCardOpen?.(session, tabId, leadId)+ swarmCardOpen(session: string, tabId: string, leadId: string | null, chat = false): void {+ this.wiring.swarmCardOpen?.(session, tabId, leadId, chat)}- swarmSay(harnessId: string, text: string): Promise<boolean> {- return this.wiring.swarmSay?.(harnessId, text) ?? Promise.resolve(false)+ swarmSay(harnessId: string, text: string, chat = false): Promise<boolean> {+ return this.wiring.swarmSay?.(harnessId, text, chat) ?? Promise.resolve(false)}superTabSelected(superTabId: string, projectId: string): void {@@ -442,12 +442,14 @@ export class DaemonCableHost implements CableHost {/*** The active tab when it is a Swarm, with its open project or '' when none is (its Chat with PM, a DM, or a Swarm* not loaded yet); `fromDevice` when the announce was a device's own pick. A Swarm tab with no project used to read- * as no Swarm at all, and the dial stayed on "Nothing on this tab" while the window showed the Swarm.+ * as no Swarm at all, and the dial stayed on "Nothing on this tab" while the window showed the Swarm. `conversationId`: the+ * conversation it has open there, when the window names one, which the round dial's face follows.*/- activeSwarmProject(): { superTabId: string; projectId: string; fromDevice: boolean } | null {+ activeSwarmProject(): { superTabId: string; projectId: string; conversationId?: string; fromDevice: boolean } | null {const app = this.swarmsconst tab = app?.swarms.find((s) => s.id === app.active)- return app && tab?.superTabId ? { superTabId: tab.superTabId, projectId: tab.projectId ?? '', fromDevice: app.fromDevice === true } : null+ return app && tab?.superTabId ? { superTabId: tab.superTabId, projectId: tab.projectId ?? '',+ ...(tab.conversationId ? { conversationId: tab.conversationId } : {}), fromDevice: app.fromDevice === true } : null}selectSwarm(swarmId: string): void {diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex b90659a76..981a78015 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -3698,7 +3698,7 @@ describe('swarm cards', () => {swarms: rows.map((r) => ({ name: r.id, agents: 0, agentIds: [] as string[], panes: 0, ...r })) })/** A host whose cards, desk tab and window project the test moves. */- function cardHost(state: { cards: SwarmCard[]; desk?: ReturnType<typeof desk>; open?: { superTabId: string; projectId: string; fromDevice: boolean } | null } , over: Partial<CableHost> = {}) {+ function cardHost(state: { cards: SwarmCard[]; desk?: ReturnType<typeof desk>; open?: { superTabId: string; projectId: string; conversationId?: string; fromDevice: boolean } | null } , over: Partial<CableHost> = {}) {return makeHost({swarmCards: () => state.cards,listSwarms: () => state.desk ?? desk(),@@ -4190,4 +4190,217 @@ describe('swarm cards', () => {expect(ofType(port, 'supertab.recap')).toEqual([])} finally { await session.stop() }})++ // ── swarmChat: 'v1' (a round dial that follows the chat, design 2026-10-28-round-dial-swarm-chat) ─────────────+ describe('swarmChat', () => {+ const ROUND = { t: 'hello', product: 'harness', mac: 'cc:dd', swarmCard: 'v1', superTab: 'wait-v1', swarmChat: 'v1' }+ const pmChat = { kind: 'pm' as const, id: 'pm1', name: 'PM', working: false }+ const group = { kind: 'group' as const, id: 'g1', name: 'Fix login', working: true, since: 9 }+ const notice = (id = 'n1', over: Record<string, unknown> = {}) => ({ chat: 'pm' as const, chatId: 'pm1', id, text: `From the PM ${id}`, at: 1792560000, ...over })+ const noticeFrame = (id = 'n1') => ({ t: 'supertab.notice', tab: 'st1', lead: 'lead1', chat: 'pm', chatId: 'pm1', id, text: `From the PM ${id}`, at: 1792560000 })+ const voice = (port: LoopbackPort, agentId: string) => {+ port.say({ t: 'voice.begin', uploadId: `u-${agentId}`, agentId })+ port.pcm(Buffer.alloc(3200)); port.say({ t: 'voice.end' })+ }++ it('a device without swarmChat gets today\'s frames', async () => {+ for (const hello of [PRO, { ...ROUND, swarmChat: undefined }]) {+ const cards = [card('st1', [lead(1, { state: 'ask', chat: pmChat, notice: notice() }), lead(2, { chat: group })])]+ const swarmSay = vi.fn(async () => true)+ const host = cardHost({ cards }, { transcribe: vi.fn(async () => 'ship it'), route: vi.fn(), swarmSay })+ const { session, port } = await connect(host)+ try {+ port.say(hello)+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))+ expect(ofType(port, 'supertab')[0].leads).toEqual([+ { id: 'lead1', projectId: 'proj1', project: 'Project 1', engine: 'claude', owner: '', local: '', state: 'ask', order: 1, since: 134 },+ { id: 'lead2', projectId: 'proj2', project: 'Project 2', engine: 'claude', owner: '', local: '', state: 'work', order: 2, since: 134 }])+ await session.syncSwarmCards()+ await new Promise((r) => setTimeout(r, 350))+ expect(port.types().filter((t) => t.startsWith('supertab.notice'))).toEqual([])+ // The recap and the open are asked as today, and the talk goes to the Lead's conversation.+ port.say({ t: 'supertab.recap.get', tab: 'st1', lead: 'lead1' })+ port.say({ t: 'supertab.open', tab: 'st1', lead: 'lead1' })+ await vi.waitFor(() => expect(ofType(port, 'supertab.recap')).toHaveLength(1))+ expect(vi.mocked(host.swarmCardRecap!).mock.calls).toEqual([['st1', 'lead1']])+ expect(vi.mocked(host.swarmCardOpen!).mock.calls.at(-1)).toEqual([expect.stringMatching(/^c\d+$/), 'st1', 'lead1'])+ expect(ofType(port, 'supertab.recap')[0]).toEqual({ t: 'supertab.recap', tab: 'st1', lead: 'lead1', text: 'Shipped it.', at: 1792560000, none: false })+ // A chat's recap is not this device's.+ await session.swarmCardRecap({ tabId: 'st1', leadId: 'lead1', text: 'the chat', at: 5, none: false, chatId: 'pm1' })+ expect(ofType(port, 'supertab.recap')).toHaveLength(1)+ voice(port, 'a1')+ await vi.waitFor(() => expect(swarmSay).toHaveBeenCalled())+ expect(swarmSay.mock.calls[0]).toEqual(['a1', 'ship it'])+ } finally { await session.stop() }+ }+ })++ it('a swarmChat device gets chat, chatId, chatName and work only for a working group', async () => {+ const cards = [card('st1', [+ lead(1, { state: 'ask', chat: pmChat }),+ lead(2, { chat: group }),+ lead(3, { chat: { kind: 'lead', id: 'lead-c3', name: 'Lead', working: false } }),+ lead(4, { state: 'stuck', chat: { ...group, id: 'g4', working: false, since: undefined } }),+ lead(5, { state: 'stuck' }),+ ])]+ const { session, port } = await connect(cardHost({ cards }))+ try {+ port.say(ROUND)+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))+ const base = (n: number) => ({ id: `lead${n}`, projectId: `proj${n}`, project: `Project ${n}`, engine: 'claude', owner: '', local: '', order: n })+ expect(ofType(port, 'supertab')[0].leads).toEqual([+ { ...base(1), state: 'done', chat: 'pm', chatId: 'pm1', chatName: 'PM' },+ { ...base(2), state: 'work', since: 9, chat: 'group', chatId: 'g1', chatName: 'Fix login' },+ { ...base(3), state: 'done', chat: 'lead', chatId: 'lead-c3', chatName: 'Lead' },+ { ...base(4), state: 'done', chat: 'group', chatId: 'g4', chatName: 'Fix login' },+ // A Lead whose chat did not come through reads as its Lead chat, and never as ask or stuck.+ { ...base(5), state: 'done' },+ ])+ } finally { await session.stop() }+ })++ it('sends a notice once per id', async () => {+ const state = { cards: [card('st1', [lead(1, { chat: pmChat })])] }+ const { session, port } = await connect(cardHost(state))+ try {+ port.say(ROUND)+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))+ state.cards = [card('st1', [lead(1, { chat: pmChat, notice: notice('n1') })])]+ await session.syncSwarmCards()+ await vi.waitFor(() => expect(ofType(port, 'supertab.notice')).toEqual([noticeFrame('n1')]))+ // The Lead goes first: the dial has it before the alert that names it.+ expect(port.types().lastIndexOf('supertab')).toBeLessThan(port.types().indexOf('supertab.notice'))+ await session.syncSwarmCards()+ await new Promise((r) => setTimeout(r, 350))+ expect(ofType(port, 'supertab.notice')).toHaveLength(1)+ state.cards = [card('st1', [lead(1, { chat: pmChat, notice: notice('n2') })])]+ await session.syncSwarmCards()+ await vi.waitFor(() => expect(ofType(port, 'supertab.notice')).toEqual([noticeFrame('n1'), noticeFrame('n2')]))+ } finally { await session.stop() }+ })++ it('replays a held notice without sending it', async () => {+ const state = { cards: [card('st1', [lead(1, { chat: pmChat, notice: notice('n1') })])] }+ const { session, port } = await connect(cardHost(state))+ try {+ port.say(ROUND)+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))+ await settle(); await settle()+ port.say({ t: 'resync' })+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(2))+ await session.syncSwarmCards(true)+ await settle(); await settle()+ expect(ofType(port, 'supertab.notice')).toEqual([])+ state.cards = [card('st1', [lead(1, { chat: pmChat, notice: notice('n2') })])]+ await session.syncSwarmCards()+ await vi.waitFor(() => expect(ofType(port, 'supertab.notice')).toEqual([noticeFrame('n2')]))+ } finally { await session.stop() }+ })++ it('a dial that attaches before the cards arrive is not sent the notices they already hold', async () => {+ // The devices' process started again: the dial attaches to an empty list, then the core replays the last one.+ const state: Parameters<typeof cardHost>[0] = { cards: [] }+ const { session, port } = await connect(cardHost(state))+ try {+ port.say(ROUND)+ await vi.waitFor(() => expect(ofType(port, 'supertabs')).toHaveLength(1))+ state.cards = [card('st1', [lead(1, { chat: pmChat, notice: notice('n1') })])]+ await session.syncSwarmCards()+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))+ await new Promise((r) => setTimeout(r, 350))+ expect(ofType(port, 'supertab.notice')).toEqual([])+ state.cards = [card('st1', [lead(1, { chat: pmChat, notice: notice('n2') })])]+ await session.syncSwarmCards()+ await vi.waitFor(() => expect(ofType(port, 'supertab.notice')).toEqual([noticeFrame('n2')]))+ } finally { await session.stop() }+ })++ it('does not send a notice for the chat the desktop has open', async () => {+ const state: Parameters<typeof cardHost>[0] = { cards: [card('st1', [lead(1, { chat: pmChat })])], open: { superTabId: 'st1', projectId: 'proj1', conversationId: 'pm1', fromDevice: false } }+ const { session, port } = await connect(cardHost(state))+ try {+ port.say(ROUND)+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))+ state.cards = [card('st1', [lead(1, { chat: pmChat, notice: notice('n1') })])]+ await session.syncSwarmCards()+ await new Promise((r) => setTimeout(r, 350))+ // The person read it on the desktop: leaving that chat later does not alert it either.+ state.open = { superTabId: 'st1', projectId: 'proj1', conversationId: 'lead-c1', fromDevice: false }+ await session.syncSwarmCards()+ await new Promise((r) => setTimeout(r, 350))+ expect(port.types().filter((t) => t.startsWith('supertab.notice'))).toEqual([])+ // The same chat id in another Swarm is another chat.+ state.open = { superTabId: 'st2', projectId: 'proj1', conversationId: 'pm1', fromDevice: false }+ state.cards = [card('st1', [lead(1, { chat: pmChat, notice: notice('n2') })])]+ await session.syncSwarmCards()+ await vi.waitFor(() => expect(ofType(port, 'supertab.notice')).toEqual([noticeFrame('n2')]))+ } finally { await session.stop() }+ })++ it('sends notice.read when the desktop opens a chat with a sent notice', async () => {+ const state: Parameters<typeof cardHost>[0] = { cards: [card('st1', [lead(1, { chat: pmChat })])] }+ const { session, port } = await connect(cardHost(state))+ try {+ port.say(ROUND)+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))+ state.cards = [card('st1', [lead(1, { chat: pmChat, notice: notice('n1') })])]+ await session.syncSwarmCards()+ await vi.waitFor(() => expect(ofType(port, 'supertab.notice')).toHaveLength(1))+ // Another chat open: still unread.+ state.open = { superTabId: 'st1', projectId: 'proj1', conversationId: 'g1', fromDevice: false }+ await session.syncSwarmCards()+ await new Promise((r) => setTimeout(r, 350))+ expect(ofType(port, 'supertab.notice.read')).toEqual([])+ state.open = { superTabId: 'st1', projectId: 'proj1', conversationId: 'pm1', fromDevice: false }+ await session.syncSwarmCards()+ await vi.waitFor(() => expect(ofType(port, 'supertab.notice.read')).toEqual([{ t: 'supertab.notice.read', tab: 'st1', lead: 'lead1', chatId: 'pm1' }]))+ await session.syncSwarmCards()+ await new Promise((r) => setTimeout(r, 350))+ expect(ofType(port, 'supertab.notice.read')).toHaveLength(1)+ } finally { await session.stop() }+ })++ it('asks recaps and talks with chat, and passes chatId on the recap', async () => {+ const swarmSay = vi.fn(async () => true)+ const host = cardHost({ cards: [card('st1', [lead(1, { chat: group })])] }, {+ transcribe: vi.fn(async () => 'ship it'), route: vi.fn(), swarmSay,+ swarmCardRecap: vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'From the group', at: 7, none: false, chatId: 'g1' })),+ })+ const { session, port } = await connect(host)+ try {+ port.say(ROUND)+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))+ port.say({ t: 'supertab.recap.get', tab: 'st1', lead: 'lead1' })+ await vi.waitFor(() => expect(ofType(port, 'supertab.recap')).toEqual([+ { t: 'supertab.recap', tab: 'st1', lead: 'lead1', text: 'From the group', at: 7, none: false, chatId: 'g1' }]))+ expect(vi.mocked(host.swarmCardRecap!).mock.calls).toEqual([['st1', 'lead1', true]])+ port.say({ t: 'supertab.open', tab: 'st1', lead: 'lead1' }); await settle()+ expect(vi.mocked(host.swarmCardOpen!).mock.calls.at(-1)).toEqual([expect.stringMatching(/^c\d+$/), 'st1', 'lead1', true])+ // A pushed recap reaches this dial only as the chat's: the Pro's Lead recap of the same Lead is not its.+ await session.swarmCardRecap({ tabId: 'st1', leadId: 'lead1', text: 'the Lead', at: 8, none: false })+ await session.swarmCardRecap({ tabId: 'st1', leadId: 'lead1', text: 'the group again', at: 9, none: false, chatId: 'g1' })+ expect(ofType(port, 'supertab.recap').map((r) => r.text)).toEqual(['From the group', 'the group again'])+ port.say({ t: 'supertab.open', tab: 'st1', lead: '' }); await settle()+ expect(vi.mocked(host.swarmCardOpen!).mock.calls.at(-1)).toEqual([expect.stringMatching(/^c\d+$/), 'st1', null, true])+ voice(port, 'a1')+ await vi.waitFor(() => expect(swarmSay).toHaveBeenCalled())+ expect(swarmSay.mock.calls[0]).toEqual(['a1', 'ship it', true])+ } finally { await session.stop() }+ })++ it('12 Leads with chats stay under the device\'s 512-token guard', async () => {+ const wide = 'é'.repeat(24) // 48 bytes+ const cards = [card('st1', Array.from({ length: 13 }, (_, l) => lead(l, {+ project: wide, owner: wide, local: 'a'.repeat(47), engine: 'codex', id: `l${'x'.repeat(40)}${l}`, projectId: `p${'y'.repeat(40)}${l}`, order: 100 + l,+ chat: { kind: 'group', id: `g${'z'.repeat(40)}${l}`, name: wide, working: true, since: 4000 }, notice: notice(`n${l}`) })), { name: wide, count: 40 })]+ const { session, port } = await connect(cardHost({ cards }))+ try {+ port.say(ROUND)+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))+ const [frame] = ofType(port, 'supertab')+ expect(frame.leads).toHaveLength(12)+ expect(tokens(frame)).toBeLessThan(512)+ } finally { await session.stop() }+ })+ })})diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex c1fc08316..a81fed114 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -167,10 +167,27 @@ const RECAP_FRAME_MAX = 6 * 1024/** Repeats of one Lead's recap request inside this are ignored; a device that picks another stale announce within this is not followed. */const RECAP_REPEAT_MS = 1000const PICK_ECHO_MS = 2000-/** The recap frame, its text shortened (on a character) until the whole JSON fits what the Pro reads. */+/** The recap frame, its text shortened (on a character) until the whole JSON fits what the Pro reads. A chat's recap names+ * its chat (`chatId`), for a round dial that speaks swarmChat; any other is today's frame. */export function recapFrame(r: LeadRecap): Message {- const make = (text: string): Message => ({ t: 'supertab.recap', tab: r.tabId, lead: r.leadId, text, at: r.at, none: r.none })- let text = r.text+ return fitText(r.text, (text) => ({ t: 'supertab.recap', tab: r.tabId, lead: r.leadId, text, at: r.at, none: r.none, ...(r.chatId ? { chatId: r.chatId } : {}) }))+}+/** A Lead's entry for a swarmChat dial: its face chat, `work` only for a working group (with that group's clock), and never+ * `ask` or `stuck`, which a group's state used to raise. A Lead whose chat did not come through reads as its Lead chat. */+function chatLead(l: SwarmLead): Record<string, unknown> {+ const working = l.chat?.kind === 'group' && l.chat.working+ return { id: l.id, projectId: l.projectId, project: l.project, engine: l.engine, owner: l.owner, local: l.local,+ state: working ? 'work' : 'done', order: l.order, ...(working && l.chat!.since !== undefined ? { since: l.chat!.since } : {}),+ ...(l.chat ? { chat: l.chat.kind, chatId: l.chat.id, chatName: l.chat.name } : {}) }+}+/** A Lead's new message as the round dial's alert, sized as the recap is. */+function noticeFrame(tab: string, lead: string, n: LeadNotice): Message {+ return fitText(n.text, (text) => ({ t: 'supertab.notice', tab, lead, chat: n.chat, chatId: n.chatId, id: n.id, text, at: n.at }))+}+/** `make(text)`, with the text shortened (on a character) until the whole JSON fits what a dial reads: escapes can grow+ * 1,500 bytes of text past it. */+function fitText(full: string, make: (text: string) => Message): Message {+ let text = fullwhile (text && Buffer.byteLength(JSON.stringify(make(text))) > RECAP_FRAME_MAX) text = truncateUtf8(text, Math.floor(Buffer.byteLength(text) * 0.9))return make(text)}@@ -277,6 +294,8 @@ export interface AppSwarms {id: string; name: string; agentIds: string[]; panes: number/** A Super Tab (Swarm) tab: which Swarm it shows and the project the window has open in it. Absent on any other tab. */superTabId?: string; projectId?: string+ /** The conversation the window has open in that Swarm tab, when it is one (its Lead's, Chat with PM or a group). */+ conversationId?: string}>/** The ACTIVE swarm's grid. Empty from a window that predates the field, or one with no panes. */tiles: CableTile[]@@ -304,7 +323,7 @@ import type { FormCommand, FormResult } from './windowForm.js'import { deriveLongRecap, extendShortRecap } from '../lib/deviceRecap.js'import type { TurnStatsFields } from './turnStats.js'import type { Tier } from '../lib/notifyTier.js'-import type { LeadRecap, SwarmCard } from '../superTabs/cards.js'+import type { LeadNotice, LeadRecap, SwarmCard, SwarmLead } from '../superTabs/cards.js'import { truncateUtf8 } from '../lib/deviceRecentTrim.js'export interface RouteDecision {@@ -340,15 +359,15 @@ export interface CableHost {/** A device that speaks `swarmCard: 'v1'` is attached (true) or gone (false): the core starts or stops reading the Swarms. */swarmCardsWanted?(on: boolean): void/** One Lead's last message, read on request; null when it could not be read. */- swarmCardRecap?(tabId: string, leadId: string): Promise<LeadRecap | null>+ swarmCardRecap?(tabId: string, leadId: string, chat?: boolean): Promise<LeadRecap | null>/** The recap a device has open (its Lead), or null once it closes: the only one pushed when its text changes. */- swarmCardOpen?(session: string, tabId: string, leadId: string | null): void+ swarmCardOpen?(session: string, tabId: string, leadId: string | null, chat?: boolean): void/** Words for a Lead that runs here: posted as the person in its Swarm chat. False: not a Lead, send the turn as before. */- swarmSay?(harnessId: string, text: string): Promise<boolean>+ swarmSay?(harnessId: string, text: string, chat?: boolean): Promise<boolean>/** A device picked a Lead: the window opens that Swarm tab and project. */superTabSelected?(superTabId: string, projectId: string): void/** The Swarm tab the window has on screen and the project open in it ('' when none is); null when the active tab is not a Swarm or there is no window. */- activeSwarmProject?(): { superTabId: string; projectId: string; fromDevice: boolean } | null+ activeSwarmProject?(): { superTabId: string; projectId: string; conversationId?: string; fromDevice: boolean } | nullappName(): stringvoiceLang(): string/** The window's latest selected pane, including selections made before this dial attached. */@@ -662,6 +681,10 @@ export class CableSession {private superTabWaits = false/** `swarmCard: 'v1'` (a Pro): the Swarm cards, their Leads' recaps and the Swarm focus travel on the cable. */private swarmCard = false+ /** `swarmChat: 'v1'` (the round dial, design 2026-10-28-round-dial-swarm-chat): each Lead's face is the chat the desktop has+ * open in its project, its recap is that chat's, `work` only for a working group, and the alerts are the Lead's new+ * messages (`supertab.notice`). Any other device gets today's frames byte for byte. */+ private swarmChat = falseprivate playerOffset = 0private playerRequest = 0private playerLibraryKey = ''@@ -675,14 +698,14 @@ export class CableSession {/** For the greeting's log line: which capabilities this hello named, or nothing. */private capabilitiesNamed(): string {- const named = [this.swarmMembers && 'swarms', this.longRecap && 'recap', this.stepsActivity && 'activity', this.statsTurn && 'stats', this.playerCapable && 'player', this.superTabWaits && 'superTab', this.swarmCard && 'swarmCard']+ const named = [this.swarmMembers && 'swarms', this.longRecap && 'recap', this.stepsActivity && 'activity', this.statsTurn && 'stats', this.playerCapable && 'player', this.superTabWaits && 'superTab', this.swarmCard && 'swarmCard', this.swarmChat && 'swarmChat'].filter(Boolean)return named.length ? ` caps ${named.join(',')}` : ''}private resetCapabilities(): void {this.swarmMembers = this.longRecap = this.stepsActivity = this.statsTurn = this.playerCapable = this.superTabWaits = false- this.swarmCard = false+ this.swarmCard = this.swarmChat = falsethis.dropCards()this.seqOn = falsethis.seq = 0@@ -1244,6 +1267,7 @@ export class CableSession {this.playerCapable = str('player') === 'library-v1'this.superTabWaits = str('superTab') === 'wait-v1'this.swarmCard = str('swarmCard') === 'v1'+ this.swarmChat = this.swarmCard && str('swarmChat') === 'v1'this.wantCards(this.swarmCard)this.seqOn = str('board') === 'pro'this.seq = 0@@ -2264,7 +2288,7 @@ export class CableSession {}// Spoken to a Swarm Lead (its card or its tile): the words go to the Swarm chat as the person's, where everyone in the// tab sees them, not typed into the Lead's terminal. Any other harness, or a failed post, gets the turn as before.- if (turn.agentId && !carried && !selection?.ok && await this.host.swarmSay?.(agentId, instruction).catch(() => false)) {+ if (turn.agentId && !carried && !selection?.ok && await this.host.swarmSay?.(agentId, instruction, ...this.chatFlag()).catch(() => false)) {if (!current()) returnthis.log(`cable: voice → Swarm chat of ${agentId.slice(0, 8)}`)await reply({ t: 'voice.transcript', routeId: '', text: transcript, agentId, agentName, needsConfirm: false })@@ -2604,6 +2628,17 @@ export class CableSession {/** The project this Pro itself picked last and when: the desktop's announce of it is no news, and a stale one of another is held off. */private picked: { key: string; at: number } | null = nullprivate lastRecapGet: { key: string; at: number } | null = null+ /** A swarmChat dial's alerts (`${tab}:${lead}`): the notice it was last given or shown as already there, and whether it+ * was read on the desktop since. A notice is sent once, never on an attach or resync (it was there before), never for+ * the chat the desktop has open; `notice.read` once when the desktop opens the chat of one that was sent. */+ private readonly notices = new Map<string, { id: string; chatId: string; open: boolean }>()+ /** Until this session has seen a list with Swarms in it: the first one is a replay too. A dial can attach before its+ * process has the cards (the devices' process started again), and the core's replay of the last list then comes as an+ * ordinary push, whose notices are old. */+ private noticesReplay = true++ /** The extra argument a swarmChat dial's requests carry; none for any other device, whose calls stay as they were. */+ private chatFlag(): [] | [true] { return this.swarmChat ? [true] : [] }/** Tell the core a capable device is here (or gone), once per change: it reads the Swarms only while one is. */private wantCards(on: boolean): void {@@ -2622,7 +2657,9 @@ export class CableSession {this.focusLogged = ''this.picked = nullthis.lastRecapGet = null- if (this.openLead) this.host.swarmCardOpen?.(this.cardSession, this.openLead.tabId, null)+ this.notices.clear()+ this.noticesReplay = true+ if (this.openLead) this.host.swarmCardOpen?.(this.cardSession, this.openLead.tabId, null, ...this.chatFlag())this.openLead = nullthis.wantCards(false)}@@ -2663,16 +2700,51 @@ export class CableSession {// The desk tab of the same Swarm, when the window has one: empty when it is closed or never opened it.const tab = desk.find((s) => s.superTabId === card.id)?.id ?? ''const frame = { t: 'supertab', id: card.id, tab, name: card.name, count: card.count,- leads: card.leads.slice(0, SWARM_LEADS_MAX).map((l) => ({ id: l.id, projectId: l.projectId, project: l.project,- engine: l.engine, owner: l.owner, local: l.local, state: l.state, order: l.order, ...(l.since === undefined ? {} : { since: l.since }) })) }+ leads: card.leads.slice(0, SWARM_LEADS_MAX).map((l) => this.swarmChat ? chatLead(l) : { id: l.id, projectId: l.projectId, project: l.project,+ engine: l.engine, owner: l.owner, local: l.local, state: l.state, order: l.order, ...(l.since === undefined ? {} : { since: l.since }) }) }const key = JSON.stringify(frame)if (this.cardKeys.get(card.id) === key) continuethis.cardKeys.set(card.id, key)await this.send(frame)}+ if (this.swarmChat) await this.pushNotices(cards, force)await this.pushSwarmFocus()}+ /**+ * A swarmChat dial's alerts, after the Leads they name. `replay` (attach, resync): the notices there now were there before+ * the dial came, so they are noted and not sent; one that arrives later is sent once. One for the chat the desktop has+ * open is read there already: noted, not sent. A sent one whose chat the desktop then opens is read on the dial too.+ */+ private async pushNotices(cards: SwarmCard[], force: boolean): Promise<void> {+ const replay = force || this.noticesReplay+ if (cards.length) this.noticesReplay = false+ const open = this.host.activeSwarmProject?.()+ const live = new Set<string>()+ for (const card of cards) {+ for (const lead of card.leads.slice(0, SWARM_LEADS_MAX)) {+ const key = `${card.id}:${lead.id}`+ live.add(key)+ const notice = lead.notice+ const opened = open?.superTabId === card.id && open.conversationId === notice?.chatId+ const held = this.notices.get(key)+ if (!notice) { this.notices.delete(key); continue }+ if (held?.id !== notice.id) {+ // Replayed or read on the desktop: noted as not open on the dial, so nothing is sent for it now or later.+ const sent = !replay && !opened+ this.notices.set(key, { id: notice.id, chatId: notice.chatId, open: sent })+ if (sent) await this.send(noticeFrame(card.id, lead.id, notice))+ continue+ }+ if (held.open && opened) {+ held.open = false+ await this.send({ t: 'supertab.notice.read', tab: card.id, lead: lead.id, chatId: held.chatId })+ }+ }+ }+ for (const key of [...this.notices.keys()]) if (!live.has(key)) this.notices.delete(key)+ }+/*** Point the Pro at the Lead of the project the window has open, once per change and never at its own pick. A Swarm tab* with no project open (its Chat with PM, a DM) still takes the device into that Swarm: `lead: ''` lets it open on the@@ -2713,6 +2785,8 @@ export class CableSession {/** A Lead's changed text, for the Pro that has that Lead's recap open. */async swarmCardRecap(recap: LeadRecap): Promise<void> {if (!this.swarmCard || this.openLead?.tabId !== recap.tabId || this.openLead.leadId !== recap.leadId) return+ // The service pushes a Lead's recap and its face chat's apart: each device takes only the kind it asked for.+ if (this.swarmChat !== (recap.chatId !== undefined)) returnreturn this.queued(async () => { await this.send(recapFrame(recap)) })}@@ -2722,13 +2796,13 @@ export class CableSession {// The recap closing names no Lead: it is the one request that may leave a field empty.if (type === 'supertab.open' && lead === '') {this.openLead = null- this.host.swarmCardOpen?.(this.cardSession, tab, null)+ this.host.swarmCardOpen?.(this.cardSession, tab, null, ...this.chatFlag())return}if (!CARD_ID.test(tab) || !CARD_ID.test(lead)) returnif (type === 'supertab.open') {this.openLead = { tabId: tab, leadId: lead }- this.host.swarmCardOpen?.(this.cardSession, tab, lead)+ this.host.swarmCardOpen?.(this.cardSession, tab, lead, ...this.chatFlag())return}if (type === 'supertab.select') {@@ -2745,7 +2819,7 @@ export class CableSession {if (this.lastRecapGet?.key === asked && now - this.lastRecapGet.at < RECAP_REPEAT_MS) returnthis.lastRecapGet = { key: asked, at: now }let recap: LeadRecap | null = null- try { recap = await this.host.swarmCardRecap?.(tab, lead) ?? null } catch (err) { this.log(`cable: recap for ${lead} failed (${(err as Error).message})`) }+ try { recap = await this.host.swarmCardRecap?.(tab, lead, ...this.chatFlag()) ?? null } catch (err) { this.log(`cable: recap for ${lead} failed (${(err as Error).message})`) }// Nothing on a failure: the Pro keeps its "…" and asks again on the next open.if (recap) await this.queued(async () => { await this.send(recapFrame(recap)) })}diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 538b77937..6ddeadff1 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -1218,11 +1218,21 @@ export type AdoptSwarmSkill = (session: RegisteredSession, current: () => booleaexport type LeadState = 'ask' | 'stuck' | 'work' | 'done'/** One Swarm's Lead on a Harness Pro's card (superTabs/cards.ts). `order`: the project's index in the Swarm (the app's* order), so a dial can show the Leads as the app does whatever their urgency. */-export interface SwarmLead { id: string; projectId: string; project: string; engine: string; owner: string; local: string; state: LeadState; order: number; since?: number }+export interface SwarmLead { id: string; projectId: string; project: string; engine: string; owner: string; local: string; state: LeadState; order: number; since?: number; chat?: SwarmChat; notice?: LeadNotice }/** One Swarm this account is in, as a Harness Pro's card: its Leads, most urgent first. */export interface SwarmCard { id: string; name: string; count: number; leads: SwarmLead[] }-/** A Lead's last message, for its card. */-export interface LeadRecap { tabId: string; leadId: string; text: string; at: number; none: boolean }+/** A Lead's last message, for its card; `chatId` when it is the last message of the chat on the round dial's face. */+export interface LeadRecap { tabId: string; leadId: string; text: string; at: number; none: boolean; chatId?: string }+/** A project's three places to chat (design 2026-10-28-round-dial-swarm-chat): its Lead conversation, the reader's Chat+ * with PM, and a group. */+export type ChatKind = 'lead' | 'pm' | 'group'+/** The chat on a project's face on the round dial: the Lead's, unless the window has the project's PM chat or a group+ * open. `working` only for a working group, `since` from one of its agents' turn here. */+export interface SwarmChat { kind: ChatKind; id: string; name: string; working: boolean; since?: number }+/** The newest message the project's Lead wrote in its Lead conversation or Chat with PM since the baseline: the dial's alert. */+export interface LeadNotice { chat: 'lead' | 'pm'; chatId: string; id: string; text: string; at: number }+/** The conversation the window has open in a Swarm tab. */+export interface CardFocus { tabId: string; conversationId: string }/** The Super Tab service's door into the core (superTabs/inCore/attention.ts): the waits of its members here. */export interface SuperTabsCore {@@ -1654,6 +1664,8 @@ export const LANE_OFF: LaneSeal = {export interface HttpAnswer {status: numberbody: Record<string, unknown>+ /** A busy or failing answer's Retry-After, when it had one (gateway/accountHttp.ts). */+ retryAfterMs?: number}/** What the core's status reads of the relay: the machine's E2EE fingerprint, its pairings and the onediff --git a/cli/src/core/devicesLink.spec.ts b/cli/src/core/devicesLink.spec.tsindex 6627ba1e8..fb123a428 100644--- a/cli/src/core/devicesLink.spec.ts+++ b/cli/src/core/devicesLink.spec.ts@@ -236,4 +236,19 @@ describe('the devices\' Swarm card requests to the Super Tab service', () => {const bare = createDevicesLink({ core: fakeCore(), notify: () => true, call: vi.fn(), state: () => STATE })expect(await bare.answer('super_tabs', { action: 'cardsWanted', on: true })).toEqual({ error: 'SERVICE_UNAVAILABLE' })})++ it('passes the window\'s focus with the wish and a swarmChat dial\'s chat flag, and only when they are there', async () => {+ const superTabRequest = vi.fn(async (payload: Record<string, unknown>) => ({ ok: true, echoed: payload }))+ const core = fakeCore()+ core.superTabRequest = superTabRequest+ const devices = createDevicesLink({ core, notify: () => true, call: vi.fn(), state: () => STATE })+ const focus = { tabId: 't1', conversationId: 'g1' }+ expect((await devices.answer('super_tabs', { action: 'cardsWanted', on: true, include: ['t1'], focus })).echoed).toEqual({ action: 'cardsWanted', on: true, include: ['t1'], focus })+ expect((await devices.answer('super_tabs', { action: 'cardRecap', tabId: 't1', leadId: 'l1', chat: true })).echoed).toEqual({ action: 'cardRecap', tabId: 't1', leadId: 'l1', chat: true })+ expect((await devices.answer('super_tabs', { action: 'cardOpen', session: 'c1', tabId: 't1', leadId: 'l1', chat: true })).echoed).toEqual({ action: 'cardOpen', session: 'c1', tabId: 't1', leadId: 'l1', chat: true })+ expect((await devices.answer('super_tabs', { action: 'cardSay', harnessId: 'h1', text: 'ship it', chat: true })).echoed).toEqual({ action: 'cardSay', harnessId: 'h1', text: 'ship it', chat: true })+ // Anything but a literal true is no chat, and a missing focus is none: today's requests exactly.+ expect((await devices.answer('super_tabs', { action: 'cardRecap', tabId: 't1', leadId: 'l1', chat: 'yes' })).echoed).toEqual({ action: 'cardRecap', tabId: 't1', leadId: 'l1' })+ expect((await devices.answer('super_tabs', { action: 'cardsWanted', on: true, include: [] })).echoed).toEqual({ action: 'cardsWanted', on: true, include: [] })+ })})diff --git a/cli/src/core/devicesLink.ts b/cli/src/core/devicesLink.tsindex e7224ef4d..41660a809 100644--- a/cli/src/core/devicesLink.ts+++ b/cli/src/core/devicesLink.ts@@ -125,9 +125,12 @@ export function createDevicesLink(deps: DevicesLinkDeps) {// The Swarm cards' requests (core/main.ts `superTabRequest` allows those and no other action of the Super Tab service).super_tabs: async (payload) => {if (!core.superTabRequest) return { error: 'SERVICE_UNAVAILABLE' }- const { action, tabId, leadId, on, include, session, harnessId, text } = payload- return core.superTabRequest(action === 'cardsWanted' ? { action, on: on === true, include }- : action === 'cardSay' ? { action, harnessId, text } : { action, tabId, leadId, session })+ const { action, tabId, leadId, on, include, session, harnessId, text, focus } = payload+ // A round dial that speaks swarmChat asks for the chat on the face, and the window's open conversation rides with the+ // wish (superTabs/inCore/cards.ts checks both); absent, the request is today's.+ const chat = payload.chat === true ? { chat: true } : {}+ return core.superTabRequest(action === 'cardsWanted' ? { action, on: on === true, include, ...(focus !== undefined ? { focus } : {}) }+ : action === 'cardSay' ? { action, harnessId, text, ...chat } : { action, tabId, leadId, session, ...chat })},// The transcriber's and the fleet's lane's sign-in, and the lane's sealing, asked of the core at every// use as every service in its own process asks them (core/accountQueries.ts): the devices hold nodiff --git a/cli/src/core/gatewayLink.spec.ts b/cli/src/core/gatewayLink.spec.tsindex 9b2ff3817..bb52b3771 100644--- a/cli/src/core/gatewayLink.spec.ts+++ b/cli/src/core/gatewayLink.spec.ts@@ -808,6 +808,14 @@ describe('account HTTP owned by the gateway', () => {expect(call).toHaveBeenLastCalledWith(GATEWAY_CALLS.backend, { method: 'GET', path: '/api/auth/me' }, 25_000)await link.ops.backend('PATCH', '/api/machines/m1', { name: 'Laptop' })expect(call).toHaveBeenLastCalledWith(GATEWAY_CALLS.backend, { method: 'PATCH', path: '/api/machines/m1', body: { name: 'Laptop' } }, 25_000)+ // A busy answer's Retry-After crosses to the core, so the daemon can pass it on to the Desktop's reports.+ const busy = { success: false, error: { code: 'USAGE_WRITE_CONFLICT' } }+ call.mockResolvedValueOnce({ status: 429, body: busy, retryAfterMs: 90_000 })+ expect(await link.ops.backend('POST', '/api/product-usage/report', {})).toEqual({ status: 429, body: busy, retryAfterMs: 90_000 })+ for (const junk of [-1, Number.NaN, 'PRIVATE', null]) {+ call.mockResolvedValueOnce({ status: 429, body: busy, retryAfterMs: junk })+ expect(await link.ops.backend('POST', '/api/product-usage/report', {})).toEqual({ status: 429, body: busy })+ }call.mockResolvedValueOnce({ name: 'private-grid' })expect(await link.ops.mintGridName()).toBe('private-grid')call.mockResolvedValueOnce({})diff --git a/cli/src/core/gatewayLink.ts b/cli/src/core/gatewayLink.tsindex c0897750d..bfa64791b 100644--- a/cli/src/core/gatewayLink.ts+++ b/cli/src/core/gatewayLink.ts@@ -214,7 +214,11 @@ export function createGatewayLink(deps: GatewayLinkDeps) {const http = async (type: string, payload: Record<string, unknown> = {}, waitMs?: number): Promise<HttpAnswer> => {const answer = await deps.call(type, payload, waitMs)- return typeof answer.status === 'number' ? { status: answer.status, body: record(answer.body) } : UNAVAILABLE+ if (typeof answer.status !== 'number') return UNAVAILABLE+ // A busy answer's Retry-After (gateway/accountHttp.ts), which the daemon passes on to the Desktop's reports.+ const retry = answer.retryAfterMs+ return { status: answer.status, body: record(answer.body),+ ...(typeof retry === 'number' && Number.isFinite(retry) && retry >= 0 ? { retryAfterMs: retry } : {}) }}/**diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex f22615132..d06f5da26 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -1965,7 +1965,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Account HTTP and the persistent machine cache belong to the gateway. The core routes the request// and keeps only state reported by that service, so a backend outage cannot stall an agent's loop.- function proxyBackend(method: string, path: string, body?: unknown): Promise<{ status: number; body: Record<string, unknown> }> {+ function proxyBackend(method: string, path: string, body?: unknown): Promise<{ status: number; body: Record<string, unknown>; retryAfterMs?: number }> {return gatewayOps.backend(method, path, body)}diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex 3c81ef9c1..970780f91 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -541,6 +541,14 @@ describe('account Experimental settings proxy', () => {const failed = await post(body)expect(failed.status).toBe(502)expect(await failed.text()).not.toContain('PRIVATE_CANARY')+ // The backend's busy answer reaches the Desktop with its Retry-After, which the Desktop waits out.+ const busy = { success: false, error: { code: 'USAGE_WRITE_CONFLICT', message: 'Usage measurement busy' } }+ send.mockResolvedValueOnce({ status: 429, body: busy, retryAfterMs: 90_500 } as never)+ const refused = await post(body)+ expect(refused.status).toBe(429)+ expect(refused.headers.get('retry-after')).toBe('91')+ expect(await refused.json()).toEqual(busy)+ expect((await post(body)).headers.get('retry-after')).toBeNull()})it('forwards the current Desktop health report intact while rejecting private context', async () => {const body = JSON.parse(readFileSync(new URL('../../tests/fixtures/desktop-product-usage-report.json', import.meta.url), 'utf8'))diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 3328a6c87..796d4a4ad 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -59,6 +59,8 @@ export function chooseHookAgent<T>(byAncestry: readonly T[], byRuntimeOnly: readexport interface PairOutcome {status: numberbody: Record<string, unknown>+ /** A busy backend's Retry-After, passed on where an answer is forwarded whole (the usage report). */+ retryAfterMs?: number}export interface HookServerHandlers {@@ -1101,6 +1103,8 @@ export function startHookServer(}try {const result = await handlers.onProductUsageReport(report)+ // The Desktop waits a busy answer out (desktop/lib/measurement/product_measurement.dart).+ if (result.retryAfterMs !== undefined) res.setHeader('Retry-After', String(Math.ceil(result.retryAfterMs / 1000)))json(result.status, result.body)} catch { json(502, { success: false, error: { code: 'USAGE_UNAVAILABLE', message: 'Product usage unavailable' } }) }returndiff --git a/cli/src/lib/spreadNotice.ts b/cli/src/lib/spreadNotice.tsnew file mode 100644index 000000000..fa03454db--- /dev/null+++ b/cli/src/lib/spreadNotice.ts@@ -0,0 +1,20 @@+/**+ * A notice handed on at a random moment within `spreadMs` of the first told, once for every notice told before it goes:+ * what it makes a reader read again is read after each of them. Prod 2026-10-28: the backend told every computer of a+ * person about an invitation at the same moment, and every window read the shares list in that same second; across a+ * Swarm's members the reads came in waves that held the backend at its pod limit.+ */+export function spreadNotice(hand: () => void, spreadMs: number): { tell(): void; stop(): void } {+ let timer: ReturnType<typeof setTimeout> | null = null+ return {+ tell() {+ if (timer) return+ timer = setTimeout(() => { timer = null; hand() }, Math.floor(Math.random() * spreadMs))+ timer.unref?.()+ },+ stop() {+ if (timer) clearTimeout(timer)+ timer = null+ },+ }+}diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.tsindex 4e9aafa38..3386bee7f 100644--- a/cli/src/lib/swarmSkills.spec.ts+++ b/cli/src/lib/swarmSkills.spec.ts@@ -75,6 +75,34 @@ describe('built-in Swarm skills', () => {const twoHours = '- A Builder or Reviewer that has been down for 2 hours (machine offline, session gone or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).\n'// A failed start is never left (the round-device group, 2026-10-27; superTabs/start.ts): the Lead's alone, in both modes.const failedStart = '- A failed start is retried elsewhere or reported, never left: when one fails, resume it; it starts once on the route\'s next machine, or tells the group and its requester. A task that requires a machine or device never moves: when its route says it waits, keep it queued and route it again once that machine can take it.\n'+ // The review the Swarm opens by itself (#610, Dee 2026-10-28: reviews start the moment work is ready): each line replaces+ // one the owner approved, which the byte-for-byte checks below put back. [mode, role, new line, approved line].+ const autoReview: Array<['orchestration' | 'default', 'lead' | 'dev', string, string]> = [+ ['orchestration', 'lead', "- When a Builder marks ready for review with a pull request of the project's repository, the Swarm opens \"Review: <group>\" by itself: its brief holds the goal, constraints, owned code, checks, the Builder's handoff and the pull request, privacy first when the work touches sharing or access. A free Reviewer gets it (the one that reviewed the earlier head, for a re-review) and joins the Builder's group to pass the independent check. You get one line there; cancel the review if it is not needed, and post what its brief lacks (the spec's constraints copied verbatim, the most-likely-wrong list). When the line says no Reviewer is free, route the review group, start a Reviewer (prefer a different engine than the Builder, with a model at least as strong), assign it and add it to the Builder's group. Work marked ready without a pull request link gets the same group from you, by hand. A review with no verdict stays open while the work it reviews goes on.\n",+ "- When a Builder marks ready for review, create a group \"Review: <group>\" whose brief holds only: goal, constraints, the spec's constraints copied verbatim, checks, the most-likely-wrong list, the Builder's rulings, the revision range and the Builder's handoff. Route it, assign it to a Reviewer (reuse an idle one first; prefer a different engine than the Builder, with a model at least as strong), and add the Reviewer to the Builder's group so it can pass the independent check.\n"],+ ['orchestration', 'dev', "No merge, and no push but your own work branch: at least every 30 minutes, and when the group needs review, with a pull request for it. Never start a reviewer for your own work.",+ "No merge, PR or push, except pushing your own work branch: at least every 30 minutes, and when the group needs review. Never start a reviewer for your own work."],+ ['orchestration', 'dev', "- If the group needs review, push your work branch, open a pull request for it (never merge it) and mark ready for review with the revision and the pull request link: the Swarm opens the review from that handoff, so it carries your rulings, revision range and doubts. Otherwise mark done.\n",+ "- If the group needs review, push your work branch (the branch only; no PR, no merge) and mark ready for review with the revision. Otherwise mark done.\n"],+ ['orchestration', 'dev', "- Merge, push, open a PR, release, force-push or discard only when told; the exceptions are pushing your own work branch every 30 minutes, and its pull request for review.\n",+ "- Merge, push, open a PR, release, force-push or discard only when told; the one exception is pushing your own work branch, every 30 minutes and for review.\n"],+ ['default', 'lead', "- Work that will be merged, or carries medium risk or more, gets a Reviewer. When its Builder marks ready for review with a pull request link, the Swarm opens \"Review: <group>\", assigns a free Reviewer and tells you in one line; cancel it there if it is not needed. When no Reviewer is free, route it, start one, assign it and add it to the Builder's group. Without a pull request link, create the review group yourself the same way.\n",+ "- Work that will be merged, or carries medium risk or more, gets a Reviewer: create \"Review: <group>\", route it, assign it, and add the Reviewer to the Builder's group.\n"],+ ['default', 'dev', "- Mark ready for review, with the revision and the PR link, when the work needs review: the Swarm opens the review from your handoff. Otherwise mark done.\n",+ "- Mark ready for review when the group has a Reviewer; otherwise mark done.\n"],+ ]+ const approved = (text: string, mode: 'orchestration' | 'default') =>+ autoReview.filter(([m]) => m === mode).reduce((t, [, , line, before]) => t.replace(line, before), text)+ it('tells each Lead the Swarm opens reviews by itself, and each Builder to hand off with a pull request link', () => {+ for (const [mode, role, line, before] of autoReview) {+ const text = readFileSync(prepareSwarmSkill(fixture(), { role, key: 'session', mode }).file, 'utf8')+ expect(text.split(line), `${mode} ${role}`).toHaveLength(2)+ expect(text).not.toContain(before)+ }+ for (const mode of ['orchestration', 'default'] as const) {+ expect(readFileSync(prepareSwarmSkill(fixture(), { role: 'review', key: 'session', mode }).file, 'utf8')).not.toContain('opens the review')+ }+ })it.each([['lead', 'b9254e4bb5c633a73e1b87e6ca6690915e1c3a7bb55db0d3d093e6710dd719db'],['dev', 'e78ce31a71f169d8956a2acd46e8bb43b79bd654b80b0fe3c33dbced9d2c3c75'],@@ -100,7 +128,7 @@ describe('built-in Swarm skills', () => {expect(text.split(ask)).toHaveLength(role === 'dev' ? 2 : 1)expect(text.split(requests)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(failedStart)).toHaveLength(role === 'lead' ? 2 : 1)- expect(sha(text.replace(twoHours, '').replace(terminal, '').replace(overlap, '').replace(local, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '')+ expect(sha(approved(text, 'orchestration').replace(twoHours, '').replace(terminal, '').replace(overlap, '').replace(local, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '').replace(limit, '').replace(digest, '').replace(decision, '').replace(ask, '').replace(requests, ''))).toBe(sha256)}})@@ -167,8 +195,9 @@ describe('built-in Swarm skills', () => {it('adds the checkpoint line where each Builder skill keeps others able to resume its work', () => {const orchestration = readFileSync(prepareSwarmSkill(fixture(), { role: 'dev', key: 'session' }).file, 'utf8')expect(orchestration).toContain(`never redo a committed step.\n${checkpoint}`)- // The orchestration Builder pushed only for review; its checkpoint push is now the other exception.- expect(orchestration).toContain('No merge, PR or push, except pushing your own work branch: at least every 30 minutes, and when the group needs review.')+ // The orchestration Builder pushed only for review; its checkpoint push is now the other exception (and its review push+ // carries a pull request, #610).+ expect(orchestration).toContain('no push but your own work branch: at least every 30 minutes, and when the group needs review, with a pull request for it.')expect(orchestration).not.toContain('only for review, only when the group needs it')const plain = readFileSync(prepareSwarmSkill(fixture(), { role: 'dev', key: 'session', mode: 'default' }).file, 'utf8')expect(plain).toContain(`- Have something to show at least every 20 minutes: a push or a short progress line.\n${checkpoint}`)@@ -195,7 +224,7 @@ describe('built-in Swarm skills', () => {expect(text.split(ask)).toHaveLength(role === 'dev' ? 2 : 1)expect(text.split(requestsLast)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(failedStart)).toHaveLength(role === 'lead' ? 2 : 1)- expect(sha(text.replace(terminal, '').replace(overlap, '').replace(localDefault, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '')+ expect(sha(approved(text, 'default').replace(terminal, '').replace(overlap, '').replace(localDefault, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '').replace(limit, '').replace(digest, '').replace(decision, '').replace(ask, '').replace(requestsLast, ''))).toBe(sha256)expect(prepared.instructions).toBe(`Use the swarm-${role} skill for this session: the team process; otherwise work your usual way. Before working, read ${JSON.stringify(prepared.file)} with your file or shell tool.`)})diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.tsindex 663f28cd9..aa1bc3441 100644--- a/cli/src/lib/swarmSkills.ts+++ b/cli/src/lib/swarmSkills.ts@@ -123,7 +123,7 @@ For large work, post the group plan and get the owner's ok before assigning; onc## 8. Review- Independent review is required when risk or difficulty is medium or higher, when the work touches security, data, defaults or a release, or when the result will be merged. Also bring in a Reviewer when a Builder is stuck, before a large refactor, or after a hard bug fix.- Read the Builder's doubts first; settle any doubt about correctness or scope before the review starts.-- When a Builder marks ready for review, create a group "Review: <group>" whose brief holds only: goal, constraints, the spec's constraints copied verbatim, checks, the most-likely-wrong list, the Builder's rulings, the revision range and the Builder's handoff. Route it, assign it to a Reviewer (reuse an idle one first; prefer a different engine than the Builder, with a model at least as strong), and add the Reviewer to the Builder's group so it can pass the independent check.+- When a Builder marks ready for review with a pull request of the project's repository, the Swarm opens "Review: <group>" by itself: its brief holds the goal, constraints, owned code, checks, the Builder's handoff and the pull request, privacy first when the work touches sharing or access. A free Reviewer gets it (the one that reviewed the earlier head, for a re-review) and joins the Builder's group to pass the independent check. You get one line there; cancel the review if it is not needed, and post what its brief lacks (the spec's constraints copied verbatim, the most-likely-wrong list). When the line says no Reviewer is free, route the review group, start a Reviewer (prefer a different engine than the Builder, with a model at least as strong), assign it and add it to the Builder's group. Work marked ready without a pull request link gets the same group from you, by hand. A review with no verdict stays open while the work it reviews goes on.- Never tell a Reviewer what not to flag or how to grade it.- Do not review the diff yourself: same blind spots, and it burns the context you need to coordinate.- Re-grade each finding by what a user gets if it ships, not by its label or by the spec's silence. Critical findings are fixed now, Important ones before you accept, Minor ones recorded for later.@@ -183,7 +183,7 @@ You finish one group's work completely, inside its brief, with proof. Work as if1. No production code without a failing test first.2. No fix without a found root cause.3. No "done", "fixed" or "passing" without running the check now and reading its output.-4. Stay inside your brief and owned code. No subagents to split the work; read-only lookups are fine. No merge, PR or push, except pushing your own work branch: at least every 30 minutes, and when the group needs review. Never start a reviewer for your own work.+4. Stay inside your brief and owned code. No subagents to split the work; read-only lookups are fine. No merge, and no push but your own work branch: at least every 30 minutes, and when the group needs review, with a pull request for it. Never start a reviewer for your own work.5. Project instructions (AGENTS.md, CLAUDE.md, CONTRIBUTING) outrank this skill.## 1. Take the assignment@@ -258,7 +258,7 @@ Record each acceptance check with the exact command, revision and observed resul- Finish everything testable. Package any remaining person or device action as one clear step.- Before handing off, re-read your diff: everything in the brief, nothing extra, names that say what things do, edge cases and errors tested, clean output. Fix what you find.- Return everything the brief's hand back names. The handoff says "Ready: yes/no", evidence, the revision range from the commit your work started on, links, and what is unverified. Include red-then-green evidence for each new test and list every Ruling you made. Keep local checks apart from real-environment runs. Put any doubts in the handoff.-- If the group needs review, push your work branch (the branch only; no PR, no merge) and mark ready for review with the revision. Otherwise mark done.+- If the group needs review, push your work branch, open a pull request for it (never merge it) and mark ready for review with the revision and the pull request link: the Swarm opens the review from that handoff, so it carries your rulings, revision range and doubts. Otherwise mark done.## 8. Review findings- Read all findings first. If any is unclear, ask about every unclear one before changing anything.@@ -272,7 +272,7 @@ Record each acceptance check with the exact command, revision and observed resul## 9. Limits- To split the work, ask the Lead to route it. Do not touch other groups' code.-- Merge, push, open a PR, release, force-push or discard only when told; the one exception is pushing your own work branch, every 30 minutes and for review.+- Merge, push, open a PR, release, force-push or discard only when told; the exceptions are pushing your own work branch every 30 minutes, and its pull request for review.- If your task is cancelled, stop and say where you left it.- Print little to save quota. Keep progress and blockers in the group chat.@@ -407,7 +407,7 @@ Keep each Builder's list a few tasks deep; do the easy, self-contained parts fir- When a worker finishes: reuse, keep or stop. Prefer stop.## 5. Review and accept-- Work that will be merged, or carries medium risk or more, gets a Reviewer: create "Review: <group>", route it, assign it, and add the Reviewer to the Builder's group.+- Work that will be merged, or carries medium risk or more, gets a Reviewer. When its Builder marks ready for review with a pull request link, the Swarm opens "Review: <group>", assigns a free Reviewer and tells you in one line; cancel it there if it is not needed. When no Reviewer is free, route it, start one, assign it and add it to the Builder's group. Without a pull request link, create the review group yourself the same way.- Findings go back to the Builder; you rule on disagreements.- Accept only when the reviewed revision is the handed-off revision, its checks have evidence, and CI is green on it.- Close the task saying what was and was not delivered.@@ -464,7 +464,7 @@ You finish one group's work completely, inside its brief, as if nobody will come## 4. Hand off- Ready means: your branch pushed, a PR when the project uses PRs, and green CI on it.- The handoff opens "Ready: yes" or "Ready: no", then: revision, what you checked (command and result), what is not shown yet, the one command or action left for the real device or person if any, and "most likely wrong here".-- Mark ready for review when the group has a Reviewer; otherwise mark done.+- Mark ready for review, with the revision and the PR link, when the work needs review: the Swarm opens the review from your handoff. Otherwise mark done.## 5. Review findings- Check each finding against the code; push back with evidence when it is wrong.diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.tsindex 91c342bbe..2b900bddb 100644--- a/cli/src/localWsServer.spec.ts+++ b/cli/src/localWsServer.spec.ts@@ -786,6 +786,33 @@ describe('local CLI WebSocket', () => {ws.close()})+ it('app_swarms keeps a Swarm tab\'s conversationId, and drops one that is not an id', async () => {+ const backend = new FakeBackend()+ const seen: unknown[] = []+ server = http.createServer((_req, res) => { res.statusCode = 404; res.end() })+ local = attachLocalWsServer(server, { machineId, backend, onAppSwarms: (swarms) => seen.push(swarms) })+ await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))+ const ws = new WebSocket(`ws://127.0.0.1:${(server.address() as AddressInfo).port}/api/local-ws`)+ await onceOpen(ws)+ const connected = onceMessage(ws)+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))+ await connected+ ws.send(JSON.stringify({ type: 'app_swarms', payload: { active: 's1', swarms: [+ { id: 's1', name: 'Swarm', agentIds: [], panes: 1, superTabId: 'st_1', projectId: 'p-1', conversationId: 'pm-1' },+ { id: 's2', name: 'Bad', agentIds: [], panes: 1, superTabId: 'st_1', conversationId: 'no spaces' },+ { id: 's3', name: 'Long', agentIds: [], panes: 1, superTabId: 'st_1', conversationId: 'c'.repeat(48) },+ { id: 's4', name: 'Number', agentIds: [], panes: 1, superTabId: 'st_1', conversationId: 7 },+ ] } }))+ await vi.waitFor(() => expect(seen).toHaveLength(1))+ expect(seen[0]).toEqual({ active: 's1', tiles: [], swarms: [+ { id: 's1', name: 'Swarm', agentIds: [], panes: 1, superTabId: 'st_1', projectId: 'p-1', conversationId: 'pm-1' },+ { id: 's2', name: 'Bad', agentIds: [], panes: 1, superTabId: 'st_1' },+ { id: 's3', name: 'Long', agentIds: [], panes: 1, superTabId: 'st_1' },+ { id: 's4', name: 'Number', agentIds: [], panes: 1, superTabId: 'st_1' },+ ] })+ ws.close()+ })+for (const latestCloses of [false, true]) {it(`keeps the device's desk when a ${latestCloses ? 'latest' : 'background'} machine connection closes`, async () => {const backend = new FakeBackend(), panes = vi.fn(), swarms = vi.fn(), tabs = vi.fn()diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.tsindex c9e83c9ae..183bc699f 100644--- a/cli/src/localWsServer.ts+++ b/cli/src/localWsServer.ts@@ -253,7 +253,10 @@ function appSwarmsFrom(payload: unknown): AppSwarms | null {// links to the tab by the first and follows the second. Ids only: anything else is dropped, not trusted.const superTabId = typeof r.superTabId === 'string' && CARD_ID.test(r.superTabId) ? r.superTabId : undefinedconst projectId = typeof r.projectId === 'string' && CARD_ID.test(r.projectId) ? r.projectId : undefined- swarms.push({ id: r.id, name: r.name.slice(0, 80), agentIds, panes, ...(superTabId ? { superTabId } : {}), ...(projectId ? { projectId } : {}) })+ // And the conversation it has open (its Lead's, its Chat with PM or a group), which the round dial's face follows.+ const conversationId = typeof r.conversationId === 'string' && CARD_ID.test(r.conversationId) ? r.conversationId : undefined+ swarms.push({ id: r.id, name: r.name.slice(0, 80), agentIds, panes, ...(superTabId ? { superTabId } : {}), ...(projectId ? { projectId } : {}),+ ...(conversationId ? { conversationId } : {}) })if (swarms.length === 24) break // the window's own ceiling}if (swarms.length === 0) return nulldiff --git a/cli/src/services/devices.spec.ts b/cli/src/services/devices.spec.tsindex a8674ed9d..e78d77420 100644--- a/cli/src/services/devices.spec.ts+++ b/cli/src/services/devices.spec.ts@@ -612,6 +612,61 @@ describe('what the windows say, reaching the dial', () => {expect(superTabRequest).not.toHaveBeenCalled()})+ it('tells the cards the window\'s open Swarm conversation, again only when it changes', () => {+ const superTabRequest = vi.fn(async () => ({ ok: true }))+ const { port, reconnected } = withRequest(superTabRequest)+ const open = (active: string, conversationId?: string) => ({ active, tiles: [], swarms: [+ { id: 'plain', name: 'plain', agentIds: [], panes: 0 },+ { id: 'tab-st1', name: 'st1', agentIds: [], panes: 0, superTabId: 'st1', projectId: 'p1', ...(conversationId ? { conversationId } : {}) }] })+ port.swarms(open('tab-st1', 'pm1'))+ seen.host.swarmCardsWanted!(true)+ expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: true, include: ['st1'], focus: { tabId: 'st1', conversationId: 'pm1' } })+ port.swarms(open('tab-st1', 'pm1'))+ expect(superTabRequest).toHaveBeenCalledTimes(1)+ port.swarms(open('tab-st1', 'g1'))+ expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: true, include: ['st1'], focus: { tabId: 'st1', conversationId: 'g1' } })+ // Another tab active, or a Swarm tab that names no conversation: no focus, and the wish says none.+ port.swarms(open('plain', 'g1'))+ expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: true, include: ['st1'] })+ port.swarms(open('tab-st1'))+ expect(superTabRequest).toHaveBeenCalledTimes(3)+ port.swarms(open('tab-st1', 'g1'))+ superTabRequest.mockClear()+ reconnected.forEach((run) => run())+ expect(superTabRequest.mock.calls).toEqual([[{ action: 'cardsWanted', on: true, include: ['st1'], focus: { tabId: 'st1', conversationId: 'g1' } }]])+ // Nobody wants cards: a focus change says nothing.+ seen.host.swarmCardsWanted!(false)+ superTabRequest.mockClear()+ port.swarms(open('tab-st1', 'pm1'))+ expect(superTabRequest).not.toHaveBeenCalled()+ })++ it('asks for the chat on the face for a swarmChat dial: recap, open and talk carry the flag, and a chat recap names its chat', async () => {+ const answers: Array<Record<string, unknown>> = [+ { ok: true, text: 'from the group', at: 3, none: false, chatId: 'g1' },+ { ok: true, text: 'no chat named', at: 3, none: false },+ { ok: true, text: 'bad chat', at: 3, none: false, chatId: 'bad id' },+ { ok: true, text: 'lead', at: 3, none: false, chatId: 'g1' },+ { ok: true, said: true },+ ]+ const superTabRequest = vi.fn(async (_payload: Record<string, unknown>) => answers.shift() ?? { ok: true })+ withRequest(superTabRequest)+ expect(await seen.host.swarmCardRecap!('st1', 'lead1', true)).toEqual({ tabId: 'st1', leadId: 'lead1', text: 'from the group', at: 3, none: false, chatId: 'g1' })+ expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardRecap', tabId: 'st1', leadId: 'lead1', chat: true })+ // A chat recap that does not name its chat by an id is no recap: the dial must not show it for another chat.+ expect(await seen.host.swarmCardRecap!('st1', 'lead1', true)).toBeNull()+ expect(await seen.host.swarmCardRecap!('st1', 'lead1', true)).toBeNull()+ // Without the flag, today's recap: no chat asked for, none passed on.+ expect(await seen.host.swarmCardRecap!('st1', 'lead1')).toEqual({ tabId: 'st1', leadId: 'lead1', text: 'lead', at: 3, none: false })+ expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardRecap', tabId: 'st1', leadId: 'lead1' })+ expect(await seen.host.swarmSay!('h1', 'ship it', true)).toBe(true)+ expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardSay', harnessId: 'h1', text: 'ship it', chat: true })+ seen.host.swarmCardOpen!('c1', 'st1', 'lead1', true)+ expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardOpen', session: 'c1', tabId: 'st1', leadId: 'lead1', chat: true })+ seen.host.swarmCardOpen!('c1', 'st1', null)+ expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardOpen', session: 'c1', tabId: 'st1', leadId: null })+ })+it('reads a recap through the service, cut to 1,500 bytes on a character; anything unusable is null', async () => {const answers: Array<Record<string, unknown> | 'throw'> = [{ ok: true, tabId: 'st1', leadId: 'lead1', text: 'é'.repeat(1000), at: 1792560000, none: false },diff --git a/cli/src/services/devices.ts b/cli/src/services/devices.tsindex 4411428eb..f2ccb51e4 100644--- a/cli/src/services/devices.ts+++ b/cli/src/services/devices.ts@@ -80,6 +80,8 @@ export interface DevicesDeps {/** ⌘K's answer while the fleet is not running: it never started, so there is no list to weigh. */const NO_AGENT_LIST = 'no agent list yet'+/** A Super Tab conversation id as the dials hold one (48 bytes with its NUL). */+const CHAT_ID = /^[A-Za-z0-9_-]{1,47}$/const unrouted = (reason: string): RouteAnswer => ({ agentId: '', machineId: '', name: '', confidence: 0, reason, candidates: [], weighed: 0, machines: 0, via: '' })const sid = (id: string): string => id.slice(0, 8)@@ -167,7 +169,13 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)// whether they are wanted (superTabs/inCore/cards.ts); this says it on a change and again when the core connects anew.let cardDevices = 0let cardInclude: string[] = []- const tellCards = (): void => { void askCards({ action: 'cardsWanted', on: cardDevices > 0, include: cardDevices > 0 ? cardInclude : [] }) }+ // The conversation the window has open in its active Swarm tab, which the round dial's face follows (design+ // 2026-10-28-round-dial-swarm-chat): said with the wish, and left out when there is none, as before.+ let cardFocus: { tabId: string; conversationId: string } | null = null+ const tellCards = (): void => {+ const on = cardDevices > 0+ void askCards({ action: 'cardsWanted', on, include: on ? cardInclude : [], ...(on && cardFocus ? { focus: cardFocus } : {}) })+ }deps.onCoreConnected?.(() => { if (cardDevices > 0) tellCards() })const cableHost = new DaemonCableHost({// The cloud harnesses too, where the core offers them: tiles on the desk the dial walks like any other.@@ -223,14 +231,17 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)if ((before === 0) !== (cardDevices === 0)) tellCards()},// The text is the service's to read and not validated by the core: cut here, on a character, to what the Pro takes.- swarmCardRecap: async (tabId, leadId) => {- const r = await askCards({ action: 'cardRecap', tabId, leadId })+ // With `chat` (a round dial that speaks swarmChat), the chat on the face's, which must name that chat by an id: a dial+ // never shows it for another one.+ swarmCardRecap: async (tabId, leadId, chat) => {+ const r = await askCards({ action: 'cardRecap', tabId, leadId, ...(chat ? { chat: true } : {}) })if (r.ok !== true || typeof r.text !== 'string' || typeof r.at !== 'number' || !Number.isInteger(r.at) || r.at < 0 || typeof r.none !== 'boolean') return null- return { tabId, leadId, text: truncateUtf8(r.text, 1500), at: r.at, none: r.none }+ if (chat && !(typeof r.chatId === 'string' && CHAT_ID.test(r.chatId))) return null+ return { tabId, leadId, text: truncateUtf8(r.text, 1500), at: r.at, none: r.none, ...(chat ? { chatId: r.chatId as string } : {}) }},- swarmCardOpen: (session, tabId, leadId) => { void askCards({ action: 'cardOpen', session, tabId, leadId }) },+ swarmCardOpen: (session, tabId, leadId, chat) => { void askCards({ action: 'cardOpen', session, tabId, leadId, ...(chat ? { chat: true } : {}) }) },// An error (no service, a refused post) is not `said`: the words go to the harness instead, never lost.- swarmSay: async (harnessId, text) => (await askCards({ action: 'cardSay', harnessId, text })).said === true,+ swarmSay: async (harnessId, text, chat) => (await askCards({ action: 'cardSay', harnessId, text, ...(chat ? { chat: true } : {}) })).said === true,// The Pro picked a Lead: the window opens that Swarm tab and project. Harmless with no window.superTabSelected: (superTabId, projectId) => core.clients.sendLocal({ type: 'dial_super_tab', payload: { superTabId, projectId } }),scrolled: (phase, dy, velocity, superTabId) => core.clients.sendLocal({ type: 'dial_scroll', payload: { phase, dy, velocity, ...(superTabId ? { superTabId } : {}) } }),@@ -491,7 +502,10 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)cableHost.setSwarms(swarms)// The Swarms the window has tabs for are read first; said again to the core only when they change.const include = [...new Set((swarms?.swarms ?? []).map((s) => s.superTabId).filter((id): id is string => !!id))].slice(0, 16)- if (include.join(',') !== cardInclude.join(',')) { cardInclude = include; if (cardDevices > 0) tellCards() }+ const open = cableHost.activeSwarmProject()+ const focus = open?.conversationId ? { tabId: open.superTabId, conversationId: open.conversationId } : null+ const refocused = `${focus?.tabId}/${focus?.conversationId}` !== `${cardFocus?.tabId}/${cardFocus?.conversationId}`+ if (include.join(',') !== cardInclude.join(',') || refocused) { cardInclude = include; cardFocus = focus; if (cardDevices > 0) tellCards() }void cable.syncSwarms()void cable.syncAgents()// The Swarm cards link to their desk tab and follow its open project.diff --git a/cli/src/superTabs/cards.spec.ts b/cli/src/superTabs/cards.spec.tsindex 52f0b1c3a..668c03835 100644--- a/cli/src/superTabs/cards.spec.ts+++ b/cli/src/superTabs/cards.spec.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest'import type { CoreApi } from '../core/api.js'import { fakeCore } from '../testing/fakeCore.js'-import { lastLeadMessage, leadsOf, SwarmCards, type SwarmCard } from './cards.js'+import { lastAgentMessage, leadsOf, SwarmCards, type SwarmCard } from './cards.js'import { swarmReply } from './fixtures/read/index.js'const agent = (id: string, over: Record<string, unknown> = {}) =>@@ -125,18 +125,82 @@ describe('leadsOf', () => {})})-describe('lastLeadMessage', () => {- const row = (sequence: number, over: Record<string, unknown> = {}) => ({ sequence, text: `t${sequence}`, author: { kind: 'agent', id: 'a1' }, createdAt: '2026-10-22T00:00:00.000Z', ...over })+/** `web`'s three kinds of chat: its Lead conversation, the reader's Chat with PM (a conversation with an audience), and a group. */+const pm = (over: Record<string, unknown> = {}) => conv('pm-web', null, { projectId: 'web', audience: { people: [{ id: 'me' }] }, agentIds: ['a1'], ...over })+const group = (over: Record<string, unknown> = {}) => conv('g-web', null, { projectId: 'web', title: 'Fix login', agentIds: ['b1'], assignment: { status: 'working' }, ...over })+const chats = (over: Record<string, unknown> = {}) => swarm({+ agents: [agent('a1'), agent('a2'), agent('b1', { projectId: 'web' })],+ conversations: [...swarm().conversations, pm(), group()],+ ...over,+})++describe('leadsOf chats', () => {+ const chatOf = (state: Record<string, unknown>, focus?: string, live: Parameters<typeof leadsOf>[2] = idle) =>+ leadsOf(state, 'm1', live, 'me', focus).leads.find(l => l.projectId === 'web')!.chat++ it('opens each project on its Lead chat', () => {+ expect(leadsOf(chats(), 'm1', idle).leads.map(l => l.chat)).toEqual([+ { kind: 'lead', id: 'lead-web', name: 'Lead', working: false }, { kind: 'lead', id: 'lead-mobile', name: 'Lead', working: false }])+ })++ it('follows the window to the project\'s Chat with PM', () => {+ expect(chatOf(chats(), 'pm-web')).toEqual({ kind: 'pm', id: 'pm-web', name: 'PM', working: false })+ // The other project keeps its Lead chat.+ expect(leadsOf(chats(), 'm1', idle, 'me', 'pm-web').leads.find(l => l.projectId === 'mobile')!.chat).toMatchObject({ kind: 'lead', id: 'lead-mobile' })+ })++ it('follows the window to a group', () => {+ expect(chatOf(chats(), 'g-web')).toEqual({ kind: 'group', id: 'g-web', name: 'Fix login', working: true })+ const long = chats({ conversations: [...swarm().conversations, group({ title: `${'g'.repeat(47)}éé` })] })+ expect(chatOf(long, 'g-web')!.name).toBe('g'.repeat(47))+ for (const status of ['review', 'needs_human', 'blocked', 'done']) {+ const other = chats({ conversations: [...swarm().conversations, group({ assignment: { status } })] })+ expect(chatOf(other, 'g-web')).toMatchObject({ kind: 'group', working: false })+ }+ // `since` comes from a live turn of one of the group's agents here, and only while the group works.+ const turn = (h: string) => h === 'h-b1' ? { inTurn: true, since: 42 } : { inTurn: false }+ expect(chatOf(chats(), 'g-web', turn)).toEqual({ kind: 'group', id: 'g-web', name: 'Fix login', working: true, since: 42 })+ expect(chatOf(chats(), 'g-web', h => h === 'h-a1' ? { inTurn: true, since: 9 } : { inTurn: false })).not.toHaveProperty('since')+ const done = chats({ conversations: [...swarm().conversations, group({ assignment: { status: 'done' } })] })+ expect(chatOf(done, 'g-web', turn)).not.toHaveProperty('since')+ })++ it('ignores a focus outside the project', () => {+ const lead = { kind: 'lead', id: 'lead-web', name: 'Lead', working: false }+ // another project's conversation, an unknown id, an archived group+ const mobileGroup = conv('g-mobile', null, { projectId: 'mobile', title: 'App', agentIds: [], assignment: { status: 'working' } })+ const state = chats({ conversations: [...swarm().conversations, pm(), group(), mobileGroup] })+ expect(chatOf(state, 'g-mobile')).toEqual(lead)+ expect(chatOf(state, 'nope')).toEqual(lead)+ expect(chatOf(chats({ conversations: [...swarm().conversations, group({ archived: true })] }), 'g-web')).toEqual(lead)+ // and the Lead's own conversation is the Lead chat+ expect(chatOf(state, 'lead-web')).toEqual(lead)+ })++ it('keeps today\'s state for old devices whatever the chat', () => {+ const asks = chats({ conversations: [...swarm().conversations, pm(), group({ assignment: { status: 'needs_human' } })] })+ expect(leadsOf(asks, 'm1', idle, 'me', 'pm-web').leads[0]).toMatchObject({ projectId: 'web', state: 'ask', chat: { kind: 'pm' } })+ })+})++describe('lastAgentMessage', () => {+ const row = (sequence: number, over: Record<string, unknown> = {}) => ({ id: `m${sequence}`, sequence, text: `t${sequence}`, author: { kind: 'agent', id: 'a1' }, createdAt: '2026-10-22T00:00:00.000Z', ...over })+ const lead = new Set(['a1'])it('takes the newest row the Lead wrote, skipping system rows and other authors', () => {const rows = [row(1), row(2, { source: { kind: 'native' } }), row(3, { author: { id: 'a2' } }), row(4, { text: 7 })]- expect(lastLeadMessage(rows, 'a1')).toEqual({ text: 't1', at: Date.parse('2026-10-22T00:00:00.000Z') / 1000 })- expect(lastLeadMessage([row(5), row(1)], 'a1')?.text).toBe('t5')- expect(lastLeadMessage([row(1, { createdAt: 1_000_500 })], 'a1')?.at).toBe(1000)- expect(lastLeadMessage([row(1, { createdAt: 'x' })], 'a1')?.at).toBe(0)+ expect(lastAgentMessage(rows, lead)).toEqual({ text: 't1', at: Date.parse('2026-10-22T00:00:00.000Z') / 1000, id: 'm1', sequence: 1 })+ expect(lastAgentMessage([row(5), row(1)], lead)?.text).toBe('t5')+ expect(lastAgentMessage([row(1, { createdAt: 1_000_500 })], lead)?.at).toBe(1000)+ expect(lastAgentMessage([row(1, { createdAt: 'x' })], lead)?.at).toBe(0)+ })+ it('takes the newest row by any of the chat\'s agents, skipping the person and source rows', () => {+ const group = new Set(['b1', 'b2'])+ const rows = [row(1, { author: { id: 'b1' } }), row(2, { author: { id: 'b2' } }), row(3, { author: { kind: 'person', id: 'me' } }), row(4, { author: { id: 'b1' }, source: { kind: 'system' } }), row(5)]+ expect(lastAgentMessage(rows, group)).toMatchObject({ text: 't2', id: 'm2', sequence: 2 })})- it('is null when the Lead has said nothing', () => {- expect(lastLeadMessage([], 'a1')).toBeNull()- expect(lastLeadMessage([row(1, { author: { id: 'a2' } })], 'a1')).toBeNull()+ it('is null when the chat\'s agents have said nothing', () => {+ expect(lastAgentMessage([], lead)).toBeNull()+ expect(lastAgentMessage([row(1, { author: { id: 'a2' } })], lead)).toBeNull()})})@@ -176,10 +240,11 @@ function setup(tabs: Record<string, { lastChangedAt: number; state: Record<strinactivitySnapshot: vi.fn(async () => ({ text: '', elapsedSeconds: extra.elapsed })) },})let clock = 1_000_000- const cards = new SwarmCards(core, 'm1', { now: () => clock, intervalMs: 5000 })+ const log = vi.fn()+ const cards = new SwarmCards(core, 'm1', { now: () => clock, intervalMs: 5000, log })const seen: SwarmCard[][] = []cards.onCards = c => seen.push(c)- return { cards, calls, seen, call, core, failing, tabs, paginate: (p: typeof pages) => { pages = p }, pageBy: (n: number) => { pageSize = n }, breakList: (v = true) => { listFails = v }, advance: (ms: number) => { clock += ms } }+ return { cards, calls, seen, call, core, failing, tabs, log, paginate: (p: typeof pages) => { pages = p }, pageBy: (n: number) => { pageSize = n }, breakList: (v = true) => { listFails = v }, advance: (ms: number) => { clock += ms } }}/** Each read of a tab, named by the tab: a changes read, or a first load that no changes read of it asked for. */function detailReads(calls: string[]): string[] {@@ -530,3 +595,193 @@ describe('SwarmCards open recaps and recap reads', () => {expect(t.calls.filter(c => c.includes('/messages'))).toHaveLength(1)})})++/** `web` with its three chats at the given sequences, each conversation's page served from `pages` (newest first or not: the code orders). */+function chatSwarm(pages: Record<string, unknown[] | (() => unknown[])>) {+ const state = (lead = 1, pmSeq = 1, groupSeq = 1) => chats({ conversations: [+ conv('lead-web', 'a1', { projectId: 'web', lastMessageSequence: lead }), conv('lead-mobile', 'a2', { projectId: 'mobile' }),+ pm({ lastMessageSequence: pmSeq }), group({ lastMessageSequence: groupSeq })] })+ const t = setup({ t1: { lastChangedAt: 1, state: state() } }, { messages: path => {+ const page = pages[/conversations\/([^/]+)\/messages/.exec(path)?.[1] ?? ''] ?? []+ return { messages: typeof page === 'function' ? page() : page, next: null }+ } })+ const move = async (lead: number, pmSeq = 1, groupSeq = 1) => { t.tabs.t1.lastChangedAt++; t.tabs.t1.state = state(lead, pmSeq, groupSeq); await t.cards.tick() }+ const webLead = (cards = t.seen.at(-1)) => cards?.[0].leads.find(l => l.id === 'a1')+ const reads = (conversation: string) => t.calls.filter(c => c.includes(`/conversations/${conversation}/messages`)).length+ return { ...t, move, webLead, reads }+}+const said = (sequence: number, who: string, over: Record<string, unknown> = {}) =>+ ({ id: `x${sequence}`, sequence, text: `m${sequence}`, author: { kind: 'agent', id: who }, source: null, createdAt: '2026-10-22T00:00:00.000Z', ...over })+const saidAt = Date.parse('2026-10-22T00:00:00.000Z') / 1000++describe('SwarmCards notices', () => {+ it('records a baseline on the first read and sends no notice', async () => {+ const t = chatSwarm({ 'lead-web': [said(1, 'a1')], 'pm-web': [said(1, 'a1')] })+ await t.cards.tick()+ await t.cards.tick()+ expect(t.webLead()).not.toHaveProperty('notice')+ expect(t.reads('lead-web') + t.reads('pm-web')).toBe(0)+ })++ it('notices a new Lead message in the Lead conversation', async () => {+ const t = chatSwarm({ 'lead-web': [said(1, 'a1'), said(2, 'a1')] })+ await t.cards.tick()+ await t.move(2)+ expect(t.webLead()?.notice).toEqual({ chat: 'lead', chatId: 'lead-web', id: 'x2', text: 'm2', at: saidAt })+ expect(t.reads('lead-web')).toBe(1)+ // Nothing moved: no read and the same notice.+ await t.cards.tick()+ expect(t.reads('lead-web')).toBe(1)+ })++ it('notices a new Lead message in Chat with PM', async () => {+ const t = chatSwarm({ 'pm-web': [said(2, 'a1', { text: `${'p'.repeat(1499)}éé` })] })+ await t.cards.tick()+ await t.move(1, 2)+ expect(t.webLead()?.notice).toEqual({ chat: 'pm', chatId: 'pm-web', id: 'x2', text: 'p'.repeat(1499), at: saidAt })+ })++ it('never notices a group message, the person\'s message or a system row', async () => {+ const t = chatSwarm({+ 'lead-web': [said(2, 'me', { author: { kind: 'person', id: 'me' } }), said(3, 'a1', { source: { kind: 'system' } }), said(4, 'b1')],+ 'g-web': [said(2, 'b1')],+ })+ await t.cards.tick()+ await t.move(4, 1, 2)+ expect(t.webLead()).not.toHaveProperty('notice')+ // Groups are never watched: their pages are not read for alerts.+ expect(t.reads('g-web')).toBe(0)+ })++ it('one notice for the newest of two messages', async () => {+ const t = chatSwarm({ 'lead-web': [said(3, 'a1'), said(2, 'a1')] })+ await t.cards.tick()+ await t.move(3)+ const notices = t.seen.map(c => t.webLead(c)?.notice?.id).filter(Boolean)+ expect(notices).toEqual(['x3'])+ })++ it('takes the newer of a Lead and a PM message that land in one read', async () => {+ const t = chatSwarm({ 'lead-web': [said(2, 'a1', { createdAt: '2026-10-22T00:05:00.000Z' })], 'pm-web': [said(2, 'a1', { createdAt: '2026-10-22T00:01:00.000Z' })] })+ await t.cards.tick()+ await t.move(2, 2)+ expect(t.webLead()?.notice).toMatchObject({ chat: 'lead', chatId: 'lead-web' })+ })++ it('drops a held notice when its Swarm leaves the cards', async () => {+ const t = chatSwarm({ 'lead-web': [said(2, 'a1')] })+ await t.cards.tick()+ await t.move(2)+ expect(t.webLead()?.notice).toMatchObject({ id: 'x2' })+ const gone = t.tabs.t1+ delete t.tabs.t1+ await t.cards.tick()+ t.tabs.t1 = gone+ await t.cards.tick()+ expect(t.webLead()).not.toHaveProperty('notice')+ })++ it('a failed read keeps the baseline', async () => {+ let fail = true+ const t = chatSwarm({ 'lead-web': () => { if (fail) throw new Error('offline'); return [said(2, 'a1')] } })+ await t.cards.tick()+ await t.move(2)+ await t.cards.tick()+ expect(t.webLead()).not.toHaveProperty('notice')+ // Logged once for the run of failures, not every 5 s.+ expect(t.log).toHaveBeenCalledOnce()+ fail = false+ await t.cards.tick()+ expect(t.webLead()?.notice).toMatchObject({ chat: 'lead', id: 'x2' })+ })++ it('reads a page only for a message after the baseline, and takes none from before it', async () => {+ // The page still holds the Lead's older message; only the person wrote since.+ const t = chatSwarm({ 'lead-web': [said(1, 'a1'), said(2, 'me', { author: { kind: 'person', id: 'me' } })] })+ await t.cards.tick()+ await t.move(2)+ expect(t.webLead()).not.toHaveProperty('notice')+ })++ it('starts a fresh baseline after the devices go, and forgets a tab that leaves the cards', async () => {+ const t = chatSwarm({ 'lead-web': [said(2, 'a1')] })+ await t.cards.tick()+ t.cards.want(false)+ await t.move(2)+ expect(t.webLead()).not.toHaveProperty('notice')+ const gone = t.tabs.t1+ delete t.tabs.t1+ await t.cards.tick()+ t.tabs.t1 = gone+ await t.move(3)+ expect(t.webLead()).not.toHaveProperty('notice')+ })+})++describe('SwarmCards chats', () => {+ const groupSays = [said(1, 'b1'), said(2, 'me', { author: { kind: 'person', id: 'me' } })]++ it('follows a focus change at once, without reading the backend again', async () => {+ const t = chatSwarm({})+ t.cards.want(true, [], null)+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))+ t.calls.length = 0+ t.cards.want(true, [], { tabId: 't1', conversationId: 'g-web' })+ expect(t.webLead()?.chat).toMatchObject({ kind: 'group', id: 'g-web' })+ expect(t.calls).toEqual([])+ // A focus on another Swarm leaves this one on its Lead chat; a bad id is no focus.+ t.cards.want(true, [], { tabId: 't2', conversationId: 'g-web' })+ expect(t.webLead()?.chat).toMatchObject({ kind: 'lead' })+ t.cards.want(true, [], { tabId: 't1', conversationId: 'bad id' })+ expect(t.webLead()?.chat).toMatchObject({ kind: 'lead' })+ t.cards.want(false)+ })++ it('recap with chat reads the face chat and names its chatId', async () => {+ const t = chatSwarm({ 'g-web': groupSays, 'pm-web': [said(1, 'a1', { text: 'from the PM' })] })+ t.cards.want(true, [], { tabId: 't1', conversationId: 'g-web' })+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))+ expect(await t.cards.recap('t1', 'a1', true)).toEqual({ tabId: 't1', leadId: 'a1', text: 'm1', at: saidAt, none: false, chatId: 'g-web' })+ t.cards.want(true, [], { tabId: 't1', conversationId: 'pm-web' })+ expect(await t.cards.recap('t1', 'a1', true)).toMatchObject({ text: 'from the PM', chatId: 'pm-web' })+ t.cards.want(false)+ })++ it('recap without chat is today\'s Lead recap', async () => {+ const t = chatSwarm({ 'lead-web': [said(1, 'a1', { text: 'lead says' })], 'g-web': groupSays })+ t.cards.want(true, [], { tabId: 't1', conversationId: 'g-web' })+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))+ const recap = await t.cards.recap('t1', 'a1')+ expect(recap).toEqual({ tabId: 't1', leadId: 'a1', text: 'lead says', at: saidAt, none: false })+ expect(t.reads('g-web')).toBe(0)+ t.cards.want(false)+ })++ it('pushes the new chat\'s recap to a dial that has the Lead open with chat when the face changes', async () => {+ const t = chatSwarm({ 'lead-web': [said(1, 'a1', { text: 'lead says' })], 'g-web': groupSays })+ const pushed: Array<{ text: string; chatId?: string }> = []+ t.cards.onRecap = r => pushed.push({ text: r.text, ...(r.chatId ? { chatId: r.chatId } : {}) })+ t.cards.want(true, [], null)+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))+ t.cards.open('s1', 't1', 'a1', true)+ t.cards.open('s2', 't1', 'a1')+ t.cards.want(true, [], { tabId: 't1', conversationId: 'g-web' })+ await vi.waitFor(() => expect(pushed).toEqual([{ text: 'm1', chatId: 'g-web' }]))+ // The group moves on: the chat session is told; the Lead conversation did not move, so the Pro is not.+ groupSays.push(said(3, 'b1', { text: 'done' }))+ await t.move(1, 1, 3)+ expect(pushed).toEqual([{ text: 'm1', chatId: 'g-web' }, { text: 'done', chatId: 'g-web' }])+ t.cards.want(false)+ })++ it('say with chat posts message.send to the face chat', async () => {+ const t = chatSwarm({})+ t.cards.want(true, [], { tabId: 't1', conversationId: 'pm-web' })+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))+ expect(await t.cards.say('h-a1', 'to the PM', true)).toBe(true)+ expect(await t.cards.say('h-a1', 'to the Lead')).toBe(true)+ const posts = t.call.mock.calls.filter(c => c[0] === 'POST').map(c => (c[2] as { command: { conversationId: string; text: string } }).command)+ expect(posts.map(p => [p.conversationId, p.text])).toEqual([['pm-web', 'to the PM'], ['lead-web', 'to the Lead']])+ t.cards.want(false)+ })+})diff --git a/cli/src/superTabs/cards.ts b/cli/src/superTabs/cards.tsindex 0efbb3d20..16c84871d 100644--- a/cli/src/superTabs/cards.ts+++ b/cli/src/superTabs/cards.ts@@ -10,6 +10,11 @@* agent working by its own live turn, `since` from the earliest of those turns; or an assignment works or is in review, all there is for agents on* other machines), else `done`.* A paused Swarm keeps its card and every Lead reads `done`.+ *+ * For the round dial (design 2026-10-28-round-dial-swarm-chat) every Lead also carries the chat on its project's face (`chat`):+ * the Lead conversation, or the project's Chat with PM or group the window has open (`want`'s focus); and the newest message+ * the Lead wrote in its Lead conversation or Chat with PM since the baseline (`notice`), the dial's one alert. `state` keeps+ * its meaning for the Pro and older dials, which never read either.*/import { randomUUID } from 'node:crypto'import type { CoreApi } from '../core/api.js'@@ -19,8 +24,8 @@ import { SwarmReads, type SwarmRead } from './swarmReads.js'type Json = Record<string, unknown>/** The cards' shapes are the core's contract with the Swarm (core/api.ts), which the core declares and the Swarm imports. */-import type { LeadRecap, LeadState, SwarmCard, SwarmLead } from '../core/api.js'-export type { LeadRecap, LeadState, SwarmCard, SwarmLead } from '../core/api.js'+import type { CardFocus, ChatKind, LeadNotice, LeadRecap, LeadState, SwarmCard, SwarmChat, SwarmLead } from '../core/api.js'+export type { CardFocus, LeadNotice, LeadRecap, LeadState, SwarmCard, SwarmChat, SwarmLead } from '../core/api.js'const MAX_CARDS = 16, MAX_LEADS = 12, NAME_BYTES = 48, RECAP_BYTES = 1500, MAX_LIST_PAGES = 10, MAX_RECAPS_IN_FLIGHT = 2/** The Pro keeps an id in 48 bytes with its NUL: 47 characters at most reach it. */@@ -39,6 +44,26 @@ function cut(text: string, bytes: number): string {return out}const list = (v: unknown): Json[] => Array.isArray(v) ? v.map(object) : []+const projectKey = (project: Json): string => String(project.id ?? 'lead')+const inProject = (conversation: Json, projectId: string): boolean => (conversation.projectId ?? 'lead') === projectId+/** The reader's Chat with PM: the backend sends a private conversation's `audience` only to the people in it (`visibleState`). */+const isPmChat = (conversation: Json): boolean => !!conversation.audience && typeof conversation.audience === 'object'+const sequenceOf = (conversation: Json): number => typeof conversation.lastMessageSequence === 'number' ? conversation.lastMessageSequence : 0++/** The conversation on a project's face and its kind: the one the window has open when it is a live conversation of this+ * project, else the project's Lead conversation; null when that one's id is not one a dial can hold. An archived group is+ * over: the face stays on the Lead (Ruling on the plan, 2026-10-28). */+function faceOf(conversations: Json[], projectId: string, lead: Json, focus?: string): { conversation: Json; kind: ChatKind } | null {+ const open = focus !== undefined && focus !== lead.id+ ? conversations.find(c => c.id === focus && inProject(c, projectId) && c.archived !== true && cardId(c.id)) : undefined+ if (open) return { conversation: open, kind: isPmChat(open) ? 'pm' : 'group' }+ return cardId(lead.id) ? { conversation: lead, kind: 'lead' } : null+}+/** Whose messages are the chat's recap: the Lead's in its conversation and Chat with PM, the group's agents' in a group. */+function voicesOf(face: { conversation: Json; kind: ChatKind }, leadId: string): Set<string> {+ if (face.kind !== 'group') return new Set([leadId])+ return new Set(Array.isArray(face.conversation.agentIds) ? face.conversation.agentIds.filter((id): id is string => typeof id === 'string') : [])+}/*** One Lead per project of the Swarm, most urgent first with ties in project order; the 12 most urgent are kept, and each@@ -46,7 +71,7 @@ const list = (v: unknown): Json[] => Array.isArray(v) ? v.map(object) : []* harness and whether it is in a turn (null: not here); `me` is the signed-in person's id, so a Lead on someone else's* machine names that owner (people[] has an email, which is the name a Swarm shows a person by).*/-export function leadsOf(state: Json, machineId: string, live: (harnessId: string) => { inTurn: boolean; since?: number } | null, me?: string): { count: number; leads: SwarmLead[] } {+export function leadsOf(state: Json, machineId: string, live: (harnessId: string) => { inTurn: boolean; since?: number } | null, me?: string, focus?: string): { count: number; leads: SwarmLead[] } {const agents = list(state.agents), conversations = list(state.conversations), people = list(state.people)// An old tab has no `projects`: its one project is the tab itself, `lead`, led by the conversation `lead`.const projects = Array.isArray(state.projects) ? list(state.projects) : [{ id: 'lead', name: state.name, leadConversationId: 'lead' }]@@ -81,10 +106,22 @@ export function leadsOf(state: Json, machineId: string, live: (harnessId: string}const ownerId = agent.machineOwnerIdconst owner = me && typeof ownerId === 'string' && ownerId !== me ? people.find(p => p.id === ownerId) : undefined+ const face = faceOf(conversations, projectKey(project), lead, focus)+ let chat: SwarmChat | undefined+ if (face) {+ const { conversation, kind } = face+ // Only a group works on the dial, and only while its assignment works: Lead and PM chats never do (design decision 4).+ const working = kind === 'group' && object(conversation.assignment).status === 'working'+ const voices = voicesOf(face, String(agent.id))+ const turns = working ? agents.filter(a => voices.has(a.id as string)).map(turnHere).filter(t => t?.inTurn) : []+ const secs = turns.map(t => t!.since).filter((v): v is number => typeof v === 'number')+ chat = { kind, id: conversation.id as string, name: kind === 'lead' ? 'Lead' : kind === 'pm' ? 'PM' : cut(String(conversation.title ?? ''), NAME_BYTES), working,+ ...(secs.length ? { since: Math.max(...secs) } : {}) }+ }leads.push({id: String(agent.id), projectId: String(project.id ?? 'lead'), project: cut(String(project.name ?? ''), NAME_BYTES), engine: String(object(agent.configuration).engine ?? ''),owner: owner && typeof owner.email === 'string' ? cut(owner.email, NAME_BYTES) : '',- local: here && cardId(harnessId) ? harnessId : '', state, order, ...(since !== undefined ? { since } : {}),+ local: here && cardId(harnessId) ? harnessId : '', state, order, ...(since !== undefined ? { since } : {}), ...(chat ? { chat } : {}),})}// Array.sort is stable: equal urgency keeps the project order.@@ -92,24 +129,30 @@ export function leadsOf(state: Json, machineId: string, live: (harnessId: stringreturn { count: ordered.length, leads: ordered.slice(0, MAX_LEADS) }}-/** The newest row the Lead itself wrote: a person-visible message, not a system row (`source`) or someone else's. `at` in seconds. */-export function lastLeadMessage(messages: Json[], leadId: string): { text: string; at: number } | null {- let best: { text: string; at: number; sequence: number } | null = null+/** The newest row one of the chat's agents wrote: a person-visible message, not a system row (`source`), the person's or+ * another agent's. `at` in seconds; `id` the message's, or '' when it has none. */+export function lastAgentMessage(messages: Json[], agentIds: ReadonlySet<string>): { text: string; at: number; id: string; sequence: number } | null {+ let best: { text: string; at: number; id: string; sequence: number } | null = nullfor (const item of messages) {const m = object(item)- if (m.source != null || object(m.author).id !== leadId || typeof m.text !== 'string') continue+ const author = object(m.author).id+ if (m.source != null || typeof author !== 'string' || !agentIds.has(author) || typeof m.text !== 'string') continueconst sequence = typeof m.sequence === 'number' ? m.sequence : -1if (best && sequence <= best.sequence) continueconst stamp = typeof m.createdAt === 'number' ? m.createdAt : Date.parse(String(m.createdAt))- best = { text: m.text, at: Number.isFinite(stamp) ? Math.floor(stamp / 1000) : 0, sequence }+ best = { text: m.text, at: Number.isFinite(stamp) ? Math.floor(stamp / 1000) : 0, id: typeof m.id === 'string' ? m.id : '', sequence }}- return best && { text: best.text, at: best.at }+ return best}interface TabCache { lastChangedAt: number | null; state: Json }interface Cached { sequence: number; recap: LeadRecap }-/** A Lead some Harness Pro has the recap of open, and the sessions (one per Pro) that have it open. */-interface Opened { tabId: string; leadId: string; sequence: number | null; sessions: Set<string> }+/** A Lead some Harness Pro has the recap of open, and the sessions (one per Pro) that have it open. With `chat` (a round dial+ * that speaks `swarmChat`), the recap is the face chat's, and `chatId` the chat it was last told of. */+interface Opened { tabId: string; leadId: string; chat: boolean; chatId: string | null; sequence: number | null; sessions: Set<string> }+/** Where a recap is read, or talk is posted: a conversation, how far it has gone, and whose messages are its recap. */+interface Target { id: string; sequence: number; voices: Set<string>; chatId?: string }+const recapKey = (tabId: string, leadId: string, chatId?: string) => chatId === undefined ? `${tabId}:${leadId}` : `${tabId}:${leadId}:${chatId}`const tabOf = (read: SwarmRead): TabCache => ({ lastChangedAt: read.lastChangedAt, state: read.state })export class SwarmCards {@@ -117,47 +160,75 @@ export class SwarmCards {onRecap?: (recap: LeadRecap) => voidprivate readonly now: () => numberprivate readonly intervalMs: number+ private readonly log: (line: string) => voidprivate timer: NodeJS.Timeout | undefinedprivate busy = falseprivate tabs = new Map<string, TabCache>()+ /** The tabs to show, in the list's order, with the name the list gave each, as the last poll read them. */+ private rows: Array<{ id: string; name: unknown }> = []private recaps = new Map<string, Cached>()/** When each local Lead's current turn began, so `since` counts on between polls. */private turns = new Map<string, number>()+ /** Whether a harness is here and in a turn, as the last poll read it; null before the first. */+ private live: ((harnessId: string) => { inTurn: boolean; since?: number } | null) | null = nullprivate last: string | null = null/** When each shown Lead's clock started (ms, `${card}/${lead}`), as the list last sent said. */private lastStarts = new Map<string, number>()private me: string | undefinedprivate include: string[] = []+ /** The conversation the window has open in a Swarm tab: that project's face follows it. */+ private focus: CardFocus | null = nullprivate opened = new Map<string, Opened>()private openBy = new Map<string, string>()private recapsRunning = 0+ /** One push of open recaps at a time: a focus change and a poll that both see a new face push it once. */+ private pushing: Promise<void> = Promise.resolve()+ /** The alert baseline: per watched conversation (`${tab}:${conversation}`), the last sequence whose messages were seen. */+ private seen = new Map<string, number>()+ /** Each Lead's newest notice (`${tab}:${lead}`), carried on its card. */+ private notices = new Map<string, LeadNotice>()+ /** Watched conversations whose last read failed, so a run of failures is logged once. */+ private failed = new Set<string>()private readonly reads: SwarmReads- constructor(private readonly core: CoreApi, private readonly machineId: string, options: { now?: () => number; intervalMs?: number; reads?: SwarmReads } = {}) {+ constructor(private readonly core: CoreApi, private readonly machineId: string, options: { now?: () => number; intervalMs?: number; reads?: SwarmReads; log?: (line: string) => void } = {}) {this.now = options.now ?? Date.nowthis.intervalMs = options.intervalMs ?? 5000this.reads = options.reads ?? new SwarmReads(core)+ this.log = options.log ?? (line => console.log(line))}- /** Poll while a capable Pro is attached; none otherwise (no request at all). `include`: the Swarms the desktop has tabs for, read first. */- want(on: boolean, include: string[] = []): void {+ /** Poll while a capable Pro is attached; none otherwise (no request at all). `include`: the Swarms the desktop has tabs for,+ * read first. `focus`: the conversation the window has open in a Swarm tab; a change rebuilds the cards at once from the+ * last reads, with no request. */+ want(on: boolean, include: string[] = [], focus: CardFocus | null = null): void {if (!on) {if (this.timer) clearInterval(this.timer)this.timer = undefined- this.opened.clear(); this.openBy.clear(); this.include = []+ this.opened.clear(); this.openBy.clear(); this.include = []; this.focus = null+ // A device that attaches again starts a fresh baseline: what was said while none was here never alerts.+ this.seen.clear(); this.notices.clear(); this.failed.clear()return}const wanted = include.filter(cardId).slice(0, MAX_CARDS)const moved = wanted.join(',') !== this.include.join(',')this.include = wanted- if (this.timer) { if (moved) void this.tick(); return }+ const next = focus && cardId(focus.tabId) && cardId(focus.conversationId) ? { tabId: focus.tabId, conversationId: focus.conversationId } : null+ const refocused = `${next?.tabId}/${next?.conversationId}` !== `${this.focus?.tabId}/${this.focus?.conversationId}`+ this.focus = next+ if (this.timer) {+ if (refocused && this.live) { this.emit(); void this.pushOpen() }+ if (moved) void this.tick()+ return+ }this.timer = setInterval(() => { void this.tick() }, this.intervalMs)this.timer.unref?.()void this.tick()}- /** The recap on a Pro's screen (leadId null: closed), per Pro `session`: a change in that Lead's conversation is pushed once. */- open(session: string, tabId: string, leadId: string | null): void {+ /** The recap on a Pro's screen (leadId null: closed), per Pro `session`: a change in that Lead's conversation is pushed once.+ * With `chat`, the face chat's: a change in it, or another chat on the face, is pushed once. */+ open(session: string, tabId: string, leadId: string | null, chat = false): void {const before = this.openBy.get(session)if (before) {const held = this.opened.get(before)@@ -166,11 +237,13 @@ export class SwarmCards {this.openBy.delete(session)}if (!leadId || !cardId(session) || !cardId(tabId) || !cardId(leadId)) return- const key = `${tabId}:${leadId}`+ const key = `${recapKey(tabId, leadId)}${chat ? ':chat' : ''}`let entry = this.opened.get(key)if (!entry) {// From what the Pro was shown when there is a recap read, else from the first read of the tab: the next change is pushed.- entry = { tabId, leadId, sequence: this.recaps.get(key)?.sequence ?? this.sequenceOf(tabId, leadId), sessions: new Set() }+ const target = this.target(tabId, leadId, chat)+ entry = { tabId, leadId, chat, chatId: target?.chatId ?? null,+ sequence: target ? this.recaps.get(recapKey(tabId, leadId, target.chatId))?.sequence ?? target.sequence : null, sessions: new Set() }this.opened.set(key, entry)}entry.sessions.add(session)@@ -212,18 +285,33 @@ export class SwarmCards {}}))this.tabs = known+ this.rows = rows.map(row => ({ id: row.id as string, name: row.name }))const me = (await this.core.account.identity().catch(() => null))?.accountId// Another person signed in: nothing of the last account's is kept, and the list is said again whatever it is.- if (this.me !== undefined && me !== this.me) { this.last = null; this.recaps.clear() }+ if (this.me !== undefined && me !== this.me) { this.last = null; this.recaps.clear(); this.seen.clear(); this.notices.clear(); this.failed.clear() }this.me = me ?? this.meconst turns = await this.turnsHere()- const live = (harnessId: string) => this.core.agents.byAgent(harnessId) ? turns.get(harnessId) ?? { inTurn: false } : null+ this.live = (harnessId: string) => this.core.agents.byAgent(harnessId) ? turns.get(harnessId) ?? { inTurn: false } : null+ await this.watchNotices()+ this.emit()+ this.prune()+ await this.pushOpen()+ }++ /** The cards from the last reads, said when they changed. */+ private emit(): void {+ const live = this.live ?? (() => null)const cards: SwarmCard[] = []- for (const row of rows) {- const tab = known.get(row.id as string)+ for (const row of this.rows) {+ const tab = this.tabs.get(row.id)if (!tab) continue- const { count, leads } = leadsOf(tab.state, this.machineId, live, me)- cards.push({ id: row.id as string, name: cut(String(tab.state.name ?? row.name ?? ''), NAME_BYTES), count, leads })+ const focus = this.focus?.tabId === row.id ? this.focus.conversationId : undefined+ const { count, leads } = leadsOf(tab.state, this.machineId, live, this.me, focus)+ const noticed = leads.map(lead => {+ const notice = this.notices.get(recapKey(row.id, lead.id))+ return notice ? { ...lead, notice } : lead+ })+ cards.push({ id: row.id, name: cut(String(tab.state.name ?? row.name ?? ''), NAME_BYTES), count, leads: noticed })}// `since` moves every poll while a turn runs and the Pro counts on by itself, so it alone never re-sends the list.// Nor does a clock that keeps its turn; one whose turn changed (the Lead's ended, a worker's goes on) does. The start is@@ -233,8 +321,55 @@ export class SwarmCards {for (const card of cards) for (const lead of card.leads) if (lead.since !== undefined) starts.set(`${card.id}/${lead.id}`, now - lead.since * 1000)const moved = [...starts].some(([key, at]) => Math.abs(at - (this.lastStarts.get(key) ?? at)) > 2000)if (signature !== this.last || moved) { this.last = signature; this.lastStarts = starts; this.onCards?.(cards) }- this.prune()- await this.pushOpen()+ }++ /**+ * The dial's alerts (design 2026-10-28 §2): each project's Lead conversation and Chat with PM, by the `lastMessageSequence`+ * the tab reads already carry. A conversation first seen sets the baseline and is not read; one that moved past it has its+ * newest page read once, under the recaps' limit, and the newest message its Lead wrote after the baseline becomes the+ * Lead's notice. Two messages between two reads make one notice, for the newest. The baseline moves only after a read+ * that worked, so a failed one is tried again at the next poll. Groups are never watched.+ */+ private async watchNotices(): Promise<void> {+ const watched = new Set<string>()+ for (const [tabId, { state }] of this.tabs) {+ const conversations = list(state.conversations)+ for (const { project, lead, leadId } of leadProjects(state)) {+ const projectId = projectKey(project)+ const chats: Array<{ conversation: Json; chat: LeadNotice['chat'] }> = [{ conversation: lead, chat: 'lead' },+ ...conversations.filter(c => inProject(c, projectId) && isPmChat(c) && c.archived !== true).map(conversation => ({ conversation, chat: 'pm' as const }))]+ for (const { conversation, chat } of chats) {+ if (!cardId(conversation.id) || typeof conversation.lastMessageSequence !== 'number') continue+ const key = `${tabId}:${conversation.id}`, sequence = conversation.lastMessageSequence+ watched.add(key)+ const baseline = this.seen.get(key)+ if (baseline === undefined) { this.seen.set(key, sequence); continue }+ if (sequence <= baseline || this.recapsRunning >= MAX_RECAPS_IN_FLIGHT) continue+ this.recapsRunning+++ try {+ const page = object(await backend(this.core, 'GET', `/api/super-tabs/${tabId}/conversations/${conversation.id}/messages`))+ const after = list(page.messages).filter(m => typeof m.sequence === 'number' && m.sequence > baseline)+ const said = lastAgentMessage(after, new Set([leadId]))+ if (said && cardId(said.id)) {+ const notice: LeadNotice = { chat, chatId: conversation.id, id: said.id, text: cut(said.text, RECAP_BYTES), at: said.at }+ const held = this.notices.get(recapKey(tabId, leadId))+ if (!held || held.at <= notice.at) this.notices.set(recapKey(tabId, leadId), notice)+ }+ this.seen.set(key, sequence)+ this.failed.delete(key)+ } catch (error) {+ if (!this.failed.has(key)) {+ this.failed.add(key)+ this.log(`[super-tabs] a Lead's new message could not be read for the dial; tried again at the next poll: ${error instanceof Error ? error.message : String(error)}`)+ }+ } finally { this.recapsRunning-- }+ }+ }+ }+ // A Swarm or project that left the cards takes its baseline and notices with it.+ for (const key of [...this.seen.keys()]) if (!watched.has(key)) this.seen.delete(key)+ for (const key of [...this.failed]) if (!watched.has(key)) this.failed.delete(key)+ for (const [key, notice] of this.notices) if (!watched.has(`${key.slice(0, key.indexOf(':'))}:${notice.chatId}`)) this.notices.delete(key)}/** Which of the Leads that run here are in a turn, and since when (the core's windows' own measure of "working"). */@@ -259,32 +394,35 @@ export class SwarmCards {return out}- /** The Lead's conversation and how far it has gone, from the tab as last read. */- private leadConversation(tabId: string, leadId: string): { id: string; sequence: number } | null {+ /** Where the Lead's recap is read and its talk posted, from the tab as last read: its Lead conversation, or with `chat` the+ * chat on its project's face (`chatId` set). */+ private target(tabId: string, leadId: string, chat: boolean): Target | null {const state = this.tabs.get(tabId)?.stateif (!state) return null- const conversations = list(state.conversations)- const projects = Array.isArray(state.projects) ? list(state.projects) : [{ leadConversationId: 'lead' }]- for (const project of projects) {- const lead = conversations.find(c => c.id === project.leadConversationId)- if (lead && lead.leadId === leadId && identifier(lead.id)) return { id: lead.id, sequence: typeof lead.lastMessageSequence === 'number' ? lead.lastMessageSequence : 0 }- }- return null+ const found = leadProjects(state).find(p => p.leadId === leadId)+ if (!found || !identifier(found.lead.id)) return null+ if (!chat) return { id: found.lead.id, sequence: sequenceOf(found.lead), voices: new Set([leadId]) }+ const focus = this.focus?.tabId === tabId ? this.focus.conversationId : undefined+ const face = faceOf(list(state.conversations), projectKey(found.project), found.lead, focus)+ if (!face) return null+ const id = face.conversation.id as string+ return { id, sequence: sequenceOf(face.conversation), voices: voicesOf(face, leadId), chatId: id }}- private sequenceOf(tabId: string, leadId: string): number | null { return this.leadConversation(tabId, leadId)?.sequence ?? null }- /** What the Lead last said: the newest page of its conversation, then one page back; `none` when neither holds a row of its own. */- async recap(tabId: string, leadId: string): Promise<LeadRecap> {+ /** What the Lead last said: the newest page of its conversation, then one page back; `none` when neither holds a row of its own.+ * With `chat`, what the chat on its face last heard from its agents, naming that chat. */+ async recap(tabId: string, leadId: string, chat = false): Promise<LeadRecap> {if (!cardId(tabId) || !cardId(leadId)) return { tabId, leadId, text: '', at: 0, none: true }- let found = this.leadConversation(tabId, leadId)+ let found = this.target(tabId, leadId, chat)if (!found) {if (this.recapsRunning >= MAX_RECAPS_IN_FLIGHT) throw new Error('too many recap reads at once')this.recapsRunning++try { this.tabs.set(tabId, tabOf(await this.reads.read(tabId))) } finally { this.recapsRunning-- }- found = this.leadConversation(tabId, leadId)+ found = this.target(tabId, leadId, chat)}if (!found) return { tabId, leadId, text: '', at: 0, none: true }- const key = `${tabId}:${leadId}`, held = this.recaps.get(key)+ const named = found.chatId === undefined ? {} : { chatId: found.chatId }+ const key = recapKey(tabId, leadId, found.chatId), held = this.recaps.get(key)if (held && held.sequence === found.sequence) return held.recap// At most two backend reads of recaps run at once: a Pro that asks in a loop cannot flood the backend.if (this.recapsRunning >= MAX_RECAPS_IN_FLIGHT) throw new Error('too many recap reads at once')@@ -292,24 +430,25 @@ export class SwarmCards {try {const path = `/api/super-tabs/${tabId}/conversations/${found.id}/messages`const newest = object(await backend(this.core, 'GET', path))- let said = lastLeadMessage(list(newest.messages), leadId)+ let said = lastAgentMessage(list(newest.messages), found.voices)// The page before, from the page's own (sequence, id) cursor: a page edge inside equal sequences skips nothing (design 4.6).const before = object(newest.next)if (!said && typeof before.sequence === 'number' && identifier(before.id)) {- said = lastLeadMessage(list(object(await backend(this.core, 'GET', `${path}?before=${before.sequence}&beforeId=${before.id}`)).messages), leadId)+ said = lastAgentMessage(list(object(await backend(this.core, 'GET', `${path}?before=${before.sequence}&beforeId=${before.id}`)).messages), found.voices)}- const recap: LeadRecap = said ? { tabId, leadId, text: cut(said.text, RECAP_BYTES), at: said.at, none: false } : { tabId, leadId, text: '', at: 0, none: true }+ const recap: LeadRecap = said ? { tabId, leadId, text: cut(said.text, RECAP_BYTES), at: said.at, none: false, ...named } : { tabId, leadId, text: '', at: 0, none: true, ...named }this.recaps.set(key, { sequence: found.sequence, recap })return recap} finally { this.recapsRunning-- }}/** Words spoken on a Pro to a Lead that runs here (its harness): posted as the person in that Lead's conversation, as typed in- * the Swarm chat. False when that harness leads no project in the Swarms as last read, so the caller sends the turn as before. */- async say(harnessId: string, text: string): Promise<boolean> {+ * the Swarm chat; with `chat`, in the chat on its face. False when that harness leads no project in the Swarms as last read,+ * so the caller sends the turn as before. */+ async say(harnessId: string, text: string, chat = false): Promise<boolean> {for (const [tabId, { state }] of this.tabs) {const agent = list(state.agents).find(a => a.machineId === this.machineId && a.harnessId === harnessId)- const found = agent && cardId(agent.id) ? this.leadConversation(tabId, agent.id) : null+ const found = agent && cardId(agent.id) ? this.target(tabId, agent.id, chat) : nullif (!found) continueawait backend(this.core, 'POST', `/api/super-tabs/${tabId}/commands`, { operationId: `pro-voice-${randomUUID()}`,command: { type: 'message.send', conversationId: found.id, text, replyTo: null, recipientIds: [] } })@@ -318,22 +457,45 @@ export class SwarmCards {return false}- /** Remembered recaps are kept only for Leads that are still in a tab. */+ /** Remembered recaps are kept only for Leads that are still in a tab, and a chat's only while it is on the face. */private prune(): void {- for (const [key, held] of this.recaps) if (!this.leadConversation(held.recap.tabId, held.recap.leadId)) this.recaps.delete(key)+ for (const [key, held] of this.recaps) {+ const { tabId, leadId, chatId } = held.recap+ const now = this.target(tabId, leadId, chatId !== undefined)+ if (!now || now.chatId !== chatId) this.recaps.delete(key)+ }}- /** Each open Lead that moved on since its Pro last got the recap: the new one is sent once. A failed read is tried again next tick. */- private async pushOpen(): Promise<void> {+ /** Each open Lead that moved on since its Pro last got the recap, or whose face shows another chat: the new one is sent once.+ * A failed read is tried again next tick. */+ private pushOpen(): Promise<void> {+ const run = this.pushing.then(() => this.pushOpenNow())+ this.pushing = run.catch(() => {})+ return run+ }+ private async pushOpenNow(): Promise<void> {for (const open of [...this.opened.values()]) {- const sequence = this.sequenceOf(open.tabId, open.leadId)- if (sequence === null) continue- if (open.sequence === null) { open.sequence = sequence; continue }- if (open.sequence === sequence) continue- const recap = await this.recap(open.tabId, open.leadId).catch(() => null)+ const target = this.target(open.tabId, open.leadId, open.chat)+ if (!target) continue+ if (open.sequence === null) { open.sequence = target.sequence; open.chatId = target.chatId ?? null; continue }+ if (open.sequence === target.sequence && open.chatId === (target.chatId ?? null)) continue+ const recap = await this.recap(open.tabId, open.leadId, open.chat).catch(() => null)if (!recap) continue- open.sequence = sequence+ open.sequence = target.sequence+ open.chatId = target.chatId ?? nullthis.onRecap?.(recap)}}}++/** Each project of a tab whose Lead conversation names its Lead: the project, that conversation and the Lead agent's id. */+function leadProjects(state: Json): Array<{ project: Json; lead: Json; leadId: string }> {+ const conversations = list(state.conversations)+ const projects = Array.isArray(state.projects) ? list(state.projects) : [{ id: 'lead', leadConversationId: 'lead' }]+ const out: Array<{ project: Json; lead: Json; leadId: string }> = []+ for (const project of projects) {+ const lead = conversations.find(c => c.id === project.leadConversationId)+ if (lead && typeof lead.leadId === 'string') out.push({ project, lead, leadId: lead.leadId })+ }+ return out+}diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex b50395a85..d59681d50 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -414,6 +414,20 @@ describe('Super Tab native delivery handoff', () => {expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)expect(t.saved().entries).toEqual({})})+ it('never types a held delivery the backend ended, and retires its journal entry', async () => {+ const t = setup(), host = t.open()+ await host.tick(); t.event('rejected', 'team_waiting_user')+ // Held past its limit, or its group archived: the backend's delivery pass ended it and lists it no more.+ const original = vi.mocked(t.core.account.backend).getMockImplementation()!+ vi.mocked(t.core.account.backend).mockImplementation(async (method, path, body) => {+ if (path.endsWith('/deliveries/delivery')) return { status: 200, body: { success: true, data: { id: 'delivery', status: 'cancelled' } } }+ if (path.endsWith('/deliveries')) return { status: 200, body: { success: true, data: [] } }+ return original(method, path, body)+ })+ await host.tick(); await host.reconcileReceipts()+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)+ expect(t.saved().entries).toEqual({})+ })it('drops the lease of a held delivery answered while its lease was being granted', async () => {const t = setup(), host = t.open()await host.tick(); t.event('rejected', 'team_waiting_busy')@@ -1530,6 +1544,30 @@ describe('the progress a host reports', () => {})})+describe('the beat a host keeps', () => {+ // 2026-10-28: the Mac Studio's reading waited behind git and launches in its pass, and its agents showed as Down.+ it('sends its machine\'s reading again every second\'s check while a launch holds its pass up', async () => {+ const t = setup()+ const pool = { tabId: 'tab', machine: { machineId: 'machine-1', generation: 'grant', cwd: '/repo', engines: ['claude'] }, harnessIds: [],+ starts: [{ id: 'start', dispatched: false }] }+ const roster = vi.mocked(t.call).getMockImplementation()!+ vi.mocked(t.call).mockImplementation(async (method, path, body) => path.includes('/hosts/machine-1/changes')+ ? { status: 200, body: { success: true, data: hostForm([t.row], { pools: [pool] }) } } : roster(method, path, body))+ const local = { machineId: 'machine-1', request: vi.fn(async () => ({})), close: vi.fn() }+ const start = vi.fn(() => new Promise(() => {}))+ let clock = 0+ const host = t.open({ machines: { open: async () => local, capabilities: async () => ({ ok: true, resources: {}, tools: {} }) as never,+ prepare: async () => null, start: start as never, now: () => clock } })+ const readings = () => vi.mocked(t.call).mock.calls.filter(([method, path]) => method === 'POST' && path === '/api/super-tabs/tab/machines/machine-1')+ host.start()+ await vi.waitFor(() => expect(start).toHaveBeenCalledOnce())+ expect(readings()).toHaveLength(1)+ clock += 15_000+ await vi.waitFor(() => expect(readings()).toHaveLength(2), { timeout: 3_000 })+ expect(readings()[1]![2]).toEqual(readings()[0]![2])+ })+})+describe('the members a host lets watch its agents', () => {it('keeps them watching through a 3 s roster read, wakes Share once, and lets a removed member go at once', async () => {const dir = mkdtempSync(join(tmpdir(), 'super-tab-host-')); roots.push(dir)@@ -1577,6 +1615,41 @@ describe('the members a host lets watch its agents', () => {expect(source.allows(peer)).toBe(false)expect(superTabs.shareObservers).toHaveBeenCalledOnce()})++ it('tells a member watching the current Lead to retry through a stop, and refuses other Swarms\', ordinary and a former Lead\'s shares for good', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'super-tab-host-')); roots.push(dir)+ // The Lead as the backend sends it: marked confidential, and its listed members watch it (Ken, 2026-10-28).+ const lead = (membersWatch: boolean) => ({ tabId: 'tab', confidential: true, membersWatch,+ agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1', name: 'River' }, observers: [{ email: '[email protected]', userId: 'peer' }] })+ let rows: unknown[] = [lead(true)], clock = 0+ const call: CoreApi['account']['backend'] = vi.fn(async (_method, path) =>+ ({ status: 200, body: { success: true, data: path.includes('/hosts/') ? hostForm(rows, { tabs: ['tab'] }) : [] } }))+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }+ const core = fakeCore({ dataDir: dir, superTabs, account: { backend: call },+ agents: { byAgent: vi.fn(() => ({ agentId: 'harness' }) as never), terminalAvailable: vi.fn(() => true) } })+ const source = observerSource(dir, () => 'machine-1', () => clock)+ const grant = (tab: string | null, recipientEmail = '[email protected]') => ({ tab, agentId: 'harness', recipientEmail }) as never+ const member = grant('super:tab'), otherSwarm = grant('super:other'), ordinary = grant(null)+ const first = new SuperTabHost(core, 'machine-1', { log: vi.fn(), now: () => clock }); hosts.push(first)+ await first.tick(); clock += 201+ expect(source.allows(member)).toBe(true)+ // Its backend link drops, or the daemon restarts for an update: viewing pauses, and the member is told to try again.+ first.stop(); clock += 201+ expect(source.allows(member)).toBe(false)+ expect(source.paused(member)).toBe(true)+ // As for any Swarm share, the next roster decides one of this Swarm's; another Swarm's or an ordinary one is closed.+ for (const refused of [otherSwarm, ordinary]) expect(source.paused(refused)).toBe(false)+ // The next host's first roster lets the member watch again.+ const next = new SuperTabHost(core, 'machine-1', { log: vi.fn(), now: () => clock }); hosts.push(next)+ await next.tick(); clock += 201+ expect(source.allows(member)).toBe(true)+ // No longer the Lead: closed, and a stop after that does not reopen it to a retry.+ rows = [lead(false)]+ clock += 1_000; await next.tick(); clock += 201+ expect(source.allows(member)).toBe(false)+ next.stop(); clock += 201+ expect(source.paused(member)).toBe(false)+ })})describe('adding the machine its own Lead runs on to the Swarm', () => {diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex 82adf9f2d..26609bddf 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -342,8 +342,9 @@ export class SuperTabHost {// until the next host's first roster says who is still a member. A host stops when its backend link drops and when// the daemon restarts for an update; an empty roster in force here withdrew every member's invitation each time,// which took this computer out of their machine lists until their apps next read them, up to 5 minutes later, and- // their panes said Harness here was out of date (Ken, 2026-10-28). The confidential marks are kept as they are.- try { this.observers(this.core.dataDir, this.machineId, [], this.now(), this.stillRuns) } catch { /* The old snapshot expires. */ }+ // their panes said Harness here was out of date (Ken, 2026-10-28). No roster, not an empty one: the confidential marks+ // and the current Leads' openings are kept as they are, so members watching a Lead are told to retry too.+ try { this.observers(this.core.dataDir, this.machineId, null, this.now(), this.stillRuns) } catch { /* The old snapshot expires. */ }// Signed out or another machine: this host's alerts are no longer anyone's. A core that is gone heard nothing, and// the next host's first roster replaces them anyway.if (this.attention !== null && this.attention !== '[]') {@@ -367,6 +368,8 @@ export class SuperTabHost {}private pollMachines() {void this.contributed().tick().catch(error => this.log(error instanceof Error ? error.message : String(error)))+ // Beside the pass, never behind it: a slow pass still keeps the machine's reading fresh (machines.ts beat).+ this.contributed().beat()this.grids ??= new SwarmGrids(this.core, this.machineId)void this.grids.tick().catch(error => this.log(`Swarm grid: ${error instanceof Error ? error.message : String(error)}`))}@@ -572,8 +575,10 @@ export class SuperTabHost {try {const result = object(await backend(this.core, 'GET', `/api/super-tabs/${entry.tabId}/agents/${entry.agentId}/deliveries/${entry.deliveryId}`))if (this.stopped) return- // Held input is retired only by an answer. A cancelled one leaves the roster, so the claim path never sees it again; it stays in the journal.- const terminal = entry.stage === 'prepared' ? ['answered'] : ['delivered', 'confirmed', 'superseded', 'cancelled', 'answered']+ // Held input is retired by an answer, or once the backend ended it: it leaves the list, so the claim path never sees it+ // again. Kept, every hold the backend's delivery pass ends (backend superTabs/deliverySettle.ts) would stay here, and+ // at 1,000 entries this host accepts no more deliveries.+ const terminal = entry.stage === 'prepared' ? ['answered', 'cancelled'] : ['delivered', 'confirmed', 'superseded', 'cancelled', 'answered']if (result.id !== entry.deliveryId || !terminal.includes(String(result.status))) continueif (this.journal.entries[entry.deliveryId] !== entry || this.active.has(typedId(entry))) continuedelete this.journal.entries[entry.deliveryId]diff --git a/cli/src/superTabs/inCore/cards.spec.ts b/cli/src/superTabs/inCore/cards.spec.tsindex 09ca014da..d887d7dca 100644--- a/cli/src/superTabs/inCore/cards.spec.ts+++ b/cli/src/superTabs/inCore/cards.spec.ts@@ -87,6 +87,38 @@ describe('the Swarm cards on the devices', () => {expect(swarmCardRecap).toHaveBeenCalledTimes(3)expect(log).toHaveBeenCalledTimes(8)})++ it('keeps a sound chat and notice, drops a malformed one', () => {+ const { cards, swarmCards, swarmCardRecap, log } = setup()+ const chat = (over: Record<string, unknown> = {}) => ({ kind: 'group', id: 'g1', name: 'Fix login', working: true, since: 5, ...over })+ const notice = (over: Record<string, unknown> = {}) => ({ chat: 'pm', chatId: 'pm1', id: 'm1', text: 'Shipped', at: 1792560000, ...over })+ cards.cards([card('t1', [lead('l1', { chat: chat({ name: 'g'.repeat(60) }), notice: notice({ text: '日'.repeat(600) }) })])])+ const [sent] = swarmCards.mock.calls[0][0][0].leads+ expect(sent.chat).toEqual(chat({ name: 'g'.repeat(48) }))+ expect(sent.notice).toEqual(notice({ text: '日'.repeat(500) }))+ // A chat without `since`, or a Lead chat that does not work, is sound too.+ cards.cards([card('t1', [lead('l1', { chat: { kind: 'lead', id: 'c1', name: 'Lead', working: false }, notice: notice({ chat: 'lead' }) })])])+ expect(swarmCards.mock.calls[1][0][0].leads[0]).toMatchObject({ chat: { kind: 'lead', id: 'c1' }, notice: { chat: 'lead' } })+ expect(swarmCards.mock.calls[1][0][0].leads[0].chat).not.toHaveProperty('since')+ swarmCards.mockClear()+ const badChats = [chat({ kind: 'other' }), chat({ id: 'bad id' }), chat({ name: 5 }), chat({ working: 'yes' }), chat({ since: -1 }), 'chat']+ const badNotices = [notice({ chat: 'group' }), notice({ chatId: 'bad id' }), notice({ id: '' }), notice({ text: 5 }), notice({ at: -1 }), 7]+ for (const bad of badChats) cards.cards([card('t1', [lead('l1', { chat: bad })])])+ for (const bad of badNotices) cards.cards([card('t1', [lead('l1', { notice: bad })])])+ // The Lead stays, without what was not sound.+ expect(swarmCards).toHaveBeenCalledTimes(badChats.length + badNotices.length)+ for (const [list] of swarmCards.mock.calls) {+ expect(list[0].leads[0]).toMatchObject({ id: 'l1' })+ expect(list[0].leads[0]).not.toHaveProperty('chat')+ expect(list[0].leads[0]).not.toHaveProperty('notice')+ }+ expect(log).not.toHaveBeenCalled()+ // A recap names its chat with an id, or is dropped: a dial must not show it for the wrong chat.+ cards.recap(recap({ chatId: 'g1' }))+ expect(swarmCardRecap).toHaveBeenLastCalledWith(recap({ chatId: 'g1' }))+ cards.recap(recap({ chatId: 'bad id' }))+ expect(swarmCardRecap).toHaveBeenCalledOnce()+ })})describe('whether the Swarm cards are wanted, which the core owns', () => {@@ -163,6 +195,42 @@ describe('whether the Swarm cards are wanted, which the core owns', () => {request.mockRejectedValueOnce(new Error('gone'))expect(await cards.ask({ action: 'cardRecap', tabId: 't1', leadId: 'l1' })).toEqual({ error: 'SERVICE_UNAVAILABLE' })})+ it('says the window\'s focus with the wish, again on a change and when the service reconnects; a malformed one is none', () => {+ const { cards, request } = wanting()+ const focus = { tabId: 't1', conversationId: 'g1' }+ cards.want(true, ['t1'], focus)+ expect(request).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: true, include: ['t1'], focus })+ cards.want(true, ['t1'], { ...focus })+ expect(request).toHaveBeenCalledTimes(1)+ cards.want(true, ['t1'], { tabId: 't1', conversationId: 'pm1' })+ expect(request).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: true, include: ['t1'], focus: { tabId: 't1', conversationId: 'pm1' } })+ request.mockClear()+ cards.serviceUp()+ expect(request.mock.calls).toEqual([[{ action: 'cardsWanted', on: true, include: ['t1'], focus: { tabId: 't1', conversationId: 'pm1' } }]])+ for (const bad of [{ tabId: 'bad id', conversationId: 'g1' }, { tabId: 't1', conversationId: 7 }, { tabId: 't1' }, 'focus', null]) {+ cards.want(true, ['t1'], { tabId: 't1', conversationId: 'pm1' })+ request.mockClear()+ cards.want(true, ['t1'], bad)+ expect(request.mock.calls).toEqual([[{ action: 'cardsWanted', on: true, include: ['t1'] }]])+ }+ // The devices gone take the focus with them.+ cards.want(true, ['t1'], focus)+ cards.devicesGone()+ expect(request).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: false, include: [] })+ })+ it('passes a device\'s focus and a swarmChat dial\'s chat flag on to the service', async () => {+ const { cards, request } = wanting()+ const focus = { tabId: 't1', conversationId: 'g1' }+ expect(await cards.ask({ action: 'cardsWanted', on: true, include: ['t1'], focus })).toEqual({ ok: true })+ expect(request).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: true, include: ['t1'], focus })+ request.mockClear()+ await cards.ask({ action: 'cardRecap', tabId: 't1', leadId: 'l1', chat: true })+ await cards.ask({ action: 'cardOpen', session: 's1', tabId: 't1', leadId: 'l1', chat: true })+ await cards.ask({ action: 'cardSay', harnessId: 'h1', text: 'ship it', chat: true })+ await cards.ask({ action: 'cardRecap', tabId: 't1', leadId: 'l1', chat: 'yes' })+ expect(request.mock.calls).toEqual([[{ action: 'cardRecap', tabId: 't1', leadId: 'l1', chat: true }], [{ action: 'cardOpen', session: 's1', tabId: 't1', leadId: 'l1', chat: true }],+ [{ action: 'cardSay', harnessId: 'h1', text: 'ship it', chat: true }], [{ action: 'cardRecap', tabId: 't1', leadId: 'l1' }]])+ })it('on an account change with no device wanting cards only clears the list', () => {const { cards, request, swarmCards } = wanting()cards.cards([card('t1')])diff --git a/cli/src/superTabs/inCore/cards.ts b/cli/src/superTabs/inCore/cards.tsindex 0ba85ed91..ffad068eb 100644--- a/cli/src/superTabs/inCore/cards.ts+++ b/cli/src/superTabs/inCore/cards.ts@@ -13,7 +13,7 @@* whether a capable Pro is attached and which Swarms the desktop has tabs for (`want`), and the core says it to the Super Tab* service, again whenever that service (re)connects (`serviceUp`), and takes it back when the devices go (`devicesGone`).*/-import type { LeadRecap, SwarmCard, SwarmLead } from '../../core/api.js'+import type { LeadNotice, LeadRecap, SwarmCard, SwarmChat, SwarmLead } from '../../core/api.js'export interface SuperTabCardsDeps {/** The devices' door for the list (`ports.devices.swarmCards`). */@@ -27,6 +27,8 @@ export interface SuperTabCardsDeps {const MAX_CARDS = 16, MAX_LEADS = 12, NAME_BYTES = 48, ENGINE_BYTES = 16, RECAP_BYTES = 1500const STATES: ReadonlySet<string> = new Set(['ask', 'stuck', 'work', 'done'])+const CHATS: ReadonlySet<string> = new Set(['lead', 'pm', 'group'])+const NOTICE_CHATS: ReadonlySet<string> = new Set(['lead', 'pm'])/** The Pro keeps an id in 48 bytes with its NUL. */const ID = /^[A-Za-z0-9_-]{1,47}$/const id = (value: unknown): value is string => typeof value === 'string' && ID.test(value)@@ -44,6 +46,21 @@ function cut(text: string, bytes: number): string {return out}+/** The chat on a Lead's face, checked and cut; null when it is not one, and the Lead goes on without it (today's frames). */+function chatIn(value: unknown): SwarmChat | null {+ const chat = object(value)+ if (typeof chat.kind !== 'string' || !CHATS.has(chat.kind) || !id(chat.id) || typeof chat.name !== 'string' || typeof chat.working !== 'boolean') return null+ if (chat.since !== undefined && !whole(chat.since)) return null+ return { kind: chat.kind as SwarmChat['kind'], id: chat.id, name: cut(chat.name, NAME_BYTES), working: chat.working, ...(chat.since === undefined ? {} : { since: chat.since }) }+}++/** A Lead's notice, checked and cut; null when it is not one, and the Lead goes on without it. */+function noticeIn(value: unknown): LeadNotice | null {+ const notice = object(value)+ if (typeof notice.chat !== 'string' || !NOTICE_CHATS.has(notice.chat) || !id(notice.chatId) || !id(notice.id) || typeof notice.text !== 'string' || !whole(notice.at)) return null+ return { chat: notice.chat as LeadNotice['chat'], chatId: notice.chatId, id: notice.id, text: cut(notice.text, RECAP_BYTES), at: notice.at }+}+/** A Lead the service sent, checked and cut; null when it is not one. */function leadIn(value: unknown): SwarmLead | null {const lead = object(value)@@ -54,10 +71,13 @@ function leadIn(value: unknown): SwarmLead | null {if (lead.since !== undefined && !whole(lead.since)) return null// The project's index in its Swarm, which the round dial shows the Leads by (the Pro sorts its own and ignores it).if (!whole(lead.order)) return null+ // The round dial's chat and alert are additions: one that is not sound is left out, and the Lead is kept as today's.+ const chat = lead.chat === undefined ? null : chatIn(lead.chat)+ const notice = lead.notice === undefined ? null : noticeIn(lead.notice)return {id: lead.id, projectId: lead.projectId, project: cut(lead.project, NAME_BYTES), engine: cut(lead.engine, ENGINE_BYTES),owner: cut(lead.owner, NAME_BYTES), local: lead.local, state: lead.state as SwarmLead['state'], order: lead.order,- ...(lead.since === undefined ? {} : { since: lead.since }),+ ...(lead.since === undefined ? {} : { since: lead.since }), ...(chat ? { chat } : {}), ...(notice ? { notice } : {}),}}@@ -78,28 +98,35 @@ function cardIn(value: unknown): SwarmCard | null {function recapIn(value: unknown): LeadRecap | null {const recap = object(value)if (!id(recap.tabId) || !id(recap.leadId) || typeof recap.text !== 'string' || !whole(recap.at) || typeof recap.none !== 'boolean') return null- return { tabId: recap.tabId, leadId: recap.leadId, text: cut(recap.text, RECAP_BYTES), at: recap.at, none: recap.none }+ // A chat's recap names its chat or is not one: a dial must never show it for another chat.+ if (recap.chatId !== undefined && !id(recap.chatId)) return null+ return { tabId: recap.tabId, leadId: recap.leadId, text: cut(recap.text, RECAP_BYTES), at: recap.at, none: recap.none, ...(recap.chatId === undefined ? {} : { chatId: recap.chatId }) }}export function createSuperTabCards({ swarmCards, swarmCardRecap, request, log = (line) => console.log(line) }: SuperTabCardsDeps) {/** The last good list, or null before the service has said one. */let last: SwarmCard[] | null = null- /** Whether any capable device wants cards, and the Swarms to read first. */+ /** Whether any capable device wants cards, the Swarms to read first, and the conversation the window has open in a Swarm tab. */let wanted = false, include: string[] = []+ let focus: { tabId: string; conversationId: string } | null = nullconst route = async (payload: Record<string, unknown>): Promise<Record<string, unknown>> => {try {const answer = await request?.(payload)return answer === undefined ? { error: 'SERVICE_UNAVAILABLE' } : object(answer)} catch { return { error: 'SERVICE_UNAVAILABLE' } }}- const tell = (): void => { void route({ action: 'cardsWanted', on: wanted, include }) }+ const tell = (): void => { void route({ action: 'cardsWanted', on: wanted, include, ...(focus ? { focus } : {}) }) }const api = {- /** The devices say whether a capable Pro is attached (and which Swarms the desktop has open): the service is told. */- want(on: boolean, swarms: unknown): void {+ /** The devices say whether a capable Pro is attached (and which Swarms the desktop has open, and the conversation it has+ * open in one): the service is told. */+ want(on: boolean, swarms: unknown, open?: unknown): void {const next = on && Array.isArray(swarms) ? [...new Set(swarms.filter(id))].slice(0, MAX_CARDS) : []- if (on === wanted && next.join(',') === include.join(',')) return+ const asked = object(open)+ const nextFocus = on && id(asked.tabId) && id(asked.conversationId) ? { tabId: asked.tabId, conversationId: asked.conversationId } : null+ if (on === wanted && next.join(',') === include.join(',') && `${nextFocus?.tabId}/${nextFocus?.conversationId}` === `${focus?.tabId}/${focus?.conversationId}`) returnwanted = oninclude = next+ focus = nextFocustell()},/** The Super Tab service (re)connected: it has forgotten, so it is told again if a device wants the cards. */@@ -111,6 +138,7 @@ export function createSuperTabCards({ swarmCards, swarmCardRecap, request, log =if (!wanted) returnwanted = falseinclude = []+ focus = nulltell()},/** The account changed or ended: the list shown and kept is of someone else, and the service starts over. */@@ -139,10 +167,12 @@ export function createSuperTabCards({ swarmCards, swarmCardRecap, request, log =/** What the devices may ask of the Super Tab service, and nothing else of it: `cardsWanted` is kept here, `cardRecap`,* `cardOpen` and `cardSay` go to the service; any other action is refused. */ask(payload: Record<string, unknown>): Promise<Record<string, unknown>> {- if (payload.action === 'cardsWanted') { api.want(payload.on === true, payload.include); return Promise.resolve({ ok: true }) }- if (payload.action === 'cardRecap') return route({ action: 'cardRecap', tabId: payload.tabId, leadId: payload.leadId })- if (payload.action === 'cardSay') return route({ action: 'cardSay', harnessId: payload.harnessId, text: payload.text })- if (payload.action === 'cardOpen') return route({ action: 'cardOpen', session: payload.session, tabId: payload.tabId, leadId: payload.leadId })+ if (payload.action === 'cardsWanted') { api.want(payload.on === true, payload.include, payload.focus); return Promise.resolve({ ok: true }) }+ // A round dial that speaks swarmChat asks for the chat on its face; without the flag, the request is today's.+ const chat = payload.chat === true ? { chat: true } : {}+ if (payload.action === 'cardRecap') return route({ action: 'cardRecap', tabId: payload.tabId, leadId: payload.leadId, ...chat })+ if (payload.action === 'cardSay') return route({ action: 'cardSay', harnessId: payload.harnessId, text: payload.text, ...chat })+ if (payload.action === 'cardOpen') return route({ action: 'cardOpen', session: payload.session, tabId: payload.tabId, leadId: payload.leadId, ...chat })return Promise.resolve({ error: 'INVALID_REQUEST' })},/** A dial attached: it has nothing, so it is shown the last list again. */diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex 703510b01..243b88d04 100644--- a/cli/src/superTabs/machines.spec.ts+++ b/cli/src/superTabs/machines.spec.ts@@ -468,9 +468,11 @@ describe('contributed machine executor', () => {: { ok: args.join(' ') === 'status --porcelain', stdout: cwd === '/work/running' ? ' M src/a.ts\n' : '', stderr: '' })const machine = new ContributedMachines(f.core, 'host', { ...f.deps, git } as never)await machine.tick()- const body = f.backend.mock.calls.find(c => c[1] === 'POST')![3] as Record<string, unknown>+ await vi.waitFor(() => expect(git).toHaveBeenCalledTimes(3))+ f.advance(); await machine.tick()+ const body = f.backend.mock.calls.filter(c => c[1] === 'POST').at(-1)![3] as Record<string, unknown>expect(body.harnessUncommitted).toEqual({ running: true, clean: false })- expect(git.mock.calls.map(c => c[0]).sort()).toEqual(['/work/broken', '/work/clean', '/work/running'])+ expect([...new Set(git.mock.calls.map(c => c[0]))].sort()).toEqual(['/work/broken', '/work/clean', '/work/running'])})it('reads each session\'s folder at most once a minute', async () => {@@ -479,10 +481,79 @@ describe('contributed machine executor', () => {const git = vi.fn(async () => ({ ok: true, stdout: '', stderr: '' }))const machine = new ContributedMachines(f.core, 'host', { ...f.deps, git } as never)await machine.tick()+ await vi.waitFor(() => expect(git).toHaveBeenCalledOnce())f.advance(); await machine.tick()expect(git).toHaveBeenCalledTimes(1)f.step(60_000); await machine.tick()+ await vi.waitFor(() => expect(git).toHaveBeenCalledTimes(2))+ })++ // 2026-10-28: git status one folder after another took 20 s for the Mac Studio's 29 worktrees, inside the pass that+ // sends the machine's reading.+ it('never holds the reading up for git: a folder still being read is sent on a later pass', async () => {+ const f = fixture()+ vi.mocked(f.core.agents.byAgent).mockImplementation(id => id === 'running' ? { agentId: id, cwd: '/work/running' } as never : undefined)+ let answer!: (value: { ok: boolean; stdout: string; stderr: string }) => void+ const git = vi.fn(() => new Promise<{ ok: boolean; stdout: string; stderr: string }>(resolve => { answer = resolve }))+ const machine = new ContributedMachines(f.core, 'host', { ...f.deps, git } as never)+ await machine.tick()+ const posts = () => f.backend.mock.calls.filter(c => c[1] === 'POST' && String(c[2]).includes('/machines/')).map(c => c[3] as Record<string, unknown>)+ expect(posts()).toHaveLength(1)+ expect(posts()[0]).not.toHaveProperty('harnessUncommitted')+ answer({ ok: true, stdout: ' M a.ts\n', stderr: '' })+ await vi.waitFor(async () => {+ f.advance(); await machine.tick()+ expect(posts().at(-1)).toHaveProperty('harnessUncommitted', { running: true })+ })+ })++ it('reads four folders at a time at most', async () => {+ const f = fixture()+ const ids = ['a', 'b', 'c', 'd', 'e', 'f']+ vi.mocked(f.core.agents.byAgent).mockImplementation(id => ids.includes(id) ? { agentId: id, cwd: `/work/${id}` } as never : undefined)+ f.pool.harnessIds = ids+ let reading = 0, most = 0+ const waiting: Array<() => void> = []+ const git = vi.fn(() => new Promise<{ ok: boolean; stdout: string; stderr: string }>(resolve => {+ most = Math.max(most, ++reading)+ waiting.push(() => { reading--; resolve({ ok: true, stdout: '', stderr: '' }) })+ }))+ const machine = new ContributedMachines(f.core, 'host', { ...f.deps, git } as never)+ await machine.tick()+ await vi.waitFor(() => expect(git).toHaveBeenCalledTimes(4))+ waiting.shift()!()+ await vi.waitFor(() => expect(git).toHaveBeenCalledTimes(5))+ while (waiting.length) { waiting.shift()!(); await new Promise(done => setTimeout(done, 0)) }+ await vi.waitFor(() => expect(git).toHaveBeenCalledTimes(6))+ waiting.shift()?.()+ expect(most).toBe(4)+ })++ it('reads a session\'s folder again only once its screen changed, or after ten minutes', async () => {+ const f = fixture()+ vi.mocked(f.core.agents.byAgent).mockImplementation(id => id === 'running' ? { agentId: id, cwd: '/work/running' } as never : undefined)+ const git = vi.fn(async () => ({ ok: true, stdout: '', stderr: '' }))+ let shown = 900+ const machine = new ContributedMachines(f.core, 'host', { ...f.deps, git, progress: () => ({ running: shown }) } as never)+ const pass = async (ms: number) => { f.step(ms); await machine.tick(); await new Promise(done => setTimeout(done, 0)) }+ await pass(0)+ await vi.waitFor(() => expect(git).toHaveBeenCalledOnce())+ // An idle session: its files have not changed since the read.+ for (let i = 0; i < 5; i++) await pass(60_000)+ expect(git).toHaveBeenCalledOnce()+ shown = 400_000+ await pass(60_000)+ await vi.waitFor(() => expect(git).toHaveBeenCalledTimes(2))+ // Changed again, but read under a minute ago.+ shown = 400_500+ await pass(30_000)expect(git).toHaveBeenCalledTimes(2)+ await pass(30_000)+ await vi.waitFor(() => expect(git).toHaveBeenCalledTimes(3))+ await pass(9 * 60_000)+ expect(git).toHaveBeenCalledTimes(3)+ await pass(60_000)+ await vi.waitFor(() => expect(git).toHaveBeenCalledTimes(4))})it('drops uncommitted changes alone for a backend that refuses them, and offers them again ten minutes later', async () => {@@ -498,7 +569,9 @@ describe('contributed machine executor', () => {const posts = () => f.backend.mock.calls.filter(c => c[1] === 'POST' && String(c[2]).includes('/machines/')).map(c => c[3] as Record<string, unknown>)const fields = (post: Record<string, unknown>) => ['harnessUncommitted', 'harnessProgress'].filter(key => key in post)await machine.tick()- expect(posts().map(fields)).toEqual([['harnessUncommitted', 'harnessProgress'], ['harnessProgress']])+ await vi.waitFor(() => expect(git).toHaveBeenCalledOnce())+ f.advance(); await machine.tick()+ expect(posts().map(fields)).toEqual([['harnessProgress'], ['harnessUncommitted', 'harnessProgress'], ['harnessProgress']])f.advance(); await machine.tick()expect(posts().map(fields).at(-1)).toEqual(['harnessProgress'])f.step(600_000); await machine.tick()@@ -1134,6 +1207,139 @@ describe('contributed machine executor', () => {expect(posts(f)).toHaveLength(2)})})++ // 2026-10-28: the Mac Studio's 15-second reading went out only at the end of a pass that also ran git in 22 session+ // folders and launched agents; it arrived 31 s apart, past 45 s under load, and every agent there showed as Down.+ describe('the beat while a pass is slow', () => {+ const posts = (f: ReturnType<typeof fixture>) => f.backend.mock.calls.filter(c => c[1] === 'POST' && String(c[2]).includes('/machines/'))+ /** A pass that stops at its launch, until `launched` is called. */+ function stuck(f: ReturnType<typeof fixture>) {+ let launched!: () => void+ f.start.mockImplementation(() => new Promise(resolve => { launched = () => resolve({ ok: true }) }) as never)+ const pass = f.machine.tick()+ return { pass, launched: () => launched() }+ }+ const beat = async (f: ReturnType<typeof fixture>, ms: number) => { f.step(ms); f.machine.beat(); await new Promise(done => setTimeout(done, 0)) }++ it('re-sends the last reading on its own once a slow pass has sent none for fifteen seconds', async () => {+ const f = fixture()+ const { pass, launched } = stuck(f)+ await vi.waitFor(() => expect(f.start).toHaveBeenCalledOnce())+ expect(posts(f)).toHaveLength(1)+ await beat(f, 14_999)+ expect(posts(f)).toHaveLength(1)+ await beat(f, 1)+ expect(posts(f)).toHaveLength(2)+ expect(posts(f)[1]![2]).toBe(posts(f)[0]![2])+ expect(posts(f)[1]![3]).toEqual(posts(f)[0]![3])+ // The beat counts from the last send, a re-send included.+ await beat(f, 14_999)+ expect(posts(f)).toHaveLength(2)+ await beat(f, 1)+ expect(posts(f)).toHaveLength(3)+ launched(); await pass+ })++ it('never re-sends while passes keep up: the pass sends its own reading', async () => {+ const f = fixture(); f.pool.starts.length = 0+ await f.machine.tick()+ for (let i = 0; i < 4; i++) await beat(f, 16_000)+ expect(posts(f)).toHaveLength(1)+ })++ it('leaves out whether folders have uncommitted changes, which only a fresh read may vouch for', async () => {+ const f = fixture()+ vi.mocked(f.core.agents.byAgent).mockImplementation(id => id === 'running' ? { agentId: id, cwd: '/work/running' } as never : undefined)+ const git = vi.fn(async () => ({ ok: true, stdout: '', stderr: '' }))+ const machine = new ContributedMachines(f.core, 'host', { ...f.deps, git } as never)+ f.pool.starts.length = 0+ await machine.tick()+ await vi.waitFor(() => expect(git).toHaveBeenCalledOnce())+ f.step(16_000); await machine.tick()+ expect(posts(f).at(-1)![3]).toHaveProperty('harnessUncommitted', { running: false })+ f.pool.starts.push({ id: 'start', dispatched: false })+ f.start.mockImplementation(() => new Promise(() => {}) as never)+ f.step(16_000); void machine.tick()+ await vi.waitFor(() => expect(f.start).toHaveBeenCalledOnce())+ const sent = posts(f).at(-1)![3] as Record<string, unknown>+ f.step(15_000); machine.beat()+ await vi.waitFor(() => expect(posts(f).length).toBeGreaterThan(3))+ const { harnessUncommitted: _uncommitted, ...rest } = sent+ expect(posts(f).at(-1)![3]).toEqual(rest)+ })++ it('stops re-sending once a pass has run for three minutes, so a stuck daemon shows as offline', async () => {+ const f = fixture()+ const { pass, launched } = stuck(f)+ await vi.waitFor(() => expect(f.start).toHaveBeenCalledOnce())+ for (let i = 0; i < 11; i++) await beat(f, 15_000)+ // 2:45 into the pass: eleven beats.+ expect(posts(f)).toHaveLength(12)+ await beat(f, 15_000)+ await beat(f, 15_000)+ expect(posts(f)).toHaveLength(12)+ launched(); await pass+ })++ it('has one re-send in flight at most, and says why one failed', async () => {+ const f = fixture()+ const { pass, launched } = stuck(f)+ await vi.waitFor(() => expect(f.start).toHaveBeenCalledOnce())+ let answer!: (value: unknown) => void+ f.backend.mockImplementationOnce(() => new Promise(resolve => { answer = resolve }))+ await beat(f, 15_000)+ await beat(f, 15_000)+ expect(posts(f)).toHaveLength(2)+ answer({ revision: 2 }); await new Promise(done => setTimeout(done, 0))+ f.backend.mockRejectedValueOnce(new SuperTabHostError('CONTRIBUTION_REVOKED', 'Read the current machine contribution.', 403))+ await beat(f, 1_000)+ expect(posts(f)).toHaveLength(3)+ expect(f.log).toHaveBeenCalledWith(expect.stringContaining('Read the current machine contribution.'))+ launched(); await pass+ })++ it('never lets a re-send land after a newer reading: the pass waits for one in flight, and none starts while it sends', async () => {+ const f = fixture(); f.pool.starts.length = 0+ await f.machine.tick()+ expect(posts(f)).toHaveLength(1)+ // The next pass is slow to measure, and a re-send goes meanwhile; the backend holds it.+ let measured!: () => void+ f.capabilities.mockImplementationOnce(() => new Promise(resolve => { measured = () => resolve({ ok: true, resources: {}, tools: { git: true } }) }) as never)+ let answer!: (value: unknown) => void+ f.step(16_000); const pass = f.machine.tick()+ await vi.waitFor(() => expect(f.capabilities).toHaveBeenCalledTimes(2))+ f.backend.mockImplementationOnce(() => new Promise(resolve => { answer = resolve }))+ f.machine.beat()+ expect(posts(f)).toHaveLength(2)+ measured()+ await new Promise(done => setTimeout(done, 10))+ expect(posts(f)).toHaveLength(2)+ answer({ revision: 2 })+ await pass+ expect(posts(f)).toHaveLength(3)+ // While the pass sends its reading, no re-send starts.+ let taken!: (value: unknown) => void+ f.backend.mockImplementation(async (_core, method, path) => path.includes('/hosts/host/changes') ? hostForm([], { pools: [f.pool] })+ : method === 'POST' ? new Promise(resolve => { taken = resolve }) : { revision: 1 })+ f.step(16_000); const sending = f.machine.tick()+ await vi.waitFor(() => expect(posts(f)).toHaveLength(4))+ f.step(15_000); f.machine.beat()+ expect(posts(f)).toHaveLength(4)+ taken({ revision: 3 }); await sending+ })++ it('re-sends nothing for a Swarm that no longer lists this machine', async () => {+ const f = fixture(); f.pool.starts.length = 0+ await f.machine.tick()+ const pools = f.backend.getMockImplementation()!+ f.backend.mockImplementation(async (core, method, path, body) => path.includes('/hosts/host/changes') ? hostForm([], { tabs: ['tab'] }) : pools(core, method, path, body))+ f.step(5_000); await f.machine.tick()+ f.backend.mockImplementation(async (core, method, path, body) => path.includes('/hosts/host/changes') ? new Promise(() => {}) : pools(core, method, path, body))+ f.step(5_000); void f.machine.tick()+ await beat(f, 15_000)+ expect(posts(f)).toHaveLength(1)+ })+ })})describe('removed machine cleanup', () => {diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex 043f8711a..81a2a4e08 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -36,6 +36,16 @@ const UNVERIFIED_TOOL_TTL_MS = 60_000/** How long a session's folder stands as clean or not before git is asked again: a minute bounds the work to one* `git status` per running session a minute, and the backend stops an idle worker only on a report under 2 minutes old. */const UNCOMMITTED_TTL_MS = 60_000+/** How long a folder whose session's screen has not changed stands before git reads it again: an agent changes its files+ * while it works, and its screen changes with them. git status one folder after another took 20 s a pass for the Mac+ * Studio's 29 worktrees (2026-10-28), most of them idle. Ten minutes still re-reads well inside the 15 idle minutes after+ * which the backend stops a clean worker (backend superTabs/tidy.ts), for a folder changed by someone else. */+const UNCOMMITTED_IDLE_TTL_MS = 10 * 60_000+/** How many session folders git reads at once. */+const UNCOMMITTED_PARALLEL = 4+/** How long into one pass the last reading is still sent again on the beat. Past it the daemon is taken as stuck, and the+ * machine is left to show as offline rather than kept healthy by a loop that no longer reads anything. */+const BEAT_LIMIT_MS = 3 * 60_000/** How long this machine refuses a start before failing it with its reason, so the Lead starts it elsewhere: a minute of* busy CPU or memory may pass, and routing saw this machine able a moment ago. A refusal no one reported left starts* "Queued" for hours (DESKTOP-0TFH0OJ, 2026-10-23). */@@ -129,6 +139,15 @@ export class ContributedMachines {* running and stopped, whether new work is paused, and which starts are waiting. A change in any of them is* sent at once; otherwise the heartbeat keeps the reading fresh. */private readonly published = new Map<string, { at: number; signature: string; starting?: boolean }>()+ /** Per tab, the reading the backend last took and when it or a re-send of it last went: what [beat] sends again. */+ private readonly lastSent = new Map<string, { path: string; body: Record<string, unknown>; at: number }>()+ /** When the pass in flight began, or null between passes. */+ private passBegan: number | null = null+ /** The re-sends in flight, which a pass waits for before it sends a newer reading: a re-send that landed after it would+ * put the older one back. */+ private beating: Promise<void> | null = null+ /** The tabs whose new reading the pass is sending: no re-send of the older one starts meanwhile. */+ private readonly sending = new Set<string>()/** Shell tool availability belongs to this machine, not a tab. Resource readings still refresh every heartbeat. */private readonly toolCache = new Map<string, { value: boolean | null; detail?: string; until: number }>()/** Per waiting start, why it was last not started, so the log says it once per reason, not every pass. */@@ -150,7 +169,9 @@ export class ContributedMachines {private progressRefusedUntil = 0private uncommittedRefusedUntil = 0/** Per running session, whether its folder had uncommitted changes when last read, and until when that stands. */- private readonly uncommittedCache = new Map<string, { cwd: string; dirty: boolean; until: number }>()+ private readonly uncommittedCache = new Map<string, { cwd: string; dirty: boolean; until: number; readAt: number; shown?: number }>()+ /** Whether git is reading session folders beside the pass now. */+ private uncommittedReading = false/** Until when the reading leaves out its readiness field, which the backend refused. */private readinessRefusedUntil = 0/** Until when the reading leaves out the starts it is preparing, which the backend refused. */@@ -232,22 +253,49 @@ export class ContributedMachines {tick(): Promise<void> {if (this.stopped || this.deps.now() < this.next) return Promise.resolve()const began = this.deps.now()+ if (!this.running) this.passBegan = beganreturn this.running ??= this.poll(began).catch(error => { this.failed = true; throw error }).finally(() => {this.running = null+ this.passBegan = nullconst done = this.deps.now()this.next = this.failed ? done + MACHINE_HEARTBEAT_MS : Math.max(began + MACHINE_POLL_MS, done + 1_000)this.failed = false})}+ /**+ * Called every second beside [tick]: while a pass is slow (git, a launch, a slow backend), each tab's last reading is+ * sent again once nothing has gone for a heartbeat, so the machine never reads as offline, and its agents as Down, only+ * because its pass is busy (the Mac Studio, 2026-10-28). It reads nothing itself, and sends what the backend already+ * holds: no extra report, only a late one filled in. Never past [BEAT_LIMIT_MS] into a pass, so a stuck daemon still+ * shows as offline. Whether a folder has uncommitted changes is left out: only a fresh read vouches for stopping a+ * worker (backend superTabs/tidy.ts).+ */+ beat(): void {+ const began = this.passBegan+ if (this.stopped || this.beating || began === null) return+ const now = this.deps.now()+ if (now - began >= BEAT_LIMIT_MS) return+ const due = [...this.lastSent].filter(([tab, sent]) => !this.sending.has(tab) && now - sent.at >= MACHINE_HEARTBEAT_MS)+ if (!due.length) return+ this.beating = (async () => {+ for (const [, sent] of due) {+ // A failed one waits a whole beat too, rather than being asked again every second.+ sent.at = now+ try { await this.deps.backend(this.core, 'POST', sent.path, sent.body) }+ catch (error) { this.log(`Could not send this machine's reading again: ${error instanceof Error ? error.message : String(error)}`) }+ }+ })().finally(() => { this.beating = null })+ }private async poll(began: number) {const where = { dataDir: this.core.dataDir, port: this.core.daemon.port, machineId: this.machineId }const pools = list((await this.sources.feed.current(POOLS_FRESH_MS)).pools).filter(row => identifier(row.tabId) && object(row.machine).machineId === this.machineId && identifier(object(row.machine).generation))- if (this.stopped || pools.length === 0) { this.published.clear(); this.waiting.clear(); return }+ if (this.stopped || pools.length === 0) { this.published.clear(); this.lastSent.clear(); this.waiting.clear(); return }const pendingIds = new Set(pools.flatMap(row => list(row.starts).map(start => start.id)))for (const id of this.waiting.keys()) if (!pendingIds.has(id)) this.waiting.delete(id)for (const id of this.refusedSince.keys()) if (!pendingIds.has(id)) this.refusedSince.delete(id)for (const id of this.preparing) if (!pendingIds.has(id)) this.preparing.delete(id)for (const tab of this.published.keys()) if (!pools.some(row => row.tabId === tab)) this.published.delete(tab)+ for (const tab of this.lastSent.keys()) if (!pools.some(row => row.tabId === tab)) this.lastSent.delete(tab)const privacy = this.privacy()// A model run or stopped for a Swarm, or an API shared with it, is sent on this pass, not on the next beat: the// machine's panel waited up to 15 s more for it (2026-10-26). Files only, so a pass with nothing new asks nobody.@@ -339,7 +387,7 @@ export class ContributedMachines {const readiness = { ...(readyEngines ? { engines: readyEngines } : {}), ...(checkouts ? { checkouts } : {}) }const shown = began >= this.progressRefusedUntil ? this.deps.progress?.(running) ?? {} : {}const progress = Object.fromEntries(running.flatMap(id => typeof shown[id] === 'number' ? [[id, shown[id]]] : []))- const uncommitted = began >= this.uncommittedRefusedUntil ? await this.uncommitted(running, began) : {}+ const uncommitted = began >= this.uncommittedRefusedUntil ? this.uncommitted(running, began, shown) : {}const observation = { generation: pool.generation, tools: reportedTools, ...(preparing.length ? { preparingStartIds: preparing } : {}),...(Object.keys(uncommitted).length ? { harnessUncommitted: uncommitted } : {}),...(Object.keys(progress).length ? { harnessProgress: progress } : {}), ...(localModels ? { localModels } : {}),@@ -359,7 +407,9 @@ export class ContributedMachines {}), runningHarnessIds: running, stoppedHarnessIds: stopped,...(Array.isArray(row.reservations) ? { stoppedReservations: list(row.reservations).filter(r => stopped.includes(String(r.harnessId))&& identifier(r.harnessId) && identifier(r.generation)).map(r => ({ harnessId: r.harnessId, generation: r.generation })) } : {}) }+ this.sending.add(String(row.tabId))try {+ await this.beatingconst path = `/api/super-tabs/${row.tabId}/machines/${this.machineId}`const refused = (error: unknown) => error instanceof SuperTabHostError && error.status === 400 && error.code === 'VALIDATION_ERROR'// Older backends reject the additive fields. The newest go alone first (the starts it is preparing, uncommitted work,@@ -382,6 +432,8 @@ export class ContributedMachines {for (const [index, attempt] of attempts.entries()) {try {await this.deps.backend(this.core, 'POST', path, attempt)+ const { harnessUncommitted: _fresh, ...taken } = attempt as Record<string, unknown>+ this.lastSent.set(String(row.tabId), { path, body: taken, at: this.deps.now() })break} catch (error) {if (!refused(error) || index === attempts.length - 1) throw error@@ -394,6 +446,7 @@ export class ContributedMachines {}this.published.set(String(row.tabId), { at: began, signature, starting: !!localModels?.some(m => m.starting) })} catch (error) { this.failed = true; throw error }+ finally { this.sending.delete(String(row.tabId)) }}this.repairTrust ??= createSwarmCloneTrustRepair(this.core, this.deps.now)try { await this.repairTrust(row) }@@ -462,26 +515,40 @@ export class ContributedMachines {}} finally { local?.close() }}- /** Whether each running session's folder has uncommitted changes (git status), for the sessions git could read: the- * backend stops a worker idle for 15 minutes only when its host says it is clean (backend superTabs/tidy.ts). */- private async uncommitted(running: readonly string[], now: number): Promise<Record<string, boolean>> {- const read: Record<string, boolean> = {}+ /** Whether each running session's folder has uncommitted changes (git status), as last read, for the sessions git could+ * read: the backend stops a worker idle for 15 minutes only when its host says it is clean (backend superTabs/tidy.ts).+ * The folders due are read beside the pass, never holding the reading up; what they say goes with a later one. A folder+ * is due a minute after its last read once its session's screen ([shown]) has changed since, and after+ * [UNCOMMITTED_IDLE_TTL_MS] whatever it shows. */+ private uncommitted(running: readonly string[], now: number, shown: Record<string, number>): Record<string, boolean> {+ const read: Record<string, boolean> = {}, due: Array<{ id: string; cwd: string; shown?: number }> = []for (const id of running) {const cwd = this.core.agents.byAgent(id)?.cwdif (!cwd) continue- let known = this.uncommittedCache.get(id)- if (!known || known.cwd !== cwd || known.until <= now) {- const dirty = await uncommittedIn(cwd, this.deps.git)- known = dirty === null ? undefined : { cwd, dirty, until: now + UNCOMMITTED_TTL_MS }- if (known) this.uncommittedCache.set(id, known)- else this.uncommittedCache.delete(id)- }- if (known) read[id] = known.dirty+ const known = this.uncommittedCache.get(id)+ const same = known?.cwd === cwd+ if (same) read[id] = known.dirty+ const idle = same && shown[id] !== undefined && known.shown === shown[id]+ if (!same || (now >= known.until && (!idle || now >= known.readAt + UNCOMMITTED_IDLE_TTL_MS))) due.push({ id, cwd, shown: shown[id] })}- // Sessions of every tab share it, so only what expired goes: a session that left is never read again.- for (const [id, entry] of this.uncommittedCache) if (entry.until <= now) this.uncommittedCache.delete(id)+ // Sessions of every tab share it, so only what no session has kept current goes: a session that left is never read again.+ for (const [id, entry] of this.uncommittedCache) if (now >= entry.readAt + 2 * UNCOMMITTED_IDLE_TTL_MS) this.uncommittedCache.delete(id)+ if (due.length && !this.uncommittedReading) this.readFolders(due)return read}+ /** Reads [due] folders with git, [UNCOMMITTED_PARALLEL] at a time, into the cache. */+ private readFolders(due: Array<{ id: string; cwd: string; shown?: number }>): void {+ this.uncommittedReading = true+ const next = async (): Promise<void> => {+ for (let folder = due.shift(); folder; folder = due.shift()) {+ const dirty = await uncommittedIn(folder.cwd, this.deps.git).catch(() => null)+ const at = this.deps.now()+ if (dirty === null) this.uncommittedCache.delete(folder.id)+ else this.uncommittedCache.set(folder.id, { cwd: folder.cwd, dirty, until: at + UNCOMMITTED_TTL_MS, readAt: at, shown: folder.shown })+ }+ }+ void Promise.all(Array.from({ length: Math.min(UNCOMMITTED_PARALLEL, due.length) }, next)).finally(() => { this.uncommittedReading = false })+ }/** Once its host confirmed a worker stopped (host.ts releaseWorker), the worktree its start made goes at once instead of* after the weekly sweep's idle week, by that sweep's own rule (lib/worktreeSweep.ts): only a worktree this machine'sdiff --git a/cli/src/superTabs/observers.spec.ts b/cli/src/superTabs/observers.spec.tsindex f1cf3c868..c6d1fba4c 100644--- a/cli/src/superTabs/observers.spec.ts+++ b/cli/src/superTabs/observers.spec.ts@@ -100,6 +100,33 @@ it('refuses every share of a session a roster marks confidential, an ordinary on} finally { rmSync(dir, { recursive: true, force: true }) }})+it('lets the members a roster lists watch its Swarm\'s current Lead through that Swarm\'s shares while it is in force, and nobody else', () => {+ const dir = mkdtempSync(join(tmpdir(), 'super-observer-'))+ let now = 1_000_000+ const source = observerSource(dir, () => 'machine', () => now)+ // Confidential, as every Lead is marked; `membersWatch` while it is that Swarm's current Lead (Ken, 2026-10-28).+ const row = (membersWatch?: boolean) => ({ tabId: 'tab', agent: { machineId: 'machine', harnessId: 'pm', name: 'PM', configuration: {} },+ observers: [{ email: '[email protected]' }], confidential: true, ...(membersWatch === undefined ? {} : { membersWatch }) })+ const grant = (tab: string | null, recipientEmail = '[email protected]') => ({ tab, agentId: 'pm', recipientEmail }) as never+ const member = grant('super:tab'), unlisted = grant('super:tab', '[email protected]'), otherSwarm = grant('super:other'), ordinary = grant(null)+ try {+ publishObservers(dir, 'machine', [row(true)], now + OBSERVER_VALID_MS, () => true); now += 201+ expect(source.allows(member)).toBe(true)+ for (const refused of [unlisted, otherSwarm, ordinary]) expect(source.allows(refused)).toBe(false)+ // The host restarts: the member's view waits for its next roster rather than ending.+ now += OBSERVER_VALID_MS + 1+ expect(source.allows(member)).toBe(false)+ expect(source.paused(member)).toBe(true)+ expect(source.paused(ordinary)).toBe(false)+ // No longer the Lead, or a backend from before the rule: closed for good.+ for (const closed of [row(false), row()]) {+ publishObservers(dir, 'machine', [closed], now + OBSERVER_VALID_MS, () => true); now += 201+ expect(source.allows(member)).toBe(false)+ expect(source.paused(member)).toBe(false)+ }+ } finally { rmSync(dir, { recursive: true, force: true }) }+})+it('tells a member to retry, not that sharing ended, while the roster has lapsed, and refuses for good otherwise', async () => {const dir = mkdtempSync(join(tmpdir(), 'super-observer-')), key = newIdentity()const grants = new HarnessGrantStore(join(dir, 'grants.json'))diff --git a/cli/src/superTabs/observers.ts b/cli/src/superTabs/observers.tsindex bf96b4659..1a0bc7f61 100644--- a/cli/src/superTabs/observers.ts+++ b/cli/src/superTabs/observers.ts@@ -8,6 +8,8 @@ import { identifier, object } from './wire.js'export { observerSnapshotFile, superTabOf }type Wanted = Omit<DerivedGrant, 'ownerPublicKey'>+/** A confidential session a Swarm's members may watch through that Swarm's shares: its current Lead (Ken, 2026-10-28). */+type Open = { tab: string; agentId: string }const PREFIX = 'super:'/** How long a published roster authorizes its observers, counted from the roster read that answered: the host's* refresh cadence (superTabs/host.ts reads the roster each second) plus a margin for a slow read. It was 2.5 s from@@ -23,15 +25,21 @@ export const OBSERVER_VALID_MS = OBSERVER_REFRESH_MS + OBSERVER_SLOW_READ_MS* snapshot expires; restarting Share never extends it from the clock alone.* Confidential sessions are the exception: a session a roster marked confidential keeps refusing every share, ordinary ones* too, until it closes on this machine (`live` says it no longer runs), whatever later rosters from any Swarm say (final- * review, Critical 1). Without `live` nothing is cleared. */-export function publishObservers(dataDir: string, machineId: string, rows: unknown[], until: number, live?: (harnessId: string) => boolean) {- const wanted: Wanted[] = []+ * review, Critical 1). Without `live` nothing is cleared. The one opening is a Swarm's current Lead (`membersWatch`): the+ * members that Swarm's roster lists watch it through its shares, view only, while that roster is in force.+ * `rows` null is no roster: the host stopped (superTabs/host.ts stop). The openings are then kept as the marks are, so a+ * member watching the Lead is told to retry, not refused for good, until the next roster replaces them; they admit nobody+ * meanwhile (`allows` needs a roster in force). An empty roster wrote none, so every such viewer was refused for good at+ * each restart (review of #1945, 2026-10-28). */+export function publishObservers(dataDir: string, machineId: string, rows: unknown[] | null, until: number, live?: (harnessId: string) => boolean) {const dir = join(dataDir, 'super-tabs'), file = observerSnapshotFile(dataDir, machineId)+ const wanted: Wanted[] = [], open: Open[] = rows ? [] : savedOpen(file, machineId).filter(o => !live || live(o.agentId))const confidential = new Set(savedConfidential(file, machineId).filter(id => !live || live(id)))- for (const value of rows) {+ for (const value of rows ?? []) {const row = object(value), agent = object(row.agent)if (identifier(agent.harnessId) && agent.machineId === machineId && row.confidential === true) confidential.add(agent.harnessId)if (!identifier(row.tabId) || !identifier(agent.harnessId) || agent.machineId !== machineId || !Array.isArray(row.observers)) continue+ if (row.confidential === true && row.membersWatch === true) open.push({ tab: `${PREFIX}${row.tabId}`, agentId: agent.harnessId })for (const observer of row.observers.map(object)) {if (typeof observer.email !== 'string') continuewanted.push({ tab: `${PREFIX}${row.tabId}`, agentId: agent.harnessId, email: observer.email.trim().toLowerCase(),@@ -39,11 +47,18 @@ export function publishObservers(dataDir: string, machineId: string, rows: unkno}}mkdirSync(dir, { recursive: true, mode: 0o700 })- writeFileSync(`${file}.next`, JSON.stringify({ machineId, until, wanted, confidential: [...confidential] }), { mode: 0o600 })+ writeFileSync(`${file}.next`, JSON.stringify({ machineId, until, wanted, confidential: [...confidential], open }), { mode: 0o600 })renameSync(`${file}.next`, file)}+/** The current Leads a snapshot opened to their Swarm's members (publishObservers). */+const openings = (saved: Record<string, unknown>, machineId: string): Open[] =>+ saved.machineId === machineId && Array.isArray(saved.open) ? saved.open.map(object)+ .filter(o => typeof o.tab === 'string' && o.tab.startsWith(PREFIX) && identifier(o.agentId)).map(o => ({ tab: o.tab, agentId: o.agentId }) as Open) : []+function savedOpen(file: string, machineId: string): Open[] {+ try { return openings(object(JSON.parse(readFileSync(file, 'utf8'))), machineId) } catch { return [] }+}export function observerSource(dataDir: string, machine: () => string, now = Date.now) {- let readAt = -Infinity, id = '', until = 0, wanted: Wanted[] = [], confidential: string[] = []+ let readAt = -Infinity, id = '', until = 0, wanted: Wanted[] = [], confidential: string[] = [], open: Open[] = []const read = (): Wanted[] => {const machineId = machine(), time = now()if (time - readAt >= 200 || machineId !== id) {@@ -54,6 +69,8 @@ export function observerSource(dataDir: string, machine: () => string, now = Datconst saved = object(JSON.parse(raw))// Kept whatever the snapshot's age: a lapsed roster must not reopen a confidential session.confidential = saved.machineId === machineId && Array.isArray(saved.confidential) ? saved.confidential.filter(identifier) : confidential+ // Read whatever the snapshot's age too, so a lapsed roster's member waits for the next one; it admits only while in force.+ open = openings(saved, machineId)if (saved.machineId === machineId && typeof saved.until === 'number' && saved.until <= time + OBSERVER_VALID_MS + 500 && Array.isArray(saved.wanted)) {until = saved.untilwanted = saved.wanted.filter(w => {@@ -69,6 +86,8 @@ export function observerSource(dataDir: string, machine: () => string, now = Dat}const live = () => now() < untilconst current = (): Wanted[] => { const rows = read(); return live() ? rows : [] }+ const opened = (grant: HarnessGrant) => open.some(o => o.tab === grant.tab && o.agentId === grant.agentId)+ const closed = (grant: HarnessGrant) => confidential.includes(grant.agentId) && !(superTabOf(grant) && opened(grant))return {current,/** What the host's last roster wants, or null when no roster is in force (its host stalled or stopped, or the file@@ -76,12 +95,13 @@ export function observerSource(dataDir: string, machine: () => string, now = Dat* withdrawing and sending them all again. Viewing is still withheld meanwhile (`allows`). The next roster in force* withdraws those of members it no longer lists. */known: (): Wanted[] | null => { const rows = read(); return live() ? rows : null },- /** A confidential session refuses every share, Swarm or ordinary; another Swarm share needs the roster in force. */- allows: (grant: HarnessGrant): boolean => { read(); return !confidential.includes(grant.agentId) && (!superTabOf(grant) || current().some(w =>+ /** A confidential session refuses every share, Swarm or ordinary, but its own Swarm's while it is that Swarm's current+ * Lead; any Swarm share needs the roster in force, and its recipient listed. */+ allows: (grant: HarnessGrant): boolean => { read(); return !closed(grant) && (!superTabOf(grant) || current().some(w =>w.tab === grant.tab && w.agentId === grant.agentId && w.email === grant.recipientEmail)) },/** A Swarm share withheld only because no roster is in force (its host is starting, or restarting for an update): the* next roster decides it, so its viewer is told to try again rather than that sharing ended. A confidential session's- * is refused for good. */- paused: (grant: HarnessGrant): boolean => { read(); return !!superTabOf(grant) && !confidential.includes(grant.agentId) && !live() },+ * is refused for good, but its Swarm's current Lead's, which waits too. */+ paused: (grant: HarnessGrant): boolean => { read(); return !!superTabOf(grant) && !closed(grant) && !live() },}}diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex e2aff9c3b..a5467ccd1 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -650,7 +650,7 @@ it('documents finished worker decisions and explains an older backend without redescribe('the Swarm cards the devices ask for', () => {function withCards() {- const cards = { want: vi.fn(), open: vi.fn(), recap: vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'Shipped', at: 5, none: false })), onCards: undefined as unknown, onRecap: undefined as unknown }+ const cards = { want: vi.fn(), open: vi.fn(), say: vi.fn(async () => true), recap: vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'Shipped', at: 5, none: false })), onCards: undefined as unknown, onRecap: undefined as unknown }const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }const core = fakeCore({ superTabs })const make = vi.fn(() => cards as never)@@ -660,11 +660,11 @@ describe('the Swarm cards the devices ask for', () => {it('starts and stops the reader as a capable Pro comes and goes, and hands what it reads to the core', async () => {const t = withCards()expect(await t.ask({ action: 'cardsWanted', on: true }, owner)).toEqual({ ok: true })- expect(t.cards.want).toHaveBeenLastCalledWith(true, [])+ expect(t.cards.want).toHaveBeenLastCalledWith(true, [], null)expect(await t.ask({ action: 'cardsWanted', on: true, include: ['s1', 'bad id', 'x'.repeat(48), 7] }, owner)).toEqual({ ok: true })- expect(t.cards.want).toHaveBeenLastCalledWith(true, ['s1'])+ expect(t.cards.want).toHaveBeenLastCalledWith(true, ['s1'], null)expect(await t.ask({ action: 'cardsWanted', on: false }, owner)).toEqual({ ok: true })- expect(t.cards.want).toHaveBeenLastCalledWith(false, [])+ expect(t.cards.want).toHaveBeenLastCalledWith(false, [], null)// One reader for the machine, whose answers go to the core.expect(t.make).toHaveBeenCalledOnce();(t.cards.onCards as (items: unknown[]) => void)([])@@ -685,14 +685,34 @@ describe('the Swarm cards the devices ask for', () => {const t = withCards()expect(await t.ask({ action: 'cardRecap', tabId: 't1', leadId: 'l1' }, owner)).toEqual({ ok: true, tabId: 't1', leadId: 'l1', text: 'Shipped', at: 5, none: false })expect(await t.ask({ action: 'cardOpen', session: 's1', tabId: 't1', leadId: 'l1' }, owner)).toEqual({ ok: true })- expect(t.cards.open).toHaveBeenLastCalledWith('s1', 't1', 'l1')+ expect(t.cards.open).toHaveBeenLastCalledWith('s1', 't1', 'l1', false)expect(await t.ask({ action: 'cardOpen', session: 's1', tabId: 't1', leadId: null }, owner)).toEqual({ ok: true })- expect(t.cards.open).toHaveBeenLastCalledWith('s1', 't1', null)+ expect(t.cards.open).toHaveBeenLastCalledWith('s1', 't1', null, false)for (const bad of [{ action: 'cardRecap', tabId: 'bad id', leadId: 'l1' }, { action: 'cardRecap', tabId: 't1' }, { action: 'cardOpen', session: 's1', tabId: 't1', leadId: 'bad id' }, { action: 'cardOpen', session: 's1', leadId: null },{ action: 'cardOpen', tabId: 't1', leadId: null }, { action: 'cardRecap', tabId: 'x'.repeat(48), leadId: 'l1' }]) {expect(await t.ask(bad, owner)).toEqual({ error: 'INVALID_REQUEST' })}})+ it('cardsWanted passes focus to the cards; cardRecap, cardOpen and cardSay pass chat', async () => {+ const t = withCards()+ await t.ask({ action: 'cardsWanted', on: true, include: ['s1'], focus: { tabId: 's1', conversationId: 'g1', extra: 1 } }, owner)+ expect(t.cards.want).toHaveBeenLastCalledWith(true, ['s1'], { tabId: 's1', conversationId: 'g1' })+ // A focus that is not two ids is none.+ for (const focus of [{ tabId: 'bad id', conversationId: 'g1' }, { tabId: 's1', conversationId: 'x'.repeat(48) }, { tabId: 's1' }, 'g1']) {+ await t.ask({ action: 'cardsWanted', on: true, include: ['s1'], focus }, owner)+ expect(t.cards.want).toHaveBeenLastCalledWith(true, ['s1'], null)+ }+ await t.ask({ action: 'cardRecap', tabId: 't1', leadId: 'l1', chat: true }, owner)+ expect(t.cards.recap).toHaveBeenLastCalledWith('t1', 'l1', true)+ await t.ask({ action: 'cardRecap', tabId: 't1', leadId: 'l1', chat: 'yes' }, owner)+ expect(t.cards.recap).toHaveBeenLastCalledWith('t1', 'l1', false)+ await t.ask({ action: 'cardOpen', session: 's1', tabId: 't1', leadId: 'l1', chat: true }, owner)+ expect(t.cards.open).toHaveBeenLastCalledWith('s1', 't1', 'l1', true)+ expect(await t.ask({ action: 'cardSay', harnessId: 'h1', text: ' ship it ', chat: true }, owner)).toEqual({ ok: true, said: true })+ expect(t.cards.say).toHaveBeenLastCalledWith('h1', 'ship it', true)+ await t.ask({ action: 'cardSay', harnessId: 'h1', text: 'ship it' }, owner)+ expect(t.cards.say).toHaveBeenLastCalledWith('h1', 'ship it', false)+ })it('answers a backend refusal while reading a recap as the service does any other', async () => {const t = withCards()t.cards.recap.mockRejectedValueOnce(new SuperTabHostError('FORBIDDEN', 'Access withdrawn', 403))diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 50248582c..c20b98025 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -362,17 +362,21 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =// Only this computer's own devices ask: an account owner on another machine does not make this one read the Swarms.if (payload.action === 'cardsWanted' || payload.action === 'cardRecap' || payload.action === 'cardOpen' || payload.action === 'cardSay') {if (!asker.local) return { error: 'OWNER_REQUIRED' }+ // A round dial that speaks swarmChat asks for the chat on its face (design 2026-10-28-round-dial-swarm-chat).+ const chat = payload.chat === trueif (payload.action === 'cardsWanted') {const include = Array.isArray(payload.include) ? payload.include.filter(cardId) : []- cards().want(payload.on === true, include)+ const asked = payload.focus && typeof payload.focus === 'object' ? payload.focus as Record<string, unknown> : {}+ const focus = cardId(asked.tabId) && cardId(asked.conversationId) ? { tabId: asked.tabId, conversationId: asked.conversationId } : null+ cards().want(payload.on === true, include, focus)return { ok: true }}- if (payload.action === 'cardRecap' && cardId(payload.tabId) && cardId(payload.leadId)) return { ok: true, ...await cards().recap(payload.tabId, payload.leadId) }+ if (payload.action === 'cardRecap' && cardId(payload.tabId) && cardId(payload.leadId)) return { ok: true, ...await cards().recap(payload.tabId, payload.leadId, chat) }if (payload.action === 'cardSay' && cardId(payload.harnessId) && typeof payload.text === 'string' && payload.text.trim() && payload.text.length <= 32_000) {- return { ok: true, said: await cards().say(payload.harnessId, payload.text.trim()) }+ return { ok: true, said: await cards().say(payload.harnessId, payload.text.trim(), chat) }}if (payload.action === 'cardOpen' && cardId(payload.session) && cardId(payload.tabId) && (payload.leadId === null || cardId(payload.leadId))) {- cards().open(payload.session, payload.tabId, payload.leadId)+ cards().open(payload.session, payload.tabId, payload.leadId, chat)return { ok: true }}return { error: 'INVALID_REQUEST' }diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dartindex 2a15ae996..da86e4731 100644--- a/desktop/lib/api/api_client.dart+++ b/desktop/lib/api/api_client.dart@@ -136,6 +136,15 @@ class ApiClient {return value != null && value > 1 ? value : 1;}+ /// An answer's Retry-After in delta-seconds (the backend's busy answers and+ /// the local CLI passing them on); null when absent or unreadable.+ static Duration? retryAfter(Headers headers) {+ final values = headers['retry-after'];+ final value = values == null || values.isEmpty ? null : values.first.trim();+ if (value == null || !RegExp(r'^\d{1,9}$').hasMatch(value)) return null;+ return Duration(seconds: int.parse(value));+ }+// -- auth (proxied by the local CLI — no credential on this leg) --/// [onVocabulary] hears [usageVocabulary] from every answer, a refusal/// included; a request that got no answer says nothing.@@ -164,11 +173,12 @@ class ApiClient {body is Map && body['error'] is Map? (body['error'] as Map)['code']: null,+ retryAfter: retryAfter(response.headers),);}return Map<String, dynamic>.from(body['data'] as Map);} on DioException catch (error) {- throw ProductReportFailure(switch (error.type) {+ final measure = switch (error.type) {DioExceptionType.connectionTimeout ||DioExceptionType.sendTimeout ||DioExceptionType.receiveTimeout =>@@ -176,7 +186,12 @@ class ApiClient {DioExceptionType.connectionError =>ProductHealthMeasure.reportFailureUnreachable,_ => ProductHealthMeasure.reportFailureOther,- });+ };+ // No answer in time, or none at all: waited out like a busy one.+ throw ProductReportFailure(+ measure,+ backOff: measure != ProductHealthMeasure.reportFailureOther,+ );}}@@ -316,7 +331,10 @@ class ApiClient {'/api/agent-messages/tabs/${Uri.encodeComponent(tabId)}',data: {'enabled': ?enabled,- if (leader != null) 'leader': leader.toJson() else if (clearLeader) 'leader': null,+ if (leader != null)+ 'leader': leader.toJson()+ else if (clearLeader)+ 'leader': null,},options: Options(headers: {'x-adapter-local': '1'}),);diff --git a/desktop/lib/measurement/product_measurement.dart b/desktop/lib/measurement/product_measurement.dartindex 5691b8331..21e80c4ec 100644--- a/desktop/lib/measurement/product_measurement.dart+++ b/desktop/lib/measurement/product_measurement.dart@@ -167,12 +167,14 @@ class ProductMeasurement extends ChangeNotifier {required this.sendSetup,DateTime Function()? now,String Function()? receipt,+ double Function()? random,this.automatic = true,this.context,LocalKeyValueStore? setupStorage,}) : assert(const ['desktop', 'phone', 'web'].contains(surface)),_setupStorage = setupStorage,_now = now ?? DateTime.now,+ _random = random ?? Random().nextDouble,_receipt = receipt ?? newProductReceipt {signedOutSharing = surface == 'desktop' && setupStorage == null;choiceLoaded = setupStorage == null;@@ -206,6 +208,7 @@ class ProductMeasurement extends ChangeNotifier {final ProductReportRequest sendSetup;final bool automatic;final DateTime Function() _now;+ final double Function() _random;final String Function() _receipt;bool signedOutSharing = false, choiceLoaded = false;static const setupPreferenceKey = 'product_setup_sharing';@@ -228,6 +231,10 @@ class ProductMeasurement extends ChangeNotifier {ProductReportRequest? _sendAccount;Timer? _timer;DateTime? _lastAttempt;+ // A channel refused as busy or failing waits until here; [_backoffs] counts+ // those refusals in a row ([_backOff]).+ final _heldUntil = <String, DateTime>{};+ final _backoffs = <String, int>{};final _active = <Object, String>{};Future<void>? _flushing;final _days = <String, Map<String, int>>{};@@ -715,7 +722,8 @@ class ProductMeasurement extends ChangeNotifier {return 6;}if (metric.startsWith('health_desktop_first_run_') ||- metric.startsWith('health_desktop_shared_invites_')) return 5;+ metric.startsWith('health_desktop_shared_invites_'))+ return 5;for (final flow in _newerFlows) {if (metric.startsWith('ui_desktop_${flow.wire}_')) return flow.vocabulary;}@@ -903,6 +911,8 @@ class ProductMeasurement extends ChangeNotifier {if (_disposed || (channel == 'setup' ? !_setupAllowed : !sharing)) {continue;}+ final held = _heldUntil[channel];+ if (held != null && _now().isBefore(held)) continue;final epoch = channel == 'setup' ? _guestEpoch : _accountEpoch;var report = _pending[channel];if (report == null) {@@ -960,6 +970,7 @@ class ProductMeasurement extends ChangeNotifier {: epoch != _accountEpoch)) {continue;}+ _answered(channel);if (result['accepted'] == true || result['reason'] == 'EXPIRED') {_pending.remove(channel);if (result['reason'] == 'EXPIRED' && channel == 'ui') {@@ -995,11 +1006,46 @@ class ProductMeasurement extends ChangeNotifier {// packet so new counts can proceed; transient failures keep the same receipt.if (error is ProductReportFailure && error.permanent)_pending.remove(channel);- /* Same receipt on the next timer. No logs, aggressive retry, or product failure. */+ if (error is ProductReportFailure && error.backOff) {+ _backOff(channel, error.retryAfter);+ } else {+ _answered(channel);+ }+ /* Same receipt later. No logs, aggressive retry, or product failure. */}}}+ // Every app of a release reported each minute whatever the answer: 165 of+ // Desktop's 272 failed reports on 2026-10-28 were busy refusals sent again a+ // minute later. As the CLI does (cli/src/gateway/productUsage.ts): full+ // jitter under a ceiling that doubles with each refusal in a row, up to half+ // an hour, and never before the answer's Retry-After (also held to that).+ static const _backoffBase = Duration(minutes: 1);+ static const _backoffMax = Duration(minutes: 30);++ void _backOff(String channel, Duration? retryAfter) {+ final count = min((_backoffs[channel] ?? 0) + 1, 16);+ _backoffs[channel] = count;+ final ceiling = min(+ _backoffMax.inMilliseconds,+ _backoffBase.inMilliseconds * (1 << count),+ );+ final r = _random();+ final unit = r.isFinite && r >= 0 && r < 1 ? r : 0.5;+ final wait = min(+ _backoffMax.inMilliseconds,+ max(retryAfter?.inMilliseconds ?? 0, (unit * ceiling).floor()),+ );+ _heldUntil[channel] = _now().add(Duration(milliseconds: wait));+ }++ /// An answer that was not busy: the next report goes at the next tick.+ void _answered(String channel) {+ _backoffs.remove(channel);+ _heldUntil.remove(channel);+ }+@overridevoid dispose() {_disposed = true;diff --git a/desktop/lib/measurement/product_report_failure.dart b/desktop/lib/measurement/product_report_failure.dartindex 1748da6eb..28ec94517 100644--- a/desktop/lib/measurement/product_report_failure.dart+++ b/desktop/lib/measurement/product_report_failure.dart@@ -3,60 +3,63 @@ import 'product_health_contract.dart';/// Only a fixed category survives the transport boundary. Never retain the/// response, URL, error message, credentials, or report in a collector error.class ProductReportFailure implements Exception {- const ProductReportFailure(this.measure, {this.permanent = false});+ const ProductReportFailure(+ this.measure, {+ this.permanent = false,+ this.backOff = false,+ this.retryAfter,+ });final ProductHealthMeasure measure;final bool permanent;+ final bool backOff;+ final Duration? retryAfter;- factory ProductReportFailure.http(int? status, Object? code) {+ /// [backOff]: a busy or failing answer (429, 5xx), after which the next+ /// report waits, and not before [retryAfter] when the answer gave one.+ factory ProductReportFailure.http(+ int? status,+ Object? code, {+ Duration? retryAfter,+ }) {+ final busy = status != null && (status == 429 || status >= 500);+ return ProductReportFailure(+ _measure(status, code),+ permanent: status == 400 || status == 413,+ backOff: busy,+ retryAfter: busy ? retryAfter : null,+ );+ }++ static ProductHealthMeasure _measure(int? status, Object? code) {if (status == 504 && code == 'BACKEND_TIMEOUT') {- return const ProductReportFailure(- ProductHealthMeasure.reportFailureTimeout,- );+ return ProductHealthMeasure.reportFailureTimeout;}if (status == 502 && code == 'BACKEND_UNREACHABLE') {- return const ProductReportFailure(- ProductHealthMeasure.reportFailureUnreachable,- );+ return ProductHealthMeasure.reportFailureUnreachable;}if (status == 401 ||status == 403 ||code == 'AUTH_UNAVAILABLE' ||+ code == 'AUTH_SERVICE_UNAVAILABLE' ||code == 'ACCOUNT_CHANGED') {- return const ProductReportFailure(ProductHealthMeasure.reportFailureAuth);- }- if (status == 400) {- return const ProductReportFailure(- ProductHealthMeasure.reportFailureInvalid,- permanent: true,- );- }- if (status == 413) {- return const ProductReportFailure(- ProductHealthMeasure.reportFailureTooLarge,- permanent: true,- );- }- if (status == 429) {- return const ProductReportFailure(- ProductHealthMeasure.reportFailureRateLimited,- );+ return ProductHealthMeasure.reportFailureAuth;}- if (status == 503 && code == 'USAGE_WRITE_CONFLICT') {- return const ProductReportFailure(- ProductHealthMeasure.reportFailureWriteConflict,- );+ if (status == 400) return ProductHealthMeasure.reportFailureInvalid;+ if (status == 413) return ProductHealthMeasure.reportFailureTooLarge;+ // A busy backend answers these 429 since 2026-10-28 (503 before): the+ // cause is kept either way, as the CLI does (cli/src/gateway/reportFailure.ts).+ if ((status == 429 || status == 503) && code == 'USAGE_WRITE_CONFLICT') {+ return ProductHealthMeasure.reportFailureWriteConflict;}- if (status == 503 && code == 'USAGE_TRANSACTION_FAILED') {- return const ProductReportFailure(- ProductHealthMeasure.reportFailureTransaction,- );+ if ((status == 429 || status == 503) &&+ code == 'USAGE_TRANSACTION_FAILED') {+ return ProductHealthMeasure.reportFailureTransaction;}+ if (status == 429) return ProductHealthMeasure.reportFailureRateLimited;if (status != null && status >= 500 && status < 600) {- return const ProductReportFailure(- ProductHealthMeasure.reportFailureServer,- );+ return ProductHealthMeasure.reportFailureServer;}- return const ProductReportFailure(ProductHealthMeasure.reportFailureOther);+ return ProductHealthMeasure.reportFailureOther;}@overridediff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 35e6fd9b5..f7cc564a0 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -5648,6 +5648,18 @@ class AppNotifier extends ChangeNotifier {null => null,};+ /// The conversation open in this Swarm tab (its Lead's, Chat with PM or a+ /// group), which the round dial's face follows (design+ /// 2026-10-28-round-dial-swarm-chat). Left out on the machines view and+ /// before the Swarm has loaded: the dial then shows each project's Lead.+ /// A change of it re-announces through `onSelection`, as a project's does.+ String? _dialConversation(String tabId) {+ final controller = superTabs.peek(tabId);+ if (controller == null || controller.devicesSelected) return null;+ final id = controller.selectedId;+ return controller.snapshot?.conversation(id) == null ? null : id;+ }+/// The tile roster and the tabs, to every daemon this window reaches over/// its loopback ([_deskConnection]) — never a relayed machine's.void _announceOpenPanesToDial() {@@ -5715,6 +5727,7 @@ class AppNotifier extends ChangeNotifier {if (swarm.superTabId case final tabId?) ...{'superTabId': tabId,'projectId': ?_rememberDialProject(tabId),+ 'conversationId': ?_dialConversation(tabId),},'agentIds': [for (final pane in swarm.panes)diff --git a/desktop/lib/super_tabs/chat_scroll.dart b/desktop/lib/super_tabs/chat_scroll.dartnew file mode 100644index 000000000..05285b62b--- /dev/null+++ b/desktop/lib/super_tabs/chat_scroll.dart@@ -0,0 +1,168 @@+import 'package:flutter/rendering.dart';+import 'package:flutter/widgets.dart';++/// A chat's scroll: what the reader looks at never moves by itself.+///+/// Rows change height after they are laid out (a receipt line moves to the+/// newest own message or grows a note, a picture or code block finishes,+/// a page of older messages arrives above). A list keeps its offset, so all+/// of that would slide the rows on screen. Instead, at every layout the+/// first visible row is kept where it was, and a reader at the very end+/// stays at the end. Both happen during layout, before anything is painted.+class SuperTabChatScroll extends ScrollController {+ SuperTabChatScroll({required this.rows});++ /// The list's rows that are built, by message id.+ final Iterable<MapEntry<String, BuildContext>> Function() rows;++ @override+ ScrollPosition createScrollPosition(+ ScrollPhysics physics,+ ScrollContext context,+ ScrollPosition? oldPosition,+ ) => _AnchoredPosition(+ rows: rows,+ physics: physics,+ context: context,+ initialPixels: initialScrollOffset,+ keepScrollOffset: keepScrollOffset,+ oldPosition: oldPosition,+ debugLabel: debugLabel,+ );+}++class _AnchoredPosition extends ScrollPositionWithSingleContext {+ _AnchoredPosition({+ required this.rows,+ required super.physics,+ required super.context,+ super.initialPixels,+ super.keepScrollOffset,+ super.oldPosition,+ super.debugLabel,+ });++ final Iterable<MapEntry<String, BuildContext>> Function() rows;++ // The first visible row and its top within the content, as last laid out.+ ({String messageId, double top})? _anchor;+ // Where the last finished layout left the view.+ double? _settledPixels, _settledMax;++ bool get _wasAtEnd =>+ _settledPixels != null && _settledPixels! >= _settledMax! - .5;++ @override+ void correctBy(double correction) {+ // The list moved every row and the view together: nothing on screen+ // moved, so the kept place moves with them.+ super.correctBy(correction);+ if (_anchor case final anchor?) {+ _anchor = (messageId: anchor.messageId, top: anchor.top + correction);+ }+ if (_settledPixels != null) _settledPixels = _settledPixels! + correction;+ }++ @override+ bool applyContentDimensions(double minScrollExtent, double maxScrollExtent) {+ final target = _keptPixels(maxScrollExtent);+ if (target != null && (target - pixels).abs() > .5) {+ correctPixels(target);+ return false;+ }+ if (!super.applyContentDimensions(minScrollExtent, maxScrollExtent)) {+ return false;+ }+ _settledPixels = pixels;+ _settledMax = maxScrollExtent;+ _anchor = _firstVisible();+ return true;+ }++ /// Where the view belongs now, or null to leave it.+ double? _keptPixels(double maxScrollExtent) {+ // Only the content changed since the reader was at the end.+ if (_wasAtEnd &&+ pixels == _settledPixels &&+ maxScrollExtent != _settledMax) {+ return maxScrollExtent;+ }+ final anchor = _anchor;+ if (anchor == null) return null;+ final edge = _rowEdges()[anchor.messageId]?.at;+ if (edge == null) return null;+ // Measured in the content, so the reader's own scrolling never counts:+ // only the rows between it and the list's dividing row changing does.+ final now = pixels + edge;+ if ((now - anchor.top).abs() <= .5) return null;+ _anchor = (messageId: anchor.messageId, top: now);+ return pixels + now - anchor.top;+ }++ /// The row at the top of the view, by the edge [_rowEdges] measures.+ ({String messageId, double top})? _firstVisible() {+ ({String messageId, double at})? first;+ for (final MapEntry(key: id, value: edge) in _rowEdges().entries) {+ final better = switch (edge) {+ // Above the dividing row (only in view when the view's top is):+ // the row whose bottom is the first below the top of the view.+ (above: true, :final at) =>+ pixels < 0 && at > 0 && (first == null || at < first.at),+ // Below it: the row containing the top of the view, else the+ // highest one in it.+ (above: false, :final at) =>+ pixels >= 0 &&+ (first == null ||+ (at <= 0 ? first.at > 0 || at > first.at : at < first.at)),+ };+ if (better) first = (messageId: id, at: edge.at);+ }+ return first == null+ ? null+ : (messageId: first.messageId, top: pixels + first.at);+ }++ /// Each laid-out row's edge facing the list's dividing row, within the+ /// view: a row below it by its top, one above by its bottom. Nothing+ /// here reads a row's size, which only its list may during layout.+ Map<String, ({bool above, double at})> _rowEdges() {+ final edges = <String, ({bool above, double at})>{};+ for (final MapEntry(key: id, value: row) in rows()) {+ if (!row.mounted) continue;+ final box = row.findRenderObject();+ if (box is! RenderBox || !box.attached) continue;+ final viewport = RenderAbstractViewport.maybeOf(box);+ if (viewport is! RenderViewportBase || viewport.offset != this) continue;+ // The row's item in its list, laid out and not only kept alive.+ RenderObject item = box;+ while (item.parent != null &&+ item.parent is! RenderSliverMultiBoxAdaptor) {+ item = item.parent!;+ }+ final list = item.parent, data = item.parentData;+ if (list is! RenderSliverMultiBoxAdaptor ||+ item is! RenderBox ||+ data is! SliverMultiBoxAdaptorParentData ||+ data.keptAlive ||+ data.layoutOffset == null) {+ continue;+ }+ final listTop = MatrixUtils.transformPoint(+ list.getTransformTo(viewport),+ Offset.zero,+ ).dy;+ final position = list.childMainAxisPosition(item);+ if (list.constraints.growthDirection == GrowthDirection.forward) {+ final inItem = box.localToGlobal(Offset.zero, ancestor: item).dy;+ edges[id] = (above: false, at: listTop + position + inItem);+ } else {+ // The row closes its item: its bottom is the item's.+ edges[id] = (+ above: true,+ at: listTop + list.geometry!.paintExtent - position,+ );+ }+ }+ return edges;+ }+}diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex b6ff1830c..752004993 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -1,4 +1,5 @@import 'dart:async';+import 'dart:collection';import 'dart:math';import 'package:clock/clock.dart';@@ -108,6 +109,9 @@ class SuperTabController extends ChangeNotifier {expandedMachines.addAll((initial['expandedMachines'] as List? ?? const []).whereType<String>(),);+ _decisionsAside.addAll(+ (initial['decisionsAside'] as List? ?? const []).whereType<String>(),+ );devicesSelected = initial['devicesSelected'] == true;projectsGroupOpen = initial['projectsGroupOpen'] as bool? ?? true;machinesGroupOpen = initial['machinesGroupOpen'] as bool? ?? true;@@ -395,6 +399,30 @@ class SuperTabController extends ChangeNotifier {_changed();}+ /// Open decisions the reader set aside in Chat with PM (Not now, Hide):+ /// saved on this computer for this reader, so they stay folded after a+ /// restart. A decision asked later is not among them, so it shows.+ final _decisionsAside = <String>{};+ Set<String> get decisionsAside => UnmodifiableSetView(_decisionsAside);++ void setDecisionsAside(Iterable<String> ids, {required bool aside}) {+ var changed = false;+ for (final id in ids) {+ changed |= aside ? _decisionsAside.add(id) : _decisionsAside.remove(id);+ }+ if (!changed) return;+ _saveSoon();+ _changed();+ }++ /// Forgets the set-aside decisions known answered or [gone], so the saved+ /// set holds only what may still wait.+ void forgetDecisionsAside(bool Function(String id) gone) {+ final before = _decisionsAside.length;+ _decisionsAside.removeWhere(gone);+ if (_decisionsAside.length != before) _saveSoon();+ }+void toggleProjectsGroup() {projectsGroupOpen = !projectsGroupOpen;_saveSoon();@@ -866,6 +894,7 @@ class SuperTabController extends ChangeNotifier {'selectedId': selectedId,'expandedProjects': expandedProjects.toList(),'expandedMachines': expandedMachines.toList(),+ 'decisionsAside': _decisionsAside.toList(),'devicesSelected': devicesSelected,'projectsGroupOpen': projectsGroupOpen,'machinesGroupOpen': machinesGroupOpen,diff --git a/desktop/lib/super_tabs/decisions.dart b/desktop/lib/super_tabs/decisions.dartindex 2a486c33c..949c31ceb 100644--- a/desktop/lib/super_tabs/decisions.dart+++ b/desktop/lib/super_tabs/decisions.dart@@ -20,18 +20,32 @@ class SuperTabDecision {options = List.unmodifiable([for (final option in row['options'] as List? ?? const []) '$option',]),- recommended = (row['recommended'] as num?)?.toInt() ?? 0,+ recommended = (row['recommended'] as num?)?.toInt(),unblocks = row['unblocks'] as String? ?? '',choice = (row['choice'] as num?)?.toInt(),+ delegated = row['delegated'] == true,note = row['note'] as String?,createdAt = DateTime.tryParse(row['createdAt'] as String? ?? '');final String id, batchId, projectId, projectName, conversationId;final String conversationTitle, askerName, question, unblocks;final List<String> options;- final int recommended;- /// The option the reader chose; null while it is open.+ /// The option the asker recommends; null, or not one of [options], when it+ /// recommends none.+ final int? recommended;++ /// Whether Let PM decide can answer it: only with a recommended option.+ bool get canDelegate {+ final r = recommended;+ return r != null && r >= 0 && r < options.length;+ }++ /// The option the reader chose, or the PM chose for them ([delegated]);+ /// null while it is open.final int? choice;++ /// The reader left it to the PM, who took the recommended option.+ final bool delegated;final String? note;final DateTime? createdAt;}@@ -58,6 +72,20 @@ class SuperTabDecisions extends ChangeNotifier {/// Decisions being answered: their buttons wait for the backend.final Set<String> answering = {};++ /// The answer that failed to send for each decision, sent again by [retry].+ final Map<String, Map<String, dynamic>> _failed = {};++ /// Whether the reader's last answer to [decision] failed to send.+ bool failedToSend(SuperTabDecision decision) =>+ _failed.containsKey(decision.id);++ /// Sends the answer that failed again: the same option, or Let PM decide.+ Future<bool> retry(SuperTabDecision decision) =>+ switch (_failed[decision.id]) {+ final answer? => _answer(decision, answer),+ null => Future.value(false),+ };int? _count;String? _digest;int? _epoch;@@ -75,6 +103,26 @@ class SuperTabDecisions extends ChangeNotifier {if (d.projectId == projectId) d,];+ /// Those of [openIn] the reader has not set aside with Not now or Hide.+ List<SuperTabDecision> shownIn(String projectId) {+ final aside = controller.decisionsAside;+ return [+ for (final d in openIn(projectId))+ if (!aside.contains(d.id)) d,+ ];+ }++ /// Not now and Hide: folded in Chat with PM until the reader shows them+ /// again; a decision asked later still shows.+ void setAside(Iterable<SuperTabDecision> decisions) =>+ controller.setDecisionsAside(decisions.map((d) => d.id), aside: true);++ /// Show: every open decision of [projectId] in its Chat with PM again.+ void showAgain(String projectId) => controller.setDecisionsAside(+ openIn(projectId).map((d) => d.id),+ aside: false,+ );+void _changed() {final snapshot = controller.snapshot;if (snapshot == null) return;@@ -111,33 +159,54 @@ class SuperTabDecisions extends ChangeNotifier {}().whenComplete(() => _loading = null);}- Future<List<SuperTabDecision>> _list(String state) async {+ /// One list, newest first, and whether it holds every one of its kind:+ /// only when the backend says it left none out.+ Future<(List<SuperTabDecision>, bool)> _list(String state) async {final Map<String, dynamic> answer;try {answer = await controller.request('GET', '$_path/decisions?state=$state');} on SuperTabFailure catch (failure) {// A backend from before decisions has no list: there is nothing to show.- if (failure.statusCode == 404) return const [];+ if (failure.statusCode == 404) return (const <SuperTabDecision>[], true);+ // One from before Let PM decide has no `settled` list: its answered+ // list has every answer, none of them the PM's.+ if (failure.statusCode == 400 && state == 'settled') {+ return _list('answered');+ }rethrow;}- return List.unmodifiable([- for (final row in answer['decisions'] as List)- SuperTabDecision.fromJson(superTabMap(row)),- ]);+ return (+ List<SuperTabDecision>.unmodifiable([+ for (final row in answer['decisions'] as List)+ SuperTabDecision.fromJson(superTabMap(row)),+ ]),+ answer['more'] == false,+ );}+ /// Whether [open] holds every open decision, as its last read said.+ bool _openComplete = false;+Future<void> _read() async {final epoch = _epoch;try {- final [nextOpen, nextAnswered] = await Future.wait([+ // `settled` has the answers the PM gave too; `answered` is what an+ // older Desktop reads, without them.+ final [(nextOpen, openComplete), (nextAnswered, _)] = await Future.wait([_list('open'),- _list('answered'),+ _list('settled'),]);// Read before who may read what changed: the read asked again since// replaces it.if (epoch != _epoch) return;open = nextOpen;answered = nextAnswered;+ _openComplete = openComplete;+ // The lists are the newest of each (the backend caps them): what is+ // set aside is forgotten only once it is known answered or gone.+ final gone = _gone();+ controller.forgetDecisionsAside(gone);+ _failed.removeWhere((id, _) => gone(id));error = null;_failedAt = null;} catch (_) {@@ -147,9 +216,32 @@ class SuperTabDecisions extends ChangeNotifier {notifyListeners();}+ static const sendFailed = 'Could not send your answer. Try again.';++ /// Whether a decision is known answered or gone: in the answered list, or+ /// missing from an open list the backend says holds every open one.+ bool Function(String id) _gone() {+ final openIds = {for (final d in open) d.id};+ final answeredIds = {for (final d in answered) d.id};+ final complete = _openComplete;+ return (id) =>+ answeredIds.contains(id) || (complete && !openIds.contains(id));+ }+/// The reader's one-tap answer. Any reader may answer what was asked of/// them, so this does not wait behind the composer's pending send.- Future<bool> answer(SuperTabDecision decision, int choice) async {+ Future<bool> answer(SuperTabDecision decision, int choice) =>+ _answer(decision, {'choice': choice});++ /// Let PM decide: the backend answers with the recommended option on the+ /// reader's behalf, recorded as the PM's choice, never as theirs.+ Future<bool> delegate(SuperTabDecision decision) =>+ _answer(decision, {'delegate': true});++ Future<bool> _answer(+ SuperTabDecision decision,+ Map<String, dynamic> answer,+ ) async {answering.add(decision.id);notifyListeners();try {@@ -161,12 +253,14 @@ class SuperTabDecisions extends ChangeNotifier {'command': {'type': 'decision.answer','decisionId': decision.id,- 'choice': choice,+ ...answer,},},);+ _failed.remove(decision.id);} catch (_) {- error = 'Could not send your answer. Try again.';+ // Said on the card that sent it ([failedToSend]), wherever it shows.+ _failed[decision.id] = answer;return false;} finally {answering.remove(decision.id);diff --git a/desktop/lib/super_tabs/decisions_view.dart b/desktop/lib/super_tabs/decisions_view.dartindex 90b91c0e1..5d23983d0 100644--- a/desktop/lib/super_tabs/decisions_view.dart+++ b/desktop/lib/super_tabs/decisions_view.dart@@ -68,7 +68,9 @@ class SuperTabDecisionList extends StatelessWidget {);}-/// The open decisions asked in one project, above its Chat with PM.+/// The open decisions asked in one project, above its Chat with PM. Hide+/// and each card's Not now fold them into the one heading line until the+/// reader shows them again; a decision asked later shows.class SuperTabDecisionsPanel extends StatelessWidget {const SuperTabDecisionsPanel({super.key,@@ -85,19 +87,39 @@ class SuperTabDecisionsPanel extends StatelessWidget {grid.AppTheme.watch(context);final open = decisions.openIn(projectId);if (open.isEmpty) return const SizedBox.shrink();+ final shown = decisions.shownIn(projectId);+ final folded = shown.isEmpty;return ConstrainedBox(constraints: const BoxConstraints(maxHeight: 320),child: ListView(key: const ValueKey('super-pm-decisions'),shrinkWrap: true,- padding: const EdgeInsets.only(bottom: 8),+ padding: EdgeInsets.only(bottom: folded ? 0 : 8),children: [- const Padding(- padding: EdgeInsets.fromLTRB(12, 12, 12, 4),- child: SuperTabSectionHeading('Decisions for you', endInset: 0),+ Padding(+ padding: EdgeInsets.fromLTRB(12, 12, 12, folded ? 0 : 4),+ child: SuperTabSectionHeading(+ 'Decisions for you (${open.length})',+ endInset: 0,+ trailing: folded+ ? quietDecisionAction(+ key: const ValueKey('super-pm-decisions-show'),+ label: 'Show',+ onPressed: () => decisions.showAgain(projectId),+ )+ : quietDecisionAction(+ key: const ValueKey('super-pm-decisions-hide'),+ label: 'Hide',+ onPressed: () => decisions.setAside(open),+ ),+ ),),- for (final decision in open)- SuperTabDecisionCard(decisions: decisions, decision: decision),+ for (final decision in shown)+ SuperTabDecisionCard(+ decisions: decisions,+ decision: decision,+ onNotNow: () => decisions.setAside([decision]),+ ),],),);@@ -105,16 +127,41 @@ class SuperTabDecisionsPanel extends StatelessWidget {);}-/// One question: what it unblocks, and one button per option, the-/// recommended one marked. Answered, it shows the choice instead.+/// A borderless text action, quieter than the options beside it (design+/// system: quiet inline controls).+Widget quietDecisionAction({+ required Key key,+ required String label,+ required VoidCallback? onPressed,+}) => TextButton(+ key: key,+ onPressed: onPressed,+ style: TextButton.styleFrom(+ foregroundColor: DesktopChrome.muted,+ backgroundColor: Colors.transparent,+ side: BorderSide.none,+ minimumSize: const Size(0, 28),+ padding: const EdgeInsets.symmetric(horizontal: 6),+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ textStyle: DesktopChrome.metadata(),+ ),+ child: Text(label),+);++/// One question: what it unblocks, one button per option, the recommended+/// one marked, and the quiet Let PM decide (only with a recommendation) and+/// Not now ([onNotNow], in Chat with PM). Answered, it shows the choice, or+/// that the PM decided.class SuperTabDecisionCard extends StatelessWidget {const SuperTabDecisionCard({super.key,required this.decisions,required this.decision,+ this.onNotNow,});final SuperTabDecisions decisions;final SuperTabDecision decision;+ final VoidCallback? onNotNow;@overrideWidget build(BuildContext context) {@@ -140,10 +187,11 @@ class SuperTabDecisionCard extends StatelessWidget {const SizedBox(height: 8),if (choice != null)Text(- 'You chose: ${decision.options.elementAtOrNull(choice) ?? ''}',+ '${decision.delegated ? 'PM decided' : 'You chose'}: '+ '${decision.options.elementAtOrNull(choice) ?? ''}',style: DesktopChrome.control(color: DesktopChrome.muted),)- else+ else ...[Wrap(spacing: 8,runSpacing: 6,@@ -152,6 +200,67 @@ class SuperTabDecisionCard extends StatelessWidget {_option(index, option),],),+ if (decisions.failedToSend(decision)) _failed(),+ if (_later() case final later?) ...[+ const SizedBox(height: 4),+ later,+ ],+ ],+ ],+ ),+ );+ }++ /// Its answer did not reach the backend: said on the card it was sent+ /// from, with Retry, wherever the card is shown.+ Widget _failed() => Padding(+ padding: EdgeInsets.only(top: grid.AppControl.menuGap),+ child: Wrap(+ crossAxisAlignment: WrapCrossAlignment.center,+ spacing: 4,+ children: [+ Text(SuperTabDecisions.sendFailed, style: DesktopChrome.metadata()),+ quietDecisionAction(+ key: ValueKey('super-decision-${decision.id}-retry'),+ label: 'Retry',+ onPressed: decisions.answering.contains(decision.id)+ ? null+ : () => unawaited(decisions.retry(decision)),+ ),+ ],+ ),+ );++ /// Let PM decide · Not now, whichever of them this card offers.+ Widget? _later() {+ final busy = decisions.answering.contains(decision.id);+ final actions = [+ if (decision.canDelegate)+ quietDecisionAction(+ key: ValueKey('super-decision-${decision.id}-delegate'),+ label: 'Let PM decide',+ onPressed: busy+ ? null+ : () => unawaited(decisions.delegate(decision)),+ ),+ if (onNotNow != null)+ quietDecisionAction(+ key: ValueKey('super-decision-${decision.id}-later'),+ label: 'Not now',+ onPressed: busy ? null : onNotNow,+ ),+ ];+ if (actions.isEmpty) return null;+ return Transform.translate(+ // The actions' text lines up with the question above.+ offset: const Offset(-6, 0),+ child: Wrap(+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ for (final (index, action) in actions.indexed) ...[+ if (index > 0) Text('·', style: DesktopChrome.metadata()),+ action,+ ],],),);diff --git a/desktop/lib/super_tabs/detail_dialog.dart b/desktop/lib/super_tabs/detail_dialog.dartnew file mode 100644index 000000000..56acda9ae--- /dev/null+++ b/desktop/lib/super_tabs/detail_dialog.dart@@ -0,0 +1,280 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../widgets/desktop_chrome.dart';+import '../widgets/desktop_prompt_surface.dart';++/// The spacing scale's steps (4, 8, 12) from the shared control gap, as the leaderboard rows take them.+const _gap = DesktopChrome.controlGap;+const _halfGap = _gap / 2;++/// Where every value of a details dialog starts: after the label column and its gap.+const superTabDetailLabelWidth = 120.0;++/// The frame the Swarm's details dialogs share (machine, person, project, Team at a glance, Share Swarm, Add+/// machine): the title with a quiet close, a hairline under it only while content has scrolled beneath it, a+/// scrolling body, and actions at the bottom — [leadingActions] at the left, [actions] at the right, at most one of+/// them filled.+class SuperTabDetailDialog extends StatefulWidget {+ const SuperTabDetailDialog({+ super.key,+ required this.title,+ required this.body,+ this.detail,+ this.leading,+ this.headerActions = const [],+ this.actions = const [],+ this.leadingActions = const [],+ this.footer,+ this.width = grid.AppDesktop.formWidth,+ this.onClose,+ });++ final String title;+ final String? detail;+ final Widget? leading;+ final List<Widget> headerActions;+ final Widget body;+ final List<Widget> actions, leadingActions;++ /// A short status or error kept beside the actions, outside the scroll.+ final Widget? footer;+ final double width;++ /// Defaults to closing the dialog.+ final VoidCallback? onClose;++ @override+ State<SuperTabDetailDialog> createState() => _SuperTabDetailDialogState();+}++class _SuperTabDetailDialogState extends State<SuperTabDetailDialog> {+ final _scroll = ScrollController();+ bool _scrolled = false;++ @override+ void dispose() {+ _scroll.dispose();+ super.dispose();+ }++ /// The body's own scroll position, not a nested list's.+ bool _onScroll(Notification notification) {+ final metrics = switch (notification) {+ ScrollNotification(:final metrics, depth: 0) => metrics,+ ScrollMetricsNotification(:final metrics, depth: 0) => metrics,+ _ => null,+ };+ if (metrics == null) return false;+ final scrolled = metrics.pixels > 0;+ if (scrolled != _scrolled) setState(() => _scrolled = scrolled);+ return false;+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ const inset = DesktopChrome.panelPadding;+ final hasActions =+ widget.actions.isNotEmpty || widget.leadingActions.isNotEmpty;+ return DesktopChrome(+ child: Dialog(+ insetPadding: const EdgeInsets.all(DesktopChrome.groupGap),+ backgroundColor: Colors.transparent,+ elevation: 0,+ shape: DesktopChrome.bareDialogShape,+ child: SizedBox(+ width: widget.width,+ child: DesktopDialogSurface(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ DesktopDialogHeader(+ title: widget.title,+ detail: widget.detail,+ leading: widget.leading,+ trailing: widget.headerActions,+ onClose: widget.onClose ?? () => Navigator.pop(context),+ padding: const EdgeInsets.fromLTRB(+ inset,+ inset,+ DesktopChrome.groupGap,+ _gap + _halfGap,+ ),+ ),+ if (_scrolled)+ Divider(+ key: const ValueKey('super-detail-hairline'),+ height: 1,+ thickness: 1,+ color: DesktopChrome.rim,+ )+ else+ const SizedBox(height: 1),+ Flexible(+ child: NotificationListener<Notification>(+ onNotification: _onScroll,+ child: Padding(+ padding: const EdgeInsets.only(+ left: inset,+ right: _gap + _halfGap,+ ),+ child: DesktopPromptScrollBody(+ controller: _scroll,+ child: Padding(+ padding: const EdgeInsets.symmetric(+ vertical: _halfGap,+ ),+ child: widget.body,+ ),+ ),+ ),+ ),+ ),+ if (widget.footer case final footer?)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ inset,+ _gap + _halfGap,+ inset,+ 0,+ ),+ child: footer,+ ),+ if (hasActions)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ inset,+ DesktopChrome.groupGap,+ inset,+ inset,+ ),+ // Leading at the left, the rest at the right; with enlarged text the right group wraps beneath.+ child: Wrap(+ alignment: widget.leadingActions.isEmpty+ ? WrapAlignment.end+ : WrapAlignment.spaceBetween,+ crossAxisAlignment: WrapCrossAlignment.center,+ runSpacing: DesktopChrome.controlGap,+ children: [+ for (final group in [+ widget.leadingActions,+ widget.actions,+ ])+ if (group.isNotEmpty)+ Wrap(+ spacing: DesktopChrome.controlGap,+ runSpacing: DesktopChrome.controlGap,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: group,+ ),+ ],+ ),+ )+ else+ const SizedBox(height: inset - 4),+ ],+ ),+ ),+ ),+ ),+ );+ }+}++/// A label and its value on one line, the value starting at the shared label column; under its label when the+/// dialog is narrow or text is enlarged. [child] replaces the plain value text.+class SuperTabDetailRow extends StatelessWidget {+ const SuperTabDetailRow({+ super.key,+ required this.label,+ this.value,+ this.child,+ this.valueStyle,+ }) : assert(value != null || child != null);++ final String label;+ final String? value;+ final Widget? child;+ final TextStyle? valueStyle;++ @override+ Widget build(BuildContext context) => LayoutBuilder(+ builder: (context, constraints) {+ final content =+ child ?? Text(value!, style: valueStyle ?? DesktopChrome.control());+ final labelText = Text(label, style: DesktopChrome.metadata());+ final stacked =+ constraints.maxWidth < 320 ||+ MediaQuery.textScalerOf(context).scale(13) > 20;+ return Padding(+ padding: const EdgeInsets.symmetric(vertical: _halfGap),+ child: stacked+ ? Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [labelText, const SizedBox(height: 2), content],+ )+ : Row(+ crossAxisAlignment: CrossAxisAlignment.baseline,+ textBaseline: TextBaseline.alphabetic,+ children: [+ SizedBox(width: superTabDetailLabelWidth, child: labelText),+ Expanded(child: content),+ ],+ ),+ );+ },+ );+}++/// A titled group of rows, 24 points below what precedes it.+class SuperTabDetailSection extends StatelessWidget {+ const SuperTabDetailSection({+ super.key,+ required this.title,+ required this.children,+ this.trailing,+ this.first = false,+ });++ final String title;+ final List<Widget> children;++ /// A count or quiet control at the heading's end.+ final Widget? trailing;++ /// No gap above: the dialog's first section.+ final bool first;++ @override+ Widget build(BuildContext context) => Padding(+ padding: EdgeInsets.only(top: first ? 0 : 24),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ crossAxisAlignment: CrossAxisAlignment.baseline,+ textBaseline: TextBaseline.alphabetic,+ children: [+ Expanded(+ child: Semantics(+ header: true,+ child: Text(title, style: DesktopChrome.control(medium: true)),+ ),+ ),+ ?trailing,+ ],+ ),+ const SizedBox(height: 4),+ ...children,+ ],+ ),+ );+}++/// A dialog's less frequent action: text with no pill, its fill only on hover, so the footer keeps one clear action.+final superTabQuietAction = TextButton.styleFrom(+ backgroundColor: Colors.transparent,+ side: BorderSide.none,+);diff --git a/desktop/lib/super_tabs/identity.dart b/desktop/lib/super_tabs/identity.dartindex 153bfc1c4..b4a059c5e 100644--- a/desktop/lib/super_tabs/identity.dart+++ b/desktop/lib/super_tabs/identity.dart@@ -52,6 +52,9 @@ class SuperTabAvatar extends StatelessWidget {pattern = true,now = null;+ /// The avatar of a roster row, agent or person, so their names start at one inset.+ static const rowSize = 24.0;+final String identity, name;final double size;final SuperTabAvatarPicture? picture;diff --git a/desktop/lib/super_tabs/leaderboard/person_row.dart b/desktop/lib/super_tabs/leaderboard/person_row.dartindex b8a7454e1..690ff6e61 100644--- a/desktop/lib/super_tabs/leaderboard/person_row.dart+++ b/desktop/lib/super_tabs/leaderboard/person_row.dart@@ -19,7 +19,7 @@ const _halfGap = _gap / 2;/// The avatar the Agents rows below draw, so without a rank column a person's/// name starts where an agent's does.-const _avatarSize = 24.0;+const _avatarSize = SuperTabAvatar.rowSize;/// Numbers and rankings (desktop design system): the rank a bold numeral in/// secondary ink, the points the one emphasized number, every figure in a@@ -253,9 +253,9 @@ class LeaderboardPersonRow extends StatelessWidget {);}- /// The name, then the status quietly; the email on hover.+ /// The name, then the status quietly; on hover the whole name, which a long one cut short needs, and the email.Widget _name() => Tooltip(- message: person.email,+ message: '${leaderboardName(person, score)}\n${person.email}',child: SuperTabUntil(until: person.status?.until,builder: (context) => Text.rich(@@ -447,35 +447,79 @@ class LeaderboardPersonWeek extends StatelessWidget {}}-/// The three lists behind a person's numbers, each saying so when empty. A-/// long week scrolls inside the window.-class _LeaderboardPersonDetails extends StatelessWidget {+/// The three lists behind a person's numbers, each with its count, its newest+/// five and the rest one click away, and saying so when empty. The dialog+/// around it scrolls (Ken, 2026-10-28).+class _LeaderboardPersonDetails extends StatefulWidget {const _LeaderboardPersonDetails({required this.score, required this.details});final SuperTabPersonScore score;final SuperTabPersonDetails details;+ @override+ State<_LeaderboardPersonDetails> createState() =>+ _LeaderboardPersonDetailsState();+}++class _LeaderboardPersonDetailsState extends State<_LeaderboardPersonDetails> {+ /// The newest a list shows before Show all.+ static const _shown = 5;+ final _expanded = <String>{};+@overrideWidget build(BuildContext context) {- final trend = leaderboardTrend(score);+ final score = widget.score, details = widget.details;final quiet = DesktopChrome.metadata();- Widget section(String title, String empty, List<Widget> items) => Padding(- padding: const EdgeInsets.only(top: _gap + _halfGap),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- title,- style: DesktopChrome.control(- color: DesktopChrome.foreground,- medium: true,+ final figures = quiet.copyWith(fontFeatures: grid.AppFont.tabularFigures);+ Widget section(String title, String empty, List<Widget> items) {+ final all = _expanded.contains(title) || items.length <= _shown;+ return Padding(+ padding: const EdgeInsets.only(top: _gap * 2),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ crossAxisAlignment: CrossAxisAlignment.baseline,+ textBaseline: TextBaseline.alphabetic,+ children: [+ Text(+ title,+ style: DesktopChrome.control(+ color: DesktopChrome.foreground,+ medium: true,+ ),+ ),+ if (items.isNotEmpty) ...[+ const SizedBox(width: _gap),+ Text('${items.length}', style: figures),+ ],+ ],),- ),- const SizedBox(height: _halfGap),- if (items.isEmpty) Text(empty, style: quiet) else ...items,- ],- ),- );- // Items stand the spacing scale's smallest step apart.+ const SizedBox(height: _halfGap),+ if (items.isEmpty)+ Text(empty, style: quiet)+ else ...[+ ...all ? items : items.take(_shown),+ if (!all)+ Align(+ alignment: AlignmentDirectional.centerStart,+ child: TextButton(+ style: TextButton.styleFrom(+ backgroundColor: Colors.transparent,+ side: BorderSide.none,+ padding: EdgeInsets.zero,+ minimumSize: Size.zero,+ ),+ onPressed: () => setState(() => _expanded.add(title)),+ child: Text('Show all ${items.length}'),+ ),+ ),+ ],+ ],+ ),+ );+ }++ // One line each, the whole title on hover; items stand the spacing scale's smallest step apart.Widget item(Widget title, String trailing) => Padding(padding: const EdgeInsets.symmetric(vertical: _halfGap / 2),child: Row(@@ -484,74 +528,69 @@ class _LeaderboardPersonDetails extends StatelessWidget {Expanded(child: title),if (trailing.isNotEmpty) ...[const SizedBox(width: _gap + _halfGap),- Text(- trailing,- style: quiet.copyWith(fontFeatures: grid.AppFont.tabularFigures),- ),+ Text(trailing, style: figures),],],),);final text = DesktopChrome.control();- return ConstrainedBox(- constraints: BoxConstraints(- maxHeight: MediaQuery.sizeOf(context).height * .5,+ Widget line(String value, {TextStyle? style}) => Tooltip(+ message: value,+ excludeFromSemantics: true,+ child: Text(+ value,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: style ?? text,),- // The small form's width, less the dialog's own content inset.- child: SizedBox(- width: grid.AppDesktop.formWidth - 2 * grid.AppDesktop.panelPadding,- child: SingleChildScrollView(- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- trend == null- ? '${score.points} pts'- : '${score.points} pts · $trend',- style: quiet,- ),- section('Shipped', 'No pull requests merged yet', [- for (final shipped in details.shipped)- item(switch (Uri.tryParse(shipped.prUrl ?? '')) {- // Only a web page opens: a link from the server is data,- // and any other scheme could open a file or an app.- final link?- when const {'http', 'https'}.contains(link.scheme) =>- Semantics(- link: true,- child: InkWell(- onTap: () => launchUrl(- link,- mode: LaunchMode.externalApplication,- ),- child: Text(- shipped.title,- style: text.copyWith(color: DesktopChrome.accent),- ),- ),- ),- _ => Text(shipped.title, style: text),- }, ''),- ]),- section('Unblocked', 'No questions answered yet', [- for (final unblocked in details.unblocked)- item(- Text(unblocked.title, style: text),- 'waited ${leaderboardDuration(unblocked.waitedMinutes * 60000)}',- ),- ]),- section('Lent', 'No machines lent yet', [- for (final lent in details.lent)- item(- Text(superTabMachineName(lent.machineName), style: text),- '${leaderboardDuration((lent.busyHours * 3600000).round())} busy',- ),- ]),- ],- ),+ );+ final before = score.prevWeekPoints;+ return Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(+ [+ '${plural(score.points, 'point')} this week',+ if (before != null) '$before last week',+ ].join(' · '),+ style: quiet,),- ),+ section('Shipped', 'No pull requests merged yet', [+ for (final shipped in details.shipped)+ item(switch (Uri.tryParse(shipped.prUrl ?? '')) {+ // Only a web page opens: a link from the server is data,+ // and any other scheme could open a file or an app.+ final link? when const {'http', 'https'}.contains(link.scheme) =>+ Semantics(+ link: true,+ child: InkWell(+ onTap: () =>+ launchUrl(link, mode: LaunchMode.externalApplication),+ child: line(+ shipped.title,+ style: text.copyWith(color: DesktopChrome.accent),+ ),+ ),+ ),+ _ => line(shipped.title),+ }, ''),+ ]),+ section('Unblocked', 'No questions answered yet', [+ for (final unblocked in details.unblocked)+ item(+ line(unblocked.title),+ 'waited ${leaderboardDuration(unblocked.waitedMinutes * 60000)}',+ ),+ ]),+ section('Lent', 'No machines lent yet', [+ for (final lent in details.lent)+ item(+ line(superTabMachineName(lent.machineName)),+ '${leaderboardDuration((lent.busyHours * 3600000).round())} busy',+ ),+ ]),+ ],);}}diff --git a/desktop/lib/super_tabs/machine_details.dart b/desktop/lib/super_tabs/machine_details.dartindex d0eebadbf..1b9e90d50 100644--- a/desktop/lib/super_tabs/machine_details.dart+++ b/desktop/lib/super_tabs/machine_details.dart@@ -2,10 +2,15 @@ import 'package:flutter/material.dart';import '../core/machine_resources.dart';import '../shared/theme/app_theme.dart' as grid;+import '../shared/theme/status_line_style.dart';import '../widgets/desktop_chrome.dart';-import '../widgets/desktop_prompt_surface.dart';import '../widgets/engine_identity.dart';import '../widgets/workspace_subscription_usage.dart';+import 'detail_dialog.dart';++/// The spacing scale's steps (4, 8, 12) from the shared control gap, as the leaderboard rows take them.+const _gap = DesktopChrome.controlGap;+const _halfGap = _gap / 2;/// Full machine context behind the sidebar's compact, live readings.class SuperTabMachineDetails extends StatelessWidget {@@ -16,13 +21,12 @@ class SuperTabMachineDetails extends StatelessWidget {required this.accounts,this.owner,this.resources,- this.cwd,this.engines,this.footer,});final String name, status;- final String? owner, cwd;+ final String? owner;final MachineResources? resources;final List<String>? engines;final List<Map<String, Object?>> accounts;@@ -30,92 +34,114 @@ class SuperTabMachineDetails extends StatelessWidget {/// Below the details, inside the same scroll: what a Swarm adds about the machine (its local models).final Widget? footer;- Widget _row(String label, String value, {required bool stacked}) => Padding(- padding: const EdgeInsets.symmetric(vertical: 5),- child: stacked- ? Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Text(label, style: DesktopChrome.metadata()),- const SizedBox(height: 2),- Text(value, style: DesktopChrome.control()),- ],- )- : Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- SizedBox(- width: 104,- child: Text(label, style: DesktopChrome.metadata()),- ),- const SizedBox(width: 16),- Expanded(child: Text(value, style: DesktopChrome.control())),- ],- ),- );-- Widget _section(String title, List<Widget> children) => Padding(- padding: const EdgeInsets.only(top: 24),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Text(title, style: DesktopChrome.control(medium: true)),- const SizedBox(height: 8),- ...children,- ],- ),- );-Widget _allowance(WorkspaceSubscriptionAccount account,Map<String, Object?> row,- bool stacked,) {- final details = (row['details'] as List? ?? const []).whereType<String>();- final accountName = row['account'] as String?;- final figure = Text(- '${account.figure} left',- style: DesktopChrome.control(- medium: true,- color: account.ink(DesktopChrome.foreground, DesktopChrome.surface),- ),+ final windows = superTabAllowanceWindows(+ (row['details'] as List? ?? const []).whereType<String>(),);+ final accountName = row['account'] as String?;+ final name = Text(account.name, style: DesktopChrome.control(medium: true));+ final email = accountName?.isNotEmpty == true+ ? Text(accountName!, style: DesktopChrome.metadata())+ : null;+ // Without its windows the account's one figure stands for them.+ final figure = windows.isEmpty+ ? Text(+ '${account.figure} left',+ style: DesktopChrome.control(+ color: account.ink(+ DesktopChrome.foreground,+ DesktopChrome.surface,+ ),+ ),+ )+ : null;return Padding(- padding: const EdgeInsets.only(bottom: 12),+ padding: const EdgeInsets.only(top: _gap, bottom: _halfGap),child: Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [- Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- EngineMark(engine: account.engine, size: 16),- const SizedBox(width: 8),- Expanded(- child: Text(account.name, style: DesktopChrome.control()),- ),- if (!stacked) ...[const SizedBox(width: 12), figure],- ],+ // On one line when there is room; narrow or with enlarged text, the email and figure go beneath, as the+ // rows' values do (review of #1962).+ LayoutBuilder(+ builder: (context, constraints) {+ final stacked =+ constraints.maxWidth < 320 ||+ MediaQuery.textScalerOf(context).scale(13) > 20;+ final mark = EngineMark(engine: account.engine, size: 16);+ if (stacked) {+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ mark,+ const SizedBox(width: 8),+ Flexible(child: name),+ ],+ ),+ if (email != null)+ Padding(+ padding: const EdgeInsets.only(top: _halfGap / 2),+ child: email,+ ),+ if (figure != null)+ Padding(+ padding: const EdgeInsets.only(top: _halfGap / 2),+ child: figure,+ ),+ ],+ );+ }+ return Row(+ children: [+ mark,+ const SizedBox(width: 8),+ Flexible(child: name),+ const SizedBox(width: 8),+ Expanded(+ child: email == null+ ? const SizedBox.shrink()+ : Text(+ accountName!,+ style: DesktopChrome.metadata(),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ if (figure != null) ...[const SizedBox(width: 12), figure],+ ],+ );+ },),- if (stacked)- Padding(padding: const EdgeInsets.only(top: 4), child: figure),- if (accountName?.isNotEmpty == true)- Padding(- padding: const EdgeInsets.only(top: 4),- child: Text(accountName!, style: DesktopChrome.metadata()),- ),- for (final detail in details)- Padding(- padding: const EdgeInsets.only(top: 6),- child: Text(- detail.replaceAll(' · resets in ', '\nResets in '),- style: DesktopChrome.metadata(),- ),+ for (final window in windows)+ SuperTabDetailRow(+ label: window.window,+ value: [window.left, ?window.reset].join(' · '),+ valueStyle: DesktopChrome.control(color: _ink(window.left)),),],),);}+ /// A window's share in the footer's colours: neutral above 20%, amber to 6%, red at 5% or less.+ static Color _ink(String left) {+ // "5.0%" is 5, "<1%" under 1; floored as the footer floors it. Unreadable stays neutral.+ final figure = left.split('%').first.replaceFirst('<', '');+ final percent = (double.tryParse(figure) ?? 100).floor();+ return statusLineInkOnSurface(+ percent > 20+ ? DesktopChrome.foreground+ : percent <= 5+ ? grid.AppPalette.usageCritical+ : grid.AppPalette.usageLow,+ DesktopChrome.surface,+ );+ }+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);@@ -156,46 +182,64 @@ class SuperTabMachineDetails extends StatelessWidget {if (value?.os case final os?) ('System', os),for (final gpu in value?.gpus ?? const <MachineGpu>[])if (gpu.id != 'observed') ('Graphics', gpu.name),- if (cwd case final path?) ('Project folder', path),if (engines?.isNotEmpty == true)('Engines', engines!.map((e) => engineIdentity(e).label).join(', ')),];- return SizedBox(- width: 400,- child: LayoutBuilder(- builder: (context, constraints) {- final stacked =- constraints.maxWidth < 320 ||- MediaQuery.textScalerOf(context).scale(13) > 20;- return DesktopPromptScrollBody(- child: SelectionArea(- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- if (owner case final email?)- _row('Owner', email, stacked: stacked),- _row('Status', status, stacked: stacked),- if (readings.isNotEmpty)- _section('Available capacity', [- for (final reading in readings)- _row(reading.$1, reading.$2, stacked: stacked),- ]),- if (knownAccounts.isNotEmpty)- _section('Model allowances', [- for (final entry in knownAccounts)- _allowance(entry.$1, entry.$2, stacked),- ]),- _section('Details', [- for (final detail in hardware)- _row(detail.$1, detail.$2, stacked: stacked),- ]),- ?footer,- ],- ),+ return SelectionArea(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (owner case final email?)+ SuperTabDetailRow(label: 'Owner', value: email),+ SuperTabDetailRow(label: 'Status', value: status),+ if (readings.isNotEmpty)+ SuperTabDetailSection(+ title: 'Available capacity',+ children: [+ for (final reading in readings)+ SuperTabDetailRow(label: reading.$1, value: reading.$2),+ ],),- );- },+ if (knownAccounts.isNotEmpty)+ SuperTabDetailSection(+ title: 'Model allowances',+ children: [+ for (final entry in knownAccounts)+ _allowance(entry.$1, entry.$2),+ ],+ ),+ SuperTabDetailSection(+ title: 'Details',+ children: [+ for (final detail in hardware)+ SuperTabDetailRow(label: detail.$1, value: detail.$2),+ ],+ ),+ ?footer,+ ],),);}}++/// One window of an allowance: its name, the share left, and when it resets.+typedef SuperTabAllowanceWindow = ({String window, String left, String? reset});++/// An allowance's windows from its detail lines, in either format: another machine's+/// (`5-hour: 44% remaining · resets in 2h 10m`) or this computer's (`5-hour — 44% remaining · resets in 2h 10m`, after+/// a `Limiting window:` line, which the windows themselves already say). Other lines are left out.+List<SuperTabAllowanceWindow> superTabAllowanceWindows(Iterable<String> lines) {+ final window = RegExp(+ r'^(.+?)(?: — |: )(\S+%) remaining(?: · (resets in .+))?$',+ );+ return [+ for (final line in lines)+ if (!line.startsWith('Limiting window: '))+ if (window.firstMatch(line) case final match?)+ (+ window: match.group(1)!,+ left: '${match.group(2)} left',+ reset: match.group(3),+ ),+ ];+}diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex 8542881b9..b66e9f2d2 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -24,6 +24,7 @@ import '../widgets/harness_activity_mark.dart';import '../widgets/workspace_subscription_usage.dart';import 'agent_details.dart';import 'controller.dart';+import 'detail_dialog.dart';import 'dialog_scope.dart';import 'identity.dart';import 'local_models.dart';@@ -338,11 +339,16 @@ class _MachinePickerState extends State<_MachinePicker> {child: ExcludeSemantics(child: Row(children: [+ // A long hostname reads whole, over two lines if it must (Ken, 2026-10-28).Expanded(- child: Text(- label,- maxLines: 1,- overflow: TextOverflow.ellipsis,+ child: Tooltip(+ message: label,+ excludeFromSemantics: true,+ child: Text(+ label,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ ),),),if (current?.unavailable != null) ...[@@ -765,100 +771,85 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {final own = ownedMachines();final canSave =machineId != null && canSelect(app.stateOf(machineId!));- return AlertDialog(- title: Text(isConfigure ? 'Configure machine' : 'Add machine'),- content: SizedBox(- width: 360,- child: SingleChildScrollView(- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- if (own.isNotEmpty)- _MachinePicker(- value: machineId,- busy: busy,- choices: [- for (final m in own)- _MachineChoice(- id: m.machine.machineId,- label: labelFor(m),- unavailable: unavailable(m),- ),- ],- onChanged: (id) {- if (busy || !canSelect(app.stateOf(id))) return;- update(() {- machineId = id;- setupId = null;- error = null;- // Another machine has its own number: the one it- // already offers, or its own suggestion.- slots = slotsFor(id);- slotsEdited = false;- });- unawaited(suggestSlots());- },- )- else- Text(- 'No computer is connected to this account yet.',- style: DesktopChrome.text(),- ),- const SizedBox(height: 16),- if (own.isNotEmpty) ...[- Text(- 'Let the product manager run agents here using this machine’s signed-in accounts.',- style: DesktopChrome.text(),- ),- const SizedBox(height: 4),- Text(- 'Agents the Swarm starts on this machine run without asking for permission.',- style: DesktopChrome.text(),- ),- const SizedBox(height: 12),- Text(- 'Harness clones each project into ~/harnesses/swarms and lets '- "the Swarm's agents work in it.",- style: DesktopChrome.text(),- ),- ] else ...[- Text(- 'To add another computer, install Harness on it and sign in with '- 'this account, or approve a device with no screen from Machines.',- style: DesktopChrome.text(),- ),- const SizedBox(height: 4),- Align(- alignment: Alignment.centerLeft,- child: TextButton(- onPressed: () {- Navigator.pop(context);- app.requestMachines();- },- child: const Text('Open Machines'),+ return SuperTabDetailDialog(+ title: isConfigure ? 'Configure machine' : 'Add machine',+ body: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (own.isNotEmpty)+ _MachinePicker(+ value: machineId,+ busy: busy,+ choices: [+ for (final m in own)+ _MachineChoice(+ id: m.machine.machineId,+ label: labelFor(m),+ unavailable: unavailable(m),),- ),],- if (own.isNotEmpty) ...[- const SizedBox(height: 16),- _AgentSlots(- value: slots,- maximum: maximumFor(machineId),- busy: busy,- onChanged: (next) => update(() {- slots = next;- slotsEdited = true;- }),- ),- ],- if (error != null) ...[- const SizedBox(height: 12),- Text(error!, style: DesktopChrome.metadata()),- ],- ],- ),- ),+ onChanged: (id) {+ if (busy || !canSelect(app.stateOf(id))) return;+ update(() {+ machineId = id;+ setupId = null;+ error = null;+ // Another machine has its own number: the one it+ // already offers, or its own suggestion.+ slots = slotsFor(id);+ slotsEdited = false;+ });+ unawaited(suggestSlots());+ },+ )+ else+ Text(+ 'No computer is connected to this account yet.',+ style: DesktopChrome.text(),+ ),+ const SizedBox(height: 16),+ if (own.isNotEmpty) ...[+ Text(+ "The Swarm's product managers can start agents here with this machine's signed-in accounts. "+ 'They run without asking for permission, in projects cloned to ~/harnesses/swarms.',+ style: DesktopChrome.text(),+ ),+ ] else ...[+ Text(+ 'To add another computer, install Harness on it and sign in with '+ 'this account, or approve a device with no screen from Machines.',+ style: DesktopChrome.text(),+ ),+ const SizedBox(height: 4),+ Align(+ alignment: Alignment.centerLeft,+ child: TextButton(+ onPressed: () {+ Navigator.pop(context);+ app.requestMachines();+ },+ child: const Text('Open Machines'),+ ),+ ),+ ],+ if (own.isNotEmpty) ...[+ const SizedBox(height: 16),+ _AgentSlots(+ value: slots,+ maximum: maximumFor(machineId),+ busy: busy,+ onChanged: (next) => update(() {+ slots = next;+ slotsEdited = true;+ }),+ ),+ ],+ if (error != null) ...[+ const SizedBox(height: 12),+ Text(error!, style: DesktopChrome.metadata()),+ ],+ ],),actions: [if (own.isNotEmpty)@@ -869,11 +860,6 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {? (isConfigure ? 'Saving…' : 'Preparing…'): (isConfigure ? 'Save' : 'Add machine'),),- )- else- TextButton(- onPressed: () => Navigator.pop(context),- child: const Text('Close'),),],);@@ -1466,47 +1452,52 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {listenable: c,builder: (context, _) {final removeReason = _removeReason(id);- return AlertDialog(- title: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Row(- children: [- Expanded(child: Text(superTabMachineName(name))),- // Out of the way of the everyday actions below: a quiet mark that turns red when pointed at.- if (_canRemove(id))- AppIconButton(- key: const ValueKey('super-machine-remove'),- icon: AppIcons.trash2,- tooltip: removeReason ?? 'Remove from Swarm',- color: DesktopChrome.muted,- destructive: true,- onPressed: removeReason != null- ? null- : () {- if (_removeReason(id) != null) return;- Navigator.pop(context);- WidgetsBinding.instance.addPostFrameCallback((- _,- ) {- if (mounted) unawaited(_remove(v));- });- },- ),- ],+ Future<void> pause() async {+ final result = await c.command({+ 'type': 'machine.pause',+ 'machineId': id,+ 'paused': !paused,+ });+ if (context.mounted && result != null) Navigator.pop(context);+ }++ void attach() {+ final group = c.selected!;+ Navigator.pop(context);+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) widget.onAddAgent(group);+ });+ }++ return SuperTabDetailDialog(+ title: superTabMachineName(name),+ headerActions: [+ // Out of the way of the everyday actions below: a quiet mark that turns red when pointed at, and says+ // why on hover when it cannot.+ if (_canRemove(id))+ AppIconButton(+ key: const ValueKey('super-machine-remove'),+ icon: AppIcons.trash2,+ tooltip: removeReason ?? 'Remove from Swarm',+ color: DesktopChrome.muted,+ destructive: true,+ onPressed: removeReason != null+ ? null+ : () {+ if (_removeReason(id) != null) return;+ Navigator.pop(context);+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) unawaited(_remove(v));+ });+ },),- if (_canRemove(id) && removeReason != null)- Text(removeReason, style: DesktopChrome.metadata()),- ],- ),- content: SuperTabMachineDetails(+ ],+ body: SuperTabMachineDetails(name: name,owner: person?.email,status: details,// Details follow the same freshness rule as the row and its disclosure.resources: dim ? null : value,- cwd: shared?['cwd'] as String?,engines: allowed,accounts: dim ? const [] : accounts,footer: SuperTabMachineLocalModels(@@ -1515,21 +1506,22 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {now: widget.now,),),- actions: [+ // One clear action at the right; the rarer ones quiet at the left (Ken, 2026-10-28).+ leadingActions: [if (shared != null && contributor == c.accountId)TextButton(- onPressed: () async {- final result = await c.command({- 'type': 'machine.pause',- 'machineId': id,- 'paused': !paused,- });- if (context.mounted && result != null) {- Navigator.pop(context);- }- },+ style: superTabQuietAction,+ onPressed: () => unawaited(pause()),child: Text(paused ? 'Resume new work' : 'Pause new work'),),+ if (c.canWrite && c.selected != null)+ TextButton(+ style: superTabQuietAction,+ onPressed: attach,+ child: const Text('Attach running agent'),+ ),+ ],+ actions: [if (contributor == c.accountId)TextButton(onPressed: () {@@ -1540,21 +1532,6 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {},child: const Text('Configure'),),- if (c.canWrite && c.selected != null)- TextButton(- onPressed: () {- final group = c.selected!;- Navigator.pop(context);- WidgetsBinding.instance.addPostFrameCallback((_) {- if (mounted) widget.onAddAgent(group);- });- },- child: const Text('Attach running agent'),- ),- TextButton(- onPressed: () => Navigator.pop(context),- child: const Text('Close'),- ),],);},diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex e50ba33af..5d79d7345 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -85,7 +85,8 @@ class SuperTabAgent {final String machineOwnerId;/// Its session read private chats: a Product Manager, now or before, or an agent in a private chat. Only the person- /// whose computer runs it may watch it; its computer refuses every share (backend projects.ts `canWatchAgent`).+ /// whose computer runs it may watch it, but every member watches the current Product Manager, view only+ /// (backend projects.ts `watchClosed`, terminal_unavailable.dart `superTabTerminalPrivate`).final bool confidential;// Keep the legacy default for callers while allowing group-based roster ownership.final bool hasProjectId;@@ -393,6 +394,9 @@ class SuperTabSnapshot {Map<String, dynamic>? best;for (final m in teamPoolsOf(machineId)) {if (m['removal'] != null) continue;+ // Removed (`harness team remove` deletes its machine): the server reads a live account never so, and the Mac is a+ // Mac without one again, which its owner can set up from its row (local Team account run, 2026-10-28).+ if (m['teamWork'] case {'code': 'TEAM_ACCOUNT_REQUIRED'}) continue;if (best == null || reported(m) >= reported(best)) best = m;}return best;diff --git a/desktop/lib/super_tabs/project_github.dart b/desktop/lib/super_tabs/project_github.dartindex 35c2eaa05..d1f41afd8 100644--- a/desktop/lib/super_tabs/project_github.dart+++ b/desktop/lib/super_tabs/project_github.dart@@ -2,12 +2,18 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:url_launcher/url_launcher.dart';+import '../shared/theme/app_icons.dart';import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_dialog.dart';import '../widgets/desktop_chrome.dart';import 'controller.dart';+import 'detail_dialog.dart';import 'model.dart';+/// The spacing scale's steps (4, 8, 12) from the shared control gap, as the leaderboard rows take them.+const _gap = DesktopChrome.controlGap;+const _halfGap = _gap / 2;+/// Whether teammates' agents can push and open pull requests on a Swarm project's repository: the Harness GitHub App is/// installed there (backend github/projectAccess.ts, docs/plans/2026-10-28-swarm-project-github-access.md). Before this,/// nothing said so until a start failed and the Lead relayed it.@@ -47,11 +53,15 @@ class ProjectGitHubAccess extends StatefulWidget {super.key,required this.controller,required this.projectId,+ this.detailRow = false,});final SuperTabController controller;final String projectId;+ /// As a row of Project details: its label in the dialog's label column, rather than a heading above it.+ final bool detailRow;+@overrideState<ProjectGitHubAccess> createState() => _ProjectGitHubAccessState();}@@ -119,29 +129,18 @@ class _ProjectGitHubAccessState extends State<ProjectGitHubAccess>if (access?.state == 'unavailable') return const SizedBox.shrink();// Read as the dialog opens: said, so the section does not appear from nothing a moment later.if (access == null) {- return Column(- key: ValueKey('super-project-github-${widget.projectId}'),- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text('GitHub access', style: DesktopChrome.control(medium: true)),- const SizedBox(height: 4),- Text(- 'Checking…',- key: ValueKey(- 'super-project-github-text-${widget.projectId}',- ),- style: DesktopChrome.text().copyWith(- color: DesktopChrome.muted,- ),- ),- ],+ return _framed(+ Text(+ 'Checking…',+ key: ValueKey('super-project-github-text-${widget.projectId}'),+ style: DesktopChrome.text().copyWith(color: DesktopChrome.muted),+ ),);}final repository = access.repository ?? 'its repository';final text = switch (access.state) {'covered' =>- "GitHub ✓ Teammates' agents can push and open pull requests on $repository.",+ "Teammates' agents can push and open pull requests on $repository.",'not-installed' =>"Teammates' agents can't push to $repository yet. Install Harness on GitHub there: ""an owner of ${repository.split('/').first}, or the repository's owner, can.",@@ -161,91 +160,127 @@ class _ProjectGitHubAccessState extends State<ProjectGitHubAccess>(access.state == 'not-installed' || access.state == 'not-approved');final install = access.installUrl;final approve = access.state == 'not-approved' && access.canApprove;- return Column(- key: ValueKey('super-project-github-${widget.projectId}'),- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text('GitHub access', style: DesktopChrome.control(medium: true)),- const SizedBox(height: 4),- Text(- text,- key: ValueKey('super-project-github-text-${widget.projectId}'),- style: DesktopChrome.text(),- ),- if (waiting)- Padding(- padding: const EdgeInsets.only(top: 4),- child: Text(- 'Finish on GitHub in your browser. This updates when you come back.',- key: const Key('super-project-github-waiting'),- style: DesktopChrome.text().copyWith(- color: DesktopChrome.muted,+ final sentence = Text(+ text,+ key: ValueKey('super-project-github-text-${widget.projectId}'),+ style: DesktopChrome.text(),+ );+ return _framed(+ Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ if (access.state == 'covered')+ Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Padding(+ padding: const EdgeInsets.only(top: _halfGap / 2),+ child: Icon(+ AppIcons.check,+ size: grid.AppControl.iconSize,+ color: grid.AppPalette.online,+ ),+ ),+ const SizedBox(width: 6),+ Expanded(child: sentence),+ ],+ )+ else+ sentence,+ if (waiting)+ Padding(+ padding: const EdgeInsets.only(top: _halfGap),+ child: Text(+ 'Finish on GitHub in your browser. This updates when you come back.',+ key: const Key('super-project-github-waiting'),+ style: DesktopChrome.text().copyWith(+ color: DesktopChrome.muted,+ ),),),- ),- if (_error != null)- Padding(- padding: const EdgeInsets.only(top: 4),- child: Text(- _error!,- key: const Key('super-project-github-error'),- style: DesktopChrome.text().copyWith(- color: grid.AppPalette.warn,+ if (_error != null)+ Padding(+ padding: const EdgeInsets.only(top: _halfGap),+ child: Text(+ _error!,+ key: const Key('super-project-github-error'),+ style: DesktopChrome.text().copyWith(+ color: grid.AppPalette.warn,+ ),),),- ),- if (access.state == 'not-installed' ||- access.state == 'not-approved' ||- access.state == 'unknown' ||- access.state == 'unread')- Padding(- padding: const EdgeInsets.only(top: 8),- child: Wrap(- spacing: 8,- runSpacing: 4,- children: [- if (install != null && access.state == 'not-installed') ...[- FilledButton(- key: const Key('super-project-github-install'),- onPressed: _busy ? null : () => _install(install),- child: const Text('Install on GitHub'),- ),+ if (access.state == 'not-installed' ||+ access.state == 'not-approved' ||+ access.state == 'unknown' ||+ access.state == 'unread')+ Padding(+ padding: const EdgeInsets.only(top: _gap),+ child: Wrap(+ spacing: 8,+ runSpacing: 4,+ children: [+ if (install != null &&+ access.state == 'not-installed') ...[+ FilledButton(+ key: const Key('super-project-github-install'),+ onPressed: _busy ? null : () => _install(install),+ child: const Text('Install on GitHub'),+ ),+ TextButton(+ key: const Key('super-project-github-copy'),+ onPressed: () async {+ await Clipboard.setData(+ ClipboardData(text: install),+ );+ if (mounted) setState(() => _copied = true);+ },+ child: Text(_copied ? 'Link copied' : 'Copy link'),+ ),+ ],+ if (approve) ...[+ FilledButton(+ key: const Key('super-project-github-approve'),+ onPressed: _busy ? null : () => _approve('project'),+ child: const Text('Approve for this project'),+ ),+ TextButton(+ key: const Key('super-project-github-approve-swarm'),+ onPressed: _busy ? null : () => _approve('swarm'),+ child: const Text('Approve for every project here'),+ ),+ ],TextButton(- key: const Key('super-project-github-copy'),- onPressed: () async {- await Clipboard.setData(ClipboardData(text: install));- if (mounted) setState(() => _copied = true);- },- child: Text(_copied ? 'Link copied' : 'Copy link'),+ key: const Key('super-project-github-check'),+ onPressed: _checking ? null : _check,+ child: Text(_checking ? 'Checking…' : 'Check again'),),],- if (approve) ...[- FilledButton(- key: const Key('super-project-github-approve'),- onPressed: _busy ? null : () => _approve('project'),- child: const Text('Approve for this project'),- ),- TextButton(- key: const Key('super-project-github-approve-swarm'),- onPressed: _busy ? null : () => _approve('swarm'),- child: const Text('Approve for every project here'),- ),- ],- TextButton(- key: const Key('super-project-github-check'),- onPressed: _checking ? null : _check,- child: Text(_checking ? 'Checking…' : 'Check again'),- ),- ],+ ),),- ),- ],+ ],+ ),);},);}+ /// Under its heading, or as Project details' row.+ Widget _framed(Widget content) => KeyedSubtree(+ key: ValueKey('super-project-github-${widget.projectId}'),+ child: widget.detailRow+ ? SuperTabDetailRow(label: 'GitHub access', child: content)+ : Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text('GitHub access', style: DesktopChrome.control(medium: true)),+ const SizedBox(height: 4),+ content,+ ],+ ),+ );+/// Installs Harness on GitHub with a link that also approves the repository for this project once installed (GitHub/// signs the installer in and sends them back); an older server's plain link otherwise.Future<void> _install(String plain) async {@@ -357,7 +392,7 @@ class _ProjectGitHubLineState extends State<ProjectGitHubLine>key: ValueKey('super-project-github-line-${widget.project.id}'),onTap: () => showProjectGitHubAccess(context, c, widget.project),child: Padding(- padding: const EdgeInsets.only(bottom: 4),+ padding: const EdgeInsets.only(bottom: _halfGap),child: Text(problem,maxLines: 1,diff --git a/desktop/lib/super_tabs/project_options.dart b/desktop/lib/super_tabs/project_options.dartindex 95e2631d7..ca5707b66 100644--- a/desktop/lib/super_tabs/project_options.dart+++ b/desktop/lib/super_tabs/project_options.dart@@ -4,12 +4,80 @@ import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_dialog.dart';import '../widgets/desktop_chrome.dart';import 'controller.dart';+import 'detail_dialog.dart';import 'dialog_scope.dart';import 'model.dart';import 'project_github.dart';import 'project_visibility.dart';import 'roles_editor.dart';+/// The spacing scale's steps (4, 8, 12) from the shared control gap, as the leaderboard rows take them.+const _gap = DesktopChrome.controlGap;+const _halfGap = _gap / 2;++/// A project's details, read only: its description, repository, Product Manager and whether teammates' agents can+/// push there, in the shared details frame (Ken, 2026-10-28).+Future<void> _showProjectDetails(+ BuildContext context,+ SuperTabController c,+ SuperTabProject project,+) => showAppDialog<void>(+ context: context,+ builder: (context) => SuperTabDialogScope(+ controller: c,+ projectId: project.id,+ requireWrite: false,+ child: ListenableBuilder(+ listenable: c,+ builder: (context, _) {+ final current = c.snapshot?.projects+ .where((p) => p.id == project.id)+ .firstOrNull;+ final group = c.snapshot?.conversation(project.leadConversationId);+ final brief = group?.brief.trim() ?? '';+ return SuperTabDetailDialog(+ title: current?.name ?? project.name,+ body: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.only(bottom: _gap + _halfGap),+ child: brief.isEmpty+ ? Text(+ 'No description yet',+ style: DesktopChrome.metadata(),+ )+ : SelectableText(brief, style: DesktopChrome.text()),+ ),+ SuperTabDetailRow(+ label: 'Repository',+ child: SelectableText(+ current?.repository?['repositoryUrl'] as String? ??+ current?.repository?['cwd'] as String? ??+ 'Not set',+ style: DesktopChrome.control(),+ ),+ ),+ SuperTabDetailRow(+ label: 'Product Manager',+ value: group?.leadId == null+ ? 'Starting…'+ : c.snapshot!.agentName(group!.leadId!),+ ),+ // Whether teammates' agents can push to its repository, and what to do about it.+ ProjectGitHubAccess(+ controller: c,+ projectId: project.id,+ detailRow: true,+ ),+ ],+ ),+ );+ },+ ),+ ),+);+Future<void> showProjectAction(BuildContext context,SuperTabController c,@@ -20,6 +88,10 @@ Future<void> showProjectAction(await _deleteProject(context, c, project);return;}+ if (action == 'details') {+ await _showProjectDetails(context, c, project);+ return;+ }var name = project.name;var visibility = project.isPrivate ? 'private' : 'public';final members = project.memberIds.toSet();@@ -31,7 +103,7 @@ Future<void> showProjectAction(builder: (context) => SuperTabDialogScope(controller: c,projectId: project.id,- requireWrite: action != 'details',+ requireWrite: true,child: StatefulBuilder(builder: (context, update) => ListenableBuilder(listenable: c,@@ -39,16 +111,13 @@ Future<void> showProjectAction(final current = c.snapshot?.projects.where((p) => p.id == project.id).firstOrNull;- final group = c.snapshot?.conversation(project.leadConversationId);final canManage = current?.ownerId == c.accountId;- final readOnly = action == 'details';return AlertDialog(title: Text(switch (action) {'rename' => 'Rename project','sharing' => 'Sharing','skills' => 'Instructions for this project',- 'cadence' => 'Project updates',- _ => 'Project details',+ _ => 'Project updates',}),content: SizedBox(width: 400,@@ -57,11 +126,6 @@ Future<void> showProjectAction(mainAxisSize: MainAxisSize.min,crossAxisAlignment: CrossAxisAlignment.start,children: [- // Whether teammates' agents can push to its repository, and what to do about it.- if (action == 'details') ...[- ProjectGitHubAccess(controller: c, projectId: project.id),- const SizedBox(height: 16),- ],if (action == 'rename')TextFormField(autofocus: true,@@ -221,34 +285,6 @@ Future<void> showProjectAction(),],),- if (readOnly) ...[- Text(- current?.name ?? project.name,- style: DesktopChrome.text(medium: true),- ),- const SizedBox(height: 12),- Text(- group?.brief.isNotEmpty == true ? group!.brief : 'Discuss the project with its product manager to define the work.',- style: DesktopChrome.text(),- ),- const SizedBox(height: 16),- Text('Repository', style: DesktopChrome.metadata()),- SelectableText(- current?.repository?['repositoryUrl'] as String? ??- current?.repository?['cwd'] as String? ??- 'Not set',- ),- const SizedBox(height: 16),- Text(- 'Product Manager',- style: DesktopChrome.metadata(),- ),- Text(- group?.leadId == null- ? 'Starting…'- : c.snapshot!.agentName(group!.leadId!),- ),- ],if (c.operationError != null) ...[const SizedBox(height: 12),Text(c.operationError!),@@ -265,49 +301,48 @@ Future<void> showProjectAction(actions: [TextButton(onPressed: busy ? null : () => Navigator.pop(context),- child: Text(readOnly ? 'Close' : 'Cancel'),+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed:+ busy ||+ c.saving ||+ c.hasPendingAction ||+ name.trim().isEmpty ||+ (action == 'skills' &&+ mode == 'custom' &&+ current?.roles == null) ||+ (action != 'cadence' && !canManage)+ ? null+ : () async {+ update(() => busy = true);+ final result = await c.command({+ 'type':+ 'project.${action == 'rename'+ ? 'rename'+ : action == 'sharing'+ ? 'sharing'+ : action == 'skills'+ ? 'skills'+ : 'cadence'}',+ 'projectId': project.id,+ if (action == 'rename') 'name': name.trim(),+ if (action == 'sharing') ...{+ 'visibility': visibility,+ 'memberIds': members.toList(),+ },+ if (action == 'cadence') 'minutes': minutes,+ if (action == 'skills') 'mode': mode,+ });+ if (!context.mounted) return;+ if (result != null) {+ Navigator.pop(context);+ } else {+ update(() => busy = false);+ }+ },+ child: const Text('Save'),),- if (!readOnly)- FilledButton(- onPressed:- busy ||- c.saving ||- c.hasPendingAction ||- name.trim().isEmpty ||- (action == 'skills' &&- mode == 'custom' &&- current?.roles == null) ||- (action != 'cadence' && !canManage)- ? null- : () async {- update(() => busy = true);- final result = await c.command({- 'type':- 'project.${action == 'rename'- ? 'rename'- : action == 'sharing'- ? 'sharing'- : action == 'skills'- ? 'skills'- : 'cadence'}',- 'projectId': project.id,- if (action == 'rename') 'name': name.trim(),- if (action == 'sharing') ...{- 'visibility': visibility,- 'memberIds': members.toList(),- },- if (action == 'cadence') 'minutes': minutes,- if (action == 'skills') 'mode': mode,- });- if (!context.mounted) return;- if (result != null) {- Navigator.pop(context);- } else {- update(() => busy = false);- }- },- child: const Text('Save'),- ),],);},diff --git a/desktop/lib/super_tabs/roles_editor.dart b/desktop/lib/super_tabs/roles_editor.dartindex 6e43ed31d..9deb95ff5 100644--- a/desktop/lib/super_tabs/roles_editor.dart+++ b/desktop/lib/super_tabs/roles_editor.dart@@ -69,7 +69,7 @@ Keep each Builder's list a few tasks deep; do the easy, self-contained parts fir- When a worker finishes: reuse, keep or stop. Prefer stop.## 5. Review and accept-- Work that will be merged, or carries medium risk or more, gets a Reviewer: create "Review: <group>", route it, assign it, and add the Reviewer to the Builder's group.+- Work that will be merged, or carries medium risk or more, gets a Reviewer. When its Builder marks ready for review with a pull request link, the Swarm opens "Review: <group>", assigns a free Reviewer and tells you in one line; cancel it there if it is not needed. When no Reviewer is free, route it, start one, assign it and add it to the Builder's group. Without a pull request link, create the review group yourself the same way.- Findings go back to the Builder; you rule on disagreements.- Accept only when the reviewed revision is the handed-off revision, its checks have evidence, and CI is green on it.- Close the task saying what was and was not delivered.@@ -127,7 +127,7 @@ You finish one group's work completely, inside its brief, as if nobody will come## 4. Hand off- Ready means: your branch pushed, a PR when the project uses PRs, and green CI on it.- The handoff opens "Ready: yes" or "Ready: no", then: revision, what you checked (command and result), what is not shown yet, the one command or action left for the real device or person if any, and "most likely wrong here".-- Mark ready for review when the group has a Reviewer; otherwise mark done.+- Mark ready for review, with the revision and the PR link, when the work needs review: the Swarm opens the review from your handoff. Otherwise mark done.## 5. Review findings- Check each finding against the code; push back with evidence when it is wrong.diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dartindex 0a24f8707..0e7445ea6 100644--- a/desktop/lib/super_tabs/roster.dart+++ b/desktop/lib/super_tabs/roster.dart@@ -17,6 +17,7 @@ import '../widgets/engine_identity.dart';import '../widgets/harness_activity_mark.dart';import 'agent_details.dart';import 'controller.dart';+import 'detail_dialog.dart';import 'dialog_scope.dart';import 'identity.dart';import 'leaderboard/format.dart';@@ -246,20 +247,27 @@ class _SuperTabRosterState extends State<SuperTabRoster> {Future<void> _person(SuperTabPerson person, SuperTabPersonScore? score) =>showAppDialog<void>(context: context,- builder: (context) => AlertDialog(- title: Text(leaderboardName(person, score)),- content: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text('${person.email}\n${person.role}'),- if (score != null) ...[- const SizedBox(height: 12),- LeaderboardPersonWeek(score: score),- ],- ],- ),+ builder: (context) => SuperTabDetailDialog(+ title: leaderboardName(person, score),+ // Who they are on one line under the name (Ken, 2026-10-28).+ detail:+ '${person.email} · ${switch (person.role) {+ 'owner' => 'Owner',+ 'viewer' => 'Can view',+ _ => 'Can collaborate',+ }}',+ leading: SuperTabAvatar.person(person, size: 40),+ body: score == null+ ? const SizedBox.shrink()+ : LeaderboardPersonWeek(score: score),actions: [+ TextButton(+ onPressed: () {+ Navigator.pop(context);+ widget.onInvite();+ },+ child: const Text('Manage people'),+ ),if (person.id == c.accountId && c.canWrite)TextButton(key: const ValueKey('super-profile-edit'),@@ -269,17 +277,6 @@ class _SuperTabRosterState extends State<SuperTabRoster> {},child: const Text('Edit profile'),),- TextButton(- onPressed: () {- Navigator.pop(context);- widget.onInvite();- },- child: const Text('Manage people'),- ),- TextButton(- onPressed: () => Navigator.pop(context),- child: const Text('Close'),- ),],),);@@ -438,7 +435,7 @@ class _SuperTabRosterState extends State<SuperTabRoster> {SuperTabAvatar.agent(agent,name: name,- size: 24,+ size: SuperTabAvatar.rowSize,engineBadge: false,),const SizedBox(width: 8),diff --git a/desktop/lib/super_tabs/sharing.dart b/desktop/lib/super_tabs/sharing.dartindex ed7778a2a..f28f90baf 100644--- a/desktop/lib/super_tabs/sharing.dart+++ b/desktop/lib/super_tabs/sharing.dart@@ -7,8 +7,8 @@ import '../shared/theme/app_icons.dart';import '../shared/widgets/app_dialog.dart';import '../shared/widgets/app_select_field.dart';import '../widgets/desktop_chrome.dart';-import '../widgets/desktop_prompt_surface.dart';import 'controller.dart';+import 'detail_dialog.dart';import 'dialog_scope.dart';import 'join_link.dart';import 'model.dart';@@ -317,6 +317,45 @@ class _SwarmSharingDialogState extends State<SwarmSharingDialog> {);}+ /// The email, its access and Invite on one line; with enlarged text, the email above the other two.+ Widget _inviteRow(Widget email, Widget role, Widget invite) => LayoutBuilder(+ builder: (context, constraints) {+ final roomy =+ constraints.maxWidth >= 360 &&+ MediaQuery.textScalerOf(context).scale(13) <= 20;+ return roomy+ ? Row(+ children: [+ Expanded(child: email),+ const SizedBox(width: DesktopChrome.controlGap),+ role,+ const SizedBox(width: DesktopChrome.controlGap),+ invite,+ ],+ )+ : Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ email,+ const SizedBox(height: DesktopChrome.controlGap),+ Row(+ children: [+ Flexible(child: role),+ const Spacer(),+ invite,+ ],+ ),+ ],+ );+ },+ );++ static Widget _explained(String? why, Widget control) =>+ why == null ? control : Tooltip(message: why, child: control);++ /// A row's own control: text with no pill, its fill only on hover.+ static final _quiet = superTabQuietAction;+static const _roles = [SelectOption(value: 'collaborator', label: 'Can collaborate'),SelectOption(value: 'viewer', label: 'Can view'),@@ -343,19 +382,22 @@ class _SwarmSharingDialogState extends State<SwarmSharingDialog> {: 'Can collaborate',style: DesktopChrome.metadata(),),- if (_removeReason(person) case final reason?)- Text(reason, style: DesktopChrome.metadata()),],),),if (person.role != 'owner' &&(c.isOwner || person.id == c.accountId)) ...[const SizedBox(width: 8),- TextButton(- onPressed: _busy || _removeReason(person) != null- ? null- : () => _remove(person),- child: Text(person.id == c.accountId ? 'Leave' : 'Remove'),+ // Quiet, and why it is unavailable on hover rather than as a sentence in the list (Ken, 2026-10-28).+ _explained(+ _removeReason(person),+ TextButton(+ style: _quiet,+ onPressed: _busy || _removeReason(person) != null+ ? null+ : () => _remove(person),+ child: Text(person.id == c.accountId ? 'Leave' : 'Remove'),+ ),),],],@@ -381,6 +423,7 @@ class _SwarmSharingDialogState extends State<SwarmSharingDialog> {if (c.isOwner) ...[const SizedBox(width: 8),TextButton(+ style: _quiet,onPressed: _busy? null: () => c.command({@@ -399,274 +442,194 @@ class _SwarmSharingDialogState extends State<SwarmSharingDialog> {@overrideWidget build(BuildContext context) => ListenableBuilder(listenable: c,- builder: (context, _) => Dialog(- backgroundColor: Colors.transparent,- elevation: 0,- shape: DesktopChrome.bareDialogShape,- child: DesktopDialogSurface(- child: SizedBox(- width: 460,- child: Padding(- padding: const EdgeInsets.all(24),- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- DesktopDialogHeader(- title: 'Share Swarm',- padding: EdgeInsets.zero,- onClose: () => Navigator.pop(context),+ builder: (context, _) => SuperTabDetailDialog(+ title: 'Share Swarm',+ body: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (c.isOwner) ...[+ _inviteRow(+ TextField(+ key: const Key('swarm-invite-email'),+ controller: _email,+ autofocus: true,+ enabled: !_busy,+ keyboardType: TextInputType.emailAddress,+ textInputAction: TextInputAction.send,+ decoration: const InputDecoration(hintText: 'Email address'),+ onSubmitted: (_) => _invite(),+ ),+ _select(+ key: const Key('swarm-invite-role'),+ value: _inviteRole,+ label: 'Invitation access',+ options: _roles,+ quiet: true,+ onChanged: (value) => setState(() => _inviteRole = value),+ ),+ // One primary action at a time: while a sharing change waits for Save, Invite steps back.+ (_pending != null || _changed+ ? OutlinedButton.new+ : FilledButton.new)(+ key: const Key('swarm-invite-send'),+ onPressed: _busy || _email.text.trim().isEmpty ? null : _invite,+ child: const Text('Invite'),+ ),+ ),+ if (_emailError != null)+ Padding(+ padding: const EdgeInsets.only(top: 8),+ child: Text(_emailError!, style: DesktopChrome.metadata()),+ ),+ const SizedBox(height: 24),+ Text('General access', style: DesktopChrome.control(medium: true)),+ const SizedBox(height: 8),+ if (_loading)+ const LinearProgressIndicator()+ else if (_settings != null) ...[+ _select(+ key: const Key('swarm-general-access'),+ value: _mode,+ label: 'General access',+ options: const [+ SelectOption(value: 'invited', label: 'Invited people'),+ SelectOption(value: 'domain', label: 'Anyone at a domain'),+ SelectOption(value: 'link', label: 'Anyone with the link'),+ ],+ onChanged: (value) => setState(() {+ _mode = value;+ _copied = false;+ if (value == 'domain' && _domain.text.isEmpty) {+ final email = c.snapshot!.people+ .where((p) => p.id == c.accountId)+ .firstOrNull+ ?.email;+ if (email != null && email.contains('@')) {+ _domain.text = email.split('@').last;+ }+ }+ }),+ ),+ if (_mode == 'domain') ...[+ const SizedBox(height: 8),+ TextField(+ key: const Key('swarm-sharing-domain'),+ controller: _domain,+ enabled: !_busy,+ keyboardType: TextInputType.url,+ decoration: const InputDecoration(hintText: 'example.com'),),- const SizedBox(height: 16),- Flexible(- child: DesktopPromptScrollBody(- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- if (c.isOwner) ...[- Row(- children: [- Expanded(- child: TextField(- key: const Key('swarm-invite-email'),- controller: _email,- autofocus: true,- enabled: !_busy,- keyboardType: TextInputType.emailAddress,- textInputAction: TextInputAction.send,- decoration: const InputDecoration(- hintText: 'Email address',- ),- onSubmitted: (_) => _invite(),- ),- ),- const SizedBox(width: 8),- FilledButton(- key: const Key('swarm-invite-send'),- onPressed: _busy || _email.text.trim().isEmpty- ? null- : _invite,- child: const Text('Invite'),- ),- ],- ),- if (_emailError != null)- Padding(- padding: const EdgeInsets.only(top: 8),- child: Text(- _emailError!,- style: DesktopChrome.metadata(),- ),- ),- const SizedBox(height: 8),- Align(- alignment: Alignment.centerLeft,- child: _select(- key: const Key('swarm-invite-role'),- value: _inviteRole,- label: 'Invitation access',- options: _roles,- quiet: true,- onChanged: (value) =>- setState(() => _inviteRole = value),- ),- ),- const SizedBox(height: 24),- Text(- 'General access',- style: DesktopChrome.control(medium: true),- ),- const SizedBox(height: 8),- if (_loading)- const LinearProgressIndicator()- else if (_settings != null) ...[- _select(- key: const Key('swarm-general-access'),- value: _mode,- label: 'General access',- options: const [- SelectOption(- value: 'invited',- label: 'Invited people',- ),- SelectOption(- value: 'domain',- label: 'Anyone at a domain',- ),- SelectOption(- value: 'link',- label: 'Anyone with the link',- ),- ],- onChanged: (value) => setState(() {- _mode = value;- _copied = false;- if (value == 'domain' && _domain.text.isEmpty) {- final email = c.snapshot!.people- .where((p) => p.id == c.accountId)- .firstOrNull- ?.email;- if (email != null && email.contains('@')) {- _domain.text = email.split('@').last;- }- }- }),- ),- if (_mode == 'domain') ...[- const SizedBox(height: 8),- TextField(- key: const Key('swarm-sharing-domain'),- controller: _domain,- enabled: !_busy,- keyboardType: TextInputType.url,- decoration: const InputDecoration(- hintText: 'example.com',- ),- ),- ],- if (_mode != 'invited') ...[- const SizedBox(height: 8),- Align(- alignment: Alignment.centerLeft,- child: _select(- key: const Key('swarm-sharing-role'),- value: _role,- label: 'General access role',- options: _roles,- quiet: true,- onChanged: (value) =>- setState(() => _role = value),- ),- ),- const SizedBox(height: 8),- Text(- 'Private projects stay private.',- style: DesktopChrome.metadata(),- ),- ],- ],- if (_sharingError != null) ...[- const SizedBox(height: 8),- Text(- _sharingError!,- style: DesktopChrome.metadata(),- ),- if (_settings == null)- Align(- alignment: Alignment.centerLeft,- child: TextButton(- onPressed: _load,- child: const Text('Retry'),- ),- ),- ],- const SizedBox(height: 24),- ],- Align(- alignment: Alignment.centerLeft,- child: TextButton.icon(- key: const Key('swarm-sharing-people'),- style: TextButton.styleFrom(- backgroundColor: Colors.transparent,- side: BorderSide.none,- padding: EdgeInsets.zero,- ),- onPressed: () => setState(- () => _peopleExpanded = !_peopleExpanded,- ),- icon: Icon(- _peopleExpanded- ? AppIcons.chevronDown- : AppIcons.chevronRight,- size: 16,- ),- label: const Text('People with access'),- ),- ),- if (_peopleExpanded) _people(),- if (c.operationError != null)- Padding(- padding: const EdgeInsets.only(top: 8),- child: Text(- c.operationError!,- style: DesktopChrome.metadata(),- ),- ),- if (c.hasPendingAction)- Align(- alignment: Alignment.centerLeft,- child: TextButton(- onPressed: c.saving ? null : c.retry,- child: const Text('Check pending invitation'),- ),- ),- ],- ),+ ],+ if (_mode != 'invited') ...[+ const SizedBox(height: 8),+ Align(+ alignment: Alignment.centerLeft,+ child: _select(+ key: const Key('swarm-sharing-role'),+ value: _role,+ label: 'General access role',+ options: _roles,+ quiet: true,+ onChanged: (value) => setState(() => _role = value),),),- const SizedBox(height: 24),- Wrap(- alignment: WrapAlignment.spaceBetween,- crossAxisAlignment: WrapCrossAlignment.center,- spacing: 8,- runSpacing: 8,- children: [- if (_joinUrl != null)- TextButton.icon(- key: const Key('swarm-copy-link'),- onPressed: _busy || _changed ? null : _copyLink,- icon: Icon(- _copied ? AppIcons.check : AppIcons.link2,- size: 16,- ),- label: Text(_copied ? 'Copied' : 'Copy link'),- )- else- const SizedBox.shrink(),- if (_mode == 'link' && !_changed && _joinUrl != null)- Tooltip(- message: 'Replace the link. The previous link will stop working.',- child: TextButton(- key: const Key('swarm-reset-link'),- style: TextButton.styleFrom(- backgroundColor: Colors.transparent,- side: BorderSide.none,- ),- onPressed: _busy ? null : () => _save(rotate: true),- child: const Text('Reset link'),- ),- ),- if (_pending != null || _changed)- FilledButton(- key: const Key('swarm-sharing-save'),- onPressed:- _saving ||- c.saving ||- c.hasPendingAction ||- !_domainValid- ? null- : () => _save(),- child: Text(- _saving- ? 'Saving…'- : _pending != null- ? 'Retry'- : 'Save',- ),- )- else- TextButton(- onPressed: () => Navigator.pop(context),- child: const Text('Done'),- ),- ],+ const SizedBox(height: 8),+ Text(+ 'Private projects stay private.',+ style: DesktopChrome.metadata(),),],+ ],+ if (_sharingError != null) ...[+ const SizedBox(height: 8),+ Text(_sharingError!, style: DesktopChrome.metadata()),+ if (_settings == null)+ Align(+ alignment: Alignment.centerLeft,+ child: TextButton(+ onPressed: _load,+ child: const Text('Retry'),+ ),+ ),+ ],+ const SizedBox(height: 24),+ ],+ Align(+ alignment: Alignment.centerLeft,+ child: TextButton.icon(+ key: const Key('swarm-sharing-people'),+ style: TextButton.styleFrom(+ backgroundColor: Colors.transparent,+ side: BorderSide.none,+ padding: EdgeInsets.zero,+ ),+ onPressed: () =>+ setState(() => _peopleExpanded = !_peopleExpanded),+ icon: Icon(+ _peopleExpanded ? AppIcons.chevronDown : AppIcons.chevronRight,+ size: 16,+ ),+ label: const Text('People with access'),),),- ),+ if (_peopleExpanded) _people(),+ if (c.operationError != null)+ Padding(+ padding: const EdgeInsets.only(top: 8),+ child: Text(c.operationError!, style: DesktopChrome.metadata()),+ ),+ if (c.hasPendingAction)+ Align(+ alignment: Alignment.centerLeft,+ child: TextButton(+ onPressed: c.saving ? null : c.retry,+ child: const Text('Check pending invitation'),+ ),+ ),+ ],),+ leadingActions: [+ if (_joinUrl != null)+ TextButton.icon(+ key: const Key('swarm-copy-link'),+ onPressed: _busy || _changed ? null : _copyLink,+ icon: Icon(_copied ? AppIcons.check : AppIcons.link2, size: 16),+ label: Text(_copied ? 'Copied' : 'Copy link'),+ ),+ if (_mode == 'link' && !_changed && _joinUrl != null)+ Tooltip(+ message: 'Replace the link. The previous link will stop working.',+ child: TextButton(+ key: const Key('swarm-reset-link'),+ style: _quiet,+ onPressed: _busy ? null : () => _save(rotate: true),+ child: const Text('Reset link'),+ ),+ ),+ ],+ actions: [+ if (_pending != null || _changed)+ FilledButton(+ key: const Key('swarm-sharing-save'),+ onPressed:+ _saving || c.saving || c.hasPendingAction || !_domainValid+ ? null+ : () => _save(),+ child: Text(+ _saving+ ? 'Saving…'+ : _pending != null+ ? 'Retry'+ : 'Save',+ ),+ )+ else+ TextButton(+ onPressed: () => Navigator.pop(context),+ child: const Text('Done'),+ ),+ ],),);}diff --git a/desktop/lib/super_tabs/team_glance.dart b/desktop/lib/super_tabs/team_glance.dartindex 1d6bedc8d..1314139f3 100644--- a/desktop/lib/super_tabs/team_glance.dart+++ b/desktop/lib/super_tabs/team_glance.dart@@ -167,6 +167,13 @@ class SuperTabGlanceMachine {int get busy => agents.where((a) => a.$2.busy).length;}+/// One thing that looks wrong, and the agents it is about, which the glance folds under it.+class SuperTabGlanceWarning {+ const SuperTabGlanceWarning(this.text, [this.names = const []]);+ final String text;+ final List<String> names;+}+class SuperTabTeamGlance {SuperTabTeamGlance._(this.machines, this.models, this.warnings);@@ -174,7 +181,7 @@ class SuperTabTeamGlance {/// "opus high" and how many agents run it, most first.final List<(String, int)> models;- final List<String> warnings;+ final List<SuperTabGlanceWarning> warnings;factory SuperTabTeamGlance.of(SuperTabController c,@@ -215,7 +222,8 @@ class SuperTabTeamGlance {);}final models = <String, int>{};- final warnings = <String>[];+ final warnings = <SuperTabGlanceWarning>[];+ final efforts = <(String, String, String)>[];for (final agent in snapshot.agents) {final info = SuperTabAgentInfo(c, app, agent);final glance = superTabAgentGlance(info, now: at);@@ -233,19 +241,51 @@ class SuperTabTeamGlance {if (glance.recordedEffort case final recorded?when glance.requestedEffort != null &&recorded != glance.requestedEffort) {- warnings.add(- '$name runs effort $recorded; its start asked for ${glance.requestedEffort}.',- );+ efforts.add((name, recorded, glance.requestedEffort!));}}+ // One line per offline machine and one for every effort that differs, not one per agent (Ken, 2026-10-28).for (final machine in machines.values) {if (machine.status != SuperTabMachineStatus.offline) continue;- for (final (name, _) in machine.agents.where((a) => a.$2.busy)) {- warnings.add('$name is busy on ${machine.name}, which is offline.');+ final busy = [+ for (final (name, agent) in machine.agents)+ if (agent.busy) name,+ ];+ if (busy.length == 1) {+ warnings.add(+ SuperTabGlanceWarning(+ '${busy.single} is busy on ${machine.name}, which is offline.',+ ),+ );+ } else if (busy.isNotEmpty) {+ warnings.add(+ SuperTabGlanceWarning(+ '${busy.length} agents are busy on ${machine.name}, which is offline.',+ busy,+ ),+ );}}+ if (efforts.length == 1) {+ final (name, recorded, requested) = efforts.single;+ warnings.add(+ SuperTabGlanceWarning(+ '$name runs at $recorded effort; it was started at $requested.',+ ),+ );+ } else if (efforts.isNotEmpty) {+ warnings.add(+ SuperTabGlanceWarning(+ '${efforts.length} agents run at another effort than they were started with.',+ [+ for (final (name, recorded, requested) in efforts)+ '$name ($recorded, started at $requested)',+ ],+ ),+ );+ }if (_pileUp(machines.values.toList()) case final warning?) {- warnings.insert(0, warning);+ warnings.insert(0, SuperTabGlanceWarning(warning));}return SuperTabTeamGlance._(machines.values.toList(),diff --git a/desktop/lib/super_tabs/team_glance_panel.dart b/desktop/lib/super_tabs/team_glance_panel.dartindex 22e4d4915..2dd914dc8 100644--- a/desktop/lib/super_tabs/team_glance_panel.dart+++ b/desktop/lib/super_tabs/team_glance_panel.dart@@ -6,9 +6,14 @@ import '../shared/widgets/app_dialog.dart';import '../state/app_state.dart';import '../widgets/desktop_chrome.dart';import 'controller.dart';+import 'detail_dialog.dart';import 'machine_status.dart';import 'team_glance.dart';+/// The spacing scale's steps (4, 8, 12) from the shared control gap, as the leaderboard rows take them.+const _gap = DesktopChrome.controlGap;+const _halfGap = _gap / 2;+/// Opens Team at a glance over the Swarm, live: it follows the Swarm as it changes.Future<void> showSuperTabTeamGlance(BuildContext context,@@ -16,24 +21,18 @@ Future<void> showSuperTabTeamGlance(AppNotifier? app,) => showAppDialog<void>(context: context,- builder: (context) => AlertDialog(- title: const Text('Team at a glance'),- content: ListenableBuilder(+ builder: (context) => SuperTabDetailDialog(+ title: 'Team at a glance',+ body: ListenableBuilder(listenable: Listenable.merge([c, ?app]),builder: (context, _) =>SuperTabTeamGlancePanel(glance: SuperTabTeamGlance.of(c, app)),),- actions: [- TextButton(- onPressed: () => Navigator.pop(context),- child: const Text('Close'),- ),- ],),);-/// The glance as one column of at most [width], so another panel (a leaderboard) can sit beside it; narrower on a-/// phone.+/// The glance as one column of at most [width]: what looks wrong, each machine with its agents by state, and the+/// models in use, in the details dialogs' label and value rows.class SuperTabTeamGlancePanel extends StatelessWidget {const SuperTabTeamGlancePanel({super.key, required this.glance});final SuperTabTeamGlance glance;@@ -42,64 +41,119 @@ class SuperTabTeamGlancePanel extends StatelessWidget {@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);- Widget heading(String text) => Padding(- padding: const EdgeInsets.only(top: 16, bottom: 6),- child: Text(- text,- style: DesktopChrome.metadata().copyWith(fontWeight: FontWeight.w600),- ),- );return ConstrainedBox(constraints: const BoxConstraints(maxWidth: width),- child: SingleChildScrollView(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- mainAxisSize: MainAxisSize.min,- children: [- if (glance.warnings.isEmpty)- Text('Nothing looks wrong.', style: DesktopChrome.metadata())- else- for (final warning in glance.warnings) _Warning(warning),- heading('Machines'),- for (final machine in glance.machines) _Machine(machine),- heading('Models'),- Column(- key: const ValueKey('glance-models'),- crossAxisAlignment: CrossAxisAlignment.start,- children: [- for (final (model, count) in glance.models)- Text('$model · $count', style: DesktopChrome.control()),- ],- ),- ],- ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ if (glance.warnings.isEmpty)+ Text('Nothing looks wrong.', style: DesktopChrome.metadata())+ else+ for (final warning in glance.warnings) _Warning(warning),+ SuperTabDetailSection(+ title: 'Machines',+ children: [+ for (final machine in glance.machines) _Machine(machine),+ ],+ ),+ SuperTabDetailSection(+ title: 'Models',+ children: [+ Column(+ key: const ValueKey('glance-models'),+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ for (final (model, count) in glance.models)+ Padding(+ padding: const EdgeInsets.symmetric(+ vertical: _halfGap / 2,+ ),+ child: Text(+ '$model · $count',+ style: DesktopChrome.control(),+ ),+ ),+ ],+ ),+ ],+ ),+ ],),);}}-class _Warning extends StatelessWidget {- const _Warning(this.text);- final String text;+/// A warning, and the agents it is about folded beneath it: the first three, the rest a click away.+class _Warning extends StatefulWidget {+ const _Warning(this.warning);+ final SuperTabGlanceWarning warning;@override- Widget build(BuildContext context) => Padding(- padding: const EdgeInsets.only(bottom: 6),- child: Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Icon(- AppIcons.triangleAlert,- size: 16,- color: grid.AppPalette.warn,- ),- const SizedBox(width: 6),- Expanded(child: Text(text, style: DesktopChrome.control())),- ],- ),- );+ State<_Warning> createState() => _WarningState();+}++class _WarningState extends State<_Warning> {+ static const _shown = 3;+ bool _expanded = false;++ @override+ Widget build(BuildContext context) {+ final names = widget.warning.names;+ final folded = !_expanded && names.length > _shown;+ final list = folded+ ? '${names.take(_shown).join(', ')} and ${names.length - _shown} more'+ : names.join(', ');+ return Padding(+ padding: const EdgeInsets.only(bottom: _gap),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Padding(+ padding: const EdgeInsets.only(top: _halfGap / 4),+ child: Icon(+ AppIcons.triangleAlert,+ size: grid.AppControl.iconSize,+ color: grid.AppPalette.warn,+ ),+ ),+ const SizedBox(width: 8),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(widget.warning.text, style: DesktopChrome.control()),+ if (names.isNotEmpty)+ Padding(+ padding: const EdgeInsets.only(top: _halfGap / 2),+ child: folded+ ? MouseRegion(+ cursor: SystemMouseCursors.click,+ child: GestureDetector(+ onTap: () => setState(() => _expanded = true),+ child: Semantics(+ button: true,+ hint: 'Shows every name',+ child: Text(+ list,+ style: DesktopChrome.metadata(),+ ),+ ),+ ),+ )+ : Text(list, style: DesktopChrome.metadata()),+ ),+ ],+ ),+ ),+ ],+ ),+ );+ }}+/// A machine as the machine details read it: its name, its state and slots, then its agents grouped by what they+/// are doing, one label and value row per state.class _Machine extends StatelessWidget {const _Machine(this.machine);final SuperTabGlanceMachine machine;@@ -120,32 +174,35 @@ class _Machine extends StatelessWidget {}@override- Widget build(BuildContext context) => Padding(- key: ValueKey('glance-machine-${machine.id}'),- padding: const EdgeInsets.only(bottom: 10),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Wrap(- spacing: 8,- crossAxisAlignment: WrapCrossAlignment.end,- children: [- Text(machine.name, style: DesktopChrome.control()),- Text(_summary, style: DesktopChrome.metadata()),- ],- ),- if (machine.agents.isEmpty)- Text('No agents', style: DesktopChrome.metadata())- else- for (final (name, agent) in machine.agents)+ Widget build(BuildContext context) {+ final byState = <String, List<String>>{};+ for (final (name, agent) in machine.agents) {+ (byState[agent.label] ??= []).add(name);+ }+ return Padding(+ key: ValueKey('glance-machine-${machine.id}'),+ padding: const EdgeInsets.only(top: _gap, bottom: _halfGap),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Wrap(+ spacing: 8,+ crossAxisAlignment: WrapCrossAlignment.end,+ children: [+ Text(machine.name, style: DesktopChrome.control(medium: true)),+ Text(_summary, style: DesktopChrome.metadata()),+ ],+ ),+ if (byState.isEmpty)Padding(- padding: const EdgeInsets.only(left: 12),- child: Text(- '$name · ${agent.label}',- style: DesktopChrome.metadata(),- ),- ),- ],- ),- );+ padding: const EdgeInsets.only(top: _halfGap),+ child: Text('No agents', style: DesktopChrome.metadata()),+ )+ else+ for (final MapEntry(key: state, value: names) in byState.entries)+ SuperTabDetailRow(label: state, value: names.join(', ')),+ ],+ ),+ );+ }}diff --git a/desktop/lib/super_tabs/terminal_unavailable.dart b/desktop/lib/super_tabs/terminal_unavailable.dartindex bdab8ea91..5cbc6cada 100644--- a/desktop/lib/super_tabs/terminal_unavailable.dart+++ b/desktop/lib/super_tabs/terminal_unavailable.dart@@ -33,9 +33,7 @@ String superTabTerminalUnavailable({// A private session is never shared, so no update or Retry brings it here. River, Ken's Product Manager, read// "update and restart Harness" to every member while that Mac ran the latest Harness (2026-10-28).if (superTabTerminalPrivate(snapshot, agent)) {- return snapshot.isLead(agent.id)- ? '$name is the Product Manager and reads private chats, so only $owner can watch its terminal.'- : '$name reads private chats, so only $owner can watch its terminal.';+ return '$name reads private chats, so only $owner can watch its terminal.';}final where = '$name runs on $computer, $owner’s computer';if (_swarmOffline(row, now ?? DateTime.now())) {@@ -45,9 +43,10 @@ String superTabTerminalUnavailable({'once it is up to date and running. Ask $owner to update and restart Harness, then Retry.';}-/// Whether an agent's terminal is private to the person whose computer runs it: it reads private chats.+/// Whether an agent's terminal is private to the person whose computer runs it: it reads private chats. The current+/// Product Manager is not, though the backend marks it: every member watches it, view only (Ken, 2026-10-28).bool superTabTerminalPrivate(SuperTabSnapshot snapshot, SuperTabAgent agent) =>- agent.confidential || snapshot.isLead(agent.id);+ agent.confidential && !snapshot.isLead(agent.id);/// Whether the Swarm last heard from this machine long enough ago to call it offline. A machine the Swarm does not/// list is not called offline: what is known of it then is only that this account cannot see it.diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 47ef7122b..9db6833fe 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -15,6 +15,7 @@ import '../widgets/new_harness_paste.dart';import '../state/app_state.dart';import '../state/harness_attachments.dart';import '../state/workspace_chrome.dart';+import 'chat_scroll.dart';import 'roster.dart';import 'recording_notice.dart';import 'identity.dart' show superTabPersonName;@@ -86,7 +87,7 @@ class _SuperTabViewState extends State<SuperTabView>final _composer = TextEditingController();final _focus = FocusNode(debugLabel: 'Swarm message');final _pullRequestsFocus = FocusNode(debugLabel: 'Project pull requests');- final _scroll = <String, ScrollController>{};+ final _scroll = <String, SuperTabChatScroll>{};final _latest = <String, int>{};final _following = <String, bool>{};final _newAfter = <String, int>{};@@ -121,6 +122,9 @@ class _SuperTabViewState extends State<SuperTabView>final _built = <String, BuildContext>{};// Rows to keep in place once their conversation is on screen again.final _anchors = <String, ({String messageId, double top})>{};+ // Each list's dividing row: see [_splitAt].+ final _split = <String, SuperTabMessage>{};+ final _newerRows = UniqueKey();int _mentionIndex = 0;late final _tagBackspace = _TagBackspace(() => c.mentions(c.selectedId).values,@@ -205,6 +209,7 @@ class _SuperTabViewState extends State<SuperTabView>scroll.dispose();}_scroll.clear();+ _split.clear();_latest.clear();_following.clear();_newAfter.clear();@@ -234,7 +239,10 @@ class _SuperTabViewState extends State<SuperTabView>_replies.removeWhere((id, _) => !visible.contains(id));final id = c.selectedId;final firstView = !_scroll.containsKey(id);- final scroll = _scroll.putIfAbsent(id, ScrollController.new);+ final scroll = _scroll.putIfAbsent(+ id,+ () => SuperTabChatScroll(rows: () => _built.entries),+ );final atEnd = scroll.hasClients? scroll.position.extentAfter < 40: (_following[id] ?? true);@@ -820,6 +828,14 @@ class _SuperTabViewState extends State<SuperTabView>return first;}+ /// Near row [index] of [count]: the list measures only rows it built,+ /// from the top of what is read to its end.+ static double _estimate(ScrollPosition position, int index, int count) =>+ position.minScrollExtent ++ (position.maxScrollExtent - position.minScrollExtent) *+ (index + 1) /+ (count + 1);+/// Brings [anchor]'s row back to where it was in [id]'s list after rows/// arrived above it: near it by its place in the list until it is built,/// then exactly. A conversation no longer on screen does so on return;@@ -848,16 +864,17 @@ class _SuperTabViewState extends State<SuperTabView>(e) => e.message.id == anchor.messageId,);if (index < 0) return;- scroll.jumpTo(- position.maxScrollExtent * (index + 1) / (entries.length + 1),- );+ scroll.jumpTo(_estimate(position, index, entries.length));continue;}if ((top - anchor.top).abs() < .5) return;// The list's extent is an estimate until laid out there: only the// start bounds the jump, and the next frame measures the row again.scroll.jumpTo(- (position.pixels + top - anchor.top).clamp(0.0, double.infinity),+ (position.pixels + top - anchor.top).clamp(+ position.minScrollExtent,+ double.infinity,+ ),);}}@@ -1182,9 +1199,7 @@ class _SuperTabViewState extends State<SuperTabView>if (scroll == null || !scroll.hasClients || index < 0 || attempt > 20) {return;}- scroll.jumpTo(- scroll.position.maxScrollExtent * (index + 1) / (entries.length + 1),- );+ scroll.jumpTo(_estimate(scroll.position, index, entries.length));_revealTarget(id, attempt + 1, arrived: arrived);});WidgetsBinding.instance.scheduleFrame();@@ -1303,7 +1318,7 @@ class _SuperTabViewState extends State<SuperTabView>if (scroll == null || !scroll.hasClients || top == null) return;scroll.jumpTo((scroll.offset + top - back.top).clamp(- 0.0,+ scroll.position.minScrollExtent,scroll.position.maxScrollExtent,),);@@ -1944,6 +1959,89 @@ class _SuperTabViewState extends State<SuperTabView>),);+ static String _rowKey(String messageId) => 'super-row-$messageId';++ /// Where [id]'s list divides: the first row drawn when it opened. Older+ /// pages go above it and newer messages below, so neither moves the rows+ /// already there.+ int _splitAt(+ String id,+ List<({SuperTabMessage message, int interruptions})> entries,+ ) {+ if (entries.isEmpty) return 0;+ final split = _split[id];+ final at = split == null+ ? -1+ : entries.indexWhere(+ (e) => superTabMessageOrder(e.message, split) >= 0,+ );+ if (at >= 0) return at;+ _split[id] = entries.first.message;+ return 0;+ }++ /// The rows that join the one above them, without their name: runs of+ /// one author's short updates, three to a group. Groups are counted from+ /// the list's dividing row both ways, so a page read in above regroups+ /// none of the rows already shown.+ static Set<String> _joined(+ List<SuperTabMessage> messages,+ SuperTabMessage? split,+ ) {+ final at = split == null+ ? -1+ : messages.indexWhere((m) => superTabMessageOrder(m, split) >= 0);+ if (at <= 0) return SuperTabMessageRow.consecutiveUpdates(messages);+ final joined = SuperTabMessageRow.consecutiveUpdates(messages.sublist(at));+ // Above it, upward: each group, newest first, keeps the name on its+ // oldest row.+ var group = [at - 1];+ for (var i = at - 2; i >= -1; i--) {+ final newest = group.first;+ if (i >= 0 &&+ newest - i < 3 &&+ SuperTabMessageRow.groupsWith(messages[i + 1], messages[i]) &&+ SuperTabMessageRow.groupsWith(messages[newest], messages[i])) {+ group.add(i);+ continue;+ }+ for (final j in group.take(group.length - 1)) {+ joined.add(messages[j].id);+ }+ group = [i];+ }+ return joined;+ }++ /// Above the oldest row read: room for, or the button to read, earlier+ /// messages. Its spinner only when [near] the view, where it is seen.+ Widget _earlierRow({required bool near}) {+ final id = c.selectedId;+ if (!c.hasOlder(id)) return const SizedBox.shrink();+ // The button only after a read failed: near+ // the top, earlier pages read by themselves.+ if (_olderFailed.contains(id)) {+ return Align(+ child: TextButton(+ onPressed: () => unawaited(_earlier()),+ child: const Text('Earlier messages'),+ ),+ );+ }+ return SizedBox(+ height: 40,+ child: near && _loadingOlder.contains(id)+ ? const Center(+ child: SizedBox.square(+ key: ValueKey('super-earlier-loading'),+ dimension: 16,+ child: CircularProgressIndicator(strokeWidth: 2),+ ),+ )+ : null,+ );+ }+Widget _date(DateTime time) => Padding(padding: const EdgeInsets.fromLTRB(24, 20, 24, 4),child: Row(@@ -2009,7 +2107,63 @@ class _SuperTabViewState extends State<SuperTabView>final messages = _shownMessages(c.selectedId);final entries = superTabTranscriptEntries(messages);final byId = {for (final message in messages) message.id: message};- final grouped = SuperTabMessageRow.consecutiveUpdates(messages);+ final rowIndex = {+ for (final (index, entry) in entries.indexed)+ _rowKey(entry.message.id): index,+ };+ // A row stays the same row as pages arrive above it, state and all.+ int? rowOf(Key key) => key is ValueKey<String> ? rowIndex[key.value] : null;+ final split = _splitAt(c.selectedId, entries);+ final grouped = _joined(messages, _split[c.selectedId]);+ Widget row(int index) {+ final entry = entries[index];+ final message = entry.message;+ final agent = message.fromAgent+ ? c.snapshot?.agent(message.authorId)+ : null;+ final previous = index > 0 ? entries[index - 1].message : null;+ final time = message.createdAt;+ return Column(+ key: ValueKey(_rowKey(message.id)),+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (time != null &&+ !DateUtils.isSameDay(+ time.toLocal(),+ previous?.createdAt?.toLocal(),+ ))+ _date(time),+ // The message itself is kept in place: its+ // date moves above earlier ones as they come.+ _BuiltRow(+ id: message.id,+ rows: _built,+ child: KeyedSubtree(+ key: message.id == _target ? _targetKey : null,+ child: SuperTabMessageHighlight(+ on: message.id == _lit,+ child: entry.interruptions > 0+ ? SuperTabRecordingNotice(+ key: ValueKey('super-message-${message.id}'),+ author: _shownAuthor(c, message),+ count: entry.interruptions,+ onOpenTerminal: agent == null+ ? null+ : () => _openAgent(agent),+ )+ : _message(+ message,+ grouped.contains(message.id),+ byId,+ showReceipt: message.id == latestOwn?.id,+ ),+ ),+ ),+ ),+ ],+ );+ }+final newAfter = _newAfter[c.selectedId];final newCount = newAfter == null? 0@@ -2105,106 +2259,71 @@ class _SuperTabViewState extends State<SuperTabView>return false;},child: SelectionArea(- child: ListView.builder(+ child: CustomScrollView(controller: _scroll[c.selectedId],key: PageStorageKey('super-messages-${c.tabId}-${c.selectedId}',),- padding: const EdgeInsets.symmetric(vertical: 8),- itemCount: entries.length + 1 + outgoing.length,- itemBuilder: (context, index) {- if (index > entries.length) {- return _outgoingRow(- outgoing[index - 1 - entries.length],- messages,- byId,- );- }- if (index == 0) {- final id = c.selectedId;- if (!c.hasOlder(id)) {- return const SizedBox.shrink();- }- // The button only after a read failed: near- // the top, earlier pages read by themselves.- if (_olderFailed.contains(id)) {- return Align(- child: TextButton(- onPressed: () => unawaited(_earlier()),- child: const Text('Earlier messages'),- ),- );- }- return SizedBox(- height: 40,- child: _loadingOlder.contains(id)- ? const Center(- child: SizedBox.square(- key: ValueKey(- 'super-earlier-loading',- ),- dimension: 16,- child: CircularProgressIndicator(- strokeWidth: 2,- ),- ),- )- : null,- );- }- final entry = entries[index - 1];- final message = entry.message;- final agent = message.fromAgent- ? c.snapshot?.agent(message.authorId)- : null;- final previous = index > 1- ? entries[index - 2].message- : null;- final time = message.createdAt;- return Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- if (time != null &&- !DateUtils.isSameDay(- time.toLocal(),- previous?.createdAt?.toLocal(),- ))- _date(time),- // The message itself is kept in place: its- // date moves above earlier ones as they come.- _BuiltRow(- id: message.id,- rows: _built,- child: KeyedSubtree(- key: message.id == _target- ? _targetKey- : null,- child: SuperTabMessageHighlight(- on: message.id == _lit,- child: entry.interruptions > 0- ? SuperTabRecordingNotice(- key: ValueKey(- 'super-message-${message.id}',- ),- author: _shownAuthor(c, message),- count: entry.interruptions,- onOpenTerminal: agent == null- ? null- : () => _openAgent(agent),- )- : _message(- message,- grouped.contains(message.id),- byId,- showReceipt:- message.id == latestOwn?.id,- ),+ // Pages read in grow upward from the rows first+ // shown, new messages downward: no row on screen+ // moves for either.+ center: _newerRows,+ slivers: [+ // Its spinner runs only near the view.+ SliverLayoutBuilder(+ builder: (context, constraints) =>+ SliverToBoxAdapter(+ child: Padding(+ padding: EdgeInsets.only(+ top: grid.AppDesktop.controlGap,+ ),+ child: _earlierRow(+ near:+ constraints.remainingCacheExtent >+ 0,+ ),),),+ ),+ SliverList(+ delegate: SliverChildBuilderDelegate(+ (context, index) => row(split - 1 - index),+ childCount: split,+ findChildIndexCallback: (key) =>+ switch (rowOf(key)) {+ final i? when i < split => split - 1 - i,+ _ => null,+ },+ ),+ ),+ SliverPadding(+ key: _newerRows,+ padding: EdgeInsets.only(+ bottom: grid.AppDesktop.controlGap,+ ),+ sliver: SliverList(+ delegate: SliverChildBuilderDelegate(+ // Messages on their way end the list.+ (context, index) =>+ index < entries.length - split+ ? row(split + index)+ : _outgoingRow(+ outgoing[index -+ (entries.length - split)],+ messages,+ byId,+ ),+ childCount:+ entries.length - split + outgoing.length,+ findChildIndexCallback: (key) =>+ switch (rowOf(key)) {+ final i? when i >= split => i - split,+ _ => null,+ },),- ],- );- },+ ),+ ),+ ],),),),@@ -2926,6 +3045,19 @@ class _BuiltRowState extends State<_BuiltRow> {}}+ // A row taken out of the tree is not measured, even before it is disposed.+ @override+ void deactivate() {+ if (widget.rows[widget.id] == context) widget.rows.remove(widget.id);+ super.deactivate();+ }++ @override+ void activate() {+ super.activate();+ widget.rows[widget.id] = context;+ }+@overridevoid dispose() {if (widget.rows[widget.id] == context) widget.rows.remove(widget.id);diff --git a/desktop/lib/widgets/desktop_chrome.dart b/desktop/lib/widgets/desktop_chrome.dartindex 14e89d8d0..521c65209 100644--- a/desktop/lib/widgets/desktop_chrome.dart+++ b/desktop/lib/widgets/desktop_chrome.dart@@ -287,56 +287,104 @@ class DesktopPill extends StatelessWidget {/// The same heading and dismiss control for every list or task dialog./// A form can omit Close when its Cancel action already provides dismissal.+/// [leading] is an identity beside the title (an avatar); [trailing] are icon+/// controls that belong to the whole dialog, placed before Close.class DesktopDialogHeader extends StatelessWidget {const DesktopDialogHeader({super.key,required this.title,this.detail,this.onClose,+ this.leading,+ this.trailing = const [],this.padding = const EdgeInsets.fromLTRB(24, 24, 16, 16),});final String title;final String? detail;final VoidCallback? onClose;+ final Widget? leading;+ final List<Widget> trailing;final EdgeInsets padding;+ /// The icon controls' target, centred on the title's first line.+ static const _control = 32.0;+@override- Widget build(BuildContext context) => Padding(- padding: padding,- child: Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Expanded(- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Semantics(- header: true,- child: Text(title, style: DesktopChrome.heading()),+ Widget build(BuildContext context) {+ final style = DesktopChrome.heading();+ final measure = TextPainter(+ text: TextSpan(text: title, style: style),+ textDirection: Directionality.of(context),+ textScaler: MediaQuery.textScalerOf(context),+ maxLines: 1,+ )..layout();+ final line = measure.height;+ measure.dispose();+ final controls = trailing.isNotEmpty || onClose != null;+ // Whichever is shorter, the title line or a control, moves down to share the other's centre.+ final titleTop = controls ? ((_control - line) / 2).clamp(0.0, 99.0) : 0.0;+ final controlsTop = ((line - _control) / 2).clamp(0.0, 99.0);+ return Padding(+ padding: padding,+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ if (leading case final leading?) ...[+ leading,+ const SizedBox(width: 12),+ ],+ Expanded(+ child: Padding(+ padding: EdgeInsets.only(top: titleTop),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Semantics(header: true, child: Text(title, style: style)),+ if (detail != null) ...[+ const SizedBox(height: 4),+ Text(detail!, style: DesktopChrome.metadata()),+ ],+ ],),- if (detail != null) ...[- const SizedBox(height: 4),- Text(detail!, style: DesktopChrome.metadata()),- ],- ],- ),- ),- if (onClose != null) ...[- const SizedBox(width: 12),- IconButton(- tooltip: 'Close',- onPressed: onClose,- icon: const Icon(AppIcons.close, size: 16),- constraints: const BoxConstraints.tightFor(width: 32, height: 32),- padding: const EdgeInsets.all(8),- visualDensity: VisualDensity.standard,+ ),),+ if (controls)+ Padding(+ padding: EdgeInsets.only(top: controlsTop),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (trailing.isNotEmpty) ...[+ const SizedBox(width: 12),+ ...trailing,+ ],+ if (onClose != null) ...[+ SizedBox(width: trailing.isEmpty ? 12 : 4),+ IconButton(+ tooltip: 'Close',+ onPressed: onClose,+ icon: const Icon(AppIcons.close, size: 16),+ constraints: const BoxConstraints.tightFor(+ width: _control,+ height: _control,+ ),+ padding: const EdgeInsets.all(8),+ visualDensity: VisualDensity.standard,+ // The 32-point target itself, not padded to 48 below the title.+ style: const ButtonStyle(+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ ),+ ),+ ],+ ],+ ),+ ),],- ],- ),- );+ ),+ );+ }}/// Keep the identifying end of a branch name without reversing its textdiff --git a/desktop/test/product_delivery_test.dart b/desktop/test/product_delivery_test.dartindex 7ad6f2e04..e5635bafe 100644--- a/desktop/test/product_delivery_test.dart+++ b/desktop/test/product_delivery_test.dart@@ -17,9 +17,14 @@ void main() {late ProductMeasurement usage;late List<Map<String, dynamic>> attempts, accepted;var status = 200;- String? code, vocabulary;+ String? code, vocabulary, retryAfter;Completer<void>? hold;+ late DateTime clock;+ var random = 0.5;setUp(() async {+ clock = DateTime.utc(2026, 10, 28, 6);+ random = 0.5;+ retryAfter = null;attempts = [];accepted = [];status = 200;@@ -35,8 +40,11 @@ void main() {expect(request.headers.value('x-adapter-local'), '1');attempts.add(report);final responseStatus = status, responseCode = code;- final responseVocabulary = vocabulary;+ final responseVocabulary = vocabulary, responseRetryAfter = retryAfter;await hold?.future;+ if (responseRetryAfter != null) {+ request.response.headers.set('retry-after', responseRetryAfter);+ }if (responseStatus == 200) accepted.add(report);if (responseVocabulary != null) {request.response.headers.set(@@ -75,6 +83,8 @@ void main() {usage = ProductMeasurement(surface: 'desktop',automatic: false,+ now: () => clock,+ random: () => random,context: ProductUsageContext(release: '1.2.77',platform: 'macos',@@ -135,6 +145,7 @@ void main() {final first = jsonEncode(attempts.single);usage.begin(ProductFlow.connectUser)(ProductOutcome.ok);status = 200;+ clock = clock.add(const Duration(minutes: 30));await usage.flush();expect(jsonEncode(attempts.last), first);await usage.flush();@@ -144,6 +155,69 @@ void main() {expect(jsonEncode(accepted), isNot(contains('PRIVATE_')));});+ test('a busy answer holds the next report until its Retry-After', () async {+ (status, code, retryAfter) = (429, 'USAGE_BUSY', '90');+ usage.begin(ProductFlow.viewerLoad)(ProductOutcome.ok);+ await usage.flush();+ final first = attempts.single['id'];+ (status, code, retryAfter) = (200, null, null);+ // Without Retry-After this draw would wait 60 s; the answer asked for 90.+ clock = clock.add(const Duration(seconds: 89));+ await usage.flush();+ expect(attempts, hasLength(1));+ clock = clock.add(const Duration(seconds: 1));+ await usage.flush();+ expect(attempts, hasLength(2));+ expect(attempts.last['id'], first);+ expect(totals()['ui_desktop_viewer_load_ok'], 1);+ });++ test(+ 'refusals in a row wait under a doubling ceiling up to half an hour',+ () async {+ (status, code) = (503, 'USAGE_UNAVAILABLE');+ random = 0.75;+ usage.begin(ProductFlow.viewerLoad)(ProductOutcome.ok);+ // 0.75 of 2, 4, 8 and 16 minutes, then of the 30-minute ceiling.+ for (final wait in const [90, 180, 360, 720, 1350, 1350]) {+ final before = attempts.length;+ await usage.flush();+ expect(attempts, hasLength(before + 1));+ clock = clock.add(Duration(seconds: wait - 1));+ await usage.flush();+ expect(attempts, hasLength(before + 1), reason: 'held for $wait s');+ clock = clock.add(const Duration(seconds: 1));+ }+ // An answer ends the run: the next refusal waits from the start again.+ (status, code) = (200, null);+ await usage.flush();+ expect(totals()['ui_desktop_viewer_load_ok'], 1);+ (status, code) = (503, 'USAGE_UNAVAILABLE');+ usage.begin(ProductFlow.connectUser)(ProductOutcome.ok);+ await usage.flush();+ final refused = attempts.length;+ clock = clock.add(const Duration(seconds: 90));+ await usage.flush();+ expect(attempts, hasLength(refused + 1));+ },+ );++ test('an unreachable CLI is a refusal to wait out as well', () async {+ await server.close(force: true);+ await expectLater(+ api.productUsageReport({'counters': {}}),+ throwsA(+ isA<ProductReportFailure>()+ .having(+ (e) => e.measure,+ 'category',+ ProductHealthMeasure.reportFailureUnreachable,+ )+ .having((e) => e.backOff, 'waits', true),+ ),+ );+ });+test('a failure from an old account cannot enter the next account counters',() async {@@ -236,6 +310,18 @@ void main() {(401, 'PRIVATE_CODE', ProductHealthMeasure.reportFailureAuth),(403, null, ProductHealthMeasure.reportFailureAuth),(429, 'USAGE_BUSY', ProductHealthMeasure.reportFailureRateLimited),+ // A busy backend answers these 429 since 2026-10-28: the cause is kept.+ (+ 429,+ 'USAGE_WRITE_CONFLICT',+ ProductHealthMeasure.reportFailureWriteConflict,+ ),+ (+ 429,+ 'USAGE_TRANSACTION_FAILED',+ ProductHealthMeasure.reportFailureTransaction,+ ),+ (503, 'AUTH_SERVICE_UNAVAILABLE', ProductHealthMeasure.reportFailureAuth),(504, 'BACKEND_TIMEOUT', ProductHealthMeasure.reportFailureTimeout),(502, 'BACKEND_UNREACHABLE', ProductHealthMeasure.reportFailureUnreachable),(@@ -258,6 +344,7 @@ void main() {isA<ProductReportFailure>().having((e) => e.measure, 'category', measure).having((e) => e.permanent, 'retryable', false)+ .having((e) => e.backOff, 'waits', http == 429 || http >= 500).having((e) => e.toString(),'safe error',diff --git a/desktop/test/super_tab_chat_scroll_test.dart b/desktop/test/super_tab_chat_scroll_test.dartnew file mode 100644index 000000000..f8d3b2878--- /dev/null+++ b/desktop/test/super_tab_chat_scroll_test.dart@@ -0,0 +1,336 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';++/// The chat never moves what the reader is looking at by itself: rows above+/// the view changing height, pages read in above, or the newest row growing+/// while the reader is at the end.+void main() {+ Future<SuperTabController> show(+ WidgetTester tester,+ ConversationServer server,+ ) async {+ final c = server.controller();+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ return c;+ }++ // Reading saves the place read a moment later: let it land.+ Future<void> close(WidgetTester tester, SuperTabController c) async {+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }++ ScrollPosition position(WidgetTester tester) => tester+ .widget<ScrollView>(+ find.byKey(const PageStorageKey('super-messages-tab-lead')),+ )+ .controller!+ .position;++ Finder row(String id) => find.byKey(ValueKey('super-message-$id'));++ double top(WidgetTester tester, String id) => tester.getTopLeft(row(id)).dy;++ void fromAgent(ConversationServer server) => server.messages.last['author'] =+ {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'};++ void agentUpdates(ConversationServer server, int count) {+ for (var i = 0; i < count; i++) {+ server.append(+ 'Update $i: checking the offline queue and reconnect behavior.',+ );+ fromAgent(server);+ }+ }++ /// Scrolls so [id]'s row ends just above the view: built, but not seen.+ Future<void> justAbove(WidgetTester tester, String id) async {+ final scroll = position(tester);+ scroll.jumpTo(0);+ await tester.pumpAndSettle();+ final listTop = tester+ .getTopLeft(find.byKey(const PageStorageKey('super-messages-tab-lead')))+ .dy;+ scroll.jumpTo(tester.getBottomLeft(row(id)).dy - listTop + 20);+ await tester.pumpAndSettle();+ }++ testWidgets(+ 'the receipt moving off a row above the view leaves the view in place',+ (tester) async {+ final server = ConversationServer()..append('My first question');+ agentUpdates(server, 30);+ final c = await show(tester, server);+ await justAbove(tester, 'message-1');+ expect(+ find.byKey(+ const ValueKey('super-message-receipt-message-1'),+ skipOffstage: false,+ ),+ findsOneWidget,+ );+ final reading = top(tester, 'message-4');++ // The reader's own next message, sent from another device: the+ // receipt line leaves the first one, above the view.+ server.append('A second question');+ await c.refresh();+ await tester.pumpAndSettle();++ expect(+ find.byKey(+ const ValueKey('super-message-receipt-message-1'),+ skipOffstage: false,+ ),+ findsNothing,+ );+ expect(top(tester, 'message-4'), moreOrLessEquals(reading, epsilon: .5));+ expect(find.text('1 new message'), findsOneWidget);+ expect(tester.takeException(), isNull);+ await close(tester, c);+ },+ );++ testWidgets(+ 'a receipt growing in a row above the view leaves the view in place',+ (tester) async {+ final server = ConversationServer()..append('My first question');+ server.messages.last['deliveries'] = [+ {'id': 'delivery-1', 'agentId': 'lead-agent', 'status': 'delivered'},+ ];+ agentUpdates(server, 30);+ final c = await show(tester, server);+ await justAbove(tester, 'message-1');+ final reading = top(tester, 'message-4');++ // The delivery turns uncertain: its receipt adds a note and actions.+ server.messages.first['deliveries'] = [+ {'id': 'delivery-1', 'agentId': 'lead-agent', 'status': 'uncertain'},+ ];+ await c.refresh();+ await tester.pumpAndSettle();++ // In the row above the view.+ expect(+ find.text("Couldn't confirm delivery", skipOffstage: false),+ findsOneWidget,+ );+ expect(top(tester, 'message-4'), moreOrLessEquals(reading, epsilon: .5));+ expect(tester.takeException(), isNull);+ await close(tester, c);+ },+ );++ testWidgets(+ 'at the end, the newest row growing keeps the end in view and the next '+ 'reply follows',+ (tester) async {+ final server = ConversationServer();+ agentUpdates(server, 30);+ server.append('Is the reconnect fixed?');+ server.messages.last['deliveries'] = [+ {'id': 'delivery-1', 'agentId': 'lead-agent', 'status': 'delivered'},+ ];+ final c = await show(tester, server);+ expect(position(tester).extentAfter, lessThan(1));++ server.messages.last['deliveries'] = [+ {'id': 'delivery-1', 'agentId': 'lead-agent', 'status': 'uncertain'},+ ];+ await c.refresh();+ await tester.pumpAndSettle();+ expect(find.text("Couldn't confirm delivery"), findsOneWidget);+ expect(position(tester).extentAfter, lessThan(1));++ server.append('Yes, it reconnects now.');+ fromAgent(server);+ await c.refresh();+ await tester.pumpAndSettle();+ expect(find.text('1 new message'), findsNothing);+ expect(position(tester).extentAfter, lessThan(1));+ expect(find.text('Yes, it reconnects now.'), findsOneWidget);+ expect(tester.takeException(), isNull);+ await close(tester, c);+ },+ );++ testWidgets('reading older messages, the end growing does not scroll', (+ tester,+ ) async {+ final server = ConversationServer();+ agentUpdates(server, 30);+ server.append('Is the reconnect fixed?');+ final c = await show(tester, server);+ // A little above the end: not following it any more.+ position(tester).jumpTo(position(tester).maxScrollExtent - 120);+ await tester.pumpAndSettle();+ final reading = position(tester).pixels;++ server.append('Yes, it reconnects now.');+ fromAgent(server);+ await c.refresh();+ await tester.pumpAndSettle();++ expect(position(tester).pixels, reading);+ expect(find.text('1 new message'), findsOneWidget);+ expect(tester.takeException(), isNull);+ await close(tester, c);+ });++ testWidgets('a page read in above keeps the rows on screen, state and all', (+ tester,+ ) async {+ final server = ConversationServer()..messagePage = 20;+ agentUpdates(server, 40);+ final c = await show(tester, server);+ expect(c.messages('lead').length, 20);+ position(tester).jumpTo(0);+ await tester.pump();+ final first = tester.element(row('message-21'));+ final reading = top(tester, 'message-21');++ // Reaching the top reads the page before it.+ await tester.pumpAndSettle();++ expect(c.messages('lead').length, 40);+ expect(tester.element(row('message-21')), same(first));+ expect(top(tester, 'message-21'), moreOrLessEquals(reading, epsilon: .5));+ expect(tester.takeException(), isNull);+ await close(tester, c);+ });++ testWidgets('a page read in above regroups none of the rows on screen', (+ tester,+ ) async {+ // One agent's run of short updates: every third shows its name.+ final server = ConversationServer()..messagePage = 20;+ agentUpdates(server, 41);+ final c = await show(tester, server);+ position(tester).jumpTo(0);+ await tester.pump();+ final shown = [+ for (final m in c.messages('lead'))+ if (row(m.id).hitTestable().evaluate().isNotEmpty) m.id,+ ];+ expect(shown.length, greaterThan(3));+ final tops = {for (final id in shown) id: top(tester, id)};++ await tester.pumpAndSettle();++ expect(c.messages('lead').length, 40);+ for (final id in shown) {+ expect(top(tester, id), moreOrLessEquals(tops[id]!, epsilon: .5));+ }+ expect(tester.takeException(), isNull);+ await close(tester, c);+ });++ testWidgets('paging with the keyboard across the dividing row moves rows '+ 'only by the page', (tester) async {+ // Two pages: the one read first, and one read in above it.+ final server = ConversationServer()..messagePage = 20;+ agentUpdates(server, 60);+ final c = await show(tester, server);+ position(tester).jumpTo(position(tester).minScrollExtent);+ await tester.pumpAndSettle();+ expect(c.messages('lead').length, greaterThanOrEqualTo(40));+ // Just below the first row drawn, where the two halves meet.+ position(tester).jumpTo(100);+ await tester.pumpAndSettle();+ final start = position(tester).pixels;++ Future<void> page(LogicalKeyboardKey key) async {+ // The reader clicks a message, then pages; the row watched stays+ // in view: the top one going up, the bottom one going down.+ final shown = [+ for (final m in c.messages('lead'))+ if (row(m.id).hitTestable().evaluate().isNotEmpty) m.id,+ ];+ final id = key == LogicalKeyboardKey.pageUp ? shown.first : shown.last;+ tester+ .widget<Focus>(+ find.descendant(of: row(id), matching: find.byType(Focus)).first,+ )+ .focusNode!+ .requestFocus();+ await tester.pump();+ final before = position(tester).pixels, top = tester.getTopLeft(row(id));+ await tester.sendKeyEvent(key);+ await tester.pumpAndSettle();+ final moved = position(tester).pixels - before;+ expect(moved.abs(), greaterThan(100));+ expect(+ tester+ .getTopLeft(+ find.byKey(ValueKey('super-message-$id'), skipOffstage: false),+ )+ .dy,+ moreOrLessEquals(top.dy - moved, epsilon: .5),+ );+ }++ for (var i = 0; i < 3; i++) {+ await page(LogicalKeyboardKey.pageUp);+ }+ expect(position(tester).pixels, lessThan(0), reason: 'above the divide');+ // Above it, the rows read in still run oldest to newest down the view.+ final above = [+ for (final m in c.messages('lead'))+ if (row(m.id).hitTestable().evaluate().isNotEmpty) m.id,+ ];+ expect(above.length, greaterThan(2));+ final tops = [for (final id in above) tester.getTopLeft(row(id)).dy];+ expect(tops, orderedEquals([...tops]..sort()));+ for (var i = 0; i < 3; i++) {+ await page(LogicalKeyboardKey.pageDown);+ }+ expect(position(tester).pixels, moreOrLessEquals(start, epsilon: .5));+ expect(tester.takeException(), isNull);+ await close(tester, c);+ });++ testWidgets('sending while reading older messages shows the message at the '+ 'end', (tester) async {+ final server = ConversationServer();+ agentUpdates(server, 30);+ final c = await show(tester, server);+ position(tester).jumpTo(200);+ await tester.pumpAndSettle();++ await tester.enterText(+ find.byKey(const ValueKey('super-message-composer')),+ 'Please check the arm64 build',+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();++ expect(server.messages.last['text'], 'Please check the arm64 build');+ expect(row('message-31').hitTestable(), findsOneWidget);+ expect(position(tester).extentAfter, lessThan(1));+ expect(find.text('1 new message'), findsNothing);+ expect(tester.takeException(), isNull);+ await close(tester, c);+ });+}diff --git a/desktop/test/super_tab_chat_test.dart b/desktop/test/super_tab_chat_test.dartindex adb0fa368..89457c285 100644--- a/desktop/test/super_tab_chat_test.dart+++ b/desktop/test/super_tab_chat_test.dart@@ -576,7 +576,7 @@ void main() {}final c = await show(tester, server);ScrollController scroll() => tester- .widget<ListView>(+ .widget<ScrollView>(find.byKey(const PageStorageKey('super-messages-tab-lead')),).controller!;diff --git a/desktop/test/super_tab_decisions_test.dart b/desktop/test/super_tab_decisions_test.dartindex 8a2df1a2d..4f2fc10e2 100644--- a/desktop/test/super_tab_decisions_test.dart+++ b/desktop/test/super_tab_decisions_test.dart@@ -57,16 +57,24 @@ ConversationServer swarm() {Future<SuperTabController> showView(WidgetTester tester,- ConversationServer server,-) async {+ ConversationServer server, {+ Map<String, dynamic>? initial,+ Brightness brightness = Brightness.dark,+}) async {await tester.binding.setSurfaceSize(const Size(1200, 900));addTearDown(() => tester.binding.setSurfaceSize(null));- final c = server.controller(account: 'peer');+ final c = server.controller(account: 'peer', initial: initial);addTearDown(c.dispose);+ // The chrome's tokens follow the app's brightness, as the app sets it.+ final before = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = before);await c.refresh();await tester.pumpWidget(MaterialApp(- theme: grid.buildAppTheme(brightness: Brightness.dark),+ // A new key for each view: a restart builds the whole view again.+ key: UniqueKey(),+ theme: grid.buildAppTheme(brightness: brightness),builder: (context, child) => RepaintBoundary(key: _picture, child: child),home: Scaffold(body: SuperTabView(@@ -90,6 +98,17 @@ Finder notificationsEntry() =>find.byKey(const ValueKey('super-notifications'));Finder option(String id, int index) =>find.byKey(ValueKey('super-decision-$id-$index'));+Finder letPmDecide(String id) =>+ find.byKey(ValueKey('super-decision-$id-delegate'));+Finder notNow(String id) => find.byKey(ValueKey('super-decision-$id-later'));+Finder pmPanel() => find.byKey(const ValueKey('super-pm-decisions'));+Finder inPanel(String text) =>+ find.descendant(of: pmPanel(), matching: find.text(text));++Future<void> openPmChat(WidgetTester tester) async {+ await tester.tap(find.byKey(const ValueKey('super-pm-chat-lead')));+ await tester.pumpAndSettle();+}void main() {setUpAll(() async {@@ -329,6 +348,293 @@ void main() {);});+ group('a decision the reader does not want to answer', () {+ test('Let PM decide sends a delegated answer, and the answer reads as the PM\'s', () async {+ final server = swarm()..ask(['Ship how?'], recommended: 1);+ final controller = server.controller(account: 'peer');+ addTearDown(controller.dispose);+ final decisions = SuperTabDecisions.of(controller);+ await controller.refresh();+ await decisions.load();++ expect(await decisions.delegate(decisions.open.single), isTrue);++ expect(server.posts.last['command'], {+ 'type': 'decision.answer',+ 'decisionId': 'decision-1',+ 'delegate': true,+ });+ expect(decisions.open, isEmpty);+ expect(decisions.answered.single.choice, 1);+ expect(decisions.answered.single.delegated, isTrue);+ });++ testWidgets(+ 'Chat with PM offers Let PM decide and Not now on each card, and no Let PM decide without a recommended option',+ (tester) async {+ final server = swarm()+ ..ask(['Ship how?'], conversationId: 'pm-chat')+ ..ask(['Which colour?'], conversationId: 'pm-chat');+ server.decisions.last['recommended'] = null;+ await showView(tester, server);+ await openPmChat(tester);+ expect(inPanel('Decisions for you (2)'), findsOneWidget);+ expect(letPmDecide('decision-1'), findsOneWidget);+ expect(notNow('decision-1'), findsOneWidget);+ expect(letPmDecide('decision-2'), findsNothing);+ expect(notNow('decision-2'), findsOneWidget);++ await tester.tap(letPmDecide('decision-1'));+ await tester.pumpAndSettle();++ expect(server.posts.last['command'], {+ 'type': 'decision.answer',+ 'decisionId': 'decision-1',+ 'delegate': true,+ });+ expect(inPanel('Ship how?'), findsNothing);+ // The answered list says the PM decided, never that the reader chose.+ await tester.tap(notificationsEntry());+ await tester.pumpAndSettle();+ expect(find.text('PM decided: Behind a flag'), findsOneWidget);+ expect(find.text('You chose: Behind a flag'), findsNothing);+ },+ );++ testWidgets(+ 'Not now folds the card into one line, still folded after a restart, until a new decision arrives',+ (tester) async {+ final server = swarm()..ask(['Ship how?'], conversationId: 'pm-chat');+ await showView(tester, server);+ await openPmChat(tester);++ await tester.tap(notNow('decision-1'));+ await tester.pumpAndSettle();++ expect(inPanel('Decisions for you (1)'), findsOneWidget);+ expect(inPanel('Ship how?'), findsNothing);+ expect(+ find.byKey(const ValueKey('super-pm-decisions-show')),+ findsOneWidget,+ );+ expect(+ server.posts.where((p) => p['command']?['type'] == 'decision.answer'),+ isEmpty,+ );++ // A restart reads what this computer saved for the reader.+ final restarted = await showView(tester, server, initial: server.saved);+ await openPmChat(tester);+ expect(inPanel('Decisions for you (1)'), findsOneWidget);+ expect(inPanel('Ship how?'), findsNothing);+ // The Decisions list still holds it, with no Not now there.+ await tester.tap(notificationsEntry());+ await tester.pumpAndSettle();+ expect(find.text('Ship how?'), findsOneWidget);+ expect(notNow('decision-1'), findsNothing);++ server.ask(['Name it?'], conversationId: 'pm-chat');+ await restarted.refresh();+ await openPmChat(tester);+ expect(inPanel('Decisions for you (2)'), findsOneWidget);+ expect(inPanel('Name it?'), findsOneWidget);+ expect(inPanel('Ship how?'), findsNothing);+ },+ );++ test('a decision set aside stays set aside while newer ones push it off the capped list, until it is answered', () async {+ final server = swarm()+ ..ask(['Ship how?'], conversationId: 'pm-chat')+ ..ask(['Name it?'], conversationId: 'pm-chat');+ final controller = server.controller(account: 'peer');+ addTearDown(controller.dispose);+ final decisions = SuperTabDecisions.of(controller);+ await controller.refresh();+ await decisions.load();+ decisions.setAside([decisions.open.last]);+ expect(controller.decisionsAside, {'decision-1'});++ // The list holds the newest two of three: the oldest is still open.+ server+ ..decisionPage = 2+ ..ask(['Which colour?'], conversationId: 'pm-chat');+ await controller.refresh();+ await pumpEventQueue();+ expect(decisions.open.map((d) => d.id), ['decision-3', 'decision-2']);+ expect(controller.decisionsAside, {'decision-1'});++ // Newer ones answered: it is back in the list, still set aside.+ server+ ..answerDecision('decision-3', 0)+ ..answerDecision('decision-2', 0);+ await controller.refresh();+ await pumpEventQueue();+ expect(decisions.open.map((d) => d.id), ['decision-1']);+ expect(decisions.shownIn('lead'), isEmpty);++ // Answered: nothing is kept for it.+ server.answerDecision('decision-1', 0);+ await controller.refresh();+ await pumpEventQueue();+ expect(controller.decisionsAside, isEmpty);+ });++ test(+ 'a decision set aside is forgotten once it is gone from a complete list',+ () async {+ final server = swarm()+ ..decisionPage = 50+ ..ask(['Ship how?', 'Name it?'], conversationId: 'pm-chat');+ final controller = server.controller(account: 'peer');+ addTearDown(controller.dispose);+ final decisions = SuperTabDecisions.of(controller);+ await controller.refresh();+ await decisions.load();+ decisions.setAside(decisions.open);++ // The reader can no longer read one: the list, holding every open+ // one, no longer has it.+ server.hideDecision('decision-1');+ await controller.refresh();+ await pumpEventQueue();++ expect(controller.decisionsAside, {'decision-2'});+ },+ );++ test('a list that does not say it holds every open one forgets nothing it left out', () async {+ // A backend from before the list said so: what is missing from it+ // may still be open.+ final server = swarm()+ ..ask(['Ship how?', 'Name it?'], conversationId: 'pm-chat');+ final controller = server.controller(account: 'peer');+ addTearDown(controller.dispose);+ final decisions = SuperTabDecisions.of(controller);+ await controller.refresh();+ await decisions.load();+ decisions.setAside(decisions.open);++ server.hideDecision('decision-1');+ await controller.refresh();+ await pumpEventQueue();++ expect(controller.decisionsAside, {'decision-1', 'decision-2'});+ });++ test('on a backend from before Let PM decide, reads answered decisions as before', () async {+ final server = swarm()+ ..settledMissing = true+ ..ask(['Ship how?']);+ final controller = server.controller(account: 'peer');+ addTearDown(controller.dispose);+ final decisions = SuperTabDecisions.of(controller);+ await controller.refresh();+ await decisions.load();++ expect(await decisions.answer(decisions.open.single, 1), isTrue);++ expect(decisions.error, isNull);+ expect(decisions.answered.single.choice, 1);+ });++ testWidgets(+ 'a refused Let PM decide shows on its card in Chat with PM, and Retry sends it again',+ (tester) async {+ final server = swarm()+ ..ask(['Ship how?', 'Name it?'], conversationId: 'pm-chat');+ await showView(tester, server);+ await openPmChat(tester);+ // An older backend, or one that refuses: the card says so.+ server.refuse = {+ 'code': 'INVALID_COMMAND',+ 'message': 'Unrecognized key: delegate',+ };++ await tester.tap(letPmDecide('decision-1'));+ await tester.pumpAndSettle();++ final card = find.byKey(const ValueKey('super-decision-decision-1'));+ expect(+ find.descendant(+ of: card,+ matching: find.text('Could not send your answer. Try again.'),+ ),+ findsOneWidget,+ );+ expect(inPanel('Ship how?'), findsOneWidget);+ // Only the card that failed says so.+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('super-decision-decision-2')),+ matching: find.text('Could not send your answer. Try again.'),+ ),+ findsNothing,+ );++ server.refuse = null;+ await tester.tap(+ find.byKey(const ValueKey('super-decision-decision-1-retry')),+ );+ await tester.pumpAndSettle();++ expect(server.posts.last['command'], {+ 'type': 'decision.answer',+ 'decisionId': 'decision-1',+ 'delegate': true,+ });+ expect(inPanel('Ship how?'), findsNothing);+ expect(+ find.text('Could not send your answer. Try again.'),+ findsNothing,+ );+ },+ );++ testWidgets(+ 'a refused answer in the Decisions list says so once, on its card',+ (tester) async {+ final server = swarm()..ask(['Ship how?']);+ await showView(tester, server);+ await tester.tap(notificationsEntry());+ await tester.pumpAndSettle();+ server.refuse = {'code': 'DECISION_ANSWERED', 'message': 'Answered.'};++ await tester.tap(option('decision-1', 1));+ await tester.pumpAndSettle();++ expect(find.text(SuperTabDecisions.sendFailed), findsOneWidget);+ expect(+ find.byKey(const ValueKey('super-decision-decision-1-retry')),+ findsOneWidget,+ );+ },+ );++ testWidgets('Hide folds the whole section, and Show opens it again', (+ tester,+ ) async {+ final server = swarm()+ ..ask(['Ship how?', 'Name it?'], conversationId: 'pm-chat');+ await showView(tester, server);+ await openPmChat(tester);++ await tester.tap(find.byKey(const ValueKey('super-pm-decisions-hide')));+ await tester.pumpAndSettle();+ expect(inPanel('Decisions for you (2)'), findsOneWidget);+ expect(inPanel('Ship how?'), findsNothing);+ expect(inPanel('Name it?'), findsNothing);++ await tester.tap(find.byKey(const ValueKey('super-pm-decisions-show')));+ await tester.pumpAndSettle();+ expect(inPanel('Ship how?'), findsOneWidget);+ expect(inPanel('Name it?'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('super-pm-decisions-hide')),+ findsOneWidget,+ );+ });+ });+testWidgets('screenshots for review', (tester) async {final server = swarm()..ask([@@ -352,4 +658,43 @@ void main() {await tester.pumpAndSettle();await shot(tester, 'chat-with-pm');}, skip: shots == null);++ for (final brightness in Brightness.values) {+ testWidgets(+ 'screenshots of Let PM decide, Not now and Hide, ${brightness.name}',+ (tester) async {+ final server = swarm()+ ..ask([+ 'For a Mac in a Swarm without the Desktop app, start agents with the CLI only?',+ ], conversationId: 'pm-chat')+ ..ask(+ ['Which name for the setting?'],+ conversationId: 'pm-chat',+ recommended: 1,+ );+ server.decisions.first['options'] = ['Yes', 'No'];+ server.decisions.first['unblocks'] = 'Starting agents on that Mac';+ server.decisions.last['options'] = ['Offline mode', 'Work offline'];+ server.decisions.last['unblocks'] = 'The settings copy';+ final name = brightness.name;+ await showView(tester, server, brightness: brightness);+ await openPmChat(tester);+ await shot(tester, 'pm-decisions-$name');+ await tester.tap(notNow('decision-2'));+ await tester.pumpAndSettle();+ await shot(tester, 'pm-decisions-not-now-$name');+ await tester.tap(find.byKey(const ValueKey('super-pm-decisions-hide')));+ await tester.pumpAndSettle();+ await shot(tester, 'pm-decisions-hidden-$name');+ await tester.tap(find.byKey(const ValueKey('super-pm-decisions-show')));+ await tester.pumpAndSettle();+ await tester.tap(letPmDecide('decision-1'));+ await tester.pumpAndSettle();+ await tester.tap(notificationsEntry());+ await tester.pumpAndSettle();+ await shot(tester, 'pm-decided-$name');+ },+ skip: shots == null,+ );+ }}diff --git a/desktop/test/super_tab_detail_dialog_test.dart b/desktop/test/super_tab_detail_dialog_test.dartnew file mode 100644index 000000000..b785c51ee--- /dev/null+++ b/desktop/test/super_tab_detail_dialog_test.dart@@ -0,0 +1,158 @@+// The six Swarm details dialogs share one frame (Ken, 2026-10-28: "polish lai UI nay, xau qua"): a title with a quiet+// close, a hairline under it once the content scrolls, label/value rows in one label column, and actions at the bottom.+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shared/widgets/app_dialog.dart';+import 'package:harness/super_tabs/detail_dialog.dart';++Future<void> _open(WidgetTester tester, WidgetBuilder builder) async {+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Builder(+ builder: (context) => Scaffold(+ body: TextButton(+ onPressed: () =>+ showAppDialog<void>(context: context, builder: builder),+ child: const Text('open'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('open'));+ await tester.pumpAndSettle();+}++void main() {+ testWidgets(+ 'the hairline under the title shows only once the content has scrolled under it',+ (tester) async {+ await tester.binding.setSurfaceSize(const Size(800, 500));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await _open(+ tester,+ (context) => SuperTabDetailDialog(+ title: 'MacbookPro',+ body: Column(+ children: [+ for (var i = 0; i < 40; i++)+ SuperTabDetailRow(label: 'Row $i', value: 'Value $i'),+ ],+ ),+ ),+ );+ final hairline = find.byKey(const ValueKey('super-detail-hairline'));+ expect(hairline, findsNothing);+ await tester.drag(find.text('Value 3'), const Offset(0, -120));+ await tester.pumpAndSettle();+ expect(hairline, findsOneWidget);+ await tester.drag(find.text('Value 8'), const Offset(0, 400));+ await tester.pumpAndSettle();+ expect(hairline, findsNothing);+ },+ );++ testWidgets(+ 'values line up in one column across rows and sections, and the close mark dismisses',+ (tester) async {+ await _open(+ tester,+ (context) => SuperTabDetailDialog(+ title: 'Project details',+ body: Column(+ children: [+ const SuperTabDetailRow(label: 'Owner', value: '[email protected]'),+ SuperTabDetailSection(+ title: 'Details',+ children: const [+ SuperTabDetailRow(label: 'Product Manager', value: 'River'),+ ],+ ),+ ],+ ),+ ),+ );+ expect(+ tester.getTopLeft(find.text('[email protected]')).dx,+ tester.getTopLeft(find.text('River')).dx,+ );+ expect(+ find.descendant(+ of: find.byType(SuperTabDetailDialog),+ matching: find.byType(TextButton),+ ),+ findsNothing,+ reason: 'no Close button repeats the close mark',+ );+ await tester.tap(find.byTooltip('Close'));+ await tester.pumpAndSettle();+ expect(find.text('Project details'), findsNothing);+ },+ );++ testWidgets(+ 'with enlarged text a row stacks its value under its label instead of squeezing it',+ (tester) async {+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: MediaQuery(+ data: const MediaQueryData(textScaler: TextScaler.linear(2)),+ child: const Scaffold(+ body: SizedBox(+ width: 400,+ child: SuperTabDetailRow(+ label: 'Owner',+ value: '[email protected]',+ ),+ ),+ ),+ ),+ ),+ );+ expect(+ tester.getTopLeft(find.text('[email protected]')).dy,+ greaterThan(tester.getBottomLeft(find.text('Owner')).dy - 1),+ );+ },+ );++ testWidgets(+ 'the close mark sits centred on the title line, also with enlarged text',+ (tester) async {+ for (final scale in [1.0, 2.0]) {+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: MediaQuery(+ data: MediaQueryData(textScaler: TextScaler.linear(scale)),+ child: const Scaffold(+ body: SuperTabDetailDialog(title: 'Pilot', body: Text('body')),+ ),+ ),+ ),+ );+ final title = tester.getCenter(find.text('Pilot')).dy;+ expect(+ tester+ .getCenter(+ find.descendant(+ of: find.byTooltip('Close'),+ matching: find.byType(Icon),+ ),+ )+ .dy,+ closeTo(title, 1),+ reason: 'at ${scale}x',+ );+ expect(+ tester.getSize(find.byType(IconButton)),+ const Size(32, 32),+ reason: 'the 32-point target',+ );+ }+ },+ );+}diff --git a/desktop/test/super_tab_dial_scroll_test.dart b/desktop/test/super_tab_dial_scroll_test.dartindex c9aba3c29..03157bd81 100644--- a/desktop/test/super_tab_dial_scroll_test.dart+++ b/desktop/test/super_tab_dial_scroll_test.dart@@ -38,7 +38,7 @@ void main() {);await tester.pumpAndSettle();ScrollPosition position() => tester- .widget<ListView>(+ .widget<ScrollView>(find.byKey(const PageStorageKey('super-messages-tab-lead')),).controller!@@ -115,7 +115,7 @@ void main() {c.select('offline');await tester.pumpAndSettle();ScrollPosition position() => tester- .widget<ListView>(+ .widget<ScrollView>(find.byKey(const PageStorageKey('super-messages-tab-offline')),).controller!diff --git a/desktop/test/super_tab_dial_test.dart b/desktop/test/super_tab_dial_test.dartindex 896d44036..803ecfe21 100644--- a/desktop/test/super_tab_dial_test.dart+++ b/desktop/test/super_tab_dial_test.dart@@ -229,4 +229,87 @@ void main() {await settle();expect(announces(f).last.containsKey('fromDevice'), isFalse);});++ // The round dial's face follows the chat the window has open (design+ // 2026-10-28-round-dial-swarm-chat): the Lead's, Chat with PM or a group.+ Future<(SuperTabLaunchFixture, SuperTabController)> openChats() async {+ final f = SuperTabLaunchFixture(local: true);+ final server = f.connection.server;+ server.state['projects'] = [+ projectFixture('lead', 'Lamp OS', 'lead'),+ projectFixture('design', 'Design', 'design-lead'),+ ];+ (server.state['conversations'] as List).addAll(<Map<String, dynamic>>[+ {...conversationFixture('design-lead', 'Lead'), 'projectId': 'design'},+ {+ ...conversationFixture('design-pm', 'Chat with PM'),+ 'projectId': 'design',+ 'audience': {+ 'people': [+ {'id': 'owner'},+ ],+ },+ },+ {+ ...conversationFixture('design-fix', 'Fix login'),+ 'projectId': 'design',+ },+ ]);+ f.app.adoptPoolConnectionForTest('m', f.connection);+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ return (f, c);+ }++ test('a Swarm tab announces the open conversation\'s id', () async {+ final (f, c) = await openChats();+ f.app.announceWindowForeground();+ await settle();+ expect(row(announces(f).last)['conversationId'], 'lead');+ for (final id in ['design-lead', 'design-pm', 'design-fix']) {+ c.select(id);+ await settle();+ expect(row(announces(f).last)['conversationId'], id);+ expect(row(announces(f).last)['projectId'], 'design');+ }+ });++ test('selecting another conversation re-announces', () async {+ final (f, c) = await openChats();+ c.select('design-pm');+ await settle();+ final before = announces(f).length;+ // Another chat of the same project: the project is unchanged, the chat is news.+ c.select('design-fix');+ await settle();+ final after = announces(f).skip(before).toList();+ expect(after, isNotEmpty);+ expect(row(after.last)['conversationId'], 'design-fix');+ });++ test('a decisions view or an unloaded Swarm leaves conversationId out', () async {+ final (f, c) = await openChats();+ c.select('design-pm');+ await settle();+ // The Swarm's machines view (the one view here that is no conversation; its+ // decisions are a panel beside the chat, which keeps the chat selected).+ c.selectDevices();+ f.app.announceWindowForeground();+ await settle();+ expect(row(announces(f).last).containsKey('conversationId'), isFalse);++ // A Swarm tab shown before its Swarm loaded names no conversation.+ final g = SuperTabLaunchFixture(local: true);+ g.app.adoptPoolConnectionForTest('m', g.connection);+ final hold = g.connection.server.holdReads = Completer<void>();+ g.app.bindSuperTab(g.app.activeSwarmId, tabId, 'Pilot');+ await g.app.superTabs.open(tabId);+ g.app.announceWindowForeground();+ await settle();+ expect(row(announces(g).last).containsKey('conversationId'), isFalse);+ g.connection.server.holdReads = null;+ hold.complete();+ await settle();+ });}diff --git a/desktop/test/super_tab_dialog_shots_test.dart b/desktop/test/super_tab_dialog_shots_test.dartnew file mode 100644index 000000000..bc25e07cf--- /dev/null+++ b/desktop/test/super_tab_dialog_shots_test.dart@@ -0,0 +1,407 @@+// The six Swarm dialogs Ken asked to polish (2026-10-28), photographed light and dark for review: machine details,+// person profile, Project details, Team at a glance, Share Swarm and Add machine, over in-memory Swarms only.+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/machines.dart';+import 'package:harness/super_tabs/project_options.dart';+import 'package:harness/super_tabs/roster.dart';+import 'package:harness/super_tabs/sharing.dart';+import 'package:harness/super_tabs/view.dart';+import 'package:harness/widgets/engine_identity.dart';++import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;+import 'swarm_sharing_test.dart' show SwarmSharingServer;+import 'support/capture.dart';+import 'support/humans_fixture.dart';+import 'support/super_tab_fixture.dart';++/// Set to a folder to write the screenshots there.+final shots = Platform.environment['SUPER_TAB_DIALOG_SHOTS'];++int _in(Duration d) => DateTime.now().add(d).millisecondsSinceEpoch;++Future<void> _pump(+ WidgetTester tester,+ Brightness brightness,+ Widget home, {+ Size size = const Size(900, 1000),+}) async {+ await tester.binding.setSurfaceSize(size);+ addTearDown(() => tester.binding.setSurfaceSize(null));+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.dark);+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(body: home),+ ),+ );+ await tester.pumpAndSettle();+}++/// A Swarm like Ken's: a MacBook Pro with both allowances, a Mac Studio gone offline with many busy agents, and+/// people to share with.+ConversationServer _swarm() {+ final server = ConversationServer();+ server.state['people'] = [+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},+ for (final name in ['diego', 'huy', 'tony', 'scholes', 'dee'])+ {'id': name, 'email': '[email protected]', 'role': 'collaborator'},+ ];+ final studio = [+ 'Milo',+ 'Kai',+ 'Iris',+ 'Ellis',+ 'Nova',+ 'Echo',+ 'Rowan',+ 'Juno',+ 'Lark',+ 'Avery',+ 'Remy',+ 'Quinn', //+ ];+ server.state['agents'] = [+ {+ 'id': 'river',+ 'name': 'Lead',+ 'displayName': 'River',+ 'machineId': 'mbp',+ 'harnessId': 'h-river',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'claude', 'model': 'opus', 'effort': 'high'},+ },+ for (final name in ['Robin', 'Sage'])+ {+ 'id': name.toLowerCase(),+ 'name': 'Builder',+ 'displayName': name,+ 'machineId': 'mbp',+ 'harnessId': 'h-$name',+ 'contributorId': 'owner',+ 'configuration': {+ 'engine': 'claude',+ 'model': 'opus',+ 'effort': 'xhigh',+ },+ },+ for (final name in studio)+ {+ 'id': name.toLowerCase(),+ 'name': 'Builder',+ 'displayName': name,+ 'machineId': 'studio',+ 'harnessId': 'h-$name',+ 'contributorId': 'owner',+ 'configuration': {+ 'engine': 'claude',+ 'model': 'opus',+ 'effort': 'high',+ },+ },+ ];+ server.state['starts'] = [+ for (final name in ['Robin', 'Sage'])+ {+ 'id': 'start-$name',+ 'harnessId': 'h-$name',+ 'request': {+ 'machineId': 'mbp',+ 'engine': 'claude',+ 'model': 'opus',+ 'effort': 'high',+ 'name': name,+ },+ },+ ];+ final conversations = server.state['conversations'] as List;+ conversations[0]+ ..['leadId'] = 'river'+ ..['agentIds'] = ['river'];+ for (final name in studio) {+ conversations.add({+ ...conversationFixture('task-$name', 'Task of $name'),+ 'leadId': 'river',+ 'agentIds': ['river', name.toLowerCase()],+ 'assignment': {+ 'id': 'as-$name',+ 'agentId': name.toLowerCase(),+ 'status': 'working',+ },+ });+ }+ server.state['machines'] = [+ {+ 'machineId': 'mbp',+ 'name': 'MacbookPro.local',+ 'contributorId': 'owner',+ 'engines': ['claude', 'codex'],+ 'maxAgents': 16,+ 'availableSlots': 14,+ 'cwd': '/Users/ken/.harness/cli/data/swarm-projects/tab',+ 'observation': {+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,+ 'resources': {+ 'deviceType': 'MacBook Pro',+ 'chip': 'Apple M2 Max',+ 'os': 'macOS',+ 'cpuPercent': 14,+ 'gpuPercent': 8,+ 'memoryTotalBytes': 34000000000,+ 'memoryUsedBytes': 25000000000,+ 'diskTotalBytes': 995000000000,+ 'diskFreeBytes': 156000000000,+ },+ 'quotas': [+ {+ 'engine': 'claude',+ 'known': true,+ 'windows': [+ {+ 'name': 'Session',+ 'usedPercent': 43,+ 'resetsAt': _in(const Duration(hours: 2, minutes: 1)),+ },+ {+ 'name': 'Weekly',+ 'usedPercent': 35,+ 'resetsAt': _in(const Duration(days: 6, hours: 2)),+ },+ ],+ },+ {+ 'engine': 'codex',+ 'known': true,+ 'windows': [+ {+ 'name': 'Weekly',+ 'usedPercent': 5,+ 'resetsAt': _in(const Duration(days: 6, hours: 22)),+ },+ ],+ },+ ],+ },+ },+ {+ 'machineId': 'studio',+ 'name': 'MACs-Mac-Studio.local',+ 'contributorId': 'owner',+ 'engines': ['claude', 'codex'],+ 'maxAgents': 32,+ 'availableSlots': 11,+ 'observation': {+ 'receivedAt': DateTime.now().millisecondsSinceEpoch - 10 * 60 * 1000,+ },+ },+ ];+ return server;+}++/// The Swarm's controller, answering the project's GitHub access as covered.+SuperTabController _controller(ConversationServer server) => SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ request: (method, path, {body}) async {+ if (path.contains('/github')) {+ return {'state': 'covered', 'repository': 'autonomous-ai/openharness'};+ }+ return server.request(method, path, body: body);+ },+ save: server.save,+ upload: server.upload,+ initial: const {},+ pollInterval: Duration.zero,+);++void main() {+ setUpAll(() => loadCaptureFonts(shots));++ for (final brightness in Brightness.values) {+ final theme = brightness.name;++ testWidgets('machine details ($theme)', (tester) async {+ final server = _swarm();+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ await _pump(+ tester,+ brightness,+ Align(+ alignment: Alignment.topLeft,+ child: SizedBox(+ width: 280,+ child: SuperTabMachines(+ controller: c,+ embedded: true,+ onAddAgent: (_) {},+ ),+ ),+ ),+ );+ final row = find.byKey(const ValueKey('super-machine-mbp'));+ await tester.longPress(row);+ await tester.pumpAndSettle();+ // Codex's mark is a picture decoded off the frame: wait for it before photographing, as the app shows it.+ await tester.runAsync(+ () => precacheImage(+ AssetImage(engineIdentity('codex').asset!),+ tester.element(find.byType(EngineMark).first),+ ).timeout(const Duration(seconds: 10)),+ );+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, '1-machine-details-$theme');+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, skip: shots == null);++ testWidgets('person profile ($theme)', (tester) async {+ final swarm = humansSwarm();+ final dee = (swarm.leaderboard!['people'] as List).first as Map;+ (dee['details'] as Map)['shipped'] = [+ for (final title in [+ 'Bug: machine last-seen time has not been written since Oct 14',+ 'Stability 2.3: remove the expensive loops — terminal long-poll, 5 s socket re-checks, skip paging',+ "Bug: viewing another person's agent terminal in a Swarm is unreliable",+ 'Main is red: 48 team-session tests fail after the GitHub approvals change',+ 'Stability 2.2 + 2.6: per-pod Swarm cache keyed by version',+ 'Hotfix: prod DB at 100% CPU, message deliveries read scans the whole Swarm',+ 'Stability 2.4: deliver work over the daemon socket, poll only as a 30 s fallback',+ 'Web app reconnect loop: one user reconnects ~3,250 times an hour',+ ])+ {+ 'title': title,+ 'prUrl': 'https://github.com/autonomous-ai/openharness/pull/1',+ },+ ];+ final c = swarm.controller(+ account: 'peer',+ initial: {'tabId': 'tab', 'accountId': 'peer', 'selectedId': 'lead'},+ );+ addTearDown(c.dispose);+ await c.refresh();+ await _pump(+ tester,+ brightness,+ SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ size: const Size(1300, 1000),+ );+ await tester.tap(find.byKey(const ValueKey('super-person-peer')));+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, '2-person-profile-$theme');+ await tester.pumpWidget(const SizedBox());+ }, skip: shots == null);++ testWidgets('project details ($theme)', (tester) async {+ final server = _swarm();+ server.state['project'] = {+ 'repositoryUrl': 'https://github.com/autonomous-ai/openharness',+ };+ final c = _controller(server);+ addTearDown(c.dispose);+ await c.refresh();+ final project = c.snapshot!.projects.first;+ await _pump(+ tester,+ brightness,+ Builder(+ builder: (context) => TextButton(+ onPressed: () => showProjectAction(context, c, project, 'details'),+ child: const Text('open'),+ ),+ ),+ );+ await tester.tap(find.text('open'));+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, '3-project-details-$theme');+ }, skip: shots == null);++ testWidgets('team at a glance ($theme)', (tester) async {+ final server = _swarm();+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ await _pump(+ tester,+ brightness,+ SuperTabRoster(+ controller: c,+ onInvite: () {},+ onOpenAgent: (_) {},+ onAddAgent: (_) {},+ onAnswer: (_) {},+ ),+ );+ await tester.tap(find.byTooltip('Team at a glance'));+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, '4-team-at-a-glance-$theme');+ await tester.pumpWidget(const SizedBox());+ }, skip: shots == null);++ testWidgets('share swarm ($theme)', (tester) async {+ final server = SwarmSharingServer();+ server.state['people'] = _swarm().state['people'];+ server.state['agents'] = _swarm().state['agents'];+ (server.state['conversations'] as List)[0]['leadId'] = 'river';+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ await _pump(+ tester,+ brightness,+ Builder(+ builder: (context) => TextButton(+ onPressed: () => showSuperTabSharing(context, c),+ child: const Text('open'),+ ),+ ),+ );+ await tester.tap(find.text('open'));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const Key('swarm-sharing-people')));+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, '5-share-swarm-$theme');+ }, skip: shots == null);++ testWidgets('add machine ($theme)', (tester) async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ f.app.machineStates['m']!.machine = f.app.machineStates['m']!.machine+ .copyWith(name: 'autonomous-code-vm-01.c.autonomous-code.internal');+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ await _pump(+ tester,+ brightness,+ SizedBox(+ width: 300,+ height: 400,+ child: SuperTabMachines(+ controller: c,+ app: f.app,+ onAddAgent: (_) {},+ ),+ ),+ );+ await tester.tap(find.byTooltip('Add machine'));+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, '6-add-machine-$theme');+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ }, skip: shots == null);+ }+}diff --git a/desktop/test/super_tab_humans_test.dart b/desktop/test/super_tab_humans_test.dartindex 8cb96189d..4af1b8a8c 100644--- a/desktop/test/super_tab_humans_test.dart+++ b/desktop/test/super_tab_humans_test.dart@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/detail_dialog.dart';import 'package:harness/shared/theme/app_icons.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/super_tabs/controller.dart';@@ -482,8 +483,8 @@ void main() {// A server from before names: the email's first part, as before.expect(within('scholes', 'scholes'), findsOneWidget);expect(find.text('dee'), findsNothing);- // The email stays on hover.- expect(find.byTooltip('[email protected]'), findsOneWidget);+ // On hover the whole name, which a long one needs when it is cut, then the email.+ expect(find.byTooltip('Dee\[email protected]'), findsOneWidget);await close(tester, controller);},@@ -587,11 +588,16 @@ void main() {final controller = await show(tester, humansSwarm());await tester.tap(person('peer'));await tester.pumpAndSettle();- final dialog = find.byType(AlertDialog);+ final dialog = find.byType(SuperTabDetailDialog);Finder inDialog(String text) =>find.descendant(of: dialog, matching: find.text(text));expect(inDialog('Dee'), findsOneWidget);- expect(inDialog('21 pts · up 6 from last week'), findsOneWidget);+ // Who they are on one line under the name (Ken, 2026-10-28).+ expect(inDialog('[email protected] · Can collaborate'), findsOneWidget);+ // This week's points in words, and last week's beside them rather than a difference.+ expect(inDialog('21 points this week · 15 last week'), findsOneWidget);+ expect(find.textContaining('pts'), findsNothing);+ expect(find.widgetWithText(TextButton, 'Close'), findsNothing);expect(inDialog('Shipped'), findsOneWidget);expect(inDialog('Unblocked'), findsOneWidget);expect(inDialog('Lent'), findsOneWidget);@@ -610,12 +616,12 @@ void main() {await tester.tap(inDialog('Swarm digest pauses with the Swarm'));await tester.pumpAndSettle();expect(launches, hasLength(1));- await tester.tap(find.text('Close'));+ await tester.tap(find.byTooltip('Close'));await tester.pumpAndSettle();await tester.tap(person('owner'));await tester.pumpAndSettle();- expect(inDialog('13 pts · down 7 from last week'), findsOneWidget);+ expect(inDialog('13 points this week · 20 last week'), findsOneWidget);expect(inDialog('No pull requests merged yet'), findsOneWidget);expect(inDialog('No questions answered yet'), findsOneWidget);// The machine as it calls itself, without .local.@@ -633,7 +639,7 @@ void main() {final controller = await show(tester, humansSwarm());await tester.tap(person('scholes'));await tester.pumpAndSettle();- final dialog = find.byType(AlertDialog);+ final dialog = find.byType(SuperTabDetailDialog);Finder inDialog(String text) =>find.descendant(of: dialog, matching: find.text(text));expect(inDialog('scholes'), findsOneWidget);@@ -698,15 +704,23 @@ void main() {await tester.tap(person('peer'));await tester.pumpAndSettle();expect(tester.takeException(), isNull);+ // A count, the newest five, and the rest one click away; not a wall of links cut off at the bottom.+ expect(find.text('20'), findsOneWidget);+ expect(find.text('Pull request 4'), findsOneWidget);+ expect(find.text('Pull request 5'), findsNothing);+ await tester.tap(find.text('Show all 20'));+ await tester.pumpAndSettle();await tester.scrollUntilVisible(find.text('No machines lent yet'),100,scrollable: find.descendant(- of: find.byType(AlertDialog),+ of: find.byType(SuperTabDetailDialog),matching: find.byType(Scrollable),),);+ expect(find.text('Pull request 19'), findsOneWidget);expect(find.text('No machines lent yet'), findsOneWidget);+ expect(tester.takeException(), isNull);await close(tester, controller);});diff --git a/desktop/test/super_tab_machine_details_test.dart b/desktop/test/super_tab_machine_details_test.dartnew file mode 100644index 000000000..add3099de--- /dev/null+++ b/desktop/test/super_tab_machine_details_test.dart@@ -0,0 +1,208 @@+// Machine details, polished (Ken, 2026-10-28): each allowance window once, with its reset; no raw project folder.+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/detail_dialog.dart';+import 'package:harness/super_tabs/machine_details.dart';+import 'package:harness/widgets/engine_identity.dart';++Future<void> _show(WidgetTester tester, Widget details) async {+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(body: Center(child: details)),+ ),+ );+ await tester.pumpAndSettle();+}++void main() {+ test('an allowance reads as one line per window, in either detail format, without the limiting-window line', () {+ // This computer's reading: the limiting window named, then each window.+ expect(+ superTabAllowanceWindows([+ 'Limiting window: Session',+ 'Read 3 min ago',+ 'Session — 57% remaining · resets in 2h 1m',+ 'Weekly — 65% remaining · resets in 6d 2h',+ ]),+ [+ (window: 'Session', left: '57% left', reset: 'resets in 2h 1m'),+ (window: 'Weekly', left: '65% left', reset: 'resets in 6d 2h'),+ ],+ );+ // Another machine's reading: the tightest window first, a window without a reset.+ expect(+ superTabAllowanceWindows([+ '5-hour: 44% remaining · resets in 2h 10m',+ 'Weekly: 80% remaining',+ ]),+ [+ (window: '5-hour', left: '44% left', reset: 'resets in 2h 10m'),+ (window: 'Weekly', left: '80% left', reset: null),+ ],+ );+ expect(superTabAllowanceWindows(['Usage unavailable']), isEmpty);+ });++ testWidgets(+ 'each window shows once with its reset; the account figure is not repeated above it',+ (tester) async {+ await _show(+ tester,+ const SuperTabMachineDetails(+ name: 'MacbookPro.local',+ status: 'Online',+ owner: '[email protected]',+ engines: ['claude'],+ accounts: [+ {+ 'engine': 'claude',+ 'account': '[email protected]',+ 'remainingPercent': 57,+ 'details': [+ 'Limiting window: Session',+ 'Session — 57% remaining · resets in 2h 1m',+ 'Weekly — 65% remaining · resets in 6d 2h',+ ],+ },+ ],+ ),+ );+ expect(find.text('Session'), findsOneWidget);+ expect(find.text('57% left · resets in 2h 1m'), findsOneWidget);+ expect(find.text('65% left · resets in 6d 2h'), findsOneWidget);+ expect(find.textContaining('Limiting window'), findsNothing);+ expect(find.textContaining('57%'), findsOneWidget);+ expect(find.text('[email protected]'), findsOneWidget);+ expect(find.text('Project folder'), findsNothing);+ expect(tester.takeException(), isNull);+ },+ );++ testWidgets('an account whose windows are not listed keeps its one figure', (+ tester,+ ) async {+ await _show(+ tester,+ const SuperTabMachineDetails(+ name: 'M2',+ status: 'Online',+ accounts: [+ {'engine': 'codex', 'remainingPercent': 95, 'details': <String>[]},+ ],+ ),+ );+ expect(find.text('95% left'), findsOneWidget);+ });++ testWidgets(+ 'every account wears its own engine mark, Codex as Claude Code does',+ (tester) async {+ await _show(+ tester,+ const SuperTabMachineDetails(+ name: 'M2',+ status: 'Online',+ accounts: [+ {+ 'engine': 'claude',+ 'remainingPercent': 57,+ 'details': ['Session — 57% remaining · resets in 2h 1m'],+ },+ {+ 'engine': 'codex',+ 'remainingPercent': 95,+ 'details': ['Weekly — 95% remaining · resets in 6d 22h'],+ },+ ],+ ),+ );+ expect(+ [+ for (final mark in tester.widgetList<EngineMark>(+ find.byType(EngineMark),+ ))+ mark.engine,+ ],+ ['claude', 'codex'],+ );+ expect(+ tester.getTopLeft(find.text('Codex')).dx,+ tester.getTopLeft(find.text('Claude Code')).dx,+ );+ },+ );++ testWidgets(+ '5%, 5.0% and 100% read with the right ink: decimals are not taken for 100%',+ (tester) async {+ await _show(+ tester,+ const SuperTabMachineDetails(+ name: 'Mac',+ status: 'Online',+ accounts: [+ {+ 'engine': 'claude',+ 'remainingPercent': 5,+ 'details': [+ 'Session: 5% remaining',+ 'Weekly: 5.0% remaining',+ 'Monthly: 100% remaining',+ ],+ },+ ],+ ),+ );+ Color? ink(String text) =>+ tester.widget<Text>(find.text(text)).style!.color;+ expect(+ ink('5.0% left'),+ ink('5% left'),+ reason: 'both at the critical limit',+ );+ expect(ink('5% left'), isNot(ink('100% left')));+ },+ );++ testWidgets(+ 'a narrow window with enlarged text stacks the allowance instead of overflowing',+ (tester) async {+ await tester.binding.setSurfaceSize(const Size(320, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: const TextScaler.linear(2)),+ child: child!,+ ),+ home: const Scaffold(+ body: Center(+ child: SuperTabDetailDialog(+ title: 'Mac',+ body: SuperTabMachineDetails(+ name: 'Mac',+ status: 'Online',+ accounts: [+ {+ 'engine': 'claude',+ 'account': '[email protected]',+ 'remainingPercent': 95,+ 'details': <String>[],+ },+ ],+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(tester.takeException(), isNull);+ expect(find.text('95% left'), findsOneWidget);+ },+ );+}diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dartindex 47d4bfc2d..404847e94 100644--- a/desktop/test/super_tab_machines_test.dart+++ b/desktop/test/super_tab_machines_test.dart@@ -15,6 +15,7 @@ import 'package:harness/state/harness_activity.dart';import 'package:harness/widgets/harness_activity_mark.dart';import 'package:harness/super_tabs/machines.dart';import 'package:harness/super_tabs/controller.dart' show SuperTabFailure;+import 'package:harness/super_tabs/detail_dialog.dart';import 'package:harness/super_tabs/machine_details.dart';import 'package:harness/super_tabs/identity.dart';import 'package:harness/super_tabs/model.dart';@@ -299,7 +300,7 @@ void main() {expect(find.text('Offline · 1'), findsNothing);await tester.tap(find.byKey(const ValueKey('super-machine-online')));await tester.pumpAndSettle();- expect(find.byType(AlertDialog), findsNothing);+ expect(find.byType(SuperTabDetailDialog), findsNothing);expect(_hw(tester, 'online', 'CPU'), '0%');expect(_hw(tester, 'online', 'RAM'), '0 GB');expect(_hw(tester, 'online', 'SSD'), '141 GB');@@ -354,23 +355,21 @@ void main() {tester.widget<EngineMark>(find.descendant(- of: find.byType(AlertDialog),+ of: find.byType(SuperTabDetailDialog),matching: find.byType(EngineMark),),).engine,'codex',);- await tester.tap(find.text('Close'));+ await tester.tap(find.byTooltip('Close'));await tester.pumpAndSettle();await openMachineDetails(tester, offline);await tester.pumpAndSettle();- expect(find.byType(AlertDialog), findsOneWidget);+ expect(find.byType(SuperTabDetailDialog), findsOneWidget);expect(find.descendant(- of: find.byWidget(- tester.widget<AlertDialog>(find.byType(AlertDialog)).title!,- ),+ of: find.byType(DesktopDialogHeader),matching: find.text('M2'),),findsOneWidget,@@ -834,7 +833,7 @@ void main() {await tester.tap(dev);await tester.pumpAndSettle();expect(opened, ['dev']);- expect(find.byType(AlertDialog), findsNothing);+ expect(find.byType(SuperTabDetailDialog), findsNothing);(server.state['machines'] as List)[0]['observation']['receivedAt'] =at - 600000;await c.refresh();@@ -1226,7 +1225,7 @@ void main() {expect(row, findsOneWidget);await openMachineDetails(tester, row);await tester.pumpAndSettle();- await tester.tap(find.widgetWithText(TextButton, 'Attach running agent'));+ await tester.tap(find.text('Attach running agent'));await tester.pumpAndSettle();expect(attached, [c.selected!.id]);await tester.pumpWidget(const SizedBox());@@ -1345,7 +1344,7 @@ void main() {find.byKey(const ValueKey('super-machine-local-models-run')),findsNothing,);- await tester.tap(find.widgetWithText(TextButton, 'Close'));+ await tester.tap(find.byTooltip('Close'));await tester.pumpAndSettle();await tester.pumpWidget(const SizedBox());await c.flush();@@ -1547,12 +1546,11 @@ void main() {await tester.pumpAndSettle();final remove = find.byKey(const ValueKey('super-machine-remove'));expect(remove, findsOneWidget);- expect(- find.text(- 'Mira is the Product Manager of project Pilot. Delete the project first.',- ),- findsOneWidget,- );+ // Why, on the unavailable control itself, not as a sentence under the title (Ken, 2026-10-28).+ const why =+ 'Mira is the Product Manager of project Pilot. Delete the project first.';+ expect(find.text(why), findsNothing);+ expect(find.byTooltip(why), findsOneWidget);expect(server.posts, isEmpty);await tester.pumpWidget(const SizedBox());await c.flush();@@ -1674,7 +1672,9 @@ void main() {await c.refresh();await tester.pumpAndSettle();expect(- find.textContaining('Product Manager of project Pilot'),+ find.byTooltip(+ 'Mira is the Product Manager of project Pilot. Delete the project first.',+ ),findsOneWidget,);final remove = tester.widget<AppIconButton>(@@ -1708,7 +1708,7 @@ void main() {);await tester.pumpAndSettle();expect(find.byKey(const ValueKey('super-machine-remove')), findsNothing);- await tester.tap(find.widgetWithText(TextButton, 'Close'));+ await tester.tap(find.byTooltip('Close'));await tester.pumpAndSettle();await tester.pumpWidget(const SizedBox());await owner.flush();@@ -1729,7 +1729,7 @@ void main() {find.byKey(const ValueKey('super-machine-remove')),findsOneWidget,);- await tester.tap(find.widgetWithText(TextButton, 'Close'));+ await tester.tap(find.byTooltip('Close'));await tester.pumpAndSettle();await tester.pumpWidget(const SizedBox());await c.flush();@@ -1964,7 +1964,7 @@ void main() {);await tester.pumpAndSettle();}- final dialog = find.byType(AlertDialog);+ final dialog = find.byType(SuperTabDetailDialog);final details = find.byType(SuperTabMachineDetails);expect(dialog, findsOneWidget);expect(details, findsOneWidget);@@ -1985,18 +1985,14 @@ void main() {expect(find.descendant(of: details,- matching: find.textContaining(- '5-hour: 70% remaining\nResets in ',- ),+ matching: find.textContaining('70% left · resets in '),),findsOneWidget,);expect(find.descendant(of: details,- matching: find.textContaining(- 'Weekly: 90% remaining\nResets in ',- ),+ matching: find.textContaining('90% left · resets in '),),findsOneWidget,);@@ -2022,7 +2018,7 @@ void main() {'machine-details-more-$captureName',);}- await tester.tap(find.widgetWithText(TextButton, 'Close'));+ await tester.tap(find.byTooltip('Close'));await tester.pumpAndSettle();expect(tester.takeException(), isNull);await tester.pumpWidget(const SizedBox());@@ -2069,6 +2065,53 @@ void main() {expect(superTabRepositoryUrl('/Users/me/project.git'), isNull);expect(superTabRepositoryUrl('github.com'), isNull);});+ testWidgets(+ 'Add machine shows a long hostname whole, over two lines if it must',+ (tester) async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ const host = 'autonomous-code-vm-01.c.autonomous-code.internal';+ f.app.machineStates['m']!.machine = f.app.machineStates['m']!.machine+ .copyWith(name: host);+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SizedBox(+ width: 300,+ height: 400,+ child: SuperTabMachines(+ controller: c,+ app: f.app,+ onAddAgent: (_) {},+ readLocal: (_) async => _reading(freeGiB: 8),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.byTooltip('Add machine'));+ await tester.pumpAndSettle();+ final label = find.descendant(+ of: _picker,+ matching: find.textContaining(host),+ );+ expect(label, findsOneWidget);+ final paragraph = tester.renderObject<RenderParagraph>(label);+ expect(+ paragraph.didExceedMaxLines,+ isFalse,+ reason: 'the whole hostname is readable',+ );+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ },+ );+testWidgets('Add machine has one field and contributes the prepared project and installed engines',(tester) async {@@ -2101,12 +2144,15 @@ void main() {await tester.pumpAndSettle();await tester.tap(find.byTooltip('Add machine'));await tester.pumpAndSettle();+ // One short paragraph instead of three (Ken, 2026-10-28).expect(find.text(- 'Agents the Swarm starts on this machine run without asking for permission.',+ "The Swarm's product managers can start agents here with this machine's signed-in accounts. "+ 'They run without asking for permission, in projects cloned to ~/harnesses/swarms.',),findsOneWidget,);+ expect(find.textContaining('Harness clones each project'), findsNothing);expect(_picker, findsOneWidget);expect(find.text('This Mac (${f.app.stateOf('m')!.machine.displayName})'),@@ -2114,19 +2160,9 @@ void main() {);expect(find.byType(Checkbox), findsNothing);expect(find.text('Choose project folder'), findsNothing);- expect(- find.descendant(- of: find.byType(AlertDialog),- matching: find.text(- 'Harness clones each project into ~/harnesses/swarms and lets '- "the Swarm's agents work in it.",- ),- ),- findsOneWidget,- );await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));await _settleSave(tester);- expect(find.byType(AlertDialog), findsNothing);+ expect(find.byType(SuperTabDetailDialog), findsNothing);expect(f.connection.server.posts.single['command'], {'type': 'machine.contribute','machineId': 'm',@@ -2441,7 +2477,7 @@ void main() {expect(_option('m2'), findsOneWidget);await tester.sendKeyEvent(LogicalKeyboardKey.escape);await tester.pumpAndSettle();- expect(find.byType(AlertDialog), findsOneWidget);+ expect(find.byType(SuperTabDetailDialog), findsOneWidget);expect(_option('m2'), findsNothing);expect(tester.widget<TextButton>(_picker).focusNode!.hasFocus, isTrue);expect(tester.takeException(), isNull);@@ -2473,7 +2509,7 @@ void main() {),isEmpty,);- expect(find.byType(AlertDialog), findsOneWidget);+ expect(find.byType(SuperTabDetailDialog), findsOneWidget);await tester.pumpWidget(const SizedBox());await c.flush();@@ -2703,7 +2739,7 @@ void main() {await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));await _settleSave(tester);- expect(find.byType(AlertDialog), findsNothing);+ expect(find.byType(SuperTabDetailDialog), findsNothing);expect(f.connection.server.posts.single['command'], {'type': 'machine.contribute','machineId': 'm',@@ -2884,7 +2920,7 @@ void main() {await tester.tap(find.widgetWithText(FilledButton, 'Save'));await _settleSave(tester);- expect(find.byType(AlertDialog), findsNothing);+ expect(find.byType(SuperTabDetailDialog), findsNothing);expect(f.connection.server.posts.single['command'], {'type': 'machine.contribute','machineId': 'm',@@ -2928,7 +2964,7 @@ void main() {f.connection.server.loseReply = true;await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));await _settleSave(tester);- expect(find.byType(AlertDialog), findsOneWidget);+ expect(find.byType(SuperTabDetailDialog), findsOneWidget);expect(f.connection.server.posts.single['command']!['maxAgents'], 4);// The owner changes their mind before trying again.@@ -2940,7 +2976,7 @@ void main() {await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));await _settleSave(tester);- expect(find.byType(AlertDialog), findsNothing);+ expect(find.byType(SuperTabDetailDialog), findsNothing);// The stored attempt is settled first, and then the six on screen — the// four it was built with is not what the machine ends up with.expect(f.connection.server.posts.last['command']!['maxAgents'], 6);@@ -2977,7 +3013,7 @@ void main() {// suggestion is the number the field would have shown.await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));await _settleSave(tester);- expect(find.byType(AlertDialog), findsNothing);+ expect(find.byType(SuperTabDetailDialog), findsNothing);expect(f.connection.server.posts.single['command']!['maxAgents'], 8);expect(tester.takeException(), isNull);@@ -3010,7 +3046,7 @@ void main() {f.connection.server.loseReply = true;await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));await _settleSave(tester);- expect(find.byType(AlertDialog), findsOneWidget);+ expect(find.byType(SuperTabDetailDialog), findsOneWidget);// Now the earlier attempt cannot be checked either, and the reason it// gives is the one worth reading.@@ -3020,7 +3056,7 @@ void main() {};await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));await _settleSave(tester);- expect(find.byType(AlertDialog), findsOneWidget);+ expect(find.byType(SuperTabDetailDialog), findsOneWidget);expect(find.text('This machine is no longer linked to this Swarm.'),findsOneWidget,diff --git a/desktop/test/super_tab_project_github_test.dart b/desktop/test/super_tab_project_github_test.dartindex 78fc516a9..207b4983e 100644--- a/desktop/test/super_tab_project_github_test.dart+++ b/desktop/test/super_tab_project_github_test.dart@@ -8,6 +8,10 @@ import 'package:flutter_test/flutter_test.dart';import 'package:harness/super_tabs/controller.dart';import 'package:harness/super_tabs/model.dart';import 'package:harness/super_tabs/project_github.dart';+import 'package:harness/super_tabs/project_options.dart';+import 'package:harness/shared/theme/app_icons.dart';+import 'package:harness/super_tabs/detail_dialog.dart';+import 'package:harness/widgets/desktop_chrome.dart';import 'support/super_tab_fixture.dart';@@ -163,7 +167,13 @@ void main() {await tester.tap(find.byKey(const Key('super-project-github-check')));await tester.pumpAndSettle();expect(asked.last, endsWith('/github?refresh=1'));- expect(find.textContaining("GitHub ✓"), findsOneWidget);+ // A check mark, the app's own, not a ✓ typed into the sentence (Ken, 2026-10-28).+ expect(+ find.text("Teammates' agents can push and open pull requests on acme/app."),+ findsOneWidget,+ );+ expect(find.textContaining('✓'), findsNothing);+ expect(find.byIcon(AppIcons.check), findsOneWidget);expect(find.byKey(const Key('super-project-github-install')),findsNothing,@@ -329,8 +339,71 @@ void main() {await tester.pumpAndSettle();expect(asked.last, endsWith('/github?refresh=1'));expect(find.text("Teammates can't push here yet"), findsNothing);- expect(find.textContaining('GitHub ✓'), findsOneWidget);+ expect(find.textContaining("Teammates' agents can push"), findsOneWidget);expect(find.byKey(const Key('super-project-github-waiting')), findsNothing);c.dispose();});++ testWidgets(+ 'Project details is titled by the project, with its repository, Product Manager and GitHub access in one column',+ (tester) async {+ answer = {'state': 'covered', 'repository': 'acme/app'};+ final c = await mount(+ tester,+ (c, p) => Builder(+ builder: (context) => TextButton(+ onPressed: () => showProjectAction(context, c, p, 'details'),+ child: const Text('open'),+ ),+ ),+ );+ final project = c.snapshot!.projects.first;+ await tester.tap(find.text('open'));+ await tester.pumpAndSettle();+ final dialog = find.byType(SuperTabDetailDialog);+ expect(dialog, findsOneWidget);+ expect(+ find.descendant(of: find.byType(DesktopDialogHeader), matching: find.text(project.name)),+ findsOneWidget,+ );+ // An empty description is quiet, not an instruction.+ expect(find.text('No description yet'), findsOneWidget);+ expect(find.textContaining('Discuss the project'), findsNothing);+ final values = [+ for (final label in ['Repository', 'Product Manager', 'GitHub access'])+ tester.getTopLeft(find.text(label)).dx,+ ];+ expect(values.toSet(), hasLength(1), reason: 'labels share one column');+ expect(find.byIcon(AppIcons.check), findsOneWidget);+ expect(find.widgetWithText(TextButton, 'Close'), findsNothing);+ await tester.tap(find.byTooltip('Close'));+ await tester.pumpAndSettle();+ expect(dialog, findsNothing);+ c.dispose();+ },+ );++ testWidgets('Project details shows a written description as it is', (tester) async {+ answer = {'state': 'covered', 'repository': 'acme/app'};+ final c = await mount(+ tester,+ (c, p) => Builder(+ builder: (context) => TextButton(+ onPressed: () => showProjectAction(context, c, p, 'details'),+ child: const Text('open'),+ ),+ ),+ );+ final project = c.snapshot!.projects.first;+ final lead = (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((g) => g['id'] == project.leadConversationId);+ lead['brief'] = 'hi';+ await c.refresh();+ await tester.tap(find.text('open'));+ await tester.pumpAndSettle();+ expect(find.text('hi'), findsOneWidget);+ expect(find.text('No description yet'), findsNothing);+ c.dispose();+ });}diff --git a/desktop/test/super_tab_reply_jump_test.dart b/desktop/test/super_tab_reply_jump_test.dartindex 3e797310b..802a0b027 100644--- a/desktop/test/super_tab_reply_jump_test.dart+++ b/desktop/test/super_tab_reply_jump_test.dart@@ -144,7 +144,7 @@ void main() {});Finder messageList() => find.byWidgetPredicate(- (w) => w is ListView && '${w.key}'.contains('super-messages-'),+ (w) => w is ScrollView && '${w.key}'.contains('super-messages-'),);ScrollPosition listPosition(WidgetTester tester) => tester.state<ScrollableState>(@@ -214,18 +214,23 @@ void main() {tester,) async {final server = chat(250, replyTo: 'message-10');- await show(tester, server);+ final c = await show(tester, server);server.holdReads = Completer<void>();await dragToTop(tester);expect(earlierLoading, findsOneWidget);// The reader moves on while the page is slow.await tester.drag(messageList(), const Offset(0, -300));await settle(tester);- final dragged = listPosition(tester).pixels;+ // The first row the reader sees, where they left it.+ final reading = c+ .messages('lead')+ .map((m) => m.id)+ .firstWhere((id) => row(id).hitTestable().evaluate().isNotEmpty);+ final dragged = tester.getTopLeft(row(reading));server.holdReads!.complete();server.holdReads = null;await tester.pumpAndSettle();- expect(listPosition(tester).pixels, dragged);+ expect(tester.getTopLeft(row(reading)), dragged);});testWidgets('a quote whose original is not loaded reads it and shows it', (diff --git a/desktop/test/super_tab_team_glance_test.dart b/desktop/test/super_tab_team_glance_test.dartindex 6d49f867c..106fbfbae 100644--- a/desktop/test/super_tab_team_glance_test.dart+++ b/desktop/test/super_tab_team_glance_test.dart@@ -7,6 +7,7 @@ import 'package:flutter_test/flutter_test.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/state/harness_activity.dart';import 'package:harness/super_tabs/agent_details.dart';+import 'package:harness/super_tabs/detail_dialog.dart';import 'package:harness/super_tabs/roster.dart';import 'package:harness/super_tabs/team_glance.dart';@@ -124,6 +125,16 @@ Finder _row(String id) => find.byKey(ValueKey('super-member-$id'));Finder _line(String id, String text) =>find.descendant(of: _row(id), matching: find.text(text));+/// The agents a machine lists for [state], as one row's value.+String? _stateRow(Finder machine, String state) {+ final row = find.descendant(+ of: machine,+ matching: find.ancestor(of: find.text(state), matching: find.byType(SuperTabDetailRow)),+ );+ if (row.evaluate().isEmpty) return null;+ return (row.evaluate().first.widget as SuperTabDetailRow).value;+}+Future<void> _openGlance(WidgetTester tester) async {await tester.tap(find.byTooltip('Team at a glance'));await tester.pumpAndSettle();@@ -292,14 +303,8 @@ void main() {),findsOneWidget,);- expect(- find.descendant(of: studio, matching: find.text('Lead · Idle')),- findsOneWidget,- );- expect(- find.descendant(of: studio, matching: find.text('Atlas · Idle')),- findsOneWidget,- );+ // Agents by what they are doing, one row per state, as label and value (Ken, 2026-10-28).+ expect(_stateRow(studio, 'Idle'), 'Lead, Atlas');final laptop = find.byKey(const ValueKey('glance-machine-m2'));expect(find.descendant(@@ -431,10 +436,7 @@ void main() {),findsOneWidget,);- expect(- find.descendant(of: studio, matching: find.text('Finn · Assigned')),- findsOneWidget,- );+ expect(_stateRow(studio, 'Assigned'), 'Finn');expect(find.textContaining('which is offline'), findsNothing);expect(find.byKey(const ValueKey('glance-machine-m1-team')),@@ -480,12 +482,45 @@ void main() {);await _openGlance(tester);expect(- find.text('Hugo runs effort xhigh; its start asked for high.'),+ find.text('Hugo runs at xhigh effort; it was started at high.'),findsOneWidget,);expect(find.textContaining('Nico runs'), findsNothing);expect(find.textContaining('Echo runs'), findsNothing);},);- });++ testWidgets('busy agents on one offline machine are one warning, their names folded', (tester) async {+ final names = ['Milo', 'Kai', 'Iris', 'Ellis', 'Nova'];+ await _swarm(+ tester,+ machines: [_machine('m1', 'Mac Studio', max: 8), _machine('m2', 'MacBook Pro', max: 8, age: _offline)],+ agents: [for (final name in names) _agent(name, 'm2')],+ tasks: [for (final name in names) _task(name, 'working')],+ );+ await _openGlance(tester);+ expect(find.text('5 agents are busy on MacBook Pro, which is offline.'), findsOneWidget);+ expect(find.textContaining('Milo is busy'), findsNothing);+ expect(find.text('Milo, Kai, Iris and 2 more'), findsOneWidget);+ await tester.tap(find.text('Milo, Kai, Iris and 2 more'));+ await tester.pumpAndSettle();+ expect(+ find.text('Milo, Kai, Iris, Ellis, Nova'),+ findsNWidgets(2),+ reason: 'the unfolded warning, and the machine\'s Assigned row',+ );+ });++ testWidgets('agents on another effort than they started with are one warning, in plain words', (tester) async {+ await _swarm(+ tester,+ agents: [_agent('Robin', 'm1', effort: 'xhigh'), _agent('Sage', 'm1', effort: 'xhigh')],+ starts: [_start('Robin', 'high'), _start('Sage', 'high')],+ );+ await _openGlance(tester);+ expect(find.text('2 agents run at another effort than they were started with.'), findsOneWidget);+ expect(find.text('Robin (xhigh, started at high), Sage (xhigh, started at high)'), findsOneWidget);+ expect(find.textContaining('runs effort'), findsNothing);+ });+});}diff --git a/desktop/test/super_tab_team_machine_test.dart b/desktop/test/super_tab_team_machine_test.dartindex 4de30314b..385ccd330 100644--- a/desktop/test/super_tab_team_machine_test.dart+++ b/desktop/test/super_tab_team_machine_test.dart@@ -296,6 +296,47 @@ void main() {},);+ // Local Team account run, 2026-10-28: after `harness team remove` its pool stays listed, and the Mac's owner read+ // "Harness Team account offline" with no way to set one up again.+ testWidgets(+ 'a removed Harness Team account leaves its Mac a Mac without one: not set up, and Set up for its owner',+ (tester) async {+ final app = createApp(connected: true)..macOSForTest = true;+ app.machineStates['m']!.localOnly = true;+ final server = _swarm();+ server.state['machines'] = [+ _pool(+ 'm',+ contributor: 'owner',+ teamWork: _refused('TEAM_ACCOUNT_REQUIRED'),+ ),+ _pool(+ 'm-team',+ contributor: 'owner',+ host: 'm',+ teamWork: _refused('TEAM_ACCOUNT_REQUIRED'),+ ),+ ];+ final c = server.controller(account: 'owner');+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabMachines(controller: c, app: app, onAddAgent: (_) {}),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(_problemText(tester, 'm'), "Teammates' agents paused: not set up");+ expect(+ find.byKey(const ValueKey('super-machine-team-setup-m')),+ findsOneWidget,+ );+ await _unmount(tester, c);+ app.dispose();+ },+ );+testWidgets('the line stays away when it would say nothing new', (tester,) async {diff --git a/desktop/test/super_tab_teammate_terminal_test.dart b/desktop/test/super_tab_teammate_terminal_test.dartindex 5fe2ef3cc..52d7dbde6 100644--- a/desktop/test/super_tab_teammate_terminal_test.dart+++ b/desktop/test/super_tab_teammate_terminal_test.dart@@ -288,11 +288,16 @@ void main() {final heard = now.subtract(const Duration(seconds: 4)).millisecondsSinceEpoch;- // River (Ken's Lead, 2026-10-28): a Product Manager reads people's private chats, so no share ever opens it.+ // Every member watches the current Product Manager, view only (Ken, 2026-10-28), though the backend marks it+ // confidential: until its invitation arrives, its computer is the one to update.+ final pm = snapshot(receivedAt: heard, lead: true, confidential: true);+ expect(superTabTerminalPrivate(pm, pm.agent('river')!), isFalse);expect(- reason(snapshot(receivedAt: heard, lead: true), 'river'),- 'River is the Product Manager and reads private chats, so only '- '[email protected] can watch its terminal.',+ reason(pm, 'river'),+ 'River runs on $_computer, [email protected]’s computer. Its '+ 'terminal is not shared with you yet: Harness there shares it with '+ 'Swarm members once it is up to date and running. Ask '+ '[email protected] to update and restart Harness, then Retry.',);// Marked confidential by the backend: in a private chat, or a Product Manager before.final private = reason(diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex 80016cc10..45620bd46 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -407,6 +407,11 @@ class ConversationServer {Completer<void>? holdDecisions;// Every read of a decisions list fails, as offline.bool failDecisions = false;+ // The most each decisions list returns, newest first, as the backend caps+ // it; set, a list also says whether it left others out, as the backend does.+ int? decisionPage;+ // A backend from before Let PM decide: no list of every answered one.+ bool settledMissing = false;// A backend from before the decisions digest: it sends the count alone.bool decisionsDigestMissing = false;// How many times the mentions list was read.@@ -633,10 +638,14 @@ class ConversationServer {} else if (command['type'] == 'message.react') {output['changed'] = _react(command, reader ?? 'owner');} else if (command['type'] == 'decision.answer') {- answerDecision(- command['decisionId'] as String,- command['choice'] as int,- );+ final id = command['decisionId'] as String;+ if (command['delegate'] == true) {+ // Left to the PM: the backend takes the recommended option.+ final asked = decisions.firstWhere((d) => d['id'] == id);+ answerDecision(id, asked['recommended'] as int, delegated: true);+ } else {+ answerDecision(id, command['choice'] as int);+ }} else if (command['type'] == 'mention.done') {mentions.firstWhere((m) => m['id'] == command['mentionId'])..['resolvedAt'] = '2026-10-24T06:00:00Z'@@ -793,12 +802,26 @@ class ConversationServer {decisionReads++;if (holdDecisions case final hold?) await hold.future;if (failDecisions) throw StateError('Offline');- final open = uri.queryParameters['state'] == 'open';+ final state = uri.queryParameters['state'];+ if (state == 'settled' && settledMissing) {+ throw const SuperTabFailure(+ 'INVALID_REQUEST',+ 'Invalid query.',+ statusCode: 400,+ );+ }+ final open = state == 'open';+ // What an older Desktop reads as answered leaves out those the PM+ // decided; `settled` has them all.+ final listed = decisions.reversed+ .where((d) => (d['answeredAt'] == null) == open)+ .where((d) => state != 'answered' || d['delegated'] != true)+ .toList();+ final page = decisionPage;return jsonDecode(jsonEncode({- 'decisions': decisions.reversed- .where((d) => (d['answeredAt'] == null) == open)- .toList(),+ 'decisions': listed.take(page ?? listed.length).toList(),+ if (page != null) 'more': listed.length > page,}),) as Map<String, dynamic>;}@@ -948,6 +971,7 @@ class ConversationServer {'answeredAt': null,'choice': null,'note': null,+ 'delegated': false,});}state['decisionsWaiting'] =@@ -957,9 +981,10 @@ class ConversationServer {}/// The reader answers one, here or on another device.- void answerDecision(String id, int choice) {+ void answerDecision(String id, int choice, {bool delegated = false}) {decisions.firstWhere((d) => d['id'] == id)..['choice'] = choice+ ..['delegated'] = delegated..['answeredAt'] = '2026-10-27T06:00:00Z';state['decisionsWaiting'] = (state['decisionsWaiting'] as int) - 1;_digestDecisions();diff --git a/desktop/test/swarm_sharing_test.dart b/desktop/test/swarm_sharing_test.dartindex 273e331d1..9cd2e83c2 100644--- a/desktop/test/swarm_sharing_test.dart+++ b/desktop/test/swarm_sharing_test.dart@@ -433,15 +433,97 @@ void main() {final remove = find.widgetWithText(TextButton, 'Remove');expect(remove, findsOneWidget);expect(tester.widget<TextButton>(remove).onPressed, isNull);+ // Why, where it matters: on the unavailable Remove, not as a sentence in the list (Ken, 2026-10-28).+ const why =+ 'Quinn is the Product Manager of project Pilot. Delete the project first.';+ expect(find.text(why), findsNothing);+ expect(find.byTooltip(why), findsOneWidget);+ // A quiet control, not a heavy pill on every row.expect(- find.text(- 'Quinn is the Product Manager of project Pilot. Delete the project first.',- ),- findsOneWidget,+ tester.widget<TextButton>(remove).style?.backgroundColor?.resolve({}),+ Colors.transparent,);expect(server.posts, isEmpty);});+ testWidgets(+ 'the owner\'s row says only Owner, even when an agent of theirs is a Product Manager',+ (tester) async {+ final server = SwarmSharingServer();+ server.state['agents'] = [+ {+ 'id': 'pm',+ 'name': 'River',+ 'machineId': 'm',+ 'harnessId': 'native-pm',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'claude'},+ },+ ];+ (server.state['conversations'] as List)[0]['leadId'] = 'pm';+ await _open(tester, server);+ await tester.tap(find.byKey(const Key('swarm-sharing-people')));+ await tester.pumpAndSettle();+ expect(find.text('Owner'), findsOneWidget);+ expect(find.textContaining('Product Manager'), findsNothing);+ expect(+ find.byTooltip(+ 'River is the Product Manager of project Pilot. Delete the project first.',+ ),+ findsNothing,+ );+ },+ );++ testWidgets(+ 'one primary action at a time: Save, not Invite as well, once general access changes',+ (tester) async {+ final server = SwarmSharingServer();+ await _open(tester, server);+ await tester.enterText(+ find.byKey(const Key('swarm-invite-email')),+ '[email protected]',+ );+ await tester.pumpAndSettle();+ expect(+ find.byType(FilledButton),+ findsOneWidget,+ reason: 'Invite, while nothing else changed',+ );+ await _choose(tester, 'swarm-general-access', 'Anyone with the link');+ expect(find.byType(FilledButton), findsOneWidget);+ expect(find.widgetWithText(FilledButton, 'Save'), findsOneWidget);+ // Invite still works, as a secondary action.+ final invite = tester.widget<ButtonStyleButton>(+ find.byKey(const Key('swarm-invite-send')),+ );+ expect(invite.onPressed, isNotNull);+ },+ );++ testWidgets('the email, its access and Invite sit on one line', (+ tester,+ ) async {+ final server = SwarmSharingServer();+ await _open(tester, server);+ double middle(Finder f) => tester.getCenter(f).dy;+ final email = middle(find.byKey(const Key('swarm-invite-email')));+ expect(+ middle(find.byKey(const Key('swarm-invite-role'))),+ closeTo(email, 1),+ );+ expect(+ middle(find.byKey(const Key('swarm-invite-send'))),+ closeTo(email, 1),+ );+ expect(+ tester.getTopLeft(find.byKey(const Key('swarm-invite-role'))).dx,+ greaterThan(+ tester.getTopRight(find.byKey(const Key('swarm-invite-email'))).dx,+ ),+ );+ });+testWidgets('member removal shows a backend Product Manager refusal', (tester,) async {diff --git a/devices/harness-device/firmware/main/cable_client.c b/devices/harness-device/firmware/main/cable_client.cindex 6f267c3b0..e7c6a3b30 100644--- a/devices/harness-device/firmware/main/cable_client.c+++ b/devices/harness-device/firmware/main/cable_client.c@@ -321,6 +321,9 @@ static void send_hello(void)// a wait back from this dial, which once had to: a wait is never an answer screen here.msg_string(&root, "swarmCard", "v1");msg_string(&root, "superTab", "wait-v1");+ // Each Lead's face is the chat the desktop has open, and the alerts are the Lead's new messages (handle_supertab_notice;+ // design 2026-10-28-round-dial-swarm-chat). A daemon that predates it ignores the field and sends today's frames.+ msg_string(&root, "swarmChat", "v1");// Which of the two dials this is (board.h) — informational, so a log or a bug report can say. A// daemon that predates the field ignores it.msg_string(&root, "hw", board()->name);@@ -955,6 +958,8 @@ static void handle_supertab(const cJSON *p)// Absent from a daemon before `order`: the frame's own order stands..order = cJSON_IsNumber(order) && order->valuedouble >= 0 && order->valuedouble < 65536 ? (int)order->valuedouble : -1,.since = cJSON_IsNumber(since) && since->valuedouble >= 0 ? (since->valuedouble > 2592000 ? 2592000 : (long)since->valuedouble) : -1,+ // The chat on the face; absent from a daemon without swarmChat, which reads as the Lead chat.+ .chat = str_of(l, "chat"), .chat_id = str_of(l, "chatId"), .chat_name = str_of(l, "chatName"),};ht_supertab_lead_add(&card, &in);}@@ -967,12 +972,34 @@ static void handle_supertab(const cJSON *p)// `supertab.recap`: one Lead's last message. The model cuts it to 1,500 bytes; `none` is "no message yet".static void handle_supertab_recap(const cJSON *p){- const char *tab = str_of(p, "tab"), *lead = str_of(p, "lead"), *text = str_of(p, "text");+ const char *tab = str_of(p, "tab"), *lead = str_of(p, "lead"), *text = str_of(p, "text"), *chat_id = str_of(p, "chatId");if (!id_fits(tab) || !id_fits(lead)) return;+ // A chat's recap names its chat; one whose chat cannot be held is not one (never shown for another).+ if (chat_id && !id_fits(chat_id)) return;const cJSON *at = cJSON_GetObjectItemCaseSensitive(p, "at");const double secs = cJSON_IsNumber(at) && at->valuedouble > 0 ? at->valuedouble : 0;const bool none = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(p, "none"));- ui_supertab_recap(tab, lead, none || !text ? "" : text, secs > 4294967295.0 ? 0xFFFFFFFFu : (uint32_t)secs, none);+ ui_supertab_recap(tab, lead, chat_id ? chat_id : "", none || !text ? "" : text, secs > 4294967295.0 ? 0xFFFFFFFFu : (uint32_t)secs, none);+}+// `supertab.notice` {tab, lead, chat, chatId, id, text, at}: the Lead's new message in its Lead conversation or Chat with+// PM, the one thing that alerts with a swarmChat daemon. The daemon sends each once; the UI decides the beep.+static void handle_supertab_notice(const cJSON *p)+{+ const char *tab = str_of(p, "tab"), *lead = str_of(p, "lead"), *chat = str_of(p, "chat"), *chat_id = str_of(p, "chatId");+ const char *id = str_of(p, "id"), *text = str_of(p, "text");+ if (!id_fits(tab) || !id_fits(lead) || !id_fits(chat_id) || !id_fits(id) || !text || !chat) return;+ if (strcmp(chat, "lead") && strcmp(chat, "pm")) return; // groups never alert+ const cJSON *at = cJSON_GetObjectItemCaseSensitive(p, "at");+ const double secs = cJSON_IsNumber(at) && at->valuedouble > 0 ? at->valuedouble : 0;+ if (ui_supertab_notice(tab, lead, strcmp(chat, "pm") ? HT_CHAT_LEAD : HT_CHAT_PM, chat_id, text,+ secs > 4294967295.0 ? 0xFFFFFFFFu : (uint32_t)secs))+ audio_notify_done();+}+// `supertab.notice.read` {tab, lead, chatId}: the desktop opened that chat, so its alert is read.+static void handle_supertab_notice_read(const cJSON *p)+{+ const char *tab = str_of(p, "tab"), *lead = str_of(p, "lead"), *chat_id = str_of(p, "chatId");+ if (id_fits(tab) && id_fits(lead) && id_fits(chat_id)) ui_supertab_notice_read(tab, lead, chat_id);}// `supertab.focus` {tab, lead}. An empty `lead` is the desktop on that Swarm's tab with no project open: still a focus.static void handle_supertab_focus(const cJSON *p)@@ -1373,6 +1400,8 @@ static void handle_message(const cJSON *root)if (strcmp(t, "supertab") == 0) { handle_supertab(p); return; }if (strcmp(t, "supertab.recap") == 0) { handle_supertab_recap(p); return; }if (strcmp(t, "supertab.focus") == 0) { handle_supertab_focus(p); return; }+ if (strcmp(t, "supertab.notice") == 0) { handle_supertab_notice(p); return; }+ if (strcmp(t, "supertab.notice.read") == 0) { handle_supertab_notice_read(p); return; }if (strcmp(t, "agent.updated") == 0) {// One agent changed. Cheapest correct answer is to re-ask: the daemon is on the other end of adiff --git a/devices/harness-device/firmware/main/cable_client.h b/devices/harness-device/firmware/main/cable_client.hindex 80afa567a..25a9c4e38 100644--- a/devices/harness-device/firmware/main/cable_client.h+++ b/devices/harness-device/firmware/main/cable_client.h@@ -210,7 +210,7 @@ typedef struct {bool read_on_dial;uint32_t display_revision;uint32_t received_ms; // ms() when the row was filed; rows expire 6 h later (notice_expire)- uint8_t swarm; // the dial's own Swarm entry, kept across notif.replace: 1 needs you, 2 stuck (0 the desktop's)+ uint8_t swarm; // the dial's own Swarm entry, kept across notif.replace: 1 needs you, 2 stuck, 3 the Lead said (0 the desktop's)} cable_notif_t;bool cable_client_notification_read(const char *agent_id, const char *read_token);diff --git a/devices/harness-device/firmware/main/ui/habitat/character_types.h b/devices/harness-device/firmware/main/ui/habitat/character_types.hindex dbc51eec8..8865e2f11 100644--- a/devices/harness-device/firmware/main/ui/habitat/character_types.h+++ b/devices/harness-device/firmware/main/ui/habitat/character_types.h@@ -38,6 +38,9 @@ typedef struct {* because they have one text seat; a skin with two reads it here instead.*/const char *tab, *engine, *activity;+ // Focus only: a Swarm face's chat under its project (Chat with PM's "PM", a group's name), on the inner arc. NULL or+ // "" for the Lead chat and every other face, which then draw exactly as before.+ const char *chat;uint32_t elapsed;ht_character_mood_t mood;ht_character_pose_t pose;diff --git a/devices/harness-device/firmware/main/ui/habitat/focus.c b/devices/harness-device/firmware/main/ui/habitat/focus.cindex 9cd5f93b8..956269886 100644--- a/devices/harness-device/firmware/main/ui/habitat/focus.c+++ b/devices/harness-device/firmware/main/ui/habitat/focus.c@@ -916,6 +916,9 @@ void ht_focus_face(ht_scene_t *s, const ht_character_face_t *f, uint8_t frame, uint title_run = s->count;ht_arc_title_face(s, ht_rgb(FOCUS_FG), f->recipient && *f->recipient ? f->recipient : "\xe2\x80\xa6",&ht_arc_inter_prop);+ // A Swarm face's chat, smaller and grey on the curve under it, in the gap above the pet (option A, 2026-10-28).+ static const ht_arc_face_t chat_face = {.prop = &ht_lv_inter_20, .mid = 12};+ if (f->chat && *f->chat) ht_arc_inner_face(s, ht_rgb(HT_THEME_SECONDARY), f->chat, &chat_face);// The engine's mark, where the octopus stands. An unknown engine leaves the place empty.int engine = ht_focus_engine_index(f->engine);diff --git a/devices/harness-device/firmware/main/ui/habitat/supertab.c b/devices/harness-device/firmware/main/ui/habitat/supertab.cindex 276182614..0ea21deb2 100644--- a/devices/harness-device/firmware/main/ui/habitat/supertab.c+++ b/devices/harness-device/firmware/main/ui/habitat/supertab.c@@ -57,6 +57,13 @@ bool ht_supertab_lead_add(ht_supertab_t *t, const ht_lead_in_t *in)!strcmp(s, "work") ? HT_LEAD_WORK : HT_LEAD_DONE;l->order = in->order < 0 ? -1 : in->order;l->since_s = in->since < 0 ? -1 : in->since > INT32_MAX ? INT32_MAX : (int32_t)in->since;+ // The chat on the face. One this dial cannot name (an unknown kind, an id it cannot hold) is the Lead chat with no+ // id: the Lead stays, and no chat's recap is taken for it.+ const char *c = in->chat ? in->chat : "";+ l->chat = !strcmp(c, "group") ? HT_CHAT_GROUP : !strcmp(c, "pm") ? HT_CHAT_PM : HT_CHAT_LEAD;+ bool named = (!strcmp(c, "group") || !strcmp(c, "pm") || !strcmp(c, "lead")) && put_id(l->chat_id, in->chat_id, true);+ if (named) put_text(l->chat_name, sizeof l->chat_name, in->chat_name);+ else { l->chat = HT_CHAT_LEAD; l->chat_id[0] = 0; l->chat_name[0] = 0; }t->lead_n++;return true;}@@ -163,15 +170,22 @@ void ht_supertabs_recap_open(ht_supertabs_t *s, const char *tab, const char *leabool open = lead && *lead && tab && *tab;put_text(s->recap.tab, sizeof s->recap.tab, open ? tab : "");put_text(s->recap.lead, sizeof s->recap.lead, open ? lead : "");+ s->recap.chat_id[0] = 0;s->recap.text[0] = 0;s->recap.at = 0;s->recap.asked_ms = now_ms;s->recap.state = open ? HT_RECAP_LOADING : HT_RECAP_NONE;}-bool ht_supertabs_recap_put(ht_supertabs_t *s, const char *tab, const char *lead, const char *text, uint32_t at, bool none)+bool ht_supertabs_recap_put(ht_supertabs_t *s, const char *tab, const char *lead, const char *chat_id, const char *text, uint32_t at, bool none){if (s->recap.state == HT_RECAP_NONE || !tab || !lead || strcmp(s->recap.tab, tab) || strcmp(s->recap.lead, lead))return false;+ // A recap for another chat than the one on the face (the desktop moved on while it was read) is not this face's.+ const ht_supertab_t *t = ht_supertabs_find(s, tab);+ const char *face = "";+ for (int i = 0; t && i < t->lead_n; i++) if (!strcmp(t->leads[i].id, lead)) face = t->leads[i].chat_id;+ if (strcmp(chat_id ? chat_id : "", face)) return false;+ put_text(s->recap.chat_id, sizeof s->recap.chat_id, face);put_text(s->recap.text, sizeof s->recap.text, none ? "" : text);s->recap.at = at;s->recap.state = s->recap.text[0] ? HT_RECAP_LOADED : HT_RECAP_EMPTY;diff --git a/devices/harness-device/firmware/main/ui/habitat/supertab.h b/devices/harness-device/firmware/main/ui/habitat/supertab.hindex ba028759e..0a6019aec 100644--- a/devices/harness-device/firmware/main/ui/habitat/supertab.h+++ b/devices/harness-device/firmware/main/ui/habitat/supertab.h@@ -11,12 +11,17 @@enum { HT_SUPERTABS_MAX = 16, HT_SUPERTAB_LEADS_MAX = 12, HT_SUPERTAB_NAME = 49, HT_SUPERTAB_TEXT = 1501 };typedef enum { HT_LEAD_DONE, HT_LEAD_WORK, HT_LEAD_ASK, HT_LEAD_STUCK } ht_lead_state_t;+// The chat on a Lead's face (design 2026-10-28-round-dial-swarm-chat): its project's Lead conversation, the reader's Chat+// with PM, or a group. A daemon without `swarmChat` sends none, which reads as the Lead chat with no id.+typedef enum { HT_CHAT_LEAD, HT_CHAT_PM, HT_CHAT_GROUP } ht_chat_kind_t;typedef struct {char id[ID_MAX], project_id[ID_MAX], project[HT_SUPERTAB_NAME], engine[12], owner[HT_SUPERTAB_NAME], local[ID_MAX];ht_lead_state_t state;int order; // -1 from a daemon that does not send itint32_t since_s; // -1 when the daemon sent none (a remote Lead)uint32_t since_at_ms; // the dial's clock when since_s arrived+ ht_chat_kind_t chat;+ char chat_id[ID_MAX], chat_name[HT_SUPERTAB_NAME]; // "" from a daemon without swarmChat} ht_lead_t;typedef struct {char id[ID_MAX], tab[ID_MAX], name[HT_SUPERTAB_NAME];@@ -31,13 +36,14 @@ typedef struct {char ids[HT_SUPERTABS_MAX][ID_MAX]; // the last `supertabs` list: the order Swarms are shown inint id_n;// One slot: the recap of the Lead on the face, and nothing else.- struct { char tab[ID_MAX], lead[ID_MAX], text[HT_SUPERTAB_TEXT]; uint32_t at, asked_ms; ht_recap_state_t state; } recap;+ // `chat_id`: the chat the text is the last message of ("" from a daemon without swarmChat).+ struct { char tab[ID_MAX], lead[ID_MAX], chat_id[ID_MAX], text[HT_SUPERTAB_TEXT]; uint32_t at, asked_ms; ht_recap_state_t state; } recap;} ht_supertabs_t;typedef enum { HT_LEAD_RAISED_ASK, HT_LEAD_RAISED_STUCK, HT_LEAD_CLEARED } ht_lead_event_kind_t;typedef struct { ht_lead_event_kind_t kind; char tab[ID_MAX], lead[ID_MAX]; } ht_lead_event_t;// One Lead of a frame, as read off the wire. NULL strings are absent fields.-typedef struct { const char *id, *project_id, *project, *engine, *owner, *local, *state; int order; long since; } ht_lead_in_t;+typedef struct { const char *id, *project_id, *project, *engine, *owner, *local, *state; int order; long since; const char *chat, *chat_id, *chat_name; } ht_lead_in_t;// false: an empty or overlong id or tab. Names are cut on a UTF-8 boundary.bool ht_supertab_init(ht_supertab_t *, const char *id, const char *tab, const char *name, int count);// false: the Lead is malformed or repeats an id (skipped, not the frame), or the record already holds 12.@@ -56,5 +62,5 @@ const ht_supertab_t *ht_supertabs_for_desk(const ht_supertabs_t *, const char *dconst ht_lead_t *ht_supertabs_lead_by_local(const ht_supertabs_t *, const char *harness_id, const ht_supertab_t **tab);// LOADING with no text; an empty lead closes the slot (NONE).void ht_supertabs_recap_open(ht_supertabs_t *, const char *tab, const char *lead, uint32_t now_ms);-// false: not the open Lead.-bool ht_supertabs_recap_put(ht_supertabs_t *, const char *tab, const char *lead, const char *text, uint32_t at, bool none);+// false: not the open Lead, or not the chat on its face (`chat_id` "" is the Lead's own, from a daemon without swarmChat).+bool ht_supertabs_recap_put(ht_supertabs_t *, const char *tab, const char *lead, const char *chat_id, const char *text, uint32_t at, bool none);diff --git a/devices/harness-device/firmware/main/ui/habitat/terminal.c b/devices/harness-device/firmware/main/ui/habitat/terminal.cindex d156b7e9c..27514c1d8 100644--- a/devices/harness-device/firmware/main/ui/habitat/terminal.c+++ b/devices/harness-device/firmware/main/ui/habitat/terminal.c@@ -1,6 +1,11 @@#include "terminal.h"#include <stdio.h>#include <string.h>+#ifdef ESP_PLATFORM+#include "esp_heap_caps.h"+#else+#include <stdlib.h>+#endif#include "arc_geometry.inc"#include "display_fallbacks.inc"@@ -667,6 +672,9 @@ bool ht_ring_arc(ht_scene_t *s, int cx16, int cy16, int radius16, int width16, i* bounds can never be smaller than the ink.*/enum { ARC_PROP_MID = 11, ARC_PROP_RADIUS = 205, ARC_PROP_LOWER = 202, ARC_PROP_SPAN16 = HT_ARC_SPAN * 16 };+// The inner upper arc (ht_arc_inner_face): its caps' middle 33 px inside the title's, and a span of about 30 degrees each+// side of 12 o'clock, so a Swarm face's chat name stays in the gap above the pet (option A of the mockup, 2026-10-28).+enum { ARC_PROP_INNER = 172, ARC_INNER_SPAN16 = 176 * 16 };#ifdef DEVICE_LAYOUT_BENCHstatic bool arc_tight; // defined below with the mask cache#endif@@ -708,6 +716,8 @@ static void arc_prop_walk(const ht_run_t *r, const ht_pfont_t *f,pen += adv;if (!gl->w || !gl->h) continue;int mag = s16 < 0 ? -s16 : s16;+ // The table steps 1 px of arc on the 205 px curve: on the inner one the same length is a wider angle.+ if (r->arc == 3) mag = mag * ARC_PROP_RADIUS / ARC_PROP_INNER;if (mag > limit) mag = limit;int i = mag >> 4, fr = mag & 15;arc_pplace_t pl = {.g = g, .index = at};@@ -715,7 +725,7 @@ static void arc_prop_walk(const ht_run_t *r, const ht_pfont_t *f,pl.cs = (arc_prop_trig[i][1] * (16 - fr) + arc_prop_trig[i + 1][1] * fr) >> 4;if (s16 < 0) pl.sn = -pl.sn;bool lower = r->arc == 2;- int radius = lower ? ARC_PROP_LOWER : ARC_PROP_RADIUS;+ int radius = lower ? ARC_PROP_LOWER : r->arc == 3 ? ARC_PROP_INNER : ARC_PROP_RADIUS;pl.cx = (233 - r->x) * 256 + (radius * pl.sn * 256 >> 14);pl.cy = (233 - r->y) * 256 + (lower ? 1 : -1) * (radius * pl.cs * 256 >> 14);if (lower) pl.sn = -pl.sn; // the lower arc reads left to right with upright letters@@ -743,7 +753,12 @@ static void arc_prop_walk(const ht_run_t *r, const ht_pfont_t *f,// `text` cut to what fits the span: whole, else at the last word when that keeps at least half the span// (as the mono rule keeps half the columns), else per character, before "…" (none when `bare`).// Newlines are spaces.+static void arc_prop_fit_span(char *dst, size_t cap, const ht_pfont_t *f, const char *text, bool bare, int span16);static void arc_prop_fit(char *dst, size_t cap, const ht_pfont_t *f, const char *text, bool bare)+{+ arc_prop_fit_span(dst, cap, f, text, bare, ARC_PROP_SPAN16);+}+static void arc_prop_fit_span(char *dst, size_t cap, const ht_pfont_t *f, const char *text, bool bare, int span16){char flat[HT_TEXT_BYTES];size_t len = strlen(text), n = len < sizeof flat - 4 ? len : sizeof flat - 4;@@ -757,7 +772,7 @@ static void arc_prop_fit(char *dst, size_t cap, const ht_pfont_t *f, const charmemcpy(dst, flat, n);dst[n] = 0;if (cut && !bare) strcpy(dst + n, "\xe2\x80\xa6");- if (arc_prop_width16(f, dst) <= ARC_PROP_SPAN16 || !n) return;+ if (arc_prop_width16(f, dst) <= span16 || !n) return;size_t k = n, word = 0;while (k && flat[k - 1] != ' ') k--;if (k) {@@ -765,7 +780,7 @@ static void arc_prop_fit(char *dst, size_t cap, const ht_pfont_t *f, const charwhile (word && flat[word - 1] == ' ') word--;memcpy(dst, flat, word);dst[word] = 0;- if (arc_prop_width16(f, dst) < ARC_PROP_SPAN16 / 2) word = 0; // too little left: cut letters+ if (arc_prop_width16(f, dst) < span16 / 2) word = 0; // too little left: cut letters}if (word) n = word;else do n--; while (n && ((uint8_t)flat[n] & 0xc0) == 0x80);@@ -825,15 +840,19 @@ static void arc_union_visit(void *ctx, const arc_pplace_t *g)u->x0 = imin(u->x0, g->x0); u->y0 = imin(u->y0, g->y0);u->x1 = imax(u->x1, g->x1); u->y1 = imax(u->y1, g->y1);}-static void arc_text(ht_scene_t *s, uint16_t fg, const char *text, bool bottom,+// `kind`: 1 the upper arc, 2 the lower, 3 the inner upper arc (proportional faces only).+static void arc_text(ht_scene_t *s, uint16_t fg, const char *text, uint8_t kind,const ht_arc_face_t *face){if (!text || !*text) return;if (!face) face = &ht_arc_geist;+ if (kind == 3 && !face->prop) return;+ bool bottom = kind == 2;char visible[HT_TEXT_BYTES];if (face->prop) {// The run carries the pfont's base as its font; a proportional run is fitted by the caller.- arc_prop_fit(visible, sizeof visible, face->prop, text, face->bare);+ if (kind == 3) arc_prop_fit_span(visible, sizeof visible, face->prop, text, face->bare, ARC_INNER_SPAN16);+ else arc_prop_fit(visible, sizeof visible, face->prop, text, face->bare);if (!ht_text(s, HT_ARC_X, HT_ARC_Y, HT_ARC_WIDTH, &face->prop->base, fg, s->background, visible)) return;} else {bool complete = ht_display_text(visible,sizeof visible,text,face->mono);@@ -847,7 +866,7 @@ static void arc_text(ht_scene_t *s, uint16_t fg, const char *text, bool bottom,}}ht_run_t *r = &s->runs[s->count - 1];- r->arc = bottom ? 2 : 1;+ r->arc = kind;r->y = bottom ? HT_HEIGHT - HT_ARC_Y - HT_ARC_HEIGHT : HT_ARC_Y;r->w = HT_ARC_WIDTH;if (face->prop) {@@ -863,21 +882,25 @@ static void arc_text(ht_scene_t *s, uint16_t fg, const char *text, bool bottom,r->ink_box = (ht_rect_t){r->x + u.x0, r->y + u.y0, u.x1 - u.x0, u.y1 - u.y0};}}-void ht_arc_title(ht_scene_t *s, uint16_t fg, const char *text) { arc_text(s, fg, text, false, &ht_arc_geist); }+void ht_arc_title(ht_scene_t *s, uint16_t fg, const char *text) { arc_text(s, fg, text, 1, &ht_arc_geist); }void ht_arc_title_face(ht_scene_t *s, uint16_t fg, const char *text, const ht_arc_face_t *face){- arc_text(s, fg, text, false, face);+ arc_text(s, fg, text, 1, face);}-void ht_arc_status(ht_scene_t *s, uint16_t fg, const char *text) { arc_text(s, fg, text, true, &ht_arc_geist); }+void ht_arc_status(ht_scene_t *s, uint16_t fg, const char *text) { arc_text(s, fg, text, 2, &ht_arc_geist); }void ht_arc_status_face(ht_scene_t *s, uint16_t fg, const char *text, const ht_arc_face_t *face){- arc_text(s, fg, text, true, face);+ arc_text(s, fg, text, 2, face);+}+void ht_arc_inner_face(ht_scene_t *s, uint16_t fg, const char *text, const ht_arc_face_t *face)+{+ arc_text(s, fg, text, 3, face);}void ht_arc_status_sweep(ht_scene_t *s, uint16_t fg, const char *text, const ht_arc_face_t *face,const uint8_t *gain){int before = s->count;- arc_text(s, fg, text, true, face);+ arc_text(s, fg, text, 2, face);if (!gain || s->count == before || !face || !face->prop) return;ht_run_t *r = &s->runs[s->count - 1];r->gained = 1;@@ -1302,6 +1325,21 @@ typedef struct {} arc_cache_t;_Static_assert(ARC_HALF <= UINT8_MAX, "arc span coordinates must fit in a byte");static arc_cache_t arc_caches[2];+// The inner arc's cache: 10.6 KB the dial spends only once a chat name is drawn, in PSRAM, beside the two above.+static arc_cache_t *arc_inner;+bool ht_arc_inner_cache_made(void) { return arc_inner != NULL; }+static arc_cache_t *arc_cache_for(const ht_run_t *r)+{+ if (r->arc != 3) return &arc_caches[r->arc == 2];+ if (!arc_inner) {+#ifdef ESP_PLATFORM+ arc_inner = heap_caps_calloc(1, sizeof *arc_inner, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);+#else+ arc_inner = calloc(1, sizeof *arc_inner);+#endif+ }+ return arc_inner; // NULL when PSRAM is out: the chat name is not drawn, nothing else changes+}static uint32_t arc_builds;uint32_t ht_arc_cache_builds(void) { return arc_builds; }#ifdef DEVICE_LAYOUT_BENCH@@ -1311,12 +1349,14 @@ void ht_arc_tight_bounds(bool enabled)arc_tight = enabled;arc_caches[0].face = arc_caches[1].face = NULL;arc_caches[0].prop = arc_caches[1].prop = NULL;+ if (arc_inner) arc_inner->face = NULL, arc_inner->prop = NULL;}void ht_arc_fast_sampling(bool enabled){arc_fast = enabled;arc_caches[0].face = arc_caches[1].face = NULL;arc_caches[0].prop = arc_caches[1].prop = NULL;+ if (arc_inner) arc_inner->face = NULL, arc_inner->prop = NULL;}static unsigned glyph_alpha_reference(const uint8_t *glyph, int x, int y){@@ -1533,7 +1573,8 @@ static void arc_prepare(const ht_run_t *r, arc_cache_t *cache)}static void arc_raster(const ht_run_t *r, ht_rect_t clip, uint16_t *out){- arc_cache_t *cache = &arc_caches[r->arc == 2];+ arc_cache_t *cache = arc_cache_for(r);+ if (!cache) return;arc_prepare(r, cache);if (!cache->mask_bytes) return;// Colour a cached mask: no glyph rotation, allocations or extra text runs. The 4-bit (proportional)diff --git a/devices/harness-device/firmware/main/ui/habitat/terminal.h b/devices/harness-device/firmware/main/ui/habitat/terminal.hindex d1e748fdb..e3e55b137 100644--- a/devices/harness-device/firmware/main/ui/habitat/terminal.h+++ b/devices/harness-device/firmware/main/ui/habitat/terminal.h@@ -136,7 +136,7 @@ typedef struct {} ht_sprite_t;typedef struct {int16_t x, y, w;- uint8_t arc; // 0 = straight, 1 = upper arc, 2 = lower arc+ uint8_t arc; // 0 = straight, 1 = upper arc, 2 = lower arc, 3 = inner upper arc (ht_arc_inner_face)uint8_t shimmer; // 0 = steady ink, 1..21 = cached-mask highlight sweepuint16_t fg, bg;const ht_font_t *font;@@ -246,6 +246,13 @@ void ht_arc_title_face(ht_scene_t *scene, uint16_t fg, const char *text, const h// The lower arc, in GeistMono (the non-Focus skins); ht_arc_status_face takes any face, like ht_arc_title_face.void ht_arc_status(ht_scene_t *scene, uint16_t fg, const char *text);void ht_arc_status_face(ht_scene_t *scene, uint16_t fg, const char *text, const ht_arc_face_t *face);+// A smaller label on a tighter curve under the upper arc: a Swarm face's chat name under its project (design+// 2026-10-28-round-dial-swarm-chat). Proportional faces only (a mono face draws nothing), fitted to a shorter span with+// "…". Its mask cache is its own, in PSRAM on the board, and made only the first time such a label is drawn, so a dial+// that never shows one spends nothing on it; the upper and lower arcs and their caches are as before.+void ht_arc_inner_face(ht_scene_t *scene, uint16_t fg, const char *text, const ht_arc_face_t *face);+// Whether the inner arc's cache has been made (for the tests: nothing before a chat name is drawn).+bool ht_arc_inner_cache_made(void);// What `text` takes of the arc in `face`, in px of arc length (a proportional face rounds up; fits when// <= HT_ARC_SPAN). A proportional title or status longer than that ends at a word and "…" (no "…"// for a `bare` face).diff --git a/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c b/devices/harness-device/firmware/main/ui/habitat/ui_habitat.cindex 212d36bb0..fced4cc35 100644--- a/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c+++ b/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c@@ -590,6 +590,7 @@ static int workspace_index(const char *id)*/enum { SUPERTAB_RECAP_GET, SUPERTAB_OPEN, SUPERTAB_SELECT };#define SWARM_WAITS 16+#define SWARM_SAID 24 // one per inbox entry the Lead messages can fill (NOTICES)static EXT_RAM_BSS_ATTR ht_supertabs_t swarm;static EXT_RAM_BSS_ATTR struct {char tab[ID_MAX], lead[ID_MAX]; // the Swarm the dial is in ("" in a desk tab) and the Lead on its face@@ -600,6 +601,8 @@ static EXT_RAM_BSS_ATTR struct {char pending[ID_MAX]; // a Swarm the desktop opened before its `swarms` frame said so (ui_supertab_focus)// Super Tab waits from this machine's harnesses, shown only through the Lead whose `local` names the harness.struct { char agent[ID_MAX], request[80], swarm[HT_SUPERTAB_NAME], text[240]; bool stuck, shown; } waits[SWARM_WAITS];+ // The chat each Lead's message entry (`swarm` 3) came from, so `supertab.notice.read` removes only that one.+ struct { char lead[ID_MAX], chat[ID_MAX]; } said[SWARM_SAID];} sw;static bool swarm_mode(void){@@ -1294,8 +1297,10 @@ static void render_swarm_face(ht_scene_t *f)const char *wait = swarm_wait_text(l);bool asking = l->state == HT_LEAD_ASK || l->state == HT_LEAD_STUCK || wait;bool working = l->state == HT_LEAD_WORK && !wait;+ // A swarmChat daemon's recap is that of the chat on the face: one read for a chat the desktop has since left is not+ // shown (design 2026-10-28-round-dial-swarm-chat §3). An older daemon names no chat on either side.const char *recap = wait ? wait : !working && swarm.recap.state == HT_RECAP_LOADED &&- !strcmp(swarm.recap.lead, l->id) && !s.nap ? swarm.recap.text : NULL;+ !strcmp(swarm.recap.lead, l->id) && !strcmp(swarm.recap.chat_id, l->chat_id) && !s.nap ? swarm.recap.text : NULL;uint32_t since_ms = working && l->since_s >= 0 ? (uint32_t)l->since_s * 1000u + (ms() - l->since_at_ms) : 0;uint32_t since = since_ms / 1000;s.timer_at = 0;@@ -1312,6 +1317,7 @@ static void render_swarm_face(ht_scene_t *f)const ht_supertab_t *t = swarm_here();ht_character_face_t f_ = {.recipient = l->project[0] ? l->project : "Untitled", .status = "", .hint = "",.tab = t ? t->name : "", .engine = l->engine, .activity = working && !s.nap ? "Working" : "",+ .chat = l->chat != HT_CHAT_LEAD ? l->chat_name : NULL,.elapsed = since, .detail = "", .mood = character_mood(), .pose = character.motion.reaction.pose,.asking = asking,.clock_ms = (s.quiet || display_is_asleep()) ? 0 : clock,@@ -4646,7 +4652,8 @@ void ui_notif_replace(const cable_notif_t *rows, int count)if (!present) s.notice_reads[i].pending = false;}for (int i = own_count - 1; i >= 0; i--) {- notice_add(own[i].agent_id, own[i].name, own[i].machine, own[i].summary, true, false);+ // A wait stays pinned as a question; a Lead's message stays news (it would otherwise never expire).+ notice_add(own[i].agent_id, own[i].name, own[i].machine, own[i].summary, own[i].question, false);for (int j = 0; j < s.notice_count; j++) if (!strcmp(s.notice[j].agent_id, own[i].agent_id)) {s.notice[j].swarm = own[i].swarm; s.notice[j].read_on_dial = own[i].read_on_dial;s.notice[j].received_ms = own[i].received_ms;@@ -4994,10 +5001,10 @@ bool ui_supertab(const ht_supertab_t *in)display_unlock();return beep;}-void ui_supertab_recap(const char *tab, const char *lead, const char *text, uint32_t at, bool none)+void ui_supertab_recap(const char *tab, const char *lead, const char *chat_id, const char *text, uint32_t at, bool none){display_lock();- if (ht_supertabs_recap_put(&swarm, tab, lead, text, at, none)) change();+ if (ht_supertabs_recap_put(&swarm, tab, lead, chat_id, text, at, none)) change();display_unlock();}// `lead` "" is the desktop on that Swarm's tab with no project open (its Chat with PM, a DM): the dial still goes in, on@@ -5027,6 +5034,56 @@ void ui_supertab_focus(const char *tab, const char *lead)change();display_unlock();}+/*+ * A LEAD'S NEW MESSAGE (design 2026-10-28-round-dial-swarm-chat §3), in its Lead conversation or Chat with PM: the one+ * alert a swarmChat daemon raises. It is that Lead's single entry, news rather than a question, the message as its text+ * and the Swarm's name (with " · PM" for Chat with PM) as its grey line. Each notice counts as unread again; it is read at+ * once only when that Lead's face shows that very chat. True when the caller should beep (the coalescing is the audio's).+ */+_Static_assert(SWARM_SAID == NOTICES, "a chat for every inbox entry a Lead's message can take");+static int swarm_said_of(const char *lead)+{+ for (int i = 0; lead && i < SWARM_SAID; i++) if (!strcmp(sw.said[i].lead, lead)) return i;+ return -1;+}+bool ui_supertab_notice(const char *tab, const char *lead, ht_chat_kind_t chat, const char *chat_id, const char *text, uint32_t at)+{+ (void)at;+ if (!tab || !lead || !chat_id || !text) return false;+ display_lock();+ const ht_supertab_t *t = ht_supertabs_find(&swarm, tab);+ int i = swarm_lead_index(t, lead);+ if (i < 0) { display_unlock(); return false; }+ const ht_lead_t *l = &t->leads[i];+ char grey[HT_SUPERTAB_NAME + 8];+ snprintf(grey, sizeof grey, "%s%s", t->name, chat == HT_CHAT_PM ? " \xc2\xb7 PM" : "");+ notice_forget_read(l->id);+ notice_add(l->id, l->project[0] ? l->project : "Untitled", grey, text, false, false);+ swarm_notice_mark(l->id, 3);+ int slot = swarm_said_of(l->id);+ for (int k = 0; k < SWARM_SAID && slot < 0; k++) if (!sw.said[k].lead[0] || swarm_notice(sw.said[k].lead) < 0) slot = k;+ if (slot < 0) slot = 0;+ COPY(sw.said[slot].lead, l->id); COPY(sw.said[slot].chat, chat_id);+ s.notice_sequence++;+ bool face = on_face(l->id) && !strcmp(l->chat_id, chat_id);+ if (face) notice_read_now(l->id);+ else display_wake();+ change();+ display_unlock();+ return !face;+}+// The desktop opened that chat: its message entry is read there, and goes from the dial.+void ui_supertab_notice_read(const char *tab, const char *lead, const char *chat_id)+{+ if (!tab || !lead || !chat_id) return;+ display_lock();+ int e = swarm_notice(lead), k = swarm_said_of(lead);+ if (e >= 0 && s.notice[e].swarm == 3 && k >= 0 && !strcmp(sw.said[k].chat, chat_id)) {+ sw.said[k].lead[0] = 0;+ swarm_notice_drop(lead);+ }+ display_unlock();+}bool ui_supertab_wait(const char *agent_id, const char *request, const char *swarm_name, bool stuck, const char *text){if (!agent_id || !agent_id[0] || strlen(agent_id) >= ID_MAX || !request) return false;diff --git a/devices/harness-device/firmware/main/ui/ui_screens.h b/devices/harness-device/firmware/main/ui/ui_screens.hindex 9ade27a37..df0e3080a 100644--- a/devices/harness-device/firmware/main/ui/ui_screens.h+++ b/devices/harness-device/firmware/main/ui/ui_screens.h@@ -258,8 +258,14 @@ void ui_swarms_replace(const cable_swarm_t *rows, int count, const char *selectevoid ui_supertabs_ids(const char ids[][ID_MAX], int n);// One Swarm's card. True when the caller should beep: a Lead started needing a person, off the face.bool ui_supertab(const ht_supertab_t *in);-void ui_supertab_recap(const char *tab, const char *lead, const char *text, uint32_t at, bool none);+// `chat_id`: the chat the text is the last message of, "" from a daemon without swarmChat. Dropped for another chat.+void ui_supertab_recap(const char *tab, const char *lead, const char *chat_id, const char *text, uint32_t at, bool none);void ui_supertab_focus(const char *tab, const char *lead);+// The Lead's new message in its Lead conversation or Chat with PM (`supertab.notice`): that Lead's one inbox entry, read at+// once when its chat is on the face. True when the caller should beep.+bool ui_supertab_notice(const char *tab, const char *lead, ht_chat_kind_t chat, const char *chat_id, const char *text, uint32_t at);+// The desktop opened that chat (`supertab.notice.read`): the entry goes.+void ui_supertab_notice_read(const char *tab, const char *lead, const char *chat_id);// A Super Tab wait from harness `agent_id` (some Lead's `local`). It only sets that Lead's inbox text and face;// it never opens the question screen. True when the caller should beep.bool ui_supertab_wait(const char *agent_id, const char *request, const char *swarm_name, bool stuck, const char *text);diff --git a/devices/harness-device/firmware/test/run.sh b/devices/harness-device/firmware/test/run.shindex 2d5c082e2..fd57c2f4b 100644--- a/devices/harness-device/firmware/test/run.sh+++ b/devices/harness-device/firmware/test/run.sh@@ -89,6 +89,11 @@ cc -std=c11 -Wall -Wextra -Werror -O1 -g -fsanitize="${SANITIZERS:-undefined,bou"$here/../main/ui/habitat/terminal.c" "$here/../main/ui/habitat/fonts.c""$out/test_arc_bounds"+cc -std=c11 -Wall -Wextra -Werror -O1 -g -fsanitize="${SANITIZERS:-undefined,bounds}" \+ -o "$out/test_arc_inner" "$here/test_arc_inner.c" \+ "$here/../main/ui/habitat/focus_faces.c" "$here/../main/ui/habitat/lvgl_fonts.c" "$here/../main/ui/habitat/fonts.c"+"$out/test_arc_inner"+cc -std=c11 -Wall -Wextra -Werror -O1 -g -fsanitize="${SANITIZERS:-undefined,bounds}" \-I "$here/../main/ui/habitat" -o "$out/test_arc_ring" "$here/test_arc_ring.c" \"$here/../main/ui/habitat/terminal.c" "$here/../main/ui/habitat/fonts.c" -lmdiff --git a/devices/harness-device/firmware/test/test_arc_inner.c b/devices/harness-device/firmware/test/test_arc_inner.cnew file mode 100644index 000000000..3bdef5fbb--- /dev/null+++ b/devices/harness-device/firmware/test/test_arc_inner.c@@ -0,0 +1,122 @@+// The inner upper arc (design 2026-10-28-round-dial-swarm-chat §3): the chat name under the project on a Swarm face,+// smaller and on a tighter curve than the title. Long, short and missing names; its span and radius; its mask cache,+// made only when a chat name is drawn; and the title arc it sits under, unchanged by it.+#include "../main/ui/habitat/terminal.c"+#include "../main/ui/habitat/focus_faces.h"+#include <assert.h>+#include <stdio.h>+#include <stdlib.h>++static const ht_arc_face_t chat_face = {.prop = &ht_lv_inter_20, .mid = 12};+static uint16_t px[HT_WIDTH * HT_HEIGHT], other[HT_WIDTH * HT_HEIGHT];++static void raster(const ht_scene_t *scene, uint16_t *out) { ht_raster(scene, (ht_rect_t){0, 0, HT_WIDTH, HT_HEIGHT}, out); }+// The rows and columns the label inked, as the panel shows them.+static ht_rect_t inked(const uint16_t *a, uint16_t ground)+{+ int x0 = HT_WIDTH, y0 = HT_HEIGHT, x1 = -1, y1 = -1;+ for (int y = 0; y < HT_HEIGHT; y++) for (int x = 0; x < HT_WIDTH; x++)+ if (a[y * HT_WIDTH + x] != ground) { x0 = imin(x0, x); x1 = imax(x1, x); y0 = imin(y0, y); y1 = imax(y1, y); }+ return x1 < 0 ? (ht_rect_t){0} : (ht_rect_t){x0, y0, x1 - x0 + 1, y1 - y0 + 1};+}++static void missing_names(void)+{+ ht_scene_t scene; ht_scene_clear(&scene, ht_rgb(0));+ ht_arc_inner_face(&scene, ht_rgb(0xada6ad), NULL, &chat_face);+ ht_arc_inner_face(&scene, ht_rgb(0xada6ad), "", &chat_face);+ assert(scene.count == 0);+ // A mono face has no place on the inner curve: nothing is drawn rather than a misplaced label.+ ht_arc_inner_face(&scene, ht_rgb(0xada6ad), "PM", &ht_arc_geist);+ assert(scene.count == 0);+ assert(!ht_arc_inner_cache_made()); // nothing drawn, nothing allocated+ puts("inner arc: no name, an empty name or a mono face draws nothing and allocates nothing PASS");+}++static void short_name(void)+{+ ht_scene_t scene; ht_scene_clear(&scene, ht_rgb(0));+ ht_arc_inner_face(&scene, ht_rgb(0xada6ad), "PM", &chat_face);+ assert(scene.count == 1 && scene.runs[0].arc == 3 && !strcmp(scene.runs[0].text, "PM"));+ assert(!ht_arc_inner_cache_made()); // laid out, not yet drawn+ raster(&scene, px);+ assert(ht_arc_inner_cache_made());+ ht_rect_t ink = inked(px, ht_rgb(0));+ // Centred under 12 o'clock, its caps' middle on the inner curve: well inside the title's 205 px curve.+ assert(ink.w > 0 && abs(ink.x + ink.w / 2 - 233) <= 2);+ int middle = ink.y + ink.h / 2;+ assert(abs((233 - middle) - ARC_PROP_INNER) <= 6);+ assert(233 - ink.y < ARC_PROP_RADIUS - 8);+ puts("inner arc: a short name is centred at 12 o'clock on the inner curve, its cache made on first draw PASS");+}++static void long_name(void)+{+ ht_scene_t scene; ht_scene_clear(&scene, ht_rgb(0));+ ht_arc_inner_face(&scene, ht_rgb(0xada6ad), "Fix the login redirect loop on Safari and Chrome", &chat_face);+ const ht_run_t *r = &scene.runs[0];+ assert(scene.count == 1 && r->arc == 3);+ // Cut to the inner span at a word, ending in "…", as every arc label is (the title's rule, owner 2026-10-03).+ assert(!strcmp(r->text, "Fix the login\xe2\x80\xa6"));+ assert(arc_prop_width16(chat_face.prop, r->text) <= ARC_INNER_SPAN16);+ // One long word has no word to end at: it is cut by letters, still inside the span.+ ht_scene_clear(&scene, ht_rgb(0));+ ht_arc_inner_face(&scene, ht_rgb(0xada6ad), "Internationalisationsprojektgruppe", &chat_face);+ size_t n = strlen(scene.runs[0].text);+ assert(n > 3 && !strcmp(scene.runs[0].text + n - 3, "\xe2\x80\xa6") && !strncmp(scene.runs[0].text, "Internation", 11));+ assert(arc_prop_width16(chat_face.prop, scene.runs[0].text) <= ARC_INNER_SPAN16);+ ht_scene_clear(&scene, ht_rgb(0));+ ht_arc_inner_face(&scene, ht_rgb(0xada6ad), "Fix the login redirect loop on Safari and Chrome", &chat_face);+ r = &scene.runs[0];+ raster(&scene, px);+ ht_rect_t ink = inked(px, ht_rgb(0));+ // The ends stay clear of the pet below: no ink lower than the gap above it.+ assert(ink.y + ink.h <= 92);+ // A 48-byte name of Vietnamese capitals, the tallest marks: whatever is let through fits the mask and draws.+ ht_scene_clear(&scene, ht_rgb(0));+ ht_arc_inner_face(&scene, ht_rgb(0xada6ad), "\xe1\xba\xa4\xe1\xba\xa6\xe1\xba\xa8\xe1\xba\xaa\xe1\xba\xac\xe1\xba\xae\xe1\xba\xb0\xe1\xba\xb2\xe1\xba\xb4\xe1\xba\xb6\xe1\xba\xa4\xe1\xba\xa6\xe1\xba\xa8\xe1\xba\xaa\xe1\xba\xac\xe1\xba\xae", &chat_face);+ arc_span_t spans[HT_ARC_HEIGHT][2];+ assert(scene.count == 1 && arc_prop_geometry(&scene.runs[0], chat_face.prop, spans) <= ARC_MASK_BYTES);+ raster(&scene, px);+ assert(inked(px, ht_rgb(0)).w > 0);+ puts("inner arc: a long name is cut to the inner span with an ellipsis, clear of the pet; the hardest marks fit the mask PASS");+}++static void title_unchanged(void)+{+ // The title alone, then the title with a chat name under it: every title pixel outside the chat's ink is the same.+ ht_scene_t a, b;+ ht_scene_clear(&a, ht_rgb(0)); ht_scene_clear(&b, ht_rgb(0));+ ht_arc_title_face(&a, ht_rgb(0xeaeaf0), "Round dial firmware release", &ht_arc_inter_prop);+ ht_arc_title_face(&b, ht_rgb(0xeaeaf0), "Round dial firmware release", &ht_arc_inter_prop);+ ht_arc_inner_face(&b, ht_rgb(0xada6ad), "Fix login", &chat_face);+ assert(a.runs[0].arc == 1 && b.runs[0].arc == 1 && b.runs[1].arc == 3);+ assert(!memcmp(&a.runs[0], &b.runs[0], sizeof a.runs[0]));+ raster(&a, px); raster(&b, other);+ ht_scene_t chat; ht_scene_clear(&chat, ht_rgb(0));+ ht_arc_inner_face(&chat, ht_rgb(0xada6ad), "Fix login", &chat_face);+ static uint16_t alone[HT_WIDTH * HT_HEIGHT];+ raster(&chat, alone);+ int same = 0, changed = 0;+ for (int i = 0; i < HT_WIDTH * HT_HEIGHT; i++) {+ if (alone[i] != ht_rgb(0)) continue; // the chat's own ink+ assert(px[i] == other[i]);+ same++;+ }+ for (int i = 0; i < HT_WIDTH * HT_HEIGHT; i++) changed += px[i] != other[i];+ assert(same > 0 && changed > 0);+ // Drawn again, the title's cached mask is not rebuilt for the chat name: each arc keeps its own cache.+ uint32_t builds = ht_arc_cache_builds();+ raster(&b, other);+ assert(ht_arc_cache_builds() == builds);+ puts("inner arc: the title above it is laid out and drawn exactly as alone, and both masks stay cached PASS");+}++int main(void)+{+ missing_names();+ short_name();+ long_name();+ title_unchanged();+ return 0;+}diff --git a/devices/harness-device/firmware/test/test_cable_supertab.py b/devices/harness-device/firmware/test/test_cable_supertab.pyindex 7fa357d74..1d9030308 100644--- a/devices/harness-device/firmware/test/test_cable_supertab.py+++ b/devices/harness-device/firmware/test/test_cable_supertab.py@@ -51,21 +51,31 @@ static bool device_mac_str(char *o,size_t n) { snprintf(o,n,"aa:bb");return truestatic void msg_settings(cJSON **root) { (void)root; }static size_t pet_store_held(char ids[][17],size_t max) { (void)ids;(void)max;return 0; }-static unsigned beeps, ids_calls, card_calls, recap_calls, focus_calls, wait_calls, close_calls, question_calls, qclose_calls;+static unsigned beeps, ids_calls, card_calls, recap_calls, focus_calls, wait_calls, close_calls, question_calls, qclose_calls, notice_calls, read_calls;static bool beep_next;static void audio_notify_done(void) { beeps++; }static char got_ids[HT_SUPERTABS_MAX][ID_MAX]; static int got_id_n;static ht_supertab_t got_card;static char got_tab[ID_MAX], got_lead[ID_MAX], got_text[2048], got_agent[ID_MAX], got_request[80], got_swarm[80];+static char got_chat_id[ID_MAX]; static ht_chat_kind_t got_chat;static uint32_t got_at; static bool got_none, got_stuck, got_text_null;static void ui_supertabs_ids(const char ids[][ID_MAX],int n) {ids_calls++;got_id_n=n;memcpy(got_ids,ids,(size_t)n*ID_MAX);}static bool ui_supertab(const ht_supertab_t *in) { card_calls++;got_card=*in;return beep_next; }-static void ui_supertab_recap(const char *tab,const char *lead,const char *text,uint32_t at,bool none) {+static void ui_supertab_recap(const char *tab,const char *lead,const char *chat_id,const char *text,uint32_t at,bool none) {recap_calls++;snprintf(got_tab,sizeof got_tab,"%s",tab);snprintf(got_lead,sizeof got_lead,"%s",lead);+ snprintf(got_chat_id,sizeof got_chat_id,"%s",chat_id);snprintf(got_text,sizeof got_text,"%s",text?text:"");got_at=at;got_none=none;}+static bool ui_supertab_notice(const char *tab,const char *lead,ht_chat_kind_t chat,const char *chat_id,const char *text,uint32_t at) {+ notice_calls++;snprintf(got_tab,sizeof got_tab,"%s",tab);snprintf(got_lead,sizeof got_lead,"%s",lead);got_chat=chat;+ snprintf(got_chat_id,sizeof got_chat_id,"%s",chat_id);snprintf(got_text,sizeof got_text,"%s",text);got_at=at;return beep_next;+}+static void ui_supertab_notice_read(const char *tab,const char *lead,const char *chat_id) {+ read_calls++;snprintf(got_tab,sizeof got_tab,"%s",tab);snprintf(got_lead,sizeof got_lead,"%s",lead);+ snprintf(got_chat_id,sizeof got_chat_id,"%s",chat_id);+}static void ui_supertab_focus(const char *tab,const char *lead) {focus_calls++;snprintf(got_tab,sizeof got_tab,"%s",tab);snprintf(got_lead,sizeof got_lead,"%s",lead);}@@ -84,6 +94,7 @@ static void ui_question_close(const char *a,const char *r) { (void)a;(void)r;qcl'''for name in ['str_of', 'msg', 'msg_check', 'msg_string', 'msg_number', 'msg_array', 'send_hello', 'id_fits','handle_supertabs', 'handle_supertab', 'handle_supertab_recap', 'handle_supertab_focus',+ 'handle_supertab_notice', 'handle_supertab_notice_read','handle_question', 'handle_question_close', 'cable_client_supertab_send']:code += function(name)code += r'''@@ -102,6 +113,8 @@ int main(void) {send_hello();assert(sends==1 && !strcmp(field(wire[0],"swarmCard"),"v1") && !strcmp(field(wire[0],"superTab"),"wait-v1"));assert(!strcmp(field(wire[0],"product"),"harness"));+ // hello says swarmChat v1: the daemon sends the chat on each face and the Lead/PM notices.+ assert(!strcmp(field(wire[0],"swarmChat"),"v1"));// supertabs: ids in order, the bad and the repeated skipped, at most 16.feed(handle_supertabs,"{\"ids\":[\"s1\",\"\",7,\"s2\",\"s1\",\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"]}");@@ -140,13 +153,57 @@ int main(void) {beep_next=true;feed(handle_supertab,big);beep_next=false;assert(card_calls==3 && got_card.lead_n==12 && got_card.count==12 && beeps==1);+ // supertab with chat fields parses; a Lead without them is the Lead chat.+ feed(handle_supertab,"{\"id\":\"s1\",\"name\":\"openharness\",\"leads\":["+ "{\"id\":\"L1\",\"state\":\"work\",\"since\":9,\"order\":0,\"chat\":\"group\",\"chatId\":\"g1\",\"chatName\":\"Fix login\"},"+ "{\"id\":\"L2\",\"state\":\"done\",\"order\":1,\"chat\":\"pm\",\"chatId\":\"pm1\",\"chatName\":\"PM\"},"+ "{\"id\":\"L3\",\"state\":\"done\",\"order\":2}]}");+ assert(card_calls==4 && got_card.lead_n==3);+ assert(got_card.leads[0].chat==HT_CHAT_GROUP && !strcmp(got_card.leads[0].chat_id,"g1") && !strcmp(got_card.leads[0].chat_name,"Fix login"));+ assert(got_card.leads[1].chat==HT_CHAT_PM && !strcmp(got_card.leads[1].chat_id,"pm1") && !strcmp(got_card.leads[1].chat_name,"PM"));+ assert(got_card.leads[2].chat==HT_CHAT_LEAD && !got_card.leads[2].chat_id[0]);++ // supertab.notice and supertab.notice.read reach the ui calls with their fields; the UI decides the beep.+ const unsigned beeps_before=beeps;+ beep_next=true;+ feed(handle_supertab_notice,"{\"tab\":\"s1\",\"lead\":\"L2\",\"chat\":\"pm\",\"chatId\":\"pm1\",\"id\":\"m9\",\"text\":\"Ready to ship.\",\"at\":1792560000}");+ beep_next=false;+ assert(notice_calls==1 && beeps==beeps_before+1 && !strcmp(got_tab,"s1") && !strcmp(got_lead,"L2") && got_chat==HT_CHAT_PM);+ assert(!strcmp(got_chat_id,"pm1") && !strcmp(got_text,"Ready to ship.") && got_at==1792560000u);+ feed(handle_supertab_notice,"{\"tab\":\"s1\",\"lead\":\"L1\",\"chat\":\"lead\",\"chatId\":\"lead-web\",\"id\":\"m10\",\"text\":\"Done.\",\"at\":5}");+ assert(notice_calls==2 && got_chat==HT_CHAT_LEAD && beeps==beeps_before+1);+ feed(handle_supertab_notice_read,"{\"tab\":\"s1\",\"lead\":\"L2\",\"chatId\":\"pm1\"}");+ assert(read_calls==1 && !strcmp(got_tab,"s1") && !strcmp(got_lead,"L2") && !strcmp(got_chat_id,"pm1"));+ // a notice with a non-id chatId or no lead is ignored, and so is one of a group, with no id, or no text.+ char longer_id[ID_MAX+8];memset(longer_id,'c',ID_MAX);longer_id[ID_MAX]=0;+ char bad[256];snprintf(bad,sizeof bad,"{\"tab\":\"s1\",\"lead\":\"L2\",\"chat\":\"pm\",\"chatId\":\"%s\",\"id\":\"m1\",\"text\":\"x\",\"at\":1}",longer_id);+ feed(handle_supertab_notice,bad);+ feed(handle_supertab_notice,"{\"tab\":\"s1\",\"chat\":\"pm\",\"chatId\":\"pm1\",\"id\":\"m1\",\"text\":\"x\",\"at\":1}");+ feed(handle_supertab_notice,"{\"tab\":\"s1\",\"lead\":\"L2\",\"chat\":\"group\",\"chatId\":\"g1\",\"id\":\"m1\",\"text\":\"x\",\"at\":1}");+ feed(handle_supertab_notice,"{\"tab\":\"s1\",\"lead\":\"L2\",\"chat\":\"pm\",\"chatId\":\"pm1\",\"text\":\"x\",\"at\":1}");+ feed(handle_supertab_notice,"{\"tab\":\"s1\",\"lead\":\"L2\",\"chat\":\"pm\",\"chatId\":\"pm1\",\"id\":\"m1\",\"at\":1}");+ feed(handle_supertab_notice,"{\"tab\":\"\",\"lead\":\"L2\",\"chat\":\"pm\",\"chatId\":\"pm1\",\"id\":\"m1\",\"text\":\"x\",\"at\":1}");+ assert(notice_calls==2);+ feed(handle_supertab_notice_read,"{\"tab\":\"s1\",\"lead\":\"L2\"}");+ feed(handle_supertab_notice_read,"{\"tab\":\"s1\",\"chatId\":\"pm1\"}");+ assert(read_calls==1);+ beeps=beeps_before; // the waits below count from here+// supertab.recap and supertab.focus.feed(handle_supertab_recap,"{\"tab\":\"s1\",\"lead\":\"L1\",\"text\":\"Shipped.\",\"at\":1792560000,\"none\":false}");assert(recap_calls==1 && !strcmp(got_text,"Shipped.") && got_at==1792560000u && !got_none && !strcmp(got_lead,"L1"));+ // From an old daemon it names no chat.+ assert(!got_chat_id[0]);feed(handle_supertab_recap,"{\"tab\":\"s1\",\"lead\":\"L1\",\"none\":true}");assert(recap_calls==2 && got_none && !got_text[0] && got_at==0);feed(handle_supertab_recap,"{\"tab\":\"s1\",\"text\":\"x\"}");assert(recap_calls==2);+ // A chat's recap names its chat; one whose chatId cannot be held is not one.+ feed(handle_supertab_recap,"{\"tab\":\"s1\",\"lead\":\"L1\",\"text\":\"Green.\",\"at\":3,\"none\":false,\"chatId\":\"g1\"}");+ assert(recap_calls==3 && !strcmp(got_chat_id,"g1") && !strcmp(got_text,"Green."));+ snprintf(bad,sizeof bad,"{\"tab\":\"s1\",\"lead\":\"L1\",\"text\":\"x\",\"at\":3,\"chatId\":\"%s\"}",longer_id);+ feed(handle_supertab_recap,bad);+ assert(recap_calls==3);feed(handle_supertab_focus,"{\"tab\":\"s1\",\"lead\":\"L2\"}");assert(focus_calls==1 && !strcmp(got_tab,"s1") && !strcmp(got_lead,"L2"));feed(handle_supertab_focus,"{\"tab\":\"s1\"}");@@ -197,7 +254,7 @@ int main(void) {cable_client_supertab_send("focus","s1","L1");cable_client_supertab_send(NULL,"s1","L1");assert(sends==3);- puts("Swarm frames: hello capabilities, supertabs/supertab/recap/focus parsing, malformed Leads skipped, Super Tab waits kept off the question screen, exact requests PASS");+ puts("Swarm frames: hello capabilities, supertabs/supertab/recap/focus parsing, chats and Lead/PM notices, malformed Leads skipped, Super Tab waits kept off the question screen, exact requests PASS");}'''with tempfile.TemporaryDirectory(prefix='harness-supertab-') as folder:diff --git a/devices/harness-device/firmware/test/test_supertab.c b/devices/harness-device/firmware/test/test_supertab.cindex efea7f7c6..d219f1c4a 100644--- a/devices/harness-device/firmware/test/test_supertab.c+++ b/devices/harness-device/firmware/test/test_supertab.c@@ -176,27 +176,76 @@ static void lookups_and_recap(void)// Recap: only the open Lead's text lands.ht_supertabs_recap_open(&model, "s1", "L0", 100);assert(model.recap.state == HT_RECAP_LOADING && model.recap.asked_ms == 100 && !model.recap.text[0]);- assert(!ht_supertabs_recap_put(&model, "s1", "L1", "other", 1, false));+ assert(!ht_supertabs_recap_put(&model, "s1", "L1", "", "other", 1, false));assert(model.recap.state == HT_RECAP_LOADING && !model.recap.text[0]);char *big = malloc(1601); memset(big, 'r', 1599); strcpy(big + 1499, "\xe2\x80\xa6"); memset(big + 1502, 'r', 98); big[1600] = 0;- assert(ht_supertabs_recap_put(&model, "s1", "L0", big, 1792560000u, false));+ assert(ht_supertabs_recap_put(&model, "s1", "L0", "", big, 1792560000u, false));assert(model.recap.state == HT_RECAP_LOADED && strlen(model.recap.text) == 1499 && model.recap.at == 1792560000u);free(big);ht_supertabs_recap_open(&model, "s1", "L1", 200);assert(model.recap.state == HT_RECAP_LOADING && !model.recap.text[0]);- assert(ht_supertabs_recap_put(&model, "s1", "L1", "", 0, true) && model.recap.state == HT_RECAP_EMPTY);+ assert(ht_supertabs_recap_put(&model, "s1", "L1", "", "", 0, true) && model.recap.state == HT_RECAP_EMPTY);ht_supertabs_recap_open(&model, "", "", 300);- assert(model.recap.state == HT_RECAP_NONE && !ht_supertabs_recap_put(&model, "", "", "x", 0, false));+ assert(model.recap.state == HT_RECAP_NONE && !ht_supertabs_recap_put(&model, "", "", "", "x", 0, false));ht_supertabs_recap_open(&model, "s1", "L0", 400);ht_supertabs_reset(&model);assert(model.n == 0 && model.id_n == 0 && model.recap.state == HT_RECAP_NONE && !model.recap.lead[0]);puts("supertab: desk link, local Lead, list order, recap slot (one Lead, UTF-8 cut, none), reset PASS");}+// The round dial's face follows the chat the desktop has open (design 2026-10-28-round-dial-swarm-chat).+static void chats(void)+{+ static ht_supertab_t t;+ ht_supertabs_reset(&model);+ const char ids[1][ID_MAX] = {"s1"};+ ht_supertabs_ids(&model, ids, 1, NULL, 0);+ assert(ht_supertab_init(&t, "s1", "", "openharness", 3));+ // lead keeps chat, chat_id, chat_name+ ht_lead_in_t g = lead("L0", "work", 0); g.chat = "group"; g.chat_id = "g1"; g.chat_name = "Fix login";+ ht_lead_in_t pm = lead("L1", "done", 1); pm.chat = "pm"; pm.chat_id = "pm1"; pm.chat_name = "PM";+ // a lead without chat fields reads as the Lead chat+ ht_lead_in_t old = lead("L2", "ask", 2);+ assert(ht_supertab_lead_add(&t, &g) && ht_supertab_lead_add(&t, &pm) && ht_supertab_lead_add(&t, &old));+ assert(t.leads[0].chat == HT_CHAT_GROUP && !strcmp(t.leads[0].chat_id, "g1") && !strcmp(t.leads[0].chat_name, "Fix login"));+ assert(t.leads[1].chat == HT_CHAT_PM && !strcmp(t.leads[1].chat_id, "pm1") && !strcmp(t.leads[1].chat_name, "PM"));+ assert(t.leads[2].chat == HT_CHAT_LEAD && !t.leads[2].chat_id[0] && !t.leads[2].chat_name[0]);+ // A long group name is cut to 48 bytes on a UTF-8 boundary; an unknown kind, or a chat id that cannot be held, is the+ // Lead chat with no id, and the Lead is kept.+ static ht_supertab_t u;+ assert(ht_supertab_init(&u, "s1", "", "openharness", 3));+ char name[64]; memset(name, 'n', 47); strcpy(name + 47, "\xc3\xa9tail");+ char longer[ID_MAX + 1]; memset(longer, 'x', ID_MAX); longer[ID_MAX] = 0;+ ht_lead_in_t cut = lead("L0", "work", 0); cut.chat = "group"; cut.chat_id = "g2"; cut.chat_name = name;+ ht_lead_in_t odd = lead("L1", "work", 1); odd.chat = "dm"; odd.chat_id = "c1"; odd.chat_name = "x";+ ht_lead_in_t wide = lead("L2", "work", 2); wide.chat = "group"; wide.chat_id = longer; wide.chat_name = "x";+ assert(ht_supertab_lead_add(&u, &cut) && ht_supertab_lead_add(&u, &odd) && ht_supertab_lead_add(&u, &wide));+ assert(strlen(u.leads[0].chat_name) == 47 && u.leads[0].chat == HT_CHAT_GROUP);+ assert(u.leads[1].chat == HT_CHAT_LEAD && !u.leads[1].chat_id[0] && !u.leads[1].chat_name[0]);+ assert(u.leads[2].chat == HT_CHAT_LEAD && !u.leads[2].chat_id[0]);+ ht_supertabs_put(&model, &t, 0, NULL, 0);++ // drops a recap for another chat: the face is the group's, so the Lead chat's recap (or none named) is not its.+ ht_supertabs_recap_open(&model, "s1", "L0", 100);+ assert(!ht_supertabs_recap_put(&model, "s1", "L0", "lead-web", "the Lead", 1, false));+ assert(!ht_supertabs_recap_put(&model, "s1", "L0", "", "no chat named", 1, false));+ assert(model.recap.state == HT_RECAP_LOADING && !model.recap.text[0]);+ assert(ht_supertabs_recap_put(&model, "s1", "L0", "g1", "Tests green.", 2, false));+ assert(model.recap.state == HT_RECAP_LOADED && !strcmp(model.recap.chat_id, "g1") && !strcmp(model.recap.text, "Tests green."));+ // An old daemon's Lead (no chat) takes the recap that names none, as before.+ ht_supertabs_recap_open(&model, "s1", "L2", 200);+ assert(ht_supertabs_recap_put(&model, "s1", "L2", "", "Shipped.", 3, false) && !model.recap.chat_id[0]);+ // Opening another Lead forgets the chat the last recap was for.+ ht_supertabs_recap_open(&model, "s1", "L1", 300);+ assert(!model.recap.chat_id[0]);+ puts("supertab: chat kind/id/name, old Leads as the Lead chat, recap only for the face's chat PASS");+}+int main(void){order_and_limits();transitions();lookups_and_recap();+ chats();return 0;}diff --git a/devices/harness-device/firmware/test/test_touch_ui.py b/devices/harness-device/firmware/test/test_touch_ui.pyindex 2aa3a14c5..51bf0c875 100644--- a/devices/harness-device/firmware/test/test_touch_ui.py+++ b/devices/harness-device/firmware/test/test_touch_ui.py@@ -236,7 +236,7 @@ code += function('focus_centred') + function('focus_header') + function('focus_cfor name in ['notice_remove', 'notice_sync_view', 'notice_selection', 'notice_restore_selection', 'notice_add', 'notice_expire', 'on_face', 'notice_read_now', 'ui_notify_summary', 'ui_turn_error', 'ui_notif_seen', 'ui_notif_read', 'ui_notif_replace', 'ui_notif_open', 'ui_question_close', 'ui_answer_receipt','utf8_trim', 'swarm_notice', 'swarm_notice_mark', 'swarm_notice_raise', 'swarm_notice_drop', 'swarm_events','swarm_tabs_changed', 'ui_supertabs_ids', 'ui_supertab', 'ui_supertab_recap', 'ui_supertab_focus',- 'ui_supertab_wait', 'ui_supertab_wait_close', 'ui_supertabs_clear']:+ 'ui_supertab_wait', 'ui_supertab_wait_close', 'ui_supertabs_clear', 'swarm_said_of', 'ui_supertab_notice', 'ui_supertab_notice_read']:code += function(name)code += '#define ui_notify_task_done(a,b,c,d) ui_notify_summary(a,b,c,d,"alert",false,false)\n'for name in ['event', 'ui_project_emit', 'ui_project_restore_event', 'ui_project_clear_event', 'ui_project_set_name', 'ui_project_remove', 'ui_project_clear_all', 'ui_project_apply_order']:@@ -416,7 +416,8 @@ static void focus_only_inter(void) {(r->font == &ht_lv_montserrat_22.base && !strcmp(r->text, HT_LV_CROSS));bool art = r->font == &ht_wave || r->font == &ht_spark;assert(focus_inter(r->font) || icon || art);- if (r->arc) assert(r->font == &ht_lv_inter_med_26.base);+ // The name and status arcs are Inter Medium 26; a Swarm face's chat, on the inner arc, is Inter 20.+ if (r->arc) assert(r->font == (r->arc == 3 ? &ht_lv_inter_20.base : &ht_lv_inter_med_26.base));}}// Every straight text run of a Focus page sits inside the glass (r 230 on its four corners) and a bracket@@ -1514,8 +1515,8 @@ static void swarm_pane_checks(const char *dir) {fake_ms += 6000; scene_take(); assert(scene_says("2:20")); // the dial's own clock carries it on// 2b a long name, done: the recap card. A recap for another Lead is dropped.enter_at("s1", "L1");- ui_supertab_recap("s1", "L2", "Not this one.", 1792560000u, false); scene_take(); assert(!scene_says("Not this one."));- ui_supertab_recap("s1", "L1", "Release candidate built and checked on both dials.", 1792560000u, false); scene_take();+ ui_supertab_recap("s1", "L2", "", "Not this one.", 1792560000u, false); scene_take(); assert(!scene_says("Not this one."));+ ui_supertab_recap("s1", "L1", "", "Release candidate built and checked on both dials.", 1792560000u, false); scene_take();assert(scene_says("Release candidate built"));FOCUS_PAGE("swarm-2b");// 2g a 1,500-byte recap: four lines, the last ending in "…".@@ -1523,13 +1524,13 @@ static void swarm_pane_checks(const char *dir) {char longer[HT_SUPERTAB_TEXT]; size_t n = 0;while (n + 6 < sizeof longer - 1) { memcpy(longer + n, "words ", 6); n += 6; }longer[n] = 0;- ui_supertab_recap("s1", "L1", longer, 1792560000u, false); scene_take();+ ui_supertab_recap("s1", "L1", "", longer, 1792560000u, false); scene_take();const char *last = ""; int lines = card_lines(&last);assert(lines >= 1 && lines <= 4 && strstr(last, "\xe2\x80\xa6"));FOCUS_PAGE("swarm-2g");}// 2f no message yet: the resting face, no card.- ui_supertab_recap("s1", "L1", "", 0, true); scene_take();+ ui_supertab_recap("s1", "L1", "", "", 0, true); scene_take();{ const char *last; assert(!card_lines(&last)); }// With nothing unread the bell leaves the lower arc to the resting face's one line, as in the mockup.for (int i = 0; i < s.notice_count; i++) notice_mark_read(&s.notice[i]);@@ -1537,7 +1538,7 @@ static void swarm_pane_checks(const char *dir) {FOCUS_PAGE("swarm-2f");// 2c "docs" needs you, here: its wait's question takes the recap's place, in the asking pose.enter_at("s1", "L2");- ui_supertab_recap("s1", "L2", "Docs drafted.", 1792560000u, false);+ ui_supertab_recap("s1", "L2", "", "Docs drafted.", 1792560000u, false);assert(!ui_supertab_wait("h2", "supertab:w1", "openharness", false, "Publish the docs today?")); // on the face: no beepscene_take(); assert(scene_says("Publish the docs") && !scene_says("Docs drafted."));FOCUS_PAGE("swarm-2c");@@ -1551,7 +1552,7 @@ static void swarm_pane_checks(const char *dir) {static const void *asking[64], *done[64]; int asking_n = pet_frames(asking);card_begin("s1", "t1", "openharness"); openharness_card(); card.leads[1].state = HT_LEAD_DONE; // L3, firmwareassert(!strcmp(card.leads[1].id, "L3")); card_send(); ui_supertab_wait_close("h3", "supertab:w2");- ui_supertab_recap("s1", "L3", "Release key found; build signed.", 1792560000u, false);+ ui_supertab_recap("s1", "L3", "", "Release key found; build signed.", 1792560000u, false);int done_n = pet_frames(done); bool other = false;for (int i = 0; i < asking_n; i++) { bool shared = false; for (int k = 0; k < done_n; k++) shared |= asking[i] == done[k]; other |= !shared; }assert(asking_n && done_n && other);@@ -1570,7 +1571,7 @@ static void swarm_pane_checks(const char *dir) {card_lead("L0", "mobile", "claude", "h0", "work", 0, 134); card_lead("L1", "Round dial firmware release candidate", "claude", "h1", "done", 1, -1);card_lead("L2", "docs", "claude", "h2", "ask", 2, -1); card_lead("L3", "firmware", "codex", "h3", "stuck", 3, -1);card_lead("L4", "backend", "cursor", "", "ask", 4, -1); card_send();- ui_supertab_recap("s1", "L4", "Need a decision on the cache size.", 1792560000u, false); scene_take();+ ui_supertab_recap("s1", "L4", "", "Need a decision on the cache size.", 1792560000u, false); scene_take();assert(scene_says("Need a decision") && !scene_says("Working"));FOCUS_PAGE("swarm-2e-ask");// 2h a Swarm with no projects: PANES' own empty page, and "Choose a tab" goes to TABS.@@ -1802,6 +1803,113 @@ static void swarm_voice_checks(const char *dir) {dispatch((action_t){.kind = A_VOICE_ABORT});puts("Swarm voice: a local Lead's face talks to its harness with its engine's scene or the seven bars, and returns to the Swarm's face PASS");}+/*+ * A DAEMON THAT SPEAKS swarmChat (docs/superpowers/specs/2026-10-28-round-dial-swarm-chat-design.md §3): each Lead's face+ * is the chat the desktop has open, `work` only for a working group, never ask or stuck, and the alerts are the Lead's+ * new messages (`supertab.notice`).+ */+static void chat_lead(const char *id, const char *project, const char *local, const char *state, int order, long since,+ const char *chat, const char *chat_id, const char *chat_name) {+ ht_lead_in_t in = {.id = id, .project = project, .engine = "claude", .local = local, .state = state, .order = order, .since = since,+ .chat = chat, .chat_id = chat_id, .chat_name = chat_name};+ assert(ht_supertab_lead_add(&card, &in));+}+// C0 on a working group, C1 on its Chat with PM, C2 on its Lead chat.+static bool chat_card(const char *group_state, const char *c1_chat, const char *c1_id) {+ card_begin("s1", "t1", "openharness");+ chat_lead("C0", "mobile", "h0", group_state, 0, !strcmp(group_state, "work") ? 9 : -1, "group", "g1", "Fix login");+ chat_lead("C1", "docs", "h1", "done", 1, -1, c1_chat, c1_id, !strcmp(c1_chat, "pm") ? "PM" : "Lead");+ chat_lead("C2", "web", "", "done", 2, -1, "lead", "lead-web", "Lead");+ return card_send();+}+static const ht_run_t *inner_arc(void) {+ for (int i = 0; i < scene.count; i++) if (scene.runs[i].arc == 3 && scene.runs[i].text[0]) return &scene.runs[i];+ return NULL;+}+static void chat_setup(void) {+ reset(); ht_character_select(&character, HT_CHARACTER_FOCUS); fake_ms = 100000;+ desk_open();+ const char ids[1][ID_MAX] = {"s1"};+ ui_supertabs_ids(ids, 1);+ assert(!chat_card("work", "pm", "pm1"));+ scene_take();+}+static void swarm_chat_checks(const char *dir) {+ // No entry from a Lead's state when chats are on: the daemon sends no ask or stuck, and a group's work is no alert.+ chat_setup();+ assert(s.notice_count == 0);+ assert(!chat_card("done", "pm", "pm1") && !chat_card("work", "pm", "pm1") && s.notice_count == 0);++ // The chat name under the project, on the inner arc: none for the Lead chat, "PM", a group's name cut at a word.+ enter_at("s1", "C2"); assert(title_is("web") && !inner_arc());+ enter_at("s1", "C1"); assert(title_is("docs") && inner_arc() && !strcmp(inner_arc()->text, "PM"));+ FOCUS_PAGE("swarm-6a");+ card_begin("s1", "t1", "openharness");+ chat_lead("C0", "mobile", "h0", "done", 0, -1, "group", "g1", "Fix the login redirect loop on Safari and Chrome");+ card_send(); enter_at("s1", "C0");+ assert(inner_arc() && !strcmp(inner_arc()->text, "Fix the login\xe2\x80\xa6"));+ FOCUS_PAGE("swarm-6b");+ assert(!chat_card("work", "pm", "pm1")); scene_take();+ // A working group shows the working pet and its clock, its name under the project, and no recap.+ enter_at("s1", "C0");+ assert(title_is("mobile") && scene_says("0:09") && inner_arc() && !strcmp(inner_arc()->text, "Fix login"));+ FOCUS_PAGE("swarm-6c");+ ui_supertab_recap("s1", "C0", "g1", "Tests green on both dials.", 1792560000u, false); scene_take();+ assert(!scene_says("Tests green"));+ // A done group shows its recap.+ assert(!chat_card("done", "pm", "pm1")); scene_take();+ assert(scene_says("Tests green") && !scene_says("0:09"));++ // The PM chat: its recap, never working.+ enter_at("s1", "C1");+ ui_supertab_recap("s1", "C1", "pm1", "The release notes are ready.", 1792560000u, false); scene_take();+ assert(scene_says("release notes") && !scene_says("Working"));+ // The desktop moved that project to its Lead chat: the PM chat's recap is no longer this face's.+ assert(!chat_card("done", "lead", "lead-docs")); scene_take();+ assert(!scene_says("release notes"));+ assert(!chat_card("done", "pm", "pm1")); scene_take();++ // A notice for the face's chat is read at once and does not beep.+ enter_at("s1", "C1");+ assert(!ui_supertab_notice("s1", "C1", HT_CHAT_PM, "pm1", "Shall I cut the release?", 1792560000u));+ int e = swarm_entry("C1");+ assert(e >= 0 && s.notice[e].read_on_dial && !s.notice[e].question && s.notice[e].swarm == 3);+ assert(!strcmp(s.notice[e].summary, "Shall I cut the release?") && !strcmp(s.notice[e].name, "docs"));+ assert(!strcmp(s.notice[e].machine, "openharness \xc2\xb7 PM"));+ // A notice for another chat stays unread and beeps once: the Lead chat, while the face shows the PM chat.+ assert(ui_supertab_notice("s1", "C1", HT_CHAT_LEAD, "lead-docs", "Docs are merged.", 1792560001u));+ e = swarm_entry("C1");+ assert(e >= 0 && !s.notice[e].read_on_dial && !strcmp(s.notice[e].summary, "Docs are merged."));+ assert(!strcmp(s.notice[e].machine, "openharness"));+ // Off the face: unread, and it beeps.+ assert(ui_supertab_notice("s1", "C2", HT_CHAT_LEAD, "lead-web", "Web is deployed.", 1792560002u));+ assert(swarm_entry("C2") >= 0 && !s.notice[swarm_entry("C2")].read_on_dial);+ // One entry per Lead: a second notice replaces the text and is unread again.+ notice_mark_read(&s.notice[swarm_entry("C2")]);+ assert(ui_supertab_notice("s1", "C2", HT_CHAT_LEAD, "lead-web", "Web is rolled back.", 1792560003u));+ { int count = 0; for (int i = 0; i < s.notice_count; i++) count += !strcmp(s.notice[i].agent_id, "C2"); assert(count == 1); }+ e = swarm_entry("C2");+ assert(!strcmp(s.notice[e].summary, "Web is rolled back.") && !s.notice[e].read_on_dial);+ // A notice for a Lead the dial does not know is nothing.+ { int before = s.notice_count; assert(!ui_supertab_notice("s1", "nobody", HT_CHAT_LEAD, "x", "?", 1)); assert(s.notice_count == before); }++ // It stays news across the desktop's inbox snapshot: kept, and not turned into a question.+ { cable_notif_t desk = {.agent_id = "a", .name = "Payments refactor", .summary = "Shipped."}; ui_notif_replace(&desk, 1); }+ e = swarm_entry("C2"); assert(e >= 0 && !s.notice[e].question && s.notice[e].swarm == 3 && !s.notice[e].read_on_dial);++ // notice.read removes the entry, only for its own chat.+ ui_supertab_notice_read("s1", "C2", "other-chat"); assert(swarm_entry("C2") >= 0);+ ui_supertab_notice_read("s1", "C2", "lead-web"); assert(swarm_entry("C2") < 0);+ ui_supertab_notice_read("s1", "C1", "lead-docs"); assert(swarm_entry("C1") < 0);++ // A Lead wait still raises its entry, and beeps off the face; its close removes it (the Lead never reads ask here).+ enter_at("s1", "C0");+ assert(ui_supertab_wait("h2-none", "supertab:x", "openharness", false, "Not a Lead's") == false);+ assert(ui_supertab_wait("h1", "supertab:w1", "openharness", false, "Publish the docs today?"));+ e = swarm_entry("C1"); assert(e >= 0 && !strcmp(s.notice[e].summary, "Publish the docs today?") && s.notice[e].question);+ ui_supertab_wait_close("h1", "supertab:w1"); assert(swarm_entry("C1") < 0);+ puts("Swarm chats: work only for a working group, the face chat's recap, Lead/PM notices read on their face or unread with a beep, one entry per Lead, news across a snapshot, notice.read, Lead waits still alert PASS");+}int main(int argc, char **argv) {test_character = getenv("HABITAT_TEST_TUX") ? HT_CHARACTER_TUX : HT_CHARACTER_TIM;notification_read_checks(argc>1 ? argv[1] : NULL);@@ -3353,6 +3461,8 @@ int main(int argc, char **argv) {habitat_touch(false,233,220,2800); assert(!stops && !reviews && recording);tap(3400,233,220); assert(stops==1 && !reviews);puts("touch UI: PASS (production contacts/renderers; voice start/finish/discard, target pinning, sensor cancellation, immediate scroll, swipes, round trips, congestion and holds)");+ // Last, so every face above renders exactly as it did before chats: the faces are compared byte for byte.+ swarm_chat_checks(argc>1 ? argv[1] : NULL);}'''extra_sources = []diff --git a/docs/design/2026-10-26-swarm-state-parts.md b/docs/design/2026-10-26-swarm-state-parts.mdindex f919673ab..df7023a5e 100644--- a/docs/design/2026-10-26-swarm-state-parts.md+++ b/docs/design/2026-10-26-swarm-state-parts.md@@ -77,9 +77,10 @@ These defaults hold for every command; the table adds what is specific.`H`, which holds the role sets, so a concurrent `project.role.*` conflicts.- **D10 Delivery rows follow group rules (rule b).** `conversation.archive`, `conversation.agent` (`present:false`) and`conversation.audience` change what `deliveryAllowed` (`store.ts:1410-1425`) accepts without cancelling rows today.- They must bump `updatedAt` on the affected queued/claimed/uncertain delivery rows (no status change; archive keeps- today's "comes back when reopened" behavior), so a concurrent claim conflicts on the row (section 3.5).- `conversation.audience` additionally cancels rows authored by people it removes.+ They must write the affected queued/claimed/uncertain delivery rows, so a concurrent claim conflicts on the row+ (section 3.5). Archive and `present:false` cancel them (2026-10-28: kept for a reopening, deliveries in archived+ groups waited unread for days; `superTabs/deliverySettle.ts` ends any other open delivery that can no longer move);+ `conversation.audience` bumps `updatedAt` and additionally cancels rows authored by people it removes.- Side writes into existing collections (`SuperTabRun`, session scopes, configurations, role texts, route decisions,terminal requests, mentions, attachments, attempts, native contexts) are unchanged from today's `executeOnce`(`store.ts:661-838`) and are not repeated below.diff --git a/docs/performance/2026-10-28-backend-resilience.md b/docs/performance/2026-10-28-backend-resilience.mdnew file mode 100644index 000000000..97df338fe--- /dev/null+++ b/docs/performance/2026-10-28-backend-resilience.md@@ -0,0 +1,105 @@+# Backend resilience: rate limits, timeouts and circuit breakers (Stability 3.2 and 3.5)++Stability roadmap items 3.2 (real rate limits) and 3.5 (protection when a dependency is slow), approved by the owner.++## What changed++| Area | Before | After |+|---|---|---|+| Feature rate limits (agent routing, community, analytics, device keys, Grid profile, QR sign-in) | Counted in each process: the limit multiplied by processes and pods, and reset on every deploy | Counted once across every pod through one Redis call (`lib/rateLimit.ts`); per process while Redis is unavailable, with one warning each way. Limits unchanged |+| Every signed-in request | No ceiling | Per method and route pattern (`middlewares/routeRateLimit.ts`), three ceilings in one Redis call: per second for its caller (the agent the route names, else the machine, each together with the person; else the person), and per second and per minute for the person whatever ids it names. 429 with Retry-After. A token already refused this window is answered before it costs a sign-in or a count: on the whole route when a person's ceiling refused it, so new agent ids do not get past it. Each refusal is held 1 s, at most 1000 at once per process |+| Turn starts from a machine | Each one counted and relayed | After 20 in a row each under 10 s after the last, neither counted nor relayed for 60 s, and the machine is logged once (`lib/shortTurnGuard.ts`) |+| SSO token check | Identity check, then profile fallback, each with its own 5 s timeout (10 s in all) | One 5 s deadline for both. A circuit breaker per account plane fails at once after 5 failures in a row; a rejected token is an answer, not a failure |+| SSO sign-in and refresh | 5 s timeout per call | The same, plus a breaker per account plane |+| Autonomous billing service | 10 s timeout per call | The same, plus a breaker per account plane; a 401, 403 or 404 is an answer |+| Redis commands | 5 s command timeout | 1 s, and a breaker at ioredis' single send point: after 5 failed commands in a row they are refused unsent for 5 s. Transactions, pipelines and a reconnecting connection's own setup pass untouched |+| Bus while Redis cannot take a publish | Publishes dropped; a new subscription waited out the whole outage | Single-pod mode: a publish that certainly never reached Redis goes to this pod's own subscribers. One that timed out is still dropped, because Redis may deliver it and a keystroke must not arrive twice. A subscription waits at most 1 s |++### Settings++| Variable | Default | Meaning |+|---|---|---|+| `ROUTE_RATE_LIMIT_PER_CALLER_SECOND` | 50 | Signed-in requests per route and second for one caller: the agent the route names, else the machine (each with its person), else the person. 0 turns it off |+| `ROUTE_RATE_LIMIT_PER_PERSON_MINUTE` | 15000 | Signed-in requests per route and minute for one person, whatever agents or machines they name. A late poll can land in the next minute, so 200 agents polling once a second can reach 12200 in one minute. 0 turns it off |+| `ROUTE_RATE_LIMIT_PER_PERSON_SECOND` | 500 | Signed-in requests per route and second for one person, whatever agents or machines they name, so made-up agent ids cannot spend the minute's budget in one second. 200 agents polling once a second land up to 400 in one second when polls arrive late. 0 turns it off |+| `REDIS_COMMAND_TIMEOUT_MS` | 1000 | The longest one Redis command may take on the shared command connection |+| `SSO_PROFILE_STALE_GRACE_MS` | 0 (off) | See below |++The route limits are generous on purpose until per-route counts from the ingress logs are in. The busiest client that+works as designed is an older CLI's delivery poll: one call a second per running agent. Each agent is its own caller,+so agents polling in the same second never crowd out one another; the person's 15000 a minute and 500 a second leave room for 200 agents whose polls arrive late, across minute boundaries too. With the+person in every caller key, naming someone else's machine or agent spends only your own budget.++**`SSO_PROFILE_STALE_GRACE_MS` needs the owner's decision.** While the SSO cannot answer (down, slow, or its breaker+open), a token this process validated within this long past its normal 60 s trust window keeps working. It never+outlives the token's own expiry, and a token the SSO rejects is dropped at once. With it off, an SSO outage signs out+everyone within about a minute: every request whose token's 60 s window has passed gets a 503. The cost of turning it+on: during an outage, a token revoked at the SSO keeps working here for up to the grace period. 600000 (10 minutes) is+the value it was built and measured with.++## KPI, before and after++Measured with `integration/bench/resilience.ts` (README in the file) on a MacBook Pro (M2 Max) shared with other agents,+so absolute numbers drift between runs. Before and after runs were interleaved so the drift hit both. One backend+process, its own MongoDB and Redis, 8 good clients listing their machines with a tenth fresh tokens, 30 s per scenario.+The bad client loads its own Swarm in full with 128 calls in flight and ignores 429. Before is main d193981; after is+390d416 (the limits as reviewed). Latency is good clients' p95 in ms.++| Scenario | Before (3 runs) | After, defaults (3 runs) | Target |+|---|---|---|---|+| Normal | 31 / 23 / 28 | 31 / 28 / 8 | — |+| One bad client | 125 / 86 / 66 (+303% / +274% / +136%) | 32 / 28 / 26 (+3% / 0% / see below) | under +10% |+| Bad client's calls in 30 s | 17,315 / 17,986 / 20,125 | 5,281 / 5,310 / 5,346 | — |+| Redis 5 s slow | 5,269 / 5,257 / 5,287 | 30 / 29 / 28 | under 1,000 |+| SSO 5 s slow | 10,006 / 10,006 / 10,008 | 24 / 25 / 20 | under 1,000 |++- **One bad client.** Within the target in two runs (+3%, 0%). In the third, the normal p95 was an outlier at 8 ms;+ every other run on this machine measured 23–31 ms. The bad-client p95 itself, 26 ms, is in line with the other runs.+ The bad client is held to 50 calls a second (its caller ceiling), and its traffic fell by about 70%: refused calls are+ answered before sign-in and held for 1 s. An earlier series with a person-wide 6000-a-minute limit counted in 1 s+ windows (100 a second) rose 36–43% in two of three runs. The per-caller ceiling is both tighter for a loop and looser+ for a person with many agents.+- **Redis 5 s slow.** p95 under 35 ms in every run. The first commands wait for the 1 s timeout until the breaker opens:+ max 1.0–1.3 s.+- **SSO 5 s slow, grace period off (the default).** p95 under 30 ms, but about half the calls are fast 503s: every token+ whose 60 s trust window passed during the slowdown. **With the grace period on (10 minutes, one run on 18f3871):**+ p95 29 ms, and 503s fell from 48% to 9%. The remaining 9% are the fresh tokens, which cannot be validated while the+ SSO is slow.++## Design (docs/feature-design-rules.md)++Reviewed revision: pending. Reviewer (another engine): pending.++1. **Growth.** Rate counters are Redis keys `rl:<limiter>:<key>:<window>`. Each expires with its own window (1 s for a+ route's caller, 1 minute for a route's person and for the feature limits); nothing else deletes them. Process memory: per-process fallback+ counters (existing windowLimiter, a bucket per key), and remembered refusals, at most 50,000, with expired ones+ swept and the map cleared beyond that. SSO stale entries live in the existing profile cache (at most 50,000) and+ only while the grace period is on. Nothing is written to Mongo.+2. **Concurrency.** A rate count is one atomic Redis EVAL (INCR, and PEXPIRE on the window's first hit); there is no+ read-modify-write. Breakers and the short-turn guard are process-local or socket-local. A breaker lets one trial+ call through at a time when half open.+3. **Read cost.** One EVAL per signed-in request with three keys, about 0.1 ms on a loopback Redis. A remembered+ refusal costs a SHA-256 of the token and two map lookups, with no Redis or Mongo. Nothing reads a whole document.+ A held refusal is a timer on a connection the client opened; at most 1000 are held at once per process, and past+ that a refusal is answered at once, so the hold never keeps more connections open than that.+4. **Scale.** At 10x, Redis takes one EVAL per signed-in request, still far below one Redis core. First warning sign:+ Redis command latency, which opens the breaker at 1 s and logs `[bus] Redis commands failing`. Rate counts then+ fall back to per pod, with one log line.+5. **Compatibility.** No client changes. Old CLI, Desktop and phone clients get a 429 only above limits set well+ beyond any working client. They already handle a 429 as they do from the existing limiters: the CLI's Swarm client+ reports it as RATE_LIMITED and its polls retry on the next tick. Rolling deploy: old and new pods count in+ different places during the rollout (old ones in memory), which only makes limits looser for a few minutes.+ Fast 503s from an open SSO breaker are the 503 clients already get when the SSO is unreachable.+6. **Migration and rollback.** No data migration. Rolling back drops the new keys, which expire on their own. Every+ new limit has an environment switch (0 turns it off) without a rollback.+7. **Audience.** Unchanged. The limit runs after the sign-in gate and before the route authorizes anything, so every+ key includes the signed-in person: an id in the URL alone never decides whose budget a call spends. It never+ authorizes anything. Rate keys hold internal user ids, route patterns and machine ids, never tokens: QR poll tokens+ and remembered refusals use a digest.+8. **Identity.** A request counts for the person it signed in as. Nothing runs as the machine owner's login.+9. **Failure.** Redis down or stuck: commands fail fast, limits count per pod, and the bus goes single-pod. Each+ change is logged once each way (`[bus]`, `[rate-limit]`). SSO or billing service down: one log line when its breaker+ opens; callers get 503, as for an unreachable service today. A looping machine: one log line naming it. A limited+ client: 429 with Retry-After.+10. **Platforms.** Backend only (Linux pods; macOS for development). The bench needs `redis-server` on PATH; the+ real-Redis counter test is skipped where there is none, as on CI's Linux runners.diff --git a/docs/product-measurement.md b/docs/product-measurement.mdindex dff55a8cf..d636b064d 100644--- a/docs/product-measurement.md+++ b/docs/product-measurement.md@@ -265,7 +265,13 @@ message, database detail, URL or unknown error code is collected. These diagnostprivacy choice and bounded queue, so a delivery outage can delay its own diagnostic counters.Desktop now splits failed delivery attempts into the same fixed categories. A permanently invalidor oversized packet is discarded so it cannot block newer reports; transient errors retry the-same receipt. Delayed errors after a choice or account change are discarded.+same receipt. Delayed errors after a choice or account change are discarded. A busy or failing+answer (429, 5xx, a timeout, an unreachable CLI) holds that channel's next report under the CLI's+backoff: full jitter under a ceiling that doubles from two minutes to half an hour, never before the+answer's Retry-After, which the CLI's proxy passes on; any other answer resets it. Until the Desktop+release after 2026-10-28 every refusal was sent again a minute later (165 of 272 failed Desktop+reports that morning were rate limited), and every 429 counted as `rate_limited`; a 429 for a write+conflict or a transaction now keeps that cause, as the CLI's does: compare releases separately.The local app proxy accepts only bounded UI counts, or Desktop health/UI counts with the exactpublic release, OS and channel context. It does not accept daemon counters or arbitrary context.Like the backend, it keeps a report whose only problem is a counter name this CLI does not know yet:@@ -323,17 +329,19 @@ website route, without cookies, only in a release browser build and never for aaccount. The same totals can come from one visitor or many.Both ingestion paths atomically add only UTC-day/metric totals plus an unlinked random retry receipt.-Fast database write conflicts retry that complete transaction up to three times with short jitter,-rechecking the sharing choice each time. No retry starts after the first second; existing transaction-deadlines still apply to each attempt. Slow or exhausted conflicts return to the client's normal-immutable-report retry. Receipts prevent both immediate and later retries from counting twice.-Reports update their counters and separate margins in one Mongo update command inside-that transaction. A partial write aborts the receipt and all counts; no per-report body is stored.-This shortens shared-row contention without adding a daemon timer or delaying product actions.-Each backend process admits one aggregate report transaction at a time, with at most 32 waiting-reports and a two-second queue deadline. Overflow returns a retryable busy response. Permission-is checked inside the transaction after admission, including every conflict retry. Other server-processes can still contend; this does not promise zero delivery failures.+Each backend process writes its reports one batch at a time (`backend/src/lib/productUsageBatch.ts`):+reports that arrive while a batch commits go together in the next, up to 256, in one transaction that+checks each report's sharing choice, skips receipts already committed (a retry, or a second copy in+the same batch), writes the new receipts and adds the batch's summed counters and separate margins+in one Mongo update command. A process's own reports therefore never conflict on the shared daily+totals; before this, each report was a transaction of its own, and on 2026-10-28 1,000 of the CLI's+1,269 rejected reports were those write conflicts. Conflicts with another process's batch retry the+whole batch up to three times with short jitter, rechecking every sharing choice each time. No retry+starts after the first second; existing transaction deadlines still apply to each attempt. A partial+write aborts the batch's receipts and all its counts; no per-report body is stored. At most 2,048+reports wait per process, each for at most two seconds; overflow, a long wait and exhausted+conflicts return a retryable busy response with a Retry-After, and the client sends the same receipt+again later. This does not promise zero delivery failures.The public `/api/health` response includes validated release tag/SHA coordinates so a successfulimage build can be distinguished from the version actually serving requests.diff --git a/docs/superpowers/plans/2026-10-28-round-dial-swarm-chat.md b/docs/superpowers/plans/2026-10-28-round-dial-swarm-chat.mdnew file mode 100644index 000000000..781fac9c7--- /dev/null+++ b/docs/superpowers/plans/2026-10-28-round-dial-swarm-chat.md@@ -0,0 +1,414 @@+# Round dial: a Swarm is its chats — Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** The round dial's Swarm tab shows, per project, the chat the person has open (Lead by default, Chat with PM or a+group when the desktop opens one): its last agent message, working only for a working group, and alerts only on new Lead or+PM messages.++**Architecture:**+- The Super Tab service's `SwarmCards` (`cli/src/superTabs/cards.ts`) decides, per Lead:+ - the chat on the face;+ - its kind;+ - whether it works;+ - the newest Lead/PM message since a baseline.+- These ride on `SwarmLead` through the existing cards path.+- `CableSession` gates the new frames on the device's hello `swarmChat: "v1"`. The firmware draws them.+- The desktop tells the daemon which conversation is open.++**Tech Stack:** TypeScript (CLI, vitest), Dart/Flutter (Desktop), C on ESP-IDF 5.5 with Python host tests (round firmware).++**Spec:** `docs/superpowers/specs/2026-10-28-round-dial-swarm-chat-design.md`++## Global Constraints++- New behaviour only for a device whose hello has `swarmChat: "v1"`. Every other device (the Pro, round ≤ 0.0.94) gets+ byte-identical frames to today.+- Chat kinds:+ - `lead`: `project.leadConversationId`;+ - `pm`: a conversation with `audience` whose project is this one;+ - `group`: any other conversation of the project.+- `state` for a `swarmChat` device is `work` only for a `group` chat whose `assignment.status === 'working'`, else+ `done`. It is never `ask` or `stuck`.+- Recap and notice text: the newest message whose `source` is null and whose `author.id` is an agent of the chat:+ - the Lead for `lead`/`pm`;+ - the group's `agentIds` for `group`.+- Alerts only for the Lead conversation and the Chat with PM, only for messages written by the project's Lead agent. Group+ messages never alert.+- Baseline: messages at or before the first sequence seen after the service starts, or when a device attaches, never+ alert.+- Names are cut to 48 bytes (`NAME_BYTES`), texts to 1500 bytes (`RECAP_BYTES` / `truncateUtf8(…, 1500)`), and ids are+ checked with `CARD_ID` / `cardId`.+- A Lead's own terminal question (the `question` frame with `superTab`) still alerts on the dial.+- Firmware dev builds are `-DPROJECT_VER=0.0.99`. Flash only with Diego's yes, naming MAC `28:84:85:90:63:E8` and the build.+ Never upload firmware or touch the OTA manifest.+- Verified on 2026-10-28 (spec's first Unverified line): Chat with PM messages carry `author: {kind: 'agent', id: <Lead+ agent id>}` and `source: null`, the same shape as the Lead conversation.++## Review Focus++1. **A device re-attaches or the daemon restarts while a Lead notice is in the cards.** The cards replay must not beep+ again. Tested in Task 3: `replays a held notice without sending it`.+2. **Two Lead messages land between two tab reads.** One notice for the newest, not two beeps. A failed page read must+ not advance the baseline, so the next move retries. Tested in Task 1: `one notice for the newest of two messages` and+ `a failed read keeps the baseline`.+3. **The desktop already has the PM chat open when the PM writes.** No beep: the notice is not sent, or is read at once.+ Tested in Task 3: `does not send a notice for the chat the desktop has open`.+4. **The desktop opens a conversation of another project or another Swarm, or one that is archived.** That project's+ face stays on its Lead chat, and a recap for the old chat is dropped by the dial. Tested in Task 1+ (`ignores a focus outside the project`) and Task 5 (`drops a recap for another chat`).+5. **An old dial or the Pro next to a new daemon.** Frames are byte-identical to today, the Pro's recap is still the+ Lead conversation, and talk still goes to the Lead conversation. Tested in Task 3: `a device without swarmChat gets+ today's frames`.++---++### Task 1: SwarmCards picks each project's chat, its recap and its Lead/PM notice++**Files:**+- Modify:+ - `cli/src/core/api.ts:1218-1225` (types)+ - `cli/src/superTabs/cards.ts` (`leadsOf`, `lastLeadMessage`, `SwarmCards.want/recap/open/say`, a notice watcher)+ - `cli/src/superTabs/inCore/cards.ts` (validate the new fields)+- Test: `cli/src/superTabs/cards.spec.ts`, `cli/src/superTabs/inCore/cards.spec.ts`++**Interfaces:**+- Produces (in `core/api.ts`):+ ```ts+ export type ChatKind = 'lead' | 'pm' | 'group'+ export interface SwarmChat { kind: ChatKind; id: string; name: string; working: boolean; since?: number }+ export interface LeadNotice { chat: 'lead' | 'pm'; chatId: string; id: string; text: string; at: number }+ // SwarmLead gains: chat?: SwarmChat; notice?: LeadNotice+ // LeadRecap gains: chatId?: string+ export interface CardFocus { tabId: string; conversationId: string }+ ```+- Produces (in `cards.ts`):+ - `leadsOf(state, machineId, live, me?, focus?: string)`. `focus` is the conversation the window has open in this tab.+ Every Lead gets `chat`. `state` keeps today's meaning, for old devices.+ - `lastAgentMessage(messages: Json[], agentIds: ReadonlySet<string>): { text: string; at: number; id: string; sequence: number } | null`.+ It replaces `lastLeadMessage`, whose callers pass `new Set([leadId])`.+ - `SwarmCards`:+ - `want(on: boolean, include?: string[], focus?: CardFocus | null): void`. A focus change rebuilds the cards at once.+ - `recap(tabId, leadId, chat = false): Promise<LeadRecap>`. With `chat`, it reads the face chat with its agents and+ returns `chatId`.+ - `open(session, tabId, leadId, chat = false)`. With `chat`, it watches the face chat's sequence.+ - `say(harnessId, text, chat = false)`. With `chat`, it posts to the face chat's id.++- [ ] **Step 1: Write the failing tests** in `cards.spec.ts`:+ - `leadsOf` (in `describe('leadsOf chats')`):+ - `opens each project on its Lead chat`: `chat` is `{kind:'lead', id: leadConversationId, name:'Lead', working:false}`.+ - `follows the window to the project's Chat with PM`: focus = the audience conversation, giving `{kind:'pm', name:'PM'}`.+ - `follows the window to a group`: `{kind:'group', name: <group title cut to 48 bytes>}`.+ `working` is true only when that group's `assignment.status === 'working'`, and `since` comes from a live turn of+ one of its agents here.+ - `ignores a focus outside the project`: a conversation of another project, an unknown id, or an archived group leaves+ the Lead chat.+ - `lastAgentMessage`: `takes the newest row by any of the chat's agents, skipping the person and source rows`.+ - `SwarmCards` notices (use the existing fake backend and tab reads):+ - `records a baseline on the first read and sends no notice`.+ - `notices a new Lead message in the Lead conversation`, giving `notice = {chat:'lead', chatId, id, text, at}`.+ - `notices a new Lead message in Chat with PM`, giving `{chat:'pm', …}`.+ - `never notices a group message, the person's message or a system row`.+ - `one notice for the newest of two messages`.+ - `a failed read keeps the baseline`: the read throws, then the next move notices the message.+ - `SwarmCards` recap:+ - `recap with chat reads the face chat and names its chatId`;+ - `recap without chat is today's Lead recap`.+ - `SwarmCards` say: `say with chat posts message.send to the face chat`.+ - In `inCore/cards.spec.ts`: `keeps a sound chat and notice, drops a malformed one`. Bad kind, non-id `chatId`, and+ over-long text are cut or dropped, and the Lead is kept without them.++- [ ] **Step 2: Run to verify they fail**++ Run: `cd cli && npx vitest run src/superTabs/cards.spec.ts src/superTabs/inCore/cards.spec.ts`+ Expected: FAIL (no `chat`/`notice`, `lastAgentMessage` undefined).++- [ ] **Step 3: Implement the types, `leadsOf` chat selection, `lastAgentMessage`, and the notice watcher**+ - Notice watcher: `SwarmCards` keeps `seen: Map<conversationId, sequence>` and `notices: Map<leadKey, LeadNotice>`+ (lead key `${tabId}:${leadId}`).+ - On each tab read, for each project's Lead conversation and PM chat, `lastMessageSequence > seen` triggers one page+ read, under the `MAX_RECAPS_IN_FLIGHT` limit, taking the newest Lead-written message after `seen`.+ - It sets `notices` and advances `seen` only after a successful read. A first sight sets `seen` without reading.+ - Clear both maps when the account changes (where `recaps.clear()` is today). Drop a tab's entries when it leaves the+ cards.+ - `leadsOf` callers attach `notice` from `notices`.++- [ ] **Step 4: Run to verify they pass**++ Run: `cd cli && npx vitest run src/superTabs && npx tsc --noEmit -p .`+ Expected: PASS, typecheck clean.++- [ ] **Step 5: Commit**++ `git add cli/src/core/api.ts cli/src/superTabs/cards.ts cli/src/superTabs/cards.spec.ts cli/src/superTabs/inCore/cards.ts cli/src/superTabs/inCore/cards.spec.ts`+ `git commit -m "feat(swarm): cards carry each project's chat on the face and the Lead's newest message as a notice"`++### Task 2: The window's open conversation reaches SwarmCards, and the chat flags reach the service++**Files:**+- Modify:+ - `cli/src/localWsServer.ts:234-262` (`appSwarmsFrom`: `conversationId`)+ - `cli/src/cable/cableSession.ts:274` (`AppSwarms` row type)+ - `cli/src/cable/cableHost.ts`:+ - `activeSwarmProject()` adds `conversationId?`;+ - `swarmCardRecap`, `swarmCardOpen` and `swarmSay` take `chat = false`.+ - `cli/src/services/devices.ts:170, 226-233, 490-500`:+ - `tellCards` sends `focus`;+ - the `swarms` handler re-tells on a focus change;+ - the chat flags are passed on.+ - `cli/src/core/devicesLink.ts:126-131`: pass `focus` and `chat`.+ - `cli/src/superTabs/service.ts:348-362`: read `focus` (both ids `cardId`) and `chat === true`.+- Test: `cli/src/localWsServer.spec.ts`, `cli/src/services/devices.spec.ts` (or the existing devices-wiring spec), `cli/src/superTabs/service.spec.ts`++**Interfaces:**+- Consumes: `CardFocus`, `SwarmCards.want/recap/open/say` (Task 1).+- Produces:+ - `DaemonCableHost.activeSwarmProject(): { superTabId; projectId; conversationId?; fromDevice } | null`;+ - `swarmCardRecap(tabId, leadId, chat?: boolean)`, `swarmCardOpen(session, tabId, leadId, chat?: boolean)`,+ `swarmSay(harnessId, text, chat?: boolean)`;+ - service actions `cardsWanted {on, include, focus?}`, `cardRecap {…, chat?}`, `cardOpen {…, chat?}`,+ `cardSay {…, chat?}`.++- [ ] **Step 1: Write the failing tests**+ - `localWsServer.spec.ts`: `app_swarms keeps a Swarm tab's conversationId, and drops one that is not an id`.+ - Devices spec: `tells the cards the window's open Swarm conversation, again only when it changes`.+ - `service.spec.ts`: `cardsWanted passes focus to the cards; cardRecap, cardOpen and cardSay pass chat`.++- [ ] **Step 2: Run to verify they fail**++ Run: `cd cli && npx vitest run src/localWsServer.spec.ts src/superTabs/service.spec.ts <devices spec>`+ Expected: FAIL.++- [ ] **Step 3: Implement the field and the pass-through.**+ `focus` is `{tabId: superTabId, conversationId}` of the window's active Swarm tab, or null when the active tab is not+ a Swarm or names no conversation.++- [ ] **Step 4: Run to verify they pass**++ Run: same command, then `npx tsc --noEmit -p .`+ Expected: PASS, clean.++- [ ] **Step 5: Commit** — `feat(swarm): the window's open Swarm conversation reaches the cards; the dial's chat flag reaches the service`++### Task 3: CableSession speaks `swarmChat: "v1"`++**Files:**+- Modify: `cli/src/cable/cableSession.ts`:+ - hello parsing, around 1240: `this.swarmChat = str('swarmChat') === 'v1'`, reset with the others at 684;+ - `pushSwarmCards`, around 2648;+ - `onSuperTab` recap/open, around 2720-2750;+ - `swarmCardRecap`, around 2714;+ - the talk path that calls `host.swarmSay`.+- Test: `cli/src/cable/cableSession.spec.ts`++**Interfaces:**+- Consumes: `SwarmLead.chat/notice`, the chat flags (Tasks 1–2).+- Produces, the wire for a `swarmChat` device:+ - `supertab` lead entries add `chat`, `chatId` and `chatName`; `state` is `chat.working ? 'work' : 'done'`, and `since`+ is `chat.since` (or none).+ - `supertab.recap` adds `chatId`.+ - New frame `supertab.notice {tab, lead, chat, chatId, id, text, at}`.+ - New frame `supertab.notice.read {tab, lead, chatId}`.++- [ ] **Step 1: Write the failing tests** in `describe('swarmChat')`:+ - `a device without swarmChat gets today's frames`: same `supertab` bytes as before for a card with `chat`/`notice`+ set. The recap is requested without `chat`, and talk without `chat`.+ - `a swarmChat device gets chat, chatId, chatName and work only for a working group`.+ - `sends a notice once per id`.+ - `replays a held notice without sending it`: attach, or a forced cards push, with a notice already present sends+ nothing. A later new id is sent.+ - `does not send a notice for the chat the desktop has open`: the active `conversationId` equals `notice.chatId`.+ - `sends notice.read when the desktop opens a chat with a sent notice`.+ - `asks recaps and talks with chat, and passes chatId on the recap`.+ - The frame size: `12 Leads with chats stay under the device's 512-token guard`. Count tokens as the existing guard+ test does.++- [ ] **Step 2: Run to verify they fail**++ Run: `cd cli && npx vitest run src/cable/cableSession.spec.ts -t swarmChat`+ Expected: FAIL.++- [ ] **Step 3: Implement.**+ - Keep per session `sentNotices: Map<leadKey, noticeId>`. On attach and on `force`, fill it from the current cards+ without sending.+ - The notice-read check runs in `pushSwarmCards` against `host.activeSwarmProject()?.conversationId`.++- [ ] **Step 4: Run to verify they pass**++ Run: `cd cli && npx vitest run src/cable src/superTabs && npx tsc --noEmit -p .`+ Expected: PASS, clean.++- [ ] **Step 5: Commit** — `feat(cable): swarmChat devices get the chat on the face, Lead/PM notices and chat recaps`++### Task 4: Desktop announces the open Swarm conversation++**Files:**+- Modify: `desktop/lib/state/app_state.dart`:+ - `_announceOpenPanesToDial` swarm rows, around 5660-5700: add `conversationId`;+ - the #1911 re-announce listener: also fire when the selected conversation changes.+- Test: `desktop/test/super_tab_dial_test.dart`++**Interfaces:**+- Produces: the `app_swarms` row field `conversationId`. It is the controller's `selectedId` when+ `snapshot.conversation(selectedId) != null`, else absent.++- [ ] **Step 1: Write the failing tests**+ - `a Swarm tab announces the open conversation's id`: the Lead conversation, then the PM chat, then a group.+ - `selecting another conversation re-announces`.+ - `a decisions view or an unloaded Swarm leaves conversationId out`.++- [ ] **Step 2: Run to verify they fail**++ Run: `cd desktop && flutter test test/super_tab_dial_test.dart`+ Expected: FAIL.++- [ ] **Step 3: Implement** next to the existing `projectId` line, with the same `superTabs.peek(tabId)` guard.++- [ ] **Step 4: Run to verify they pass**++ Run: `cd desktop && flutter test test/super_tab_dial_test.dart && flutter analyze lib/state/app_state.dart`+ Expected: PASS, no issues. `dart format` on the touched files only.++- [ ] **Step 5: Commit** — `feat(desktop): tell the dial which Swarm conversation is open`++### Task 5: Firmware model and cable: parse the chat, the chat recap and the notices++**Files:**+- Modify:+ - `devices/harness-device/firmware/main/ui/habitat/supertab.h:14-40`:+ - `typedef enum { HT_CHAT_LEAD, HT_CHAT_PM, HT_CHAT_GROUP } ht_chat_kind_t;`+ - `ht_lead_t` adds `ht_chat_kind_t chat`, `chat_id[ID_MAX]` and+ `chat_name[HT_SUPERTAB_NAME]`;+ - `ht_lead_in_t` adds `chat`, `chat_id` and `chat_name`;+ - the recap struct adds `chat_id[ID_MAX]`.+ - `supertab.c`: copy the fields in `ht_supertab_lead_add`/`ht_supertabs_put`. `ht_supertabs_recap_put` takes `chat_id`+ and drops a recap whose `chat_id` differs from the face Lead's.+ - `main/cable_client.c`:+ - hello `msg_string(&root, "swarmChat", "v1")` beside line 323;+ - `handle_supertab` reads `chat`/`chatId`/`chatName`;+ - `handle_supertab_recap` reads `chatId`;+ - new `handle_supertab_notice` and `handle_supertab_notice_read`, registered beside line 1375, calling+ `ui_supertab_notice` and `ui_supertab_notice_read`.+ - `main/cable_client.h`: declare the two `ui_` functions next to `ui_supertab_focus`.+- Test: `devices/harness-device/firmware/test/test_supertab.c`, `test/test_cable_supertab.py`++**Interfaces:**+- Produces (C):+ ```c+ void ui_supertab_notice(const char *tab, const char *lead, ht_chat_kind_t chat, const char *chat_id, const char *text, uint32_t at);+ void ui_supertab_notice_read(const char *tab, const char *lead, const char *chat_id);+ ```+ - A missing `chat` means `HT_CHAT_LEAD`, `chat_id` "" and `chat_name` "", for frames from an old daemon.++- [ ] **Step 1: Write the failing tests**+ - `test_supertab.c`:+ - `lead keeps chat, chat_id, chat_name`;+ - `drops a recap for another chat`;+ - `a lead without chat fields reads as the Lead chat`.+ - `test_cable_supertab.py`:+ - `hello says swarmChat v1`;+ - `supertab with chat fields parses`;+ - `supertab.notice and supertab.notice.read reach the ui calls with their fields`;+ - `a notice with a non-id chatId or no lead is ignored`.++- [ ] **Step 2: Run to verify they fail**++ Run: `source ~/esp/esp-idf/export.sh && make device-test`+ Expected: the new cases FAIL.++- [ ] **Step 3: Implement the fields, parsing and handlers.** The `ui_` bodies land in Task 6. Here, a weak stub in the+ test harness records the calls.++- [ ] **Step 4: Run to verify they pass**++ Run: `make device-test`+ Expected: all PASS.++- [ ] **Step 5: Commit** — `feat(dial): parse a Lead's chat, chat recaps and Lead/PM notices; say swarmChat v1`++### Task 6: Firmware face and alerts follow the chat++**Files:**+- Mockup first, not committed: `devices/harness-device/mockup/swarm-chat.html` in the **main checkout** (gitignored).+ - It shows the face for a Lead chat, a PM chat, a long group name and a working group.+ - Open it with `open`, and get Diego's OK on how the chat name sits under the project before coding.+- Modify: `devices/harness-device/firmware/main/ui/habitat/ui_habitat.c`:+ - `render_swarm_face` (~1290);+ - `swarm_notice_raise`/`swarm_notice_drop` (~4892-4930);+ - `ui_supertab_wait_close` (~5051);+ - new `ui_supertab_notice` and `ui_supertab_notice_read` after `ui_supertab_focus` (~5005).+- Test: `devices/harness-device/firmware/test/test_touch_ui.py` (add the two functions to its lifted list at line 238)++**Interfaces:**+- Consumes: the `ht_lead_t` chat fields and the two `ui_` declarations (Task 5).++**Behaviour:**+- Face:+ - The chat name is drawn under the project on the upper arc when `chat != HT_CHAT_LEAD`.+ - The recap shows whenever it is loaded for the face's `chat_id`.+ - The working pet and clock show only when `l->state == HT_LEAD_WORK`.+ - `asking` comes only from an open wait.+- Alerts:+ - `ui_supertab_notice` raises the Lead's single entry with the text as its body. The grey line is the Swarm name,+ plus " · PM" for `HT_CHAT_PM`.+ - It beeps and wakes with the existing coalescing.+ - It is read at once only when `on_face(lead)` and the face Lead's `chat_id` equals the notice's.+ - A newer notice replaces the text and marks the entry unread.+ - `ui_supertab_notice_read` removes the entry when its `chat_id` matches.+- `ui_supertab_wait_close`: when the Lead's state is not `ask`/`stuck`, which is always the case with a `swarmChat`+ daemon, the entry is dropped, as the `else` branch already does. Check that no change is needed there and add the test.++- [ ] **Step 1: Write the failing tests** in `test_touch_ui.py`:+ - `swarm face shows PM under the project and the recap, no working`;+ - `a working group shows the working pet`, `a done group shows its recap`;+ - `notice for the face's chat is read at once and does not beep`;+ - `notice for another chat stays unread and beeps once`;+ - `notice.read removes the entry`;+ - `a second notice replaces the text and is unread again`;+ - `a Lead wait still raises its entry`;+ - `no entry from a lead state change when chats are on`.++- [ ] **Step 2: Run to verify they fail**++ Run: `make device-test`+ Expected: the new cases FAIL.++- [ ] **Step 3: Implement** as described under Behaviour.++- [ ] **Step 4: Run to verify they pass, and build**++ Run: `make device-test`, then+ `idf.py -C devices/harness-device/firmware -B build-dev99 -DIDF_TARGET=esp32s3 -DSDKCONFIG=build-dev99/sdkconfig.dev -DDEVICE_FORCE_PROD=1 -DPROJECT_VER=0.0.99 build`+ Expected: all PASS; build succeeds.++- [ ] **Step 5: Commit** — `feat(dial): the Swarm face shows the open chat; alerts come from Lead/PM notices`++### Task 7: Real check on Diego's round, and the docs++**Files:**+- Modify:+ - `docs/superpowers/specs/2026-10-23-round-swarm-tab-design.md`: a short note at §4/§5 pointing to the new spec for+ `swarmChat` devices;+ - `docs/swarms.md`: the device part, if it describes dial alerts.++- [ ] **Step 1:** Run the CLI from this branch on Diego's Mac only with his yes (`make install-cli`, without+ `--no-updates`). Or wait for the release that carries Tasks 1–3.+- [ ] **Step 2:** Ask Diego, naming MAC `28:84:85:90:63:E8` and the build (0.0.99 from this branch's HEAD). On his yes,+ flash with the round procedure:+ 1. quit the app;+ 2. write the flasher flag;+ 3. `harness stop`;+ 4. `idf.py -p /dev/cu.usbmodem21301 flash`;+ 5. remove the flag;+ 6. `harness start`;+ 7. reopen the app.++ Check that the log shows `on fw 0.0.99` with `swarmChat`.+- [ ] **Step 3:** Diego's checks:+ 1. Swipe between projects: each opens on its Lead.+ 2. Open Chat with PM, then a group, on the desktop: the dial follows.+ 3. A working group shows working; the Lead chat never does.+ 4. A new PM message alerts once; a group message does not.++ Read the daemon log lines for each.+- [ ] **Step 4: Commit** the docs: `docs: the round Swarm tab follows the chat for swarmChat devices`.diff --git a/docs/superpowers/specs/2026-10-23-round-swarm-tab-design.md b/docs/superpowers/specs/2026-10-23-round-swarm-tab-design.mdindex 1e4c82bd6..de7d43313 100644--- a/docs/superpowers/specs/2026-10-23-round-swarm-tab-design.md+++ b/docs/superpowers/specs/2026-10-23-round-swarm-tab-design.md@@ -160,6 +160,10 @@ Hold on the face still opens TABS (`tabs_open`); the carousel opens on the curre### 4. Inside a Swarm tab (screens 2a–2h, 3a–3c)+> A dial whose hello says `swarmChat: "v1"` (round firmware after 0.0.94) follows the chat instead: each Lead's face is+> the chat the desktop has open in its project (Lead, Chat with PM or a group, named on an inner arc under the project),+> its recap is that chat's, and it works only for a working group. See [2026-10-28-round-dial-swarm-chat-design.md](2026-10-28-round-dial-swarm-chat-design.md) §2–§3.+While the dial is in a Swarm tab, its panes are that Swarm's Leads in `order`, not the desk roster (`s.agents`). Adesk roster that arrives for the linked desk tab (the Lead's terminal pane) does not replace them. Decision 6: onepane per project, no workers.@@ -206,6 +210,10 @@ to TABS.### 5. Needs you / stuck: beep and inbox (screens 4a–4f, 2e′)+> With `swarmChat: "v1"` no Lead reads `ask` or `stuck`: the dial alerts only on the Lead's new messages in its Lead+> conversation or Chat with PM (`supertab.notice`, read with `supertab.notice.read`), and a Lead's own terminal wait+> still alerts as below. See [2026-10-28-round-dial-swarm-chat-design.md](2026-10-28-round-dial-swarm-chat-design.md) §2–§3.+There is no toast. A Lead entering `ask` or `stuck` gets the existing alert path: a beep (`audio_notify_done`, at mostone per 30 s), a display wake, and one inbox entry. The face changes only as it does today: the green bell pill aty 400 with the unread count, or the pet's bell bubble while the pet is working (4a, 4b). Pull down from the face, or tap@@ -238,6 +246,9 @@ shows 2c / 2d / 2e′ instead of the agent open path. 4f "No notification" is th### 6. Talk (screens 5a–5e)+> With `swarmChat: "v1"` the words go to the chat on the face, not always the Lead conversation. See+> [2026-10-28-round-dial-swarm-chat-design.md](2026-10-28-round-dial-swarm-chat-design.md) §2.+A tap on the face of a Lead with `local` talks to it exactly as to any pane: the existing listening, sending and backflow, with `cable_client_voice_begin(local, …)` (5a–5d). An engine without a listening scene uses the seven bars (5e).After sending, the face returns to the working state from the next `supertab` (the daemon reads a local Lead's livediff --git a/docs/superpowers/specs/2026-10-28-round-dial-swarm-chat-design.md b/docs/superpowers/specs/2026-10-28-round-dial-swarm-chat-design.mdnew file mode 100644index 000000000..293fdc87b--- /dev/null+++ b/docs/superpowers/specs/2026-10-28-round-dial-swarm-chat-design.md@@ -0,0 +1,214 @@+# Round dial: a Swarm is its chats, not its work++Status: spec · 2026-10-28 · owner Diego · changes the Swarm tab of+[2026-10-23-round-swarm-tab-design.md](2026-10-23-round-swarm-tab-design.md) (§4 face, §5 alerts, §6 talk)++## Why++Today the dial's Swarm tab follows the **work**:+- A project's Lead face reads `work` whenever any agent of the project is in a turn here, or any group is `working` or+ `review` (`cli/src/superTabs/cards.ts` `leadsOf`). While it reads `work`, the face shows the working pet and clock+ and hides the recap (`ui_habitat.c` `render_swarm_face`).+- The dial alerts when a project turns `ask` or `stuck`, which a **group** causes (`needs_human` or `blocked`)+ (`supertab.c` lead events → `swarm_notice_raise`). A new message from the Lead alerts nothing.+- The recap is always the Lead's last message in the project's Lead conversation, and talking posts there, whatever+ the desktop has open.++The owner wants the dial to follow the **conversation**. Each project has three places to chat:+- Chat with PM (the person's private chat with the project's Lead);+- the Lead conversation (`# project`);+- one chat per group.++The dial should show the one the person is in, and speak up only when the Lead or the PM says something new.++## What the owner decided (2026-10-28)++1. A horizontal swipe on the dial moves between **projects**, as today. A project opens on its **Lead** chat.+2. When the person opens that project's **Chat with PM** or one of its **groups** on the desktop, the dial follows to+ that chat.+3. The face shows only the **recap of the chat's last message from the agent side** (the Lead, the PM, or an agent of+ the group). The person's own messages are not the recap.+4. **Working** shows only for a **group** chat whose group is `working`. Lead and PM chats never show working.+5. The dial **alerts only when the Lead or the PM posts a new message** (Lead conversation or Chat with PM). Groups+ never alert, whatever their state.+6. A question asked by the Lead's own terminal on this machine (the existing Super Tab wait, a `question` frame with+ `superTab`) **still alerts**, as today.+7. Talking on the dial posts into the chat on the face.+8. Round dial only. The Harness Pro keeps its current Swarm cards.++Approach chosen: **the daemon decides, the firmware draws** (A). The rules live in the CLI, so changing them later+needs a CLI release, not a firmware flash.++## Design++### 1. Desktop: say which chat is open++- `desktop/lib/state/app_state.dart` `_announceOpenPanesToDial`: a Swarm tab's row in `app_swarms` gains+ `conversationId`. It is the Swarm controller's `selectedId` when that id is a conversation in its snapshot (Lead+ conversation, Chat with PM or a group). Otherwise it is left out (a decisions view, a machine, not loaded yet).+- A change of the selected conversation re-announces, as a change of the project does since #1911.+- `cli/src/localWsServer.ts` `appSwarmsFrom` accepts it with the same id check as `projectId`.+ `cli/src/cable/cableHost.ts` `activeSwarmProject()` returns it.++### 2. Daemon: one chat per project, chosen and read here++The new rules apply only to a device whose hello carries **`swarmChat: "v1"`** (`cableSession.ts` hello parsing,+beside `superTab: "wait-v1"`). Every other device, the Pro and round firmware up to 0.0.94, keeps today's frames.++**The chat on a project's face** (`cli/src/superTabs/cards.ts`):+- If the window's active tab is this Swarm and its `conversationId` belongs to this project, it is that conversation.+- Otherwise it is the project's Lead conversation (`project.leadConversationId`).++**Its kind:**+- `lead`: the project's Lead conversation;+- `pm`: a conversation with `audience` (the reader's private chat) in this project;+- `group`: any other conversation of the project.++**The `supertab` frame, per Lead** (one per project, as today), for a `swarmChat` device:+- `chat`: `lead` | `pm` | `group`.+- `chatId`: the conversation id.+- `chatName`: "Lead", "PM", or the group's title, cut to 48 bytes like `project`.+- `state`: `work` only when `chat` is `group` and that group's `assignment.status` is `working`. Otherwise `done`.+ It is never `ask` or `stuck`, so group states raise nothing on the device. `since` is sent only with `work`, from the+ group agent's live turn here when there is one.++**Recap:**+- `supertab.recap.get {tab, lead}` answers with the last message of the **chat on that Lead's face** whose author is+ an agent and whose `source` is null (system rows such as "Routed to…" are not recaps).+- `lastLeadMessage` becomes `lastAgentMessage(messages, agentIds)`, where `agentIds` is the Lead for `lead`/`pm` and+ the group's `agentIds` for `group`.+- The `supertab.recap` frame gains `chatId`. A recap for another chat than the one on the face is dropped by the+ device, as a recap for another Lead is today.+- When the chat on the face changes (the desktop opened another one), the daemon sends the new `supertab` and, for a+ device that has that Lead's recap open, the new recap.++**Alerts (new frame `supertab.notice`):**+- For each project of each Swarm, the daemon watches two conversations: the Lead conversation and the reader's Chat+ with PM. It uses `lastMessageSequence` from the tab reads it already makes every 5 s (`SwarmCards`).+- When one moves, it reads that conversation's newest page once. That is the same read and the same 2-at-once limit+ as recaps (`MAX_RECAPS_IN_FLIGHT`).+- For each new message after the last one seen whose author is that project's Lead agent and whose `source` is null,+ it sends `supertab.notice {tab, lead, chat: "lead"|"pm", chatId, id, text, at}` once. `id` is the message id, and+ `text` is cut to the recap's length.+- **Baseline:** the first read of a conversation after the daemon starts, or after a device attaches, records the last+ sequence and alerts nothing. Old messages never alert.+- **Read on the desktop:** when the window's `conversationId` is a conversation with an open alert, the daemon sends+ `supertab.notice.read {tab, lead, chatId}`.+- Groups are never watched for alerts.++**Talk:** `say(harnessId, text)` posts into the chat on that Lead's face (`message.send` to `chatId`) instead of+always the Lead conversation. A remote Lead still has no talk (today's rule).++### 3. Firmware (round): draw the chat, alert on its notice++- **Hello:** add `swarmChat: "v1"` (`cable_client.c`, beside `superTab: "wait-v1"`).+- **Parse:** `handle_supertab` reads `chat`, `chatId` and `chatName` into `ht_lead_t` (`supertab.h`; `chat_name` sized+ like `project`). `handle_supertab_recap` reads `chatId`. New handlers parse `supertab.notice` and+ `supertab.notice.read`.+- **Face** (`render_swarm_face`):+ - The upper arc shows the project, as today. The chat name is shown under it when the chat is not `lead`.+ - The recap always shows when loaded. The working pet and clock show only for `state == work`, which only a group+ chat can be.+ - The asking pose comes only from an open Lead wait (decision 6). The firmware no longer draws it from `ask`/`stuck`+ for a `swarmChat` daemon; those states are not sent anyway.+- **Alerts:**+ - A `supertab.notice` raises that Lead's inbox entry, which stays one per Lead (today's `swarm_notice_raise`). The+ body is the message text, the green line is engine + project, the grey line is the Swarm name plus "PM" when+ `chat` is `pm`.+ - It beeps and wakes the display with the existing coalescing (one beep per 30 s).+ - The entry is read at once only when the face shows that Lead **and** the face's `chatId` equals the notice's.+ Otherwise it stays unread.+ - `supertab.notice.read` removes it.+ - A later notice for the same Lead replaces the text and counts as unread again.+- **Lead waits** (decision 6): unchanged. The `question` frame with `superTab` for a Lead's `local` sets the wait text+ and raises the entry. With a `swarmChat` daemon the Lead never reads `ask`, so `ui_supertab_wait_close` removes the+ entry instead of reverting it to the fixed text.+- **Following:** unchanged (`supertab.focus` picks the project). The chat comes with the next `supertab`.++### 4. What does not change++- TABS, the tab list and the entry into a Swarm (#1891, #1911).+- The swipe between projects, and PANES.+- `supertab.select`, `supertab.open` and the echo suppression.+- The Pro: it never says `swarmChat`, so it gets today's frames.++## Design (docs/feature-design-rules.md)++Reviewed revision: ______ Reviewer (another engine): ______++1. **Growth:**+ - The daemon's alert baseline is in memory: one sequence per watched conversation, at most 16 Swarms × 12 projects+ × 2 conversations.+ - Entries are deleted when a Swarm or project leaves the cards, and the whole map when the account changes or the+ daemon stops.+ - The device keeps one inbox entry per Lead, as today. [x]+2. **Concurrency:**+ - Alerts and recaps are computed on the cable session's queue (`queued`), one at a time per device.+ - The baseline map has one writer, the cards refresh. Two moves seen in one refresh produce one read. [x]+3. **Read cost:**+ - No new periodic read: sequences come from the 5 s tab reads that already run.+ - A message page is read only when a watched sequence moved, capped at 2 at once.+ - The frames grow by about 70 bytes per Lead, under the 512-token guard for 12 Leads (test). [x]+4. **Scale:** at 10× messages from Leads, reads grow with messages, still capped at 2 at once and by the 5 s tab+ cadence. The first warning is the existing "too many recap reads at once" log line. [x]+5. **Compatibility:**+ - Gated on `swarmChat: "v1"`: old firmware and the Pro get today's frames.+ - New firmware with an old CLI gets today's frames and behaves as today.+ - A desktop without `conversationId` gives the Lead chat always.+ - Existing readers of `supertab`/`supertab.recap`: `cable_client.c`, `cableSession.ts`, `superTabs/inCore/cards.ts`+ (validation `STATES`), and the Pro firmware, which is not gated in. [x]+6. **Migration and rollback:**+ - Order: CLI, then Desktop, then firmware. Each is safe alone.+ - Rolling back the CLI returns every device to today's frames.+ - Rolling back the firmware (0.0.94) just stops saying `swarmChat`. [x]+7. **Audience:**+ - Chat with PM is private. The daemon reads as the signed-in person, and the backend returns only that person's+ private chats (`visibleState`).+ - The recap and the alert of a PM chat go only to that person's own dial: the daemon owns the USB device only for+ the console user (`usbConsoleUser.ts`), never the Team account. [x]+8. **Identity:** reads and the talk post run as the signed-in person (`backend(this.core, …)`), as today. [x]+9. **Failure:**+ - A failed page read is logged once and retried when the sequence moves again.+ - A failed recap leaves "…" and the device asks again (today's 5 s retry).+ - Nothing alerts twice: the baseline only advances past messages it has sent or skipped. [x]+10. **Platforms:** the round dial on macOS, Linux and Windows daemons alike. No platform-specific code. [x]++## Testing++- **CLI** (`cards.spec.ts`, `cableSession.spec.ts`, `localWsServer` spec):+ - `conversationId` parsing.+ - The chat on the face: default Lead, follows a PM chat or group of the same project, ignores one of another project.+ - Kind detection for `lead`, `pm` and `group`.+ - `state` is `work` only for a working group, and never `ask`/`stuck` for a `swarmChat` device.+ - Recap is the last agent message of the chat and skips the person's messages and `source` rows.+ - Alerts:+ - one alert per new Lead or PM message;+ - none for a group message, for the person's own message or for a system row;+ - none for messages before the baseline;+ - `notice.read` when the desktop opens the chat.+ - Talk posts to the face's `chatId`.+ - A device without `swarmChat` gets byte-identical frames to today.+- **Desktop** (`super_tab_dial_test.dart`): opening a PM chat or a group re-announces with its `conversationId`;+ opening a decisions view leaves it out.+- **Firmware host tests** (`test_cable_supertab.py`, `test_touch_ui.py`):+ - parse of the new fields and frames;+ - the face with a PM chat (chat name, recap, no working);+ - a working group (working pet), and a done group (recap);+ - a notice for another chat stays unread, one for the face's chat is read at once;+ - `notice.read` removes it;+ - no alert from `ask`/`stuck`;+ - a Lead wait still alerts;+ - `make device-test`.+- **On Diego's round** (dev build 0.0.99, flashed with Diego's yes):+ 1. Swipe between projects: each opens on its Lead.+ 2. Open Chat with PM, then a group, on the desktop: the dial follows.+ 3. A working group shows working; the Lead chat never does.+ 4. A new PM message alerts once; a group message does not.++## Unverified++- ~~That the messages page of a Chat with PM names the Lead as `author.id` in the same shape as the Lead+ conversation.~~ Checked 2026-10-28: `author: {kind: 'agent', id: <Lead agent id>}`, `source: null`, as in the Lead+ conversation.+- Group titles can be long. Check how the 48-byte `chatName` looks under the project on the arc with a mockup in+ `devices/harness-device/mockup/` before the firmware task.diff --git a/scripts/ui-style-allowlist/desktop.json b/scripts/ui-style-allowlist/desktop.jsonindex 9426cf953..3452e75ea 100644--- a/scripts/ui-style-allowlist/desktop.json+++ b/scripts/ui-style-allowlist/desktop.json@@ -22,9 +22,6 @@"edge-insets": 7,"border-radius": 3},- "desktop/lib/super_tabs/machine_details.dart": {- "edge-insets": 6- },"desktop/lib/super_tabs/machine_status.dart": {"font-size": 1,"edge-insets": 2@@ -54,9 +51,6 @@"desktop/lib/super_tabs/profile_sheet.dart": {"font-size": 1},- "desktop/lib/super_tabs/project_github.dart": {- "edge-insets": 4- },"desktop/lib/super_tabs/project_sidebar.dart": {"edge-insets": 10},@@ -92,20 +86,17 @@"edge-insets": 1},"desktop/lib/super_tabs/sharing.dart": {- "edge-insets": 5+ "edge-insets": 4},"desktop/lib/super_tabs/ship_row.dart": {"font-size": 1,"edge-insets": 2},- "desktop/lib/super_tabs/team_glance_panel.dart": {- "edge-insets": 4- },"desktop/lib/super_tabs/terminal_row.dart": {"edge-insets": 2},"desktop/lib/super_tabs/view.dart": {- "edge-insets": 24,+ "edge-insets": 23,"border-radius": 1}}