The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-04 b1644: #2964 #2944 #2976 #2977 #2973 #2984 #2982 (#2994)
0xken154aa1780845b7
diff --git a/backend/integration/bench/README.md b/backend/integration/bench/README.mdindex ce48598cd..f724a37b8 100644--- a/backend/integration/bench/README.md+++ b/backend/integration/bench/README.md@@ -61,6 +61,16 @@ NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADATABASE_URL=mongodb://127.0.0.1:1/bench-never-used npx tsx integration/bench/observeReads.ts```+To see what one `GET changes` poll costs MongoDB with many pollers on one backend process (task #2783): every person's+windows and every worker agent poll together after nothing, one machine reading, every machine reading and one post, and+it prints per poll the operations, part reads, bytes MongoDB sent, database and wall time, and by collection per round.+`--windows N` (3), `--rounds N` (5), `--light` (`machines=light`), and the benchmark's options:++```bash+NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= \+ DATABASE_URL=mongodb://127.0.0.1:1/bench-never-used npx tsx integration/bench/changesPollCost.ts+```+The bench's own tests (helpers, plus a short run of the whole scenario), and its typecheck:```bashdiff --git a/backend/integration/bench/changesPollCost.ts b/backend/integration/bench/changesPollCost.tsnew file mode 100644index 000000000..b7c8d9d12--- /dev/null+++ b/backend/integration/bench/changesPollCost.ts@@ -0,0 +1,141 @@+import { performance } from 'node:perf_hooks'+import { setTimeout as sleep } from 'node:timers/promises'+import type { PrismaClient } from '@prisma/client'+import type { AuthUser } from '../../src/lib/ssoAuth.js'+import type { Changes } from '../../src/superTabs/read/contract.js'+import { readDelta } from '../../src/superTabs/cachedReads.js'+import { listGroupIndexes } from '../../src/superTabs/parts/indexed.js'+import { parseArgs } from './config.js'+import { partsDriver } from './drivers/parts.js'+import { machineId, seedAccounts } from './fixtures.js'+import { storeRoutes } from './legacyDriver.js'+import { localDatabase } from './mongo.js'+import { plan } from './plan.js'+import { bytesOut } from './probe.js'+import { PROFILE_STAGES, profileEntry, startProfiling, type ProfileEntry } from './profile.js'+import { seedSwarm } from './seed.js'+import { benchStamps } from './stamps.js'++/** Past the change reads' 30 s overlap, so the polls after it resend nothing they sent before. */+const QUIET_MS = 35_000+const PARTS = new Set(['SwarmHead', 'SwarmMember', 'SwarmGroup', 'SwarmAgent', 'SwarmMachine', 'SwarmStart', 'SwarmProgress'])++interface Poller { label: string; poll(): Promise<{ bytes: number; code: string | null }> }++/**+ * What one `GET changes` poll costs MongoDB with many pollers on one backend process (task #2783): the benchmark's seeded+ * Swarm, every person's windows and every worker agent polling as clients do, then rounds where all of them poll at once,+ * after nothing, after one machine's reading, after every machine's and after one post. Per poll: database operations+ * (all, and part reads), what MongoDB sent (`serverStatus` bytes out), the profiler's database time, wall time and reply+ * size; per round, operations and bytes by collection. `--light` polls with `machines=light` as the 17:30 CLI does;+ * POLL_COST_SHAPES=1 prints each part read's command. Takes the benchmark's options too. From `backend/`:+ *+ * NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= \+ * DATABASE_URL=mongodb://127.0.0.1:1/bench-never-used npx tsx integration/bench/changesPollCost.ts [--windows 3] [--rounds 5] [--light]+ */+async function main() {+ const argv = process.argv.slice(2)+ const flag = (name: string, fallback: number) => { const i = argv.indexOf(name); return i < 0 ? fallback : Number(argv[i + 1]) }+ const windows = flag('--windows', 3), rounds = flag('--rounds', 5), light = argv.includes('--light')+ const rest = argv.filter((arg, i) => !['--windows', '--rounds', '--light'].includes(arg) && !['--windows', '--rounds'].includes(argv[i - 1]!))+ const { config } = parseArgs(rest)+ const database = await localDatabase()+ await listGroupIndexes(database.db)+ const stamps = await benchStamps('memory', readDelta(database.db))+ try {+ const people = await seedAccounts(database.db, config.machines)+ const driver = await partsDriver(database.db, () => people)+ const { call, close } = await storeRoutes(database.db, () => people)+ const { swarm } = await seedSwarm(driver, config, plan(config), people)+ const query = light ? '&machines=light' : ''+ const poller = (label: string, user: AuthUser, asAgentId?: string): Poller => {+ let cursor: string | null = null+ const as = asAgentId ? `asAgentId=${asAgentId}` : ''+ return { label, async poll() {+ if (cursor === null) {+ const reply = await call<{ cursor: string }>(user, 'GET', `/api/super-tabs/${swarm.tabId}/parts${as ? `?${as}` : ''}`)+ cursor = reply.data?.cursor ?? null+ return reply+ }+ const reply = await call<Changes>(user, 'GET', `/api/super-tabs/${swarm.tabId}/changes?cursor=${cursor}${as ? `&${as}` : ''}${query}`)+ if (reply.data?.reload) throw new Error(`${label} was told to reload`)+ if (reply.data) cursor = reply.data.cursor+ return reply+ } }+ }+ const pollers: Poller[] = [+ ...people.flatMap((person, n) => Array.from({ length: windows }, (_, w) => poller(`person ${n} window ${w}`, person))),+ ...swarm.workers.map(w => poller(`agent ${w.id}`, people[w.machine]!, w.id)),+ ]+ let n = 0+ const reading = (machine: number) => driver.observeMachine(swarm.tabId, people[machine]!, machineId(machine), {+ generation: swarm.generations[machine]!, quotas: [], tools: {}, runningHarnessIds: machine === 0 ? ['bench-lead'] : [], stoppedHarnessIds: [],+ resources: { cpuPercent: 10 + (n++ % 50), memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9, diskTotalBytes: 500e9,+ projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Bench', os: 'macOS', gpuPercent: null } })+ const post = () => driver.execute(swarm.tabId, people[0]!, `poll-cost-${n++}`,+ { type: 'message.send', conversationId: swarm.workers[0]!.group, text: 'One post.', replyTo: null, recipientIds: [] })+ for (const p of pollers) await p.poll()+ await sleep(QUIET_MS)+ for (const p of pollers) await p.poll()+ process.stdout.write(`${pollers.length} pollers (${people.length} people × ${windows} windows, ${swarm.workers.length} agents), ` ++ `${config.machines} machines, ${config.groups} groups${light ? ', machines=light' : ''}\n\n`)+ process.stdout.write('| Before each round | Ops/poll | Part reads/poll | DB KB/poll | DB ms/poll | Wall ms/poll (p50) | Reply KB/poll |\n|---|---|---|---|---|---|---|\n')+ const detail: string[] = []+ const phases: Array<[string, () => Promise<unknown>]> = [['nothing', async () => {}], ['one machine reading', () => reading(1)],+ ['every machine reading', () => Promise.all(people.map((_, m) => reading(m)))], ['one post', post]]+ for (const [label, before] of phases) {+ let ops = 0, partOps = 0, dbBytes = 0, dbMs = 0, replyBytes = 0+ const byCollection = new Map<string, { ops: number; ms: number; bytes: number }>()+ const walls: number[] = []+ for (let r = 0; r < rounds; r++) {+ await before()+ await sleep(200)+ await startProfiling(database.db)+ const start = await bytesOut(database.db)+ await Promise.all(pollers.map(async p => {+ const t = performance.now(), reply = await p.poll()+ walls.push(performance.now() - t)+ if (reply.code) throw new Error(`${p.label}: ${reply.code}`)+ replyBytes += reply.bytes+ }))+ dbBytes += await bytesOut(database.db) - start+ const entries = await profiled(database.db)+ ops += entries.length+ partOps += entries.filter(e => PARTS.has(e.ns.slice(e.ns.indexOf('.') + 1))).length+ dbMs += entries.reduce((sum, e) => sum + e.millis, 0)+ if (process.env.POLL_COST_SHAPES) for (const e of entries.filter(e => PARTS.has(e.ns.slice(e.ns.indexOf('.') + 1))))+ process.stdout.write(`${label} ${e.ns} n=${e.nreturned} bytes=${e.responseLength} ${JSON.stringify(e.command).slice(0, 400)}\n`)+ for (const e of entries) {+ const name = e.ns.slice(e.ns.indexOf('.') + 1), held = byCollection.get(name) ?? { ops: 0, ms: 0, bytes: 0 }+ byCollection.set(name, { ops: held.ops + 1, ms: held.ms + e.millis, bytes: held.bytes + (e.responseLength ?? 0) })+ }+ // Each round past the 30 s overlap is too slow; a round counts what moved since the round before, as a 3 s poll does.+ await sleep(3_000)+ }+ const polls = rounds * pollers.length, sorted = walls.sort((a, b) => a - b)+ process.stdout.write(`| ${label} | ${(ops / polls).toFixed(2)} | ${(partOps / polls).toFixed(2)} | ${(dbBytes / polls / 1024).toFixed(2)} | ` ++ `${(dbMs / polls).toFixed(2)} | ${sorted[Math.floor(sorted.length / 2)]!.toFixed(1)} | ${(replyBytes / polls / 1024).toFixed(2)} |\n`)+ detail.push(`${label}: ${[...byCollection].sort((a, b) => b[1].ops - a[1].ops).map(([name, c]) => `${name} ${(c.ops / rounds).toFixed(1)} (${(c.bytes / rounds / 1024).toFixed(1)} KB)`).join(', ')}`)+ }+ process.stdout.write(`\nDatabase operations per round (all ${pollers.length} pollers), by collection:\n${detail.map(d => `- ${d}`).join('\n')}\n`)+ await close()+ await driver.close()+ } finally {+ await stamps.close()+ await database.stop()+ }+}++/** Every operation profiled since startProfiling, the profiler's own reads left out. */+async function profiled(db: PrismaClient): Promise<Array<ProfileEntry & { responseLength: number }>> {+ await db.$runCommandRaw({ profile: 0 })+ const rows = (await db.$runCommandRaw({ aggregate: 'system.profile', pipeline: [{ $match: { ns: { $not: { $regex: String.raw`\.(system\.|\$cmd)` } } } },+ { $set: { keep: '$responseLength' } }, ...PROFILE_STAGES.map(stage => ({ $project: { ...stage.$project, responseLength: '$keep' } }))],+ cursor: { batchSize: 100_000 } }) as unknown as { cursor: { firstBatch?: Array<ProfileEntry & { responseLength?: unknown }> } }).cursor.firstBatch ?? []+ return rows.map(row => ({ ...profileEntry(row), responseLength: Number(row.responseLength ?? 0) })).filter(e => e.op !== 'command' || e.command?.aggregate || e.command?.find)+}++main().catch(error => {+ process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`)+ process.exitCode = 1+})diff --git a/backend/integration/superTabGroupPlans.test.ts b/backend/integration/superTabGroupPlans.test.tsindex a80c6a954..37b071536 100644--- a/backend/integration/superTabGroupPlans.test.ts+++ b/backend/integration/superTabGroupPlans.test.ts@@ -203,6 +203,23 @@ describe('hot SwarmGroup reads name their index and read only what they return (expect(whole.map(r => [r.plans, r.returned]), JSON.stringify(changed)).toEqual([[['IXSCAN { tabId: 1, key: 1 }'], 1]])})+ it('the read cache\'s next delta reads keys and versions through the changes index, and whole by id only what moved (#2783)', async () => {+ const held: parts.DeltaRows = new Map()+ // Every row of the scene: its writes are dated at the fixture's time.+ const since = 0+ const delta = () => db.$transaction(tx => parts.loadDelta(tx, s.tabId, since, ['group'], held))+ const first = await delta()+ expect(first.parts.length).toBeGreaterThan(0)+ const quiet = await profiled(delta)+ expectIndexed(quiet)+ expect(where(quiet, ['_id'])).toEqual([])+ await db.swarmGroup.update({ where: { id: `${s.tabId}:${s.web}` }, data: { version: { increment: 1 }, changedAt: new Date() } })+ const changed = await profiled(delta)+ expectIndexed(changed)+ expect(where(changed, ['_id']).map(r => [r.plans, r.returned]), JSON.stringify(changed)).toEqual([[['IXSCAN { _id: 1 }'], 1]])+ expectOnlyReturned(where(changed, ['_id']))+ })+it('a command loads the Swarm\'s open conversations and those it names, each read through its index', async () => {const quiet = s.quietLead[5]!.keyfor (const [named, expected] of [diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex a581cf491..facfc5687 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -34,6 +34,7 @@ import { assignmentRows, poolRows, rosterRows } from './hostRows.test-support.jsimport { recipientShare } from '../src/routes/harnessShares.js'import { beforeFirstWrite } from './interleave.test-support.js'import { wantDefaultDigest } from './noDefaultDigest.test-support.js'+import { profiled } from './plans.test-support.js'// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.let replica: MongoMemoryReplSet@@ -3823,6 +3824,36 @@ describe('the Lead reads and types in an agent terminal', () => {expect(loads()).toBeLessThanOrEqual(3)})+ // Task #2800: while the server pushes, a host picks up terminal requests only when told (cli superTabs/terminal.ts), so a push+ // lost on the way is told again by the sender's own wait, at each re-check of a request still waiting for its host: inside+ // the 10 s pickup window, and with no read the wait does not already make.+ it('tells the host again of a request still waiting for pickup at each re-check, and never of one picked up', async () => {+ const { tab, lead, worker, claim } = await terminalFixture()+ const told: unknown[] = []+ const at = new SuperTabStore(db, Date.now, null, { terminalWaiting: waiting => { told.push(waiting) } })+ const unseen = (await run(tab, { type: 'agent.screen', agentId: worker }, host, lead)).result.requestId as string+ expect(await at.terminalResult(host, tab, unseen, lead, 1_500)).toEqual({ requestId: unseen, pending: true })+ expect(told).toEqual([{ machineId: 'test-host', tabId: tab, agentId: worker }])+ expect(await claim()).toHaveLength(1)+ told.length = 0+ expect(await at.terminalResult(host, tab, unseen, lead, 1_500)).toEqual({ requestId: unseen, pending: true })+ expect(told).toEqual([])+ })++ // Task #2800's measure: the database operations one empty answer costs, which each read a timer no longer makes saves.+ // Printed for the pull request.+ it('measures the database operations of an empty worker list read and an empty terminal pickup', async () => {+ const { tab, worker } = await terminalFixture()+ const ops = async (run: () => Promise<unknown>) => (await profiled(db, run)).filter(e => !e.ns.endsWith('.system.profile')).length+ const full = await ops(() => store.deliveries(host, tab, worker))+ const quiet = await ops(() => store.deliveries(host, tab, worker))+ // 30 s on, as the host's timer read came: the full poll again, the read cache warm.+ const warm = await ops(() => later(31_000).deliveries(host, tab, worker))+ const pickup = await ops(() => store.hostTerminal(host, 'test-host'))+ process.stderr.write(`[#2800 measure] DB operations per empty answer: worker list full ${full} (cold cache) / ${warm} (warm), quiet ${quiet}, terminal pickup ${pickup}\n`)+ expect(Math.min(full, warm, quiet, pickup)).toBeGreaterThan(0)+ })+it('expires an unread answer after two minutes, without waiting for another request', async () => {const { tab, lead, worker } = await terminalFixture()const requestId = await answered(tab, worker, host, lead)diff --git a/backend/integration/workerIndexPlans.test.ts b/backend/integration/workerIndexPlans.test.tsindex 07fca64c8..0a85d94c9 100644--- a/backend/integration/workerIndexPlans.test.ts+++ b/backend/integration/workerIndexPlans.test.ts@@ -318,3 +318,24 @@ describe('the hourly unused-upload sweep', () => {expect(taken[0]!.planSummary, JSON.stringify(plan(taken))).toMatch(/IXSCAN \{ usedBy: 1/)})})++describe('the delivery re-push pass (superTabs/deliveryRepush.ts, task #2800)', () => {+ // Every 15 s for every Swarm: it must read the queued deliveries alone, by the (status, _id) index, never the finished+ // ones that make up almost all of the collection.+ it('reads only the queued deliveries, by the status index, and tells each of their agents', async () => {+ const { repushQueuedDeliveries } = await import('../src/superTabs/deliveryRepush.js')+ const row = (status: string, agentId: string) => ({ id: randomUUID(), tabId: 'repush-tab', conversationId: 'c', messageId: randomUUID(), agentId,+ machineId: 'repush-machine', membershipGeneration: 'g', authorKind: 'person', authorId: 'p', authorGeneration: 'g', status })+ await db.superTabDelivery.createMany({ data: [...Array.from({ length: 40 }, () => row('delivered', 'done')), row('claimed', 'busy'),+ ...['a1', 'a1', 'a2'].map(agent => row('queued', agent))] })+ const told: unknown[] = []+ const entries = await profiled(db, () => repushQueuedDeliveries(db, waiting => { told.push(waiting) }, Date.now() + 60_000))+ expect(told).toHaveLength(2)+ expect(told).toEqual(expect.arrayContaining([{ machineId: 'repush-machine', tabId: 'repush-tab', agentId: 'a1' },+ { machineId: 'repush-machine', tabId: 'repush-tab', agentId: 'a2' }]))+ const read = plan(reads(entries, 'SuperTabDelivery', ['status']))+ expect(read).toHaveLength(1)+ expect(read[0]!.plan).toMatch(/^IXSCAN \{ status: 1, _id: 1 \}/)+ expect(read[0]!.docsExamined).toBe(3)+ })+})diff --git a/backend/src/lib/bus.ts b/backend/src/lib/bus.tsindex 8840cf829..92aee0cd3 100644--- a/backend/src/lib/bus.ts+++ b/backend/src/lib/bus.ts@@ -866,8 +866,9 @@ export function subscribeDeviceMachineListChanged(userId: string, cb: (msg: Devi// Per-MACHINE Swarm deliveries: a delivery committed for one of this machine's agents (superTabs/store.ts deliveriesWaiting),// on some REST worker; the worker holding that machine's adapter socket tells its host (lib/swarmDeliveryPushes.ts).-/** `terminal`: a terminal request waits, not a delivery (lib/swarmDeliveryPushes.ts announceSwarmTerminal). */-export interface SwarmDeliveriesMsg { tabId: string; agentId: string; terminal?: true }+/** `terminal`: a terminal request waits, not a delivery (lib/swarmDeliveryPushes.ts announceSwarmTerminal). `pushes` is that+ * socket's own 4-minute repeat that it pushes, sent through Redis so a silent Redis stops it. */+export type SwarmDeliveriesMsg = { tabId: string; agentId: string; terminal?: true } | { pushes: true }const swarmDeliveriesChannel = (machineId: string): string => `swarm-deliveries:${machineId}`diff --git a/backend/src/lib/swarmDeliveryPushes.test.ts b/backend/src/lib/swarmDeliveryPushes.test.tsindex 1a26e337d..d85b6183c 100644--- a/backend/src/lib/swarmDeliveryPushes.test.ts+++ b/backend/src/lib/swarmDeliveryPushes.test.ts@@ -12,11 +12,21 @@ const bus = vi.hoisted(() => {return () => { set.delete(cb) }},publish(machineId: string, msg: unknown) { for (const cb of channels.get(machineId) ?? []) cb(msg) },+ published: [] as Array<[string, unknown]>,+ /** False: Redis has gone silent, and a publish reaches nobody. */+ carries: true,}})+const warn = vi.hoisted(() => vi.fn())+vi.mock('../utils/logger.js', () => ({ logger: { warn, info: vi.fn(), error: vi.fn() } }))vi.mock('./bus.js', () => ({subscribeSwarmDeliveries: (machineId: string, cb: (msg: unknown) => void) => bus.subscribe(machineId, cb),- publishSwarmDeliveries: async (machineId: string, msg: unknown) => { bus.publish(machineId, JSON.parse(JSON.stringify(msg))); return 1 },+ publishSwarmDeliveries: async (machineId: string, msg: unknown) => {+ bus.published.push([machineId, msg])+ if (!bus.carries) return 0+ bus.publish(machineId, JSON.parse(JSON.stringify(msg)))+ return 1+ },}))import { announceSwarmDeliveries, announceSwarmTerminal, relaySwarmDeliveries } from './swarmDeliveryPushes.js'@@ -25,7 +35,7 @@ const pushes = (send: ReturnType<typeof vi.fn>) => send.mock.calls.map(([frame])const told = (payload: object) => ({ t: 'down', connId: '', frame: { type: 'super_tab_deliveries', payload } })describe('Swarm delivery pushes on a daemon socket', () => {- beforeEach(() => { bus.channels.clear(); vi.useFakeTimers() })+ beforeEach(() => { bus.channels.clear(); bus.published.length = 0; bus.carries = true; warn.mockClear(); vi.useFakeTimers() })afterEach(() => { vi.useRealTimers() })it('says it pushes as soon as the socket is attached, so the host reads every 30 s instead of each second', async () => {@@ -95,15 +105,39 @@ describe('Swarm delivery pushes on a daemon socket', () => {expect(pushes(send)).toEqual([told({ tabId: 'tab-1', agentId: 'agent-1' })])})- // The host goes back to reading each second 10 minutes after it last heard this (cli superTabs/host.ts PUSH_LEASE_MS).- it('says again that it pushes every 4 minutes', async () => {+ // Review of #2977 (Important 1): an idle worker's list is read only when told, so a host must learn within minutes that the+ // channel went silent. Each minute the server renews the host's push lease through Redis (cli superTabs/host.ts+ // PUSH_LEASE_MS, 2.5 min) with a `__` frame an older daemon drops; every 4 minutes it also says it pushes as before, which+ // makes a host read every list once, the net an older daemon already had.+ const lease = { t: 'down', connId: '', frame: { type: '__deliveries_lease', payload: {} } }+ it('renews the lease each minute, and says it pushes every 4 minutes', async () => {const send = vi.fn()await relaySwarmDeliveries('machine-a', send)send.mockClear()- await vi.advanceTimersByTimeAsync(4 * 60_000 - 1)+ await vi.advanceTimersByTimeAsync(60_000 - 1)expect(pushes(send)).toEqual([])await vi.advanceTimersByTimeAsync(1)- expect(pushes(send)).toEqual([told({})])+ expect(pushes(send)).toEqual([lease])+ await vi.advanceTimersByTimeAsync(3 * 60_000)+ expect(pushes(send)).toEqual([lease, lease, lease, lease, told({})])+ expect(bus.published).toHaveLength(4)+ })++ // Task #2800: an idle worker's list is read only when the server says so, so a repeat from a local timer would keep a host+ // sure that pushes come while Redis is silent, and nothing would be read for good. As the host-changes repeat (review of+ // #2113), it goes through the machine's own channel: no Redis, no repeat, and in 10 minutes the host reads each second again.+ it('says it again through the machine\'s own channel, and logs a repeat nobody heard', async () => {+ const send = vi.fn()+ await relaySwarmDeliveries('machine-a', send)+ send.mockClear()+ await vi.advanceTimersByTimeAsync(60_000)+ expect(bus.published).toEqual([['machine-a', { pushes: true }]])+ expect(pushes(send)).toEqual([lease])+ send.mockClear()+ bus.carries = false+ await vi.advanceTimersByTimeAsync(4 * 60_000)+ expect(pushes(send)).toEqual([])+ expect(warn).toHaveBeenCalledWith('[swarm] delivery push repeat reached no one; hosts fall back to reading each second', { machineId: 'machine-a' })})// The host keeps reading each second while it has not heard that the server pushes: nothing is lost, only the saving.diff --git a/backend/src/lib/swarmDeliveryPushes.ts b/backend/src/lib/swarmDeliveryPushes.tsindex 00ee1aa01..2d30417db 100644--- a/backend/src/lib/swarmDeliveryPushes.ts+++ b/backend/src/lib/swarmDeliveryPushes.ts@@ -2,9 +2,14 @@ import { publishSwarmDeliveries, subscribeSwarmDeliveries } from './bus.js'import { logger } from '../utils/logger.js'import type { DeliveriesWaiting } from '../superTabs/store.js'-/** Repeated so a host keeps reading idle agents every 30 s: it goes back to each second 10 minutes after it last heard it- * (cli superTabs/host.ts PUSH_LEASE_MS), which covers a missed repeat and a server rolled back to one that does not push. */-const PUSHES_REPEAT_MS = 4 * 60_000+/** Each minute this socket renews its host's push lease (`__deliveries_lease`, cli superTabs/host.ts PUSH_LEASE_MS, 2.5 min),+ * and every LEASES_PER_WORD of them also says it pushes (the empty `super_tab_deliveries` frame), on which a host reads every+ * list once. Both go through the machine's own channel, as the host-changes repeat does (swarmHostPushes.ts): a host reads an+ * idle worker's list only when told (task #2800), so a Redis gone silent must end its lease within minutes and put it back+ * to reading each second (review of #2977, Important 1), and a repeat nobody heard is logged. An older daemon drops the `__`+ * frame and keeps its lease on the 4-minute word, as before. */+const LEASE_REPEAT_MS = 60_000+const LEASES_PER_WORD = 4/*** Stability roadmap 2.4: every Swarm host read each running agent's deliveries each second, almost always to find nothing.@@ -12,8 +17,9 @@ const PUSHES_REPEAT_MS = 4 * 60_000* the write commits), as a connection-less `super_tab_deliveries` down frame naming the Swarm and agent; the daemon hands it* to its Swarm host, which reads that list at once (cli gateway.ts, superTabs/host.ts).*- * The frame with no payload says this server pushes: the host then reads an idle agent's list only every 30 s, the safety- * net for a push lost on the way. A daemon from before this ignores the frame and keeps reading each second.+ * The frame with no payload says this server pushes: the host then reads an idle worker's list only when told (a Lead's every+ * 30 s), and this server tells it again of any delivery still queued after 10 s (superTabs/deliveryRepush.ts), the safety net+ * for a push lost on the way (task #2800). A daemon from before this ignores the frame and keeps reading each second.** `machineId` is the machine the socket signed in as (adapterWs.ts), never one the client names, so a socket hears only its* own machine's work. The frame carries nothing but the two ids; the host reads the deliveries through the checked poll.@@ -22,10 +28,15 @@ const PUSHES_REPEAT_MS = 4 * 60_000*/export async function relaySwarmDeliveries(machineId: string, send: (frame: unknown) => unknown): Promise<() => void> {const tell = (payload: { tabId?: string; agentId?: string }) => { send({ t: 'down', connId: '', frame: { type: 'super_tab_deliveries', payload } }) }- let unsubscribe: () => void+ let unsubscribe: () => void, leases = 0try {unsubscribe = await subscribeSwarmDeliveries(machineId, msg => {- const { tabId, agentId, terminal } = (msg && typeof msg === 'object' ? msg : {}) as Record<string, unknown>+ const { tabId, agentId, terminal, pushes } = (msg && typeof msg === 'object' ? msg : {}) as Record<string, unknown>+ if (pushes === true) {+ send({ t: 'down', connId: '', frame: { type: '__deliveries_lease', payload: {} } })+ if (++leases % LEASES_PER_WORD === 0) tell({})+ return+ }if (typeof tabId !== 'string' || typeof agentId !== 'string') return// A terminal request waiting for this machine (announceSwarmTerminal): a `__` control frame, which an older daemon drops.if (terminal === true) send({ t: 'down', connId: '', frame: { type: '__terminal_waiting', payload: { tabId, agentId } } })@@ -37,7 +48,11 @@ export async function relaySwarmDeliveries(machineId: string, send: (frame: unknreturn () => {}}tell({})- const repeat = setInterval(() => tell({}), PUSHES_REPEAT_MS)+ const repeat = setInterval(() => {+ void publishSwarmDeliveries(machineId, { pushes: true }).then(heard => {+ if (!heard) logger.warn('[swarm] delivery push repeat reached no one; hosts fall back to reading each second', { machineId })+ })+ }, LEASE_REPEAT_MS)return () => {clearInterval(repeat)unsubscribe()diff --git a/backend/src/superTabs/cache.test.ts b/backend/src/superTabs/cache.test.tsindex edf898f27..b7063b28d 100644--- a/backend/src/superTabs/cache.test.ts+++ b/backend/src/superTabs/cache.test.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest'import { configureSwarmStamps, freeze, noteChange, readStamps, sizeOf, stampOwed, swarmTransaction, SwarmCache } from './cache.js'import { MemoryStamps } from './cache.test-support.js'-import { feedRule, machinesRule, type PatchRule } from './cachePatch.js'+import { machineFeedRule, machinesRule, type PatchRule } from './cachePatch.js'import { logger } from '../utils/logger.js'import type { MachineData, Part, PartKind } from './parts/index.js'import type { SwarmDelta } from './parts/load.js'@@ -407,6 +407,21 @@ describe('a stale entry is patched, not loaded again (spec 2026-11-02, Phase 1)'expect(load).toHaveBeenCalledTimes(3)})+ it('an entry nobody read since an earlier stamp does not drag a hot entry\'s delta back, and is still patched when read (#2783)', async () => {+ const { stamps, delta, read, advance } = setup()+ await read(rule(), 'main', 'cold')+ await read(rule(), 'main', 'hot')+ for (let i = 0; i < 3; i++) {+ advance(20_000)+ await stamps.bump('t1', ['main'])+ await read(rule(), 'main', 'hot')+ }+ // From the hot entry's last refresh (1_040_000), not the cold one's (1_000_000), less the overlap.+ expect(delta.mock.calls.map(c => c[1])).toEqual([970_000, 990_000, 1_010_000])+ expect(await read(rule(), 'main', 'cold')).toEqual({ keys: ['g1', 'g2'] })+ expect(delta.mock.calls.at(-1)![1]).toBe(970_000)+ })+it('readers of one Swarm at one stamp share one delta', async () => {const { stamps, delta, read } = setup()await read()@@ -580,7 +595,7 @@ describe('the verify sample (spec 2026-11-02, "Checking it on prod")', () => {const cache = new SwarmCache(stamps, { verifyRate: 1, random: () => 0, delta: async () => ({ parts: [machine('m1', 2, { a: 2 })], head: null }) })let from = 100const load = vi.fn(async () => ({ from: from += 50, parts: [machine('m1', from > 200 ? 2 : 1, { a: from > 200 ? 2 : 1 })] }))- const read = async () => (await cache.at(['t1'])).get('t1', 'feed', 'all', load, feedRule)+ const read = async () => (await cache.at(['t1'])).get('t1', 'machine-feed', 'all', load, machineFeedRule)await read()await stamps.bump('t1', ['machine'])from = 200diff --git a/backend/src/superTabs/cache.ts b/backend/src/superTabs/cache.tsindex dda26399a..c50322ad7 100644--- a/backend/src/superTabs/cache.ts+++ b/backend/src/superTabs/cache.ts@@ -74,6 +74,11 @@ export const DELTA_MAX_PARTS = 500* forgotten entry made every delta of its Swarm read an hour of changes (final review, Important 2). Twice the age at which* a read refreshes an entry, so one read every minute keeps it patched. */export const DELTA_MAX_GAP_MS = 120_000+/** Another entry joins an entry's delta only when it was refreshed at most this long before it: entries read at the same+ * stamps share one delta, and Desktop's background cadence (15 s) still joins. An entry nobody read since (a first load's+ * dormant selections, one window's conversation) is refreshed by its own delta when it is read: joined, it moved every delta+ * of its Swarm back to its time, so each machine reading read ~190 whole conversations again on the bench (#2783). */+export const DELTA_JOIN_MS = 15_000/** One delta read: the stamps it was read at, the kinds it holds, from when, and when it started. */interface Delta { stamp: string; kinds: ReadonlySet<PartKind>; since: number; at: number; read: Promise<SwarmDelta> }@@ -246,7 +251,8 @@ export class SwarmCache {* This Swarm's changes at these stamps, read once for every entry patched from them (the spec's one delta per Swarm and* stamp: one read per kind was up to five reads of the same window per bump, final review Important 3): over the kinds* of every entry of the Swarm due for a refresh, from the earliest of their reads, less OVERLAP_MS. An entry refreshed- * too long ago (DELTA_MAX_GAP_MS) is left out: it loads in full when read.+ * too long ago (DELTA_MAX_GAP_MS) is left out: it loads in full when read. So is one refreshed more than DELTA_JOIN_MS+ * before this entry: it reads its own delta when it is read.** The stamps can stand still while the Swarm changes (a bump lost, or owed by this process), so a delta is shared only with* an entry read before it started: an older one could miss a change the entry's refresh exists to find, or bring back a@@ -260,7 +266,8 @@ export class SwarmCache {let earliest = entry.atfor (const name of this.bySwarm.get(tabId) ?? []) {const other = this.entries.get(name)!- if (other === entry || !other.patch || now - other.at > DELTA_MAX_GAP_MS || now - other.fullAt >= this.deltaMaxAgeMs || !this.due(other, stamp, now)) continue+ if (other === entry || !other.patch || now - other.at > DELTA_MAX_GAP_MS || now - other.fullAt >= this.deltaMaxAgeMs || !this.due(other, stamp, now)+ || other.at < entry.at - DELTA_JOIN_MS) continuefor (const kind of other.patch.kinds) union.add(kind)earliest = Math.min(earliest, other.at)}diff --git a/backend/src/superTabs/cachePatch.test.ts b/backend/src/superTabs/cachePatch.test.tsindex f1dc4be6f..edc0f2192 100644--- a/backend/src/superTabs/cachePatch.test.ts+++ b/backend/src/superTabs/cachePatch.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'import { stableId } from './model.js'-import { baseRule, boardRule, cacheDigest, dormantAgentRule, lightDormantAgentRule, feedRule, startsOfRule, dormantProjectRule, dormantRule, finishedStartsRule, groupRule, machinesRule } from './cachePatch.js'+import { baseRule, boardRule, cacheDigest, dormantAgentRule, lightDormantAgentRule, feedRule, machineFeedRule, startsOfRule, dormantProjectRule, dormantRule, finishedStartsRule, groupRule, machinesRule } from './cachePatch.js'import type { GroupData, Part, PartKind, SwarmParts } from './parts/index.js'import { projectLightGroup } from './parts/lightSelect.js'import type { SwarmDelta } from './parts/load.js'@@ -161,8 +161,8 @@ describe('lightDormantAgentRule (B4, #2597)', () => {})describe('feedRule (spec 2026-11-02 poll cost, Part 1.1)', () => {- it('keeps tombstones, dormant groups and readAt, takes the newer version', () => {- const held = { from: 500, parts: [part('group', 'g1', 1, { a: 1 }), part('machine', 'm1', 1, {}, { readAt: 900 })] }+ it('keeps tombstones and dormant groups, takes the newer version, and leaves machine parts to the machine feed (#2783)', () => {+ const held = { from: 500, parts: [part('group', 'g1', 1, { a: 1 })] }const next = feedRule.apply(held, delta([part('group', 'g1', 2, { a: 2 }),part('group', 'g2', 3, {}, { dormant: true }),@@ -171,10 +171,18 @@ describe('feedRule (spec 2026-11-02 poll cost, Part 1.1)', () => {part('group', 'g1', 1, { stale: true }),])) as { from: number; parts: Part[] }expect(next.from).toBe(500)- expect(next.parts.map(p => [p.kind, p.key, p.version]).sort()).toEqual([['agent', 'a9', 4], ['group', 'g1', 2], ['group', 'g2', 3], ['machine', 'm1', 2]])+ expect(next.parts.map(p => [p.kind, p.key, p.version]).sort()).toEqual([['agent', 'a9', 4], ['group', 'g1', 2], ['group', 'g2', 3]])expect(next.parts.find(p => p.key === 'a9')!.deleted).toBe(true)expect(next.parts.find(p => p.key === 'g2')!.dormant).toBe(true)- expect(next.parts.find(p => p.key === 'm1')!.readAt).toBe(2_000)+ })++ it('the machine feed keeps readAt and only machine parts', () => {+ const held = { from: 500, parts: [part('machine', 'm1', 1, {}, { readAt: 900 })] }+ const next = machineFeedRule.apply(held, delta([part('machine', 'm1', 2, {}, { readAt: 2_000 }), part('group', 'g1', 2, {})])) as { from: number; parts: Part[] }+ expect(next.parts.map(p => [p.kind, p.key, p.version])).toEqual([['machine', 'm1', 2]])+ expect(next.parts[0]!.readAt).toBe(2_000)+ expect(machineFeedRule.kinds).toEqual(['machine'])+ expect([...feedRule.kinds].sort()).toEqual(['agent', 'group', 'head', 'member', 'progress', 'start'])})it('returns what it holds when nothing is newer', () => {diff --git a/backend/src/superTabs/cachePatch.ts b/backend/src/superTabs/cachePatch.tsindex 451fae57d..a9a40d384 100644--- a/backend/src/superTabs/cachePatch.ts+++ b/backend/src/superTabs/cachePatch.ts@@ -94,29 +94,42 @@ export const finishedStartsRule: PatchRule<Part<AgentStart>[]> = {apply: (held, delta) => applyByKey(held, delta.parts, 'start', p => live(p) && finished(p)),}-/** The `feed` entry (cachedReads.ts readChanged): every part changed after `from`, as `loadChanged` reads them, tombstones,- * dormant groups and machines' `readAt` included. Its full reloads were 610 MB per 20 minutes on prod (2026-11-02). */-export const feedRule: PatchRule<{ from: number; parts: Part[] }> = {- kinds: PART_KINDS,- apply(held, delta) {- let next: Map<string, Part> | null = null- const id = (part: Part) => `${part.kind}\u0000${part.key}`- for (const part of delta.parts) {- const current = (next ?? null)?.get(id(part)) ?? held.parts.find(p => p.kind === part.kind && p.key === part.key)- if (current && part.version <= current.version) continue- next ??= new Map(held.parts.map(p => [id(p), p]))- next.set(id(part), part)- }- return next ? { from: held.from, parts: [...next.values()] } : held- },- // The check's own load starts where its reader's cursor does: only the parts both windows cover compare (final review).- comparable(patched, fresh) {- const from = Math.max(patched.from, fresh.from)- const covered = (parts: Part[]) => parts.filter(p => Math.max(p.changedAt, p.readAt ?? 0) > from)- return [covered(patched.parts), covered(fresh.parts)]- },+/** A change feed entry (cachedReads.ts readChanged): every part of `kinds` changed after `from`, as `loadChanged` reads them,+ * tombstones, dormant groups and machines' `readAt` included. Its full reloads were 610 MB per 20 minutes on prod+ * (2026-11-02). A delta shared with other entries brings their kinds too: only this feed's are applied. */+function feedRuleOf(kinds: readonly PartKind[]): PatchRule<{ from: number; parts: Part[] }> {+ const mine = new Set(kinds)+ return {+ kinds,+ apply(held, delta) {+ let next: Map<string, Part> | null = null+ const id = (part: Part) => `${part.kind}\u0000${part.key}`+ for (const part of delta.parts) {+ if (!mine.has(part.kind)) continue+ const current = (next ?? null)?.get(id(part)) ?? held.parts.find(p => p.kind === part.kind && p.key === part.key)+ if (current && part.version <= current.version) continue+ next ??= new Map(held.parts.map(p => [id(p), p]))+ next.set(id(part), part)+ }+ return next ? { from: held.from, parts: [...next.values()] } : held+ },+ // The check's own load starts where its reader's cursor does: only the parts both windows cover compare (final review).+ comparable(patched, fresh) {+ const from = Math.max(patched.from, fresh.from)+ const covered = (parts: Part[]) => parts.filter(p => Math.max(p.changedAt, p.readAt ?? 0) > from)+ return [covered(patched.parts), covered(fresh.parts)]+ },+ }}+/** The feed's kinds that a machine's reading never changes, held at the main stamp (#2783): under the `all` scope with the+ * machines, every reading made the next refresh read all seven part collections, though only a machine part moved. */+export const FEED_MAIN_KINDS: readonly PartKind[] = PART_KINDS.filter(kind => kind !== 'machine')+/** The `feed` entry: changed parts of every kind but machines. */+export const feedRule = feedRuleOf(FEED_MAIN_KINDS)+/** The `machine-feed` entry: changed machine parts, readings included, held at both stamps. */+export const machineFeedRule = feedRuleOf(['machine'])+/** A `startsOf:{agents}` entry (read/service.ts pollStarts): the live starts of these agents, an agent being its machine and* harness (`stableId`). A start whose agent left the list goes, as does a tombstone. */export function startsOfRule(agents: readonly string[]): PatchRule<Part<AgentStart>[]> {diff --git a/backend/src/superTabs/cacheStats.test.ts b/backend/src/superTabs/cacheStats.test.tsindex b8f6cd203..2e960b2e7 100644--- a/backend/src/superTabs/cacheStats.test.ts+++ b/backend/src/superTabs/cacheStats.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest'-import { recordCache, startCacheStats } from './cacheStats.js'+import { recordCache, recordDeltaRows, startCacheStats } from './cacheStats.js'describe('swarm cache log', () => {it('counts by entry name and reason, and logs nothing in an empty window', () => {@@ -22,4 +22,17 @@ describe('swarm cache log', () => {stop()} finally { vi.useRealTimers() }})++ it('counts the rows deltas read whole and those they reused, beside the entries (#2783)', () => {+ vi.useFakeTimers()+ try {+ const log = vi.fn()+ const stop = startCacheStats({ everyMs: 60_000, log })+ recordDeltaRows({ stamps: 10, whole: 2 })+ recordDeltaRows({ stamps: 5, whole: 1 })+ vi.advanceTimersByTime(60_000)+ expect(log).toHaveBeenCalledWith('swarm cache', { windowMs: 60_000, entries: {}, deltaRows: { deltas: 2, stamps: 15, whole: 3 } })+ stop()+ } finally { vi.useRealTimers() }+ })})diff --git a/backend/src/superTabs/cacheStats.ts b/backend/src/superTabs/cacheStats.tsindex 3c77bc724..45f97ec6b 100644--- a/backend/src/superTabs/cacheStats.ts+++ b/backend/src/superTabs/cacheStats.ts@@ -14,6 +14,15 @@ interface Counts {}let entries = new Map<string, Counts>()+/** The read cache's deltas (parts/load.ts loadDelta with held rows): how many, how many changed rows they listed by key and+ * version, and how many of those they read whole. The rest came from the delta before (#2783). */+let deltaRows = { deltas: 0, stamps: 0, whole: 0 }++export function recordDeltaRows(rows: { stamps: number; whole: number }): void {+ deltaRows.deltas+++ deltaRows.stamps += rows.stamps+ deltaRows.whole += rows.whole+}export function recordCache(name: string, event: CacheEvent, detail: { bytes?: number; parts?: number; reason?: ReloadReason } = {}): void {const key = name.split(':', 1)[0]!@@ -36,9 +45,10 @@ export function startCacheStats({ everyMs = 60_000, log = (message: string, cont{ everyMs?: number; log?: (message: string, context: Record<string, unknown>) => void } = {}): () => void {let since = Date.now()const timer = setInterval(() => {- const now = Date.now(), window = entries+ const now = Date.now(), window = entries, rows = deltaRowsentries = new Map()- if (window.size) log('swarm cache', { windowMs: now - since, entries: Object.fromEntries(window) })+ deltaRows = { deltas: 0, stamps: 0, whole: 0 }+ if (window.size || rows.deltas) log('swarm cache', { windowMs: now - since, entries: Object.fromEntries(window), ...rows.deltas ? { deltaRows: rows } : {} })since = now}, everyMs)timer.unref()diff --git a/backend/src/superTabs/cachedReads.test.ts b/backend/src/superTabs/cachedReads.test.tsindex 44fa53119..95fceadbd 100644--- a/backend/src/superTabs/cachedReads.test.ts+++ b/backend/src/superTabs/cachedReads.test.ts@@ -1,9 +1,10 @@import { describe, expect, it, vi } from 'vitest'import { stableId, type AgentStart } from './model.js'-import type { Part } from './parts/index.js'+import { PART_KINDS, type Part, type PartKind } from './parts/index.js'import { deriveLight, namedStarts, readChanged, readDelta, readLastChangedAt, readLastChangedAts, readLight, readLightGroups, readMachines, readParts } from './cachedReads.js'-import { CacheView } from './cache.js'-import { baseRule, dormantRule, feedRule, machinesRule } from './cachePatch.js'+import { CacheView, SwarmCache } from './cache.js'+import { MemoryStamps } from './cache.test-support.js'+import { baseRule, dormantRule, feedRule, machineFeedRule, machinesRule } from './cachePatch.js'/** A start, finished once it has a harness. `untouchable`: reading its request throws, so a test sees the read hash its* agent (stableId, a sha256 of the request's machine and the harness). */@@ -88,7 +89,7 @@ describe('which entries a refresh patches (spec 2026-11-02, Phase 1)', () => {vi.spyOn(view, 'get').mockImplementation(async (_tabId, name, _scope, _load, patch) => {rules.set(name.startsWith('light:') ? 'light:' : name, patch)if (name === 'parts') return { tabId: 't', head: {}, members: [], agents: [], groups: [], machines: [], starts: [], progress: [] }- if (name === 'feed') return { from: 0, parts: [] }+ if (name === 'feed' || name === 'machine-feed') return { from: 0, parts: [] }if (name === 'lastChangedAt') return nullif (name.startsWith('light:')) return { groups: [], starts: [] }if (name.startsWith('light-group:')) return null@@ -112,6 +113,7 @@ describe('which entries a refresh patches (spec 2026-11-02, Phase 1)', () => {expect(rules.get('light:')).toBeUndefined()expect(rules.get('light-group:g2')).toBeUndefined()expect(rules.get('feed')).toBe(feedRule)+ expect(rules.get('machine-feed')).toBe(machineFeedRule)})})@@ -176,6 +178,24 @@ describe('the delta a refresh reads', () => {expect(db.$transaction).toHaveBeenCalledTimes(1)expect(aggregateRaw).toHaveBeenCalledTimes(2)})++ it('reads whole, per Swarm, only the rows its last delta of that Swarm did not read (#2783)', async () => {+ const row = { _id: 't:g1', tabId: 't', key: 'g1', version: 1, changedAt: { $date: new Date(10).toISOString() }, ordinal: 1, data: { id: 'g1' } }+ const whole: string[] = []+ const aggregateRaw = vi.fn(async ({ pipeline }: { pipeline: Array<Record<string, Record<string, unknown>>> }) => {+ const match = pipeline[0]!.$match!, tabId = match._id ? match.tabId as string : (match.tabId as { $in: string[] }).$in[0]!+ // A whole row: its projection takes the data.+ if (pipeline[1]?.$project?.data) whole.push(tabId)+ return [{ ...row, tabId }]+ })+ const tx = { swarmGroup: { aggregateRaw } }+ const db = { $transaction: vi.fn(async (body: (tx: unknown) => Promise<unknown>) => body(tx)) }+ const delta = readDelta(db as never)+ const first = await delta('t', 5, ['group'])+ expect(await delta('t', 5, ['group'])).toEqual(first)+ await delta('u', 5, ['group'])+ expect(whole).toEqual(['t', 'u'])+ })})describe('light and host state derived from held entries (spec 2026-11-02 poll cost, Part 1.2)', () => {@@ -243,3 +263,48 @@ describe('light and host state derived from held entries (spec 2026-11-02 poll cexpect(light.groups.map(x => x.key)).toEqual(['run'])})})++describe('the change feed by stamp scope (#2783)', () => {+ /** A database whose part collections each hold one row changed at `at`, and that records which collections were read. */+ function partsDb(at: number) {+ const read: string[] = []+ const db = new Proxy({}, { get: (_t, model) => ({ aggregateRaw: async () => {+ read.push(String(model))+ return [{ _id: `t:${String(model)}`, tabId: 't', key: String(model), version: 1, changedAt: { $date: new Date(at).toISOString() }, ordinal: 1, data: {} }]+ } }) }) as never+ return { db, read }+ }+ function setup() {+ let now = 1_000_000+ const stamps = new MemoryStamps(), kinds: PartKind[][] = []+ const cache = new SwarmCache(stamps, { now: () => now, delta: async (_tabId, _since, asked) => { kinds.push([...asked]); return { parts: [], head: null } } })+ return { stamps, kinds, view: () => cache.at(['t']), now: () => now, advance: (ms: number) => { now += ms } }+ }++ it('a machine reading refreshes only the machine part of the feed: one collection, not seven', async () => {+ const { stamps, kinds, view, now, advance } = setup()+ const { db } = partsDb(now() - 5_000)+ await readChanged(db, await view(), 't', now() - 10_000)+ advance(1_000)+ await stamps.bump('t', ['machine'])+ await readChanged(db, await view(), 't', now() - 10_000)+ expect(kinds).toEqual([['machine']])+ })++ it('a poller a minute behind the one that loaded the feed reads the held feed, not the collections (#2783)', async () => {+ const { view, now } = setup()+ const { db, read } = partsDb(now() - 5_000)+ await readChanged(db, await view(), 't', now() - 3_000)+ read.length = 0+ const parts = await readChanged(db, await view(), 't', now() - 60_000)+ expect(read).toEqual([])+ expect(parts.map(p => p.kind).sort()).toEqual([...PART_KINDS].sort())+ })++ it('answers every kind, as loadChanged does', async () => {+ const { view, now } = setup()+ const { db } = partsDb(now() - 5_000)+ const parts = await readChanged(db, await view(), 't', now() - 10_000)+ expect(parts.map(p => p.kind).sort()).toEqual([...PART_KINDS].sort())+ })+})diff --git a/backend/src/superTabs/cachedReads.ts b/backend/src/superTabs/cachedReads.tsindex 3700b8877..463cd9df5 100644--- a/backend/src/superTabs/cachedReads.ts+++ b/backend/src/superTabs/cachedReads.ts@@ -7,7 +7,8 @@import type { Prisma, PrismaClient } from '@prisma/client'import { stableId, type AgentStart } from './model.js'import { CacheView } from './cache.js'-import { baseRule, dormantAgentRule, dormantProjectRule, dormantRule, feedRule, finishedStartsRule, groupRule, lightDormantAgentRule, machinesRule } from './cachePatch.js'+import { baseRule, dormantAgentRule, dormantProjectRule, dormantRule, FEED_MAIN_KINDS, feedRule, finishedStartsRule, groupRule, lightDormantAgentRule, machineFeedRule,+ machinesRule } from './cachePatch.js'import * as store from './parts/index.js'import type { GroupData, Part, PartKind, SwarmParts, SwarmDelta } from './parts/index.js'import { retryTransient } from './retry.js'@@ -26,6 +27,9 @@ export const DIRECT = new CacheView(null, null)/** A miss loads the feed from this long before its reader's cursor, so readers polling a few seconds apart share it. */const FEED_SLACK_MS = 15_000+/** ... and from at least this long before the read, so a phone (5 s), a background window (15 s) or a CLI reading a minute+ * or two after the poller that loaded it reads the held feed too, not every changed part itself (#2783). */+export const FEED_REACH_MS = 120_000/** A Swarm's live machine parts, held at both stamps: a machine's reading moves only the machine stamp. */export const readMachines = (db: Prisma.TransactionClient, view: CacheView, tabId: string) =>@@ -107,10 +111,26 @@ const pickFinished = (finished: Part<AgentStart>[], named: ReadNamed): Part<Agenreturn [...finished.filter(s => ids.has(s.key)), ...(named.startAgentIds ?? []).flatMap(agent => index!.get(agent) ?? [])]}+/** The Swarms whose last delta's rows a process keeps (store.loadDelta `held`), most recently read last. Each keeps only its+ * last delta's rows of each kind: about what changed in its last 30 s (the overlap) and more. */+export const DELTA_ROWS_SWARMS = 256+/** The read cache's delta (cache.ts): one snapshot, as a base load is (final review, Important 5), and tried again on a- * transient error as one is. */-export const readDelta = (db: Pick<PrismaClient, '$transaction'>) => (tabId: string, since: number, kinds: readonly PartKind[]): Promise<SwarmDelta> =>- retryTransient(() => db.$transaction(tx => store.loadDelta(tx, tabId, since, kinds)))+ * transient error as one is. It keeps each Swarm's rows its last delta read, so the next reads whole only what moved since+ * (#2783). */+export function readDelta(db: Pick<PrismaClient, '$transaction'>): (tabId: string, since: number, kinds: readonly PartKind[]) => Promise<SwarmDelta> {+ const held = new Map<string, store.DeltaRows>()+ return (tabId, since, kinds) => {+ const rows = held.get(tabId) ?? new Map()+ held.delete(tabId)+ held.set(tabId, rows)+ for (const oldest of held.keys()) {+ if (held.size <= DELTA_ROWS_SWARMS) break+ held.delete(oldest)+ }+ return retryTransient(() => db.$transaction(tx => store.loadDelta(tx, tabId, since, kinds, rows)))+ }+}/** The parts loadLight gives for `opts`, held whole by what it selects. */export async function readLight(db: Db, view: CacheView, tabId: string, opts: Omit<LightOptions, 'machines'>): Promise<SwarmParts> {@@ -187,13 +207,18 @@ export async function readLastChangedAts(db: Db, view: CacheView, tabIds: string})] as const)))}-/** The Swarm's parts changed after `since` (parts/load.ts loadChanged): from the held feed when it reaches back that far, else read. */+/** The Swarm's parts changed after `since` (parts/load.ts loadChanged): from the held feed when it reaches back that far, else+ * read. The feed is held in two entries by the stamp each depends on (#2783): a machine's reading refreshes only its+ * machine part, and every other kind stays as held. */export async function readChanged(db: Db, view: CacheView, tabId: string, since: number): Promise<Part[]> {const direct = async () => (await store.loadChanged(db, [tabId], new Date(since))).get(tabId) ?? []if (!view.available) return direct()- const feed = await view.get(tabId, 'feed', 'all', async () => {- const from = since - FEED_SLACK_MS- return { from, parts: (await store.loadChanged(db, [tabId], new Date(from))).get(tabId) ?? [] }- }, feedRule)- return since >= feed.from ? feed.parts.filter(p => Math.max(p.changedAt, p.readAt ?? 0) > since) : direct()+ const load = (kinds: readonly PartKind[]) => async () => {+ const from = Math.min(since - FEED_SLACK_MS, view.at - FEED_REACH_MS)+ return { from, parts: (await store.loadChanged(db, [tabId], new Date(from), kinds)).get(tabId) ?? [] }+ }+ const [main, machines] = await Promise.all([view.get(tabId, 'feed', 'main', load(FEED_MAIN_KINDS), feedRule),+ view.get(tabId, 'machine-feed', 'all', load(['machine']), machineFeedRule)])+ if (since < main.from || since < machines.from) return direct()+ return [...main.parts, ...machines.parts].filter(p => Math.max(p.changedAt, p.readAt ?? 0) > since)}diff --git a/backend/src/superTabs/deliveryRepush.test.ts b/backend/src/superTabs/deliveryRepush.test.tsnew file mode 100644index 000000000..effe8991e--- /dev/null+++ b/backend/src/superTabs/deliveryRepush.test.ts@@ -0,0 +1,65 @@+import { describe, expect, it, vi } from 'vitest'+import type { PrismaClient } from '@prisma/client'+import { REPUSH_AFTER_MS, repushQueuedDeliveries } from './deliveryRepush.js'++const NOW = 10_000_000++/** SuperTabDelivery's aggregate, in memory: the pipeline's match on status, its page after an id, its sort and limit. */+function fakeDb(rows: Array<{ id: string; status: string; tabId: string; agentId: string; machineId: string; updatedAt: number }>) {+ const pipelines: unknown[][] = []+ const aggregateRaw = vi.fn(async ({ pipeline }: { pipeline: Array<Record<string, any>> }) => {+ pipelines.push(pipeline)+ const match = pipeline.find(stage => stage.$match)!.$match+ const limit = pipeline.find(stage => stage.$limit)!.$limit as number+ return rows.filter(row => row.status === match.status && (!match._id || row.id > match._id.$gt))+ .sort((a, b) => a.id.localeCompare(b.id)).slice(0, limit)+ .map(row => ({ _id: row.id, tabId: row.tabId, agentId: row.agentId, machineId: row.machineId, updatedAt: { $date: new Date(row.updatedAt).toISOString() } }))+ })+ return { db: { superTabDelivery: { aggregateRaw } } as unknown as PrismaClient, pipelines }+}++describe('the server repeats the push of a delivery still queued (task #2800)', () => {+ it('tells each machine once per agent with a delivery queued 10 s or more', async () => {+ const { db } = fakeDb([+ { id: 'd1', status: 'queued', tabId: 't', agentId: 'a1', machineId: 'm1', updatedAt: NOW - REPUSH_AFTER_MS },+ { id: 'd2', status: 'queued', tabId: 't', agentId: 'a1', machineId: 'm1', updatedAt: NOW - 60_000 },+ { id: 'd3', status: 'queued', tabId: 't', agentId: 'a2', machineId: 'm2', updatedAt: NOW - 3_600_000 },+ ])+ const tell = vi.fn()+ expect(await repushQueuedDeliveries(db, tell, NOW)).toEqual({ told: 2, read: 3 })+ expect(tell.mock.calls).toEqual([[{ machineId: 'm1', tabId: 't', agentId: 'a1' }], [{ machineId: 'm2', tabId: 't', agentId: 'a2' }]])+ })++ // Its own push went out a moment ago and is almost always heard: a repeat would only cost the host a read.+ it('leaves a delivery queued under 10 s to its own push', async () => {+ const { db } = fakeDb([{ id: 'd1', status: 'queued', tabId: 't', agentId: 'a1', machineId: 'm1', updatedAt: NOW - REPUSH_AFTER_MS + 1 }])+ const tell = vi.fn()+ expect(await repushQueuedDeliveries(db, tell, NOW)).toEqual({ told: 0, read: 1 })+ expect(tell).not.toHaveBeenCalled()+ })++ // A claimed delivery is the host's already; uncertain and held ones wait on a person or the pane, and the host reads them.+ it('reads only queued deliveries, through the status index, never a whole collection', async () => {+ const { db, pipelines } = fakeDb([+ { id: 'd1', status: 'claimed', tabId: 't', agentId: 'a1', machineId: 'm1', updatedAt: NOW - 60_000 },+ { id: 'd2', status: 'uncertain', tabId: 't', agentId: 'a1', machineId: 'm1', updatedAt: NOW - 60_000 },+ ])+ const tell = vi.fn()+ expect(await repushQueuedDeliveries(db, tell, NOW)).toEqual({ told: 0, read: 0 })+ expect(pipelines[0]).toContainEqual({ $match: { status: 'queued' } })+ expect(pipelines[0]).toContainEqual({ $sort: { _id: 1 } })+ })++ // Ids are hashes, not times: a first page of old rows on machines that are away must not hide a newer one behind it. The+ // pass's cost is the rows it reads, so that is what it reports (review of #2977: agents told stays small while an offline+ // machine's queue grows).+ it('reads every page, so a delivery after 500 old ones is told too, and reports the rows it read', async () => {+ const rows = Array.from({ length: 501 }, (_, i) => ({ id: `d${String(i).padStart(4, '0')}`, status: 'queued', tabId: 't',+ agentId: i === 500 ? 'late' : 'away', machineId: i === 500 ? 'm2' : 'm1', updatedAt: NOW - 60_000 }))+ const { db, pipelines } = fakeDb(rows)+ const tell = vi.fn()+ expect(await repushQueuedDeliveries(db, tell, NOW)).toEqual({ told: 2, read: 501 })+ expect(pipelines).toHaveLength(2)+ expect(tell).toHaveBeenCalledWith({ machineId: 'm2', tabId: 't', agentId: 'late' })+ })+})diff --git a/backend/src/superTabs/deliveryRepush.ts b/backend/src/superTabs/deliveryRepush.tsnew file mode 100644index 000000000..62a9d57a6--- /dev/null+++ b/backend/src/superTabs/deliveryRepush.ts@@ -0,0 +1,61 @@+import type { Prisma, PrismaClient } from '@prisma/client'+import { readBy } from './parts/indexed.js'+import { ms } from './parts/light.js'+import type { DeliveriesWaiting } from './store.js'+import { logger } from '../utils/logger.js'++// Task #2800 (Watch Production, 2026-11-04): GET deliveries was 84% empty. While this server pushes, a host read each idle+// agent's list every 30 s anyway, only in case a push was lost on the way (Redis pub/sub keeps nothing for a socket that+// missed it). That net moves here: one read of the queued deliveries of every Swarm every 15 s, and the machine of each agent+// with one waiting is told again. The host then reads an idle worker's list only when told (cli superTabs/host.ts).++/** A delivery's own push went out when it was written (store.ts announce) and is almost always heard; one still queued after+ * this long is told again. With the pass's 15 s, a lost push is read within 25 s, sooner than the host's old 30 s. */+export const REPUSH_AFTER_MS = 10_000+const REPUSH_EVERY_MS = 15_000+const BATCH = 500++/** Tells each machine once per agent that has a delivery queued REPUSH_AFTER_MS or more. Reads queued rows only, by the+ * delivery status index `(status, _id)` with a plain match, page by page: ids are hashes, so no page order puts new rows+ * first. Resolves to the agents told and the rows read: the rows are the pass's cost, and grow with an offline machine's+ * queue while the agents told stay few (review of #2977). A delivery its host keeps withholding (cli host.ts mayRead) stays+ * queued and is told every pass, so that one agent's list is read every 15 s, where it was every 30 s. */+export async function repushQueuedDeliveries(db: PrismaClient, tell: (waiting: DeliveriesWaiting) => void, now: number): Promise<{ told: number; read: number }> {+ const told = new Set<string>()+ let after: string | null = null, read = 0+ for (;;) {+ const rows = await readBy(db as unknown as Prisma.TransactionClient, 'SuperTabDelivery', 'settle', [+ { $match: { status: 'queued', ...after ? { _id: { $gt: after } } : {} } }, { $sort: { _id: 1 } }, { $limit: BATCH },+ { $project: { tabId: 1, agentId: 1, machineId: 1, updatedAt: 1 } }])+ read += rows.length+ for (const row of rows) {+ const { tabId, agentId, machineId } = row as { tabId: string; agentId: string; machineId: string }+ if (now - ms(row.updatedAt) < REPUSH_AFTER_MS) continue+ const key = `${machineId}\u0000${tabId}\u0000${agentId}`+ if (told.has(key)) continue+ told.add(key)+ tell({ machineId, tabId, agentId })+ }+ if (rows.length < BATCH) return { told: told.size, read }+ after = rows.at(-1)!._id as string+ }+}++/** Runs the pass every 15 s in the singleton worker. A pass that fails is logged as an error each time: until it runs again,+ * a delivery whose push was lost waits for the host's next read (its 4-minute repeat, a reconnect). */+export function startDeliveryRepush(db: PrismaClient, tell: (waiting: DeliveriesWaiting) => void, everyMs = REPUSH_EVERY_MS): () => void {+ let running = false+ const run = () => {+ if (running) return+ running = true+ void repushQueuedDeliveries(db, tell, Date.now())+ // The first sign of growth: rows read nearing a page (500) or past it, from queues of machines that are away.+ .then(({ told, read }) => { if (read) logger.info('[swarm-deliveries] re-announced', { told, read }) })+ .catch(error => logger.error('[swarm-deliveries] re-announce failed; a delivery whose push was lost waits for its host\'s 4-minute read',+ { error: error instanceof Error ? error.message : String(error) }))+ .finally(() => { running = false })+ }+ const timer = setInterval(run, everyMs)+ timer.unref()+ return () => clearInterval(timer)+}diff --git a/backend/src/superTabs/parts/index.ts b/backend/src/superTabs/parts/index.tsindex 7ff8ebc7a..528b7d7a5 100644--- a/backend/src/superTabs/parts/index.ts+++ b/backend/src/superTabs/parts/index.ts@@ -11,3 +11,4 @@ export { DORMANT_PAGE, insertParts, lastChangedAt, loadActive, loadAll, loadChanexport type { SwarmDelta } from './load.js'export { loadLight, loadLightGroups } from './light.js'export { guardedWrite, PartConflict, type PartWrite } from './write.js'+export type { DeltaRows } from './load.js'diff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.tsindex 21fe663e9..d77b77854 100644--- a/backend/src/superTabs/parts/indexed.ts+++ b/backend/src/superTabs/parts/indexed.ts@@ -23,6 +23,8 @@ export const GROUP_INDEX = {wake: { hostMachineIds: 1, tabId: 1, changedAt: 1 },/** Every live group: the host signature's index. */live: { tabId: 1, deleted: 1, key: 1, hostDigest: 1, dormant: 1 },+ /** Rows by id: a delta's whole rows of the versions it has not read (parts/load.ts loadDelta). */+ id: { _id: 1 },} as constexport type GroupIndex = keyof typeof GROUP_INDEX@@ -48,16 +50,17 @@ export const NAMED_INDEX = {/** The Swarms people at a domain join by themselves (autoJoin.ts): one read per person at most every 2 minutes. */autoJoin: { autonomousEnv: 1, autoJoinDomain: 1 },},- /** Each part kind's changes since a cursor; machines also by when they were last read. */- SwarmHead: { changes: { tabId: 1, changedAt: 1 } },+ /** Each part kind's changes since a cursor; machines also by when they were last read. `id`: rows by id, a delta's whole+ * rows of the versions it has not read (parts/load.ts loadDelta). */+ SwarmHead: { changes: { tabId: 1, changedAt: 1 }, id: { _id: 1 } },/** `purge`: tombstones past their purge time (the hourly sweep). */- SwarmMember: { changes: { tabId: 1, changedAt: 1 }, purge: { purgeAt: 1 } },- SwarmAgent: { changes: { tabId: 1, changedAt: 1 }, purge: { purgeAt: 1 } },- SwarmMachine: { changes: { tabId: 1, changedAt: 1 }, read: { tabId: 1, readAt: 1 }, purge: { purgeAt: 1 } },+ SwarmMember: { changes: { tabId: 1, changedAt: 1 }, purge: { purgeAt: 1 }, id: { _id: 1 } },+ SwarmAgent: { changes: { tabId: 1, changedAt: 1 }, purge: { purgeAt: 1 }, id: { _id: 1 } },+ SwarmMachine: { changes: { tabId: 1, changedAt: 1 }, read: { tabId: 1, readAt: 1 }, purge: { purgeAt: 1 }, id: { _id: 1 } },/** `expiry`: live starts by finish time (the hourly sweep). `agents`: a Swarm's starts of some agents (agentTombstones.ts):* unnamed, Mongo planned that read on `expiry` and read every live start of every Swarm. */- SwarmStart: { changes: { tabId: 1, changedAt: 1 }, expiry: { deleted: 1, finishedAt: 1 }, agents: { tabId: 1, agentId: 1 } },- SwarmProgress: { changes: { tabId: 1, changedAt: 1 } },+ SwarmStart: { changes: { tabId: 1, changedAt: 1 }, expiry: { deleted: 1, finishedAt: 1 }, agents: { tabId: 1, agentId: 1 }, id: { _id: 1 } },+ SwarmProgress: { changes: { tabId: 1, changedAt: 1 }, id: { _id: 1 } },SuperTabMessage: {/** A conversation's page in (sequence, id) order. */sequence: { tabId: 1, conversationId: 1, sequence: 1, _id: 1 },diff --git a/backend/src/superTabs/parts/load.ts b/backend/src/superTabs/parts/load.tsindex 62f0ca41b..c93851d19 100644--- a/backend/src/superTabs/parts/load.ts+++ b/backend/src/superTabs/parts/load.ts@@ -3,6 +3,7 @@ import { delegate, extracted, partId, type HeadColumns, type PartRow } from './wimport type { GroupData, HeadData, MachineData, Part, PartKind, SwarmParts } from './types.js'import { PART_KINDS } from './types.js'import { noteChange } from '../cache.js'+import { recordDeltaRows } from '../cacheStats.js'import type { AgentStart } from '../model.js'import { ms } from './light.js'import { groupsBy, readBy, type GroupIndex, type NamedCollection } from './indexed.js'@@ -170,16 +171,17 @@ export async function loadChanged(tx: Transaction, tabIds: string[], since: Date}/** Each kind's rows changed after `since`, read in parallel: a refresh of the read cache waits for one round trip, not seven. */-async function changedRows(tx: Transaction, tabIds: string[], since: Date, kinds: readonly PartKind[]): Promise<Array<[PartKind, Array<Record<string, unknown>>]>> {+async function changedRows(tx: Transaction, tabIds: string[], since: Date, kinds: readonly PartKind[], fields: Record<string, number> = CHANGED_FIELDS):+ Promise<Array<[PartKind, Array<Record<string, unknown>>]>> {// Plain matches that name each kind's (tabId, changedAt) index (parts/indexed.ts). Prisma sent `tabId: { in }` as an $expr// $or, one planned scan per Swarm, and could pick an index that is not bounded by time at all (roadmap Phase 3.5).const after = { $gt: { $date: since.toISOString() } }- const read = (kind: PartKind) => readBy(tx, COLLECTION[kind], 'changes', [{ $match: { tabId: { $in: tabIds }, changedAt: after } }, { $project: CHANGED_FIELDS }])+ const read = (kind: PartKind) => readBy(tx, COLLECTION[kind], 'changes', [{ $match: { tabId: { $in: tabIds }, changedAt: after } }, { $project: fields }])return Promise.all(kinds.map(async kind => {if (kind !== 'machine') return [kind, await read(kind)] as [PartKind, Array<Record<string, unknown>>]// A machine read since the cursor counts as changed too: two bounded reads, not one $or the planner cannot bound.const [changes, readings] = await Promise.all([read(kind), readBy(tx, 'SwarmMachine', 'read',- [{ $match: { tabId: { $in: tabIds }, readAt: after } }, { $project: CHANGED_FIELDS }])])+ [{ $match: { tabId: { $in: tabIds }, readAt: after } }, { $project: fields }])])return [kind, [...new Map([...changes, ...readings].map(row => [row._id as string, row])).values()]] as [PartKind, Array<Record<string, unknown>>]}))}@@ -199,10 +201,23 @@ export interface SwarmDelta {hostDigests?: ReadonlyMap<string, string | null>}-export async function loadDelta(tx: Transaction, tabId: string, since: number, kinds: readonly PartKind[]): Promise<SwarmDelta> {+/** Each kind's rows of one Swarm that its last delta read whole, by row id (#2783). */+export type DeltaRows = Map<PartKind, Map<string, Record<string, unknown>>>+/** What a delta reads of each changed row first: enough to tell the row it read whole before from a newer one. Every write of+ * what a delta reads moves the version (parts/write.ts), and a reading moves `readAt`. */+const STAMP_FIELDS = { key: 1, version: 1, changedAt: 1, readAt: 1, contentAt: 1, deleted: 1 } as const+const rowStamp = (row: Record<string, unknown>) => JSON.stringify([Number(row.version), row.changedAt ?? null, row.readAt ?? null, row.contentAt ?? null, !!row.deleted])++/**+ * The parts of `kinds` changed after `since`. With `held`, the Swarm's rows its last delta read: each changed row is read+ * as its key and version first, and whole only when `held` lacks it at that version, so a delta reads whole only what+ * moved since the one before, not every part of its window again (#2783: a 30 s overlap re-read each conversation that+ * changed in it on every bump). `held` then holds this delta's rows of each kind it read.+ */+export async function loadDelta(tx: Transaction, tabId: string, since: number, kinds: readonly PartKind[], held?: DeltaRows): Promise<SwarmDelta> {const parts: Part[] = [], hostDigests = new Map<string, string | null>()let head: HeadColumns | null = null- for (const [kind, rows] of await changedRows(tx, [tabId], new Date(since), kinds)) {+ for (const [kind, rows] of held ? await heldRows(tx, tabId, since, kinds, held) : await changedRows(tx, [tabId], new Date(since), kinds)) {for (const row of rows) {parts.push(changedPart(kind, row))if (kind === 'group') hostDigests.set(row.key as string, typeof row.hostDigest === 'string' ? row.hostDigest : null)@@ -212,6 +227,35 @@ export async function loadDelta(tx: Transaction, tabId: string, since: number, kreturn { parts, head, hostDigests }}+/** Each kind's changed rows whole: those `held` has at the same version from it, the rest read by id in one read per kind. */+async function heldRows(tx: Transaction, tabId: string, since: number, kinds: readonly PartKind[], held: DeltaRows):+ Promise<Array<[PartKind, Array<Record<string, unknown>>]>> {+ const counted = { stamps: 0, whole: 0 }+ // A kind with nothing held (the Swarm's first delta of it here) is read whole in one read: by key and version first it+ // would take two reads for the same rows.+ const cold = kinds.filter(kind => !held.get(kind)?.size), warm = kinds.filter(kind => held.get(kind)?.size)+ const whole = cold.length ? await changedRows(tx, [tabId], new Date(since), cold) : []+ for (const [kind, rows] of whole) {+ held.set(kind, new Map(rows.map(row => [row._id as string, row])))+ counted.stamps += rows.length+ counted.whole += rows.length+ }+ const rows = await Promise.all((warm.length ? await changedRows(tx, [tabId], new Date(since), warm, STAMP_FIELDS) : []).map(async ([kind, stamps]) => {+ const known = held.get(kind)+ const same = (row: Record<string, unknown>) => { const kept = known?.get(row._id as string); return kept && rowStamp(kept) === rowStamp(row) ? kept : null }+ const missing = stamps.filter(row => !same(row)).map(row => row._id as string)+ const read = new Map((missing.length ? await readBy(tx, COLLECTION[kind], 'id', [{ $match: { _id: { $in: missing }, tabId } }, { $project: CHANGED_FIELDS }]) : [])+ .map(row => [row._id as string, row]))+ const rows = stamps.flatMap(row => { const whole = same(row) ?? read.get(row._id as string); return whole ? [whole] : [] })+ held.set(kind, new Map(rows.map(row => [row._id as string, row])))+ counted.stamps += stamps.length+ counted.whole += read.size+ return [kind, rows] as [PartKind, Array<Record<string, unknown>>]+ }))+ recordDeltaRows(counted)+ return [...whole, ...rows]+}+/** The live starts of these agents (an agent is its machine and harness: write.ts extracted), whole, by the (tabId, agentId)* index: a change poll reads the finished starts whose harness a machine record still lists, and no other (read/service.ts).* A plain match: through Prisma, `agentId: { in }` was $expr, which no index bounds. */diff --git a/backend/src/superTabs/parts/loadDelta.test.ts b/backend/src/superTabs/parts/loadDelta.test.tsnew file mode 100644index 000000000..5587b471a--- /dev/null+++ b/backend/src/superTabs/parts/loadDelta.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from 'vitest'+import { loadDelta, type DeltaRows } from './load.js'++/** Part collections as rows, read through aggregateRaw: a `$match` on `_id`, or on `tabId` and a time, then `$project`. Counts+ * each read, and each whole row (one with `data`) it sends. */+function fakeDb(rows: Record<string, Array<Record<string, unknown>>>) {+ const reads: Array<{ collection: string; ids: boolean; whole: number }> = []+ const time = (value: unknown) => Date.parse((value as { $date: string }).$date)+ const db = new Proxy({}, { get: (_t, name) => ({ aggregateRaw: async ({ pipeline }: { pipeline: Array<Record<string, Record<string, unknown>>> }) => {+ const collection = String(name)[0]!.toUpperCase() + String(name).slice(1)+ const match = pipeline.find(stage => '$match' in stage)!.$match!, project = pipeline.find(stage => '$project' in stage)?.$project+ const found = (rows[collection] ?? []).filter(row => {+ if (match._id) return (match._id as { $in: string[] }).$in.includes(row._id as string)+ const [field, bound] = 'readAt' in match ? ['readAt', match.readAt] : ['changedAt', match.changedAt]+ return row[field] !== undefined && time(row[field]) > time((bound as { $gt: unknown }).$gt)+ }).map(row => project ? Object.fromEntries(Object.entries(row).filter(([key]) => key === '_id' || project[key] === 1)) : row)+ reads.push({ collection, ids: !!match._id, whole: found.filter(row => 'data' in row).length })+ return found+ } }) }) as never+ return { db, reads }+}++const at = (ms: number) => ({ $date: new Date(ms).toISOString() })+const group = (key: string, version: number, changed: number) =>+ ({ _id: `t:${key}`, tabId: 't', key, version, changedAt: at(changed), deleted: false, ordinal: 1, data: { id: key, text: 'x'.repeat(100) }, hostDigest: `d${version}` })++describe('a delta reads whole rows only for versions it has not read (#2783)', () => {+ it('a second delta over the same window reads keys and versions only, and answers the same', async () => {+ const stored = { SwarmGroup: [group('g1', 1, 2_000), group('g2', 3, 3_000)] }+ const { db, reads } = fakeDb(stored)+ const memo: DeltaRows = new Map()+ const first = await loadDelta(db, 't', 1_000, ['group'], memo)+ const before = reads.reduce((sum, r) => sum + r.whole, 0)+ const second = await loadDelta(db, 't', 1_000, ['group'], memo)+ expect(reads.reduce((sum, r) => sum + r.whole, 0)).toBe(before)+ expect(second).toEqual(first)+ expect(second).toEqual(await loadDelta(fakeDb(stored).db, 't', 1_000, ['group']))+ expect(second.hostDigests!.get('g2')).toBe('d3')+ })++ it('the first delta of a kind, with nothing held, reads its rows whole in one read, as before (CI shard 2 of #2976)', async () => {+ const stored = { SwarmGroup: [group('g1', 1, 2_000)] }+ const { db, reads } = fakeDb(stored)+ const memo: DeltaRows = new Map()+ const delta = await loadDelta(db, 't', 1_000, ['group'], memo)+ expect(reads.map(r => [r.collection, r.ids, r.whole])).toEqual([['SwarmGroup', false, 1]])+ expect(delta).toEqual(await loadDelta(fakeDb(stored).db, 't', 1_000, ['group']))+ reads.length = 0+ await loadDelta(db, 't', 1_000, ['group'], memo)+ expect(reads.map(r => [r.collection, r.ids, r.whole])).toEqual([['SwarmGroup', false, 0]])+ })++ it('reads whole only the part whose version moved', async () => {+ const stored = { SwarmGroup: [group('g1', 1, 2_000), group('g2', 3, 3_000)] }+ const { db, reads } = fakeDb(stored)+ const memo: DeltaRows = new Map()+ await loadDelta(db, 't', 1_000, ['group'], memo)+ stored.SwarmGroup[1] = { ...group('g2', 4, 4_000), data: { id: 'g2', text: 'moved' } }+ reads.length = 0+ const delta = await loadDelta(db, 't', 1_000, ['group'], memo)+ expect(reads.filter(r => r.ids).map(r => r.whole)).toEqual([1])+ expect(delta.parts.find(p => p.key === 'g2')!.data).toEqual({ id: 'g2', text: 'moved' })+ expect(delta).toEqual(await loadDelta(fakeDb(stored).db, 't', 1_000, ['group']))+ })++ it('a machine read again only for its reading time is read whole again', async () => {+ const machine = (readAt: number) => ({ _id: 't:m1', tabId: 't', key: 'm1', version: 2, changedAt: at(500), readAt: at(readAt), deleted: false, ordinal: 1,+ data: { machineId: 'm1', reading: readAt } })+ const stored = { SwarmMachine: [machine(2_000)] }+ const { db } = fakeDb(stored)+ const memo: DeltaRows = new Map()+ await loadDelta(db, 't', 1_000, ['machine'], memo)+ stored.SwarmMachine[0] = machine(3_000)+ const delta = await loadDelta(db, 't', 1_000, ['machine'], memo)+ expect(delta.parts[0]!.readAt).toBe(3_000)+ expect(delta.parts[0]!.data).toEqual({ machineId: 'm1', reading: 3_000 })+ })+})diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex bfad7863c..9ce0ee17d 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -2631,7 +2631,9 @@ export class SuperTabStore {}/** The requester alone reads the answer, once: the screen text is deleted as it is returned. Waits up to `waitMs` for it,- * reading again when the host's answer or refusal is told, when the request turns late, or every few seconds unwoken. */+ * reading again when the host's answer or refusal is told, when the request turns late, or every few seconds unwoken. Each+ * read after the first that finds the request still waiting for pickup tells its machine again: a host that hears the+ * server push picks up only when told (cli superTabs/terminal.ts), so this is the net for a push lost on the way (#2800). */async terminalResult(user: AuthUser, tabId: string, requestId: string, asAgentId?: string, waitMs = 0) {const deadline = Date.now() + waitMslet told = false, done = false, wake = () => {}, stop = () => {}@@ -2639,9 +2641,9 @@ export class SuperTabStore {if (waitMs > 0) this.hooks.watchTerminal?.(requestId, () => { told = true; wake() }).then(dispose => { if (done) dispose(); else stop = dispose }, () => {})try {- for (;;) {+ for (let reads = 0; ; reads++) {told = false- const { answer, lateIn } = await transaction(this.db, async tx => {+ const { answer, lateIn, waiting } = await transaction(this.db, async tx => {const { state } = await this.load(tx, user, tabId)const actor = await this.actor(tx, user, state, asAgentId)author(state, actor)@@ -2657,12 +2659,13 @@ export class SuperTabStore {? 'The agent’s machine did not pick up the request within 10 seconds. It may be offline or asleep.': row.status === 'claimed' && lateIn < 0? 'The agent’s machine picked up the request but did not answer within 30 seconds.' : null- if (row.status !== 'done' && !late) return { answer: null, lateIn }+ if (row.status !== 'done' && !late) return { answer: null, lateIn, waiting: row.status === 'pending' ? { machineId: row.machineId, agentId: row.agentId } : null }await tx.superTabTerminalRequest.delete({ where: { id: row.id } })if (late || !row.ok) return { answer: { requestId, ok: false, error: late ?? row.error }, lateIn }return { answer: { requestId, ok: true, ...(row.result !== null ? { text: row.result } : {}) }, lateIn }})if (answer) return answer+ if (reads && waiting) this.hooks.terminalWaiting?.({ machineId: waiting.machineId, tabId, agentId: waiting.agentId })const left = deadline - Date.now()if (left <= 0) return { requestId, pending: true }if (told) continuediff --git a/backend/src/worker.ts b/backend/src/worker.tsindex ed21d86fa..a5beec716 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -21,6 +21,7 @@ import { startSwarmSweeps } from './superTabs/sweeps.js'import { requeueCompactedAgents } from './superTabs/agentTombstones.js'import { startLegacyDrop } from './superTabs/migration/dropLegacyJob.js'import { startDeliverySettle } from './superTabs/deliverySettle.js'+import { startDeliveryRepush } from './superTabs/deliveryRepush.js'import { startDeliveryCompaction } from './superTabs/deliveryCompaction.js'import { startThreadBackfill } from './superTabs/threadBackfill.js'import { appPullRequests, markFinishedGroups, startSwarmArchive, unknownPullRequests } from './superTabs/archive.js'@@ -76,6 +77,7 @@ async function start(): Promise<void> {let stopArchive = (): void => {}let stopPullRequestWatch = (): void => {}let stopDeliveries = (): void => {}+ let stopRepush = (): void => {}let stopCompaction = (): void => {}let stopThreadBackfill = (): void => {}let stopReceiptSweep = (): void => {}@@ -95,6 +97,7 @@ async function start(): Promise<void> {stopArchive()stopPullRequestWatch()stopDeliveries()+ stopRepush()stopCompaction()stopReceiptSweep()stopReadMarkSweep()@@ -150,6 +153,9 @@ async function start(): Promise<void> {if (githubApp) stopPullRequestWatch = startPullRequestWatch(prisma, swarms, () => appPullRequestWatch(githubApp))// A delivery that can no longer move ends as Not sent, instead of waiting for good (superTabs/deliverySettle.ts).stopDeliveries = startDeliverySettle(prisma, swarms)+ // Every 15 s, the machine of each agent with a delivery still queued after 10 s is told again, in case its push was lost:+ // hosts read an idle worker's list only when told (superTabs/deliveryRepush.ts, task #2800).+ stopRepush = startDeliveryRepush(prisma, announceSwarmDeliveries)// Every hour, finished deliveries 14 days old move into their messages' receipts, kept forever (superTabs/deliveryCompaction.ts).stopCompaction = startDeliveryCompaction(prisma, env.SWARM_DELIVERY_COMPACTION)// Every 15 minutes, thread summaries for replies no write summed up: all of a Swarm's at first, then only what changeddiff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 5d033c503..162d45718 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -2875,6 +2875,27 @@ describe('desk_changed relay', () => {await socket.stop()})+ // Task #2800, review of #2977: the server renews the Swarm host's delivery push lease each minute.+ it('hands the backend\'s __deliveries_lease to the Swarm host, never to the windows, and only the backend\'s', async () => {+ const socket = relaySocket('token')+ const heard: unknown[] = []+ const frames: Array<Record<string, unknown>> = []+ socket.onAccountNotice = (notice) => { heard.push(notice) }+ socket.registerLocalClient('local:swarm', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })+ socket.connect()+ const ws = wsMock.instances[0]+ ws.open()+ ws.message({ t: 'down', connId: '', frame: { type: '__deliveries_lease', payload: {} } })+ await vi.waitFor(() => expect(heard).toEqual([{ type: '__deliveries_lease' }]))+ ws.message({ t: 'down', connId: 'web-1', frame: { type: '__deliveries_lease', payload: {} } })+ socket.handleLocalFrame('local:swarm', { type: '__deliveries_lease', payload: {} })+ await new Promise((r) => setTimeout(r, 20))+ expect(heard).toHaveLength(1)+ expect(frames.filter((f) => f.type === '__deliveries_lease')).toEqual([])+ await socket.unregisterLocalClient('local:swarm')+ await socket.stop()+ })+// Spec 2026-11-02-poll-cost Part 4.2: the server says a Lead's terminal request waits for this machine.it('hands the backend\'s __terminal_waiting to the Swarm host, never to the windows, and only the backend\'s', async () => {const socket = relaySocket('token')diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 56b3e263b..6aaded7d0 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -479,7 +479,7 @@ export class BackendSocket {notice: (notice: BackendNotice) => {this.onAccountNotice?.(notice)// Only the Swarm host acts on these (superTabs/host.ts): the windows have nothing to re-read.- if (notice.type === 'super_tab_deliveries' || notice.type === 'swarm_host_changed' || notice.type === '__terminal_waiting') return+ if (notice.type === 'super_tab_deliveries' || notice.type === 'swarm_host_changed' || notice.type === '__terminal_waiting' || notice.type === '__deliveries_lease') returnif (notice.type === 'machines_changed' && notice.reason === 'harness_shares') { this.sharesNotice.tell(); return }// A Swarm changed: its id, time and parts, or nothing for the server's word that it pushes (desktop swarm_pushes.dart).if (notice.type === 'swarm_changed') {diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 3f4cd88d8..10eb283cb 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -1617,6 +1617,9 @@ export type BackendNotice =/** A Lead's terminal request waits for an agent of this machine (backend lib/swarmDeliveryPushes.ts): its Swarm host picks* it up now rather than at its next poll (superTabs/terminal.ts). The backend's `__` frame, kept by name. */| { type: '__terminal_waiting'; tabId: string; agentId: string }+ /** The server renews the Swarm host's delivery push lease, each minute through Redis (backend lib/swarmDeliveryPushes.ts):+ * the host keeps reading an idle worker's list only when told (superTabs/host.ts PUSH_LEASE_MS). A `__` frame, kept by name. */+ | { type: '__deliveries_lease' }/** A commit changed what this machine's Swarm host reads (backend lib/swarmHostPushes.ts): it reads its changes now. Naming* none, the server says it pushes them, and the host reads only when told (superTabs/hostFeed.ts HOST_PUSH_LEASE_MS). */| { type: 'swarm_host_changed'; tabId?: string; lastChangedAt?: number }diff --git a/cli/src/gateway/gateway.ts b/cli/src/gateway/gateway.tsindex 57539ee45..09022d132 100644--- a/cli/src/gateway/gateway.ts+++ b/cli/src/gateway/gateway.ts@@ -719,6 +719,12 @@ export class RelayGateway implements GatewayPort {if (typeof p.tabId === 'string' && typeof p.agentId === 'string') this.core.notice({ type, tabId: p.tabId, agentId: p.agentId })return}+ // The server renews the Swarm host's delivery push lease (task #2800, review of #2977): nothing to read, the host only+ // keeps reading idle workers' lists when told. A `__` frame, so a daemon from before it drops it below.+ if (type === '__deliveries_lease') {+ this.core.notice({ type })+ return+ }// Other backend-hub internal control frames (__clients_dirty) — not for us; drop silently.if (type.startsWith('__')) returndiff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex 348c58759..5f745e756 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -2958,8 +2958,9 @@ describe('a Lead\'s terminal requests', () => {{ operationId: 'terminal-r1', asAgentId: 'agent', command: { type: 'agent.screenResult', requestId: 'r1', ok: true, text: 'Allow? 1. Yes' } }))})- // Spec 2026-11-02-poll-cost Part 4.2: picked up on the server's word, polled every 8 s while it pushes, every 3 s without.- it('picks one up at once when the server says one waits, and polls every 8 s only while the server pushes', async () => {+ // Spec 2026-11-02-poll-cost Part 4.2 and task #2800: picked up on the server's word, which the sender's wait repeats while+ // the request waits; asked for on a timer only without it, every 3 s.+ it('picks one up at once when the server says one waits, and asks only when told while the server pushes', async () => {const t = setup()Object.assign(t.core, { superTabs: { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), input: vi.fn(),screen: vi.fn(async () => ({ ok: true as const, text: '> ', hold: null })) } })@@ -2968,13 +2969,12 @@ describe('a Lead\'s terminal requests', () => {t.idle()t.push({ type: 'super_tab_deliveries' })await host.tick()- await vi.waitFor(() => expect(pickups()).toBe(1))t.wait(3_000); await host.tick()- expect(pickups()).toBe(1)+ expect(pickups()).toBe(0)t.push({ type: '__terminal_waiting', tabId: 'tab', agentId: 'agent' })- await vi.waitFor(() => expect(pickups()).toBe(2))- t.wait(8_000); await host.tick()- await vi.waitFor(() => expect(pickups()).toBe(3))+ await vi.waitFor(() => expect(pickups()).toBe(1))+ for (let i = 0; i < 6; i++) { t.wait(10_000); await host.tick() }+ expect(pickups()).toBe(1)})})@@ -5127,8 +5127,9 @@ describe('a machine its owner removed from a Swarm', () => {})// Stability roadmap 2.4 (2026-10-28): every running agent's host read its delivery list each second, which kept a 5-pod-// backend busy with almost nothing waiting. The server now says over the daemon socket when an agent has work; the read-// every 30 s stays as the safety net, and the read each second comes back whenever the server has not said it pushes.+// backend busy with almost nothing waiting. The server now says over the daemon socket when an agent has work, and tells+// again of what is still queued (task #2800); a Lead's read every 30 s stays, and the read each second comes back whenever+// the server has not said it pushes.describe('deliveries the server pushes', () => {const reads = (t: ReturnType<typeof setup>) => vi.mocked(t.call).mock.calls.filter(([method, path]) => method === 'GET' && path.endsWith('/deliveries')).length@@ -5147,8 +5148,29 @@ describe('deliveries the server pushes', () => {expect(reads(t)).toBe(11)})- it('reads an idle agent\'s list every 30 s once the server pushes', async () => {+ // Task #2800 (Watch Production): GET deliveries was 84% empty, mostly these 30 s reads. While the server pushes, it also tells+ // again of a delivery still queued after 10 s (backend superTabs/deliveryRepush.ts), so an idle worker's list is read only+ // when told: a push, the server's 4-minute repeat, a reconnect.+ it('reads an idle worker\'s list only when told once the server pushes', async () => {+ const t = setup(), host = t.open()+ t.idle()+ t.push(announced)+ await host.tick()+ // The server renews the lease each minute (backend lib/swarmDeliveryPushes.ts): that reads nothing.+ for (let minute = 0; minute < 3; minute++) {+ await seconds(t, host, 60)+ t.push({ type: '__deliveries_lease' })+ }+ expect(reads(t)).toBe(1)+ t.push(announced)+ await host.tick()+ expect(reads(t)).toBe(2)+ }, 20_000)++ // A Lead's poll runs its project's time checks (backend liveness.ts SWEEP_EVERY_MS): it keeps its 30 s read.+ it('still reads a Lead\'s list every 30 s', async () => {const t = setup(), host = t.open()+ t.row.lead = truet.idle()t.push(announced)await host.tick()@@ -5158,6 +5180,20 @@ describe('deliveries the server pushes', () => {expect(reads(t)).toBe(2)})+ // A read that failed is not a list read: it is tried again after its backoff, told or not.+ it('reads again after a failed read\'s backoff, without waiting to be told', async () => {+ const t = setup(), host = t.open()+ t.idle()+ t.push(announced)+ t.revoke()+ await host.tick()+ expect(reads(t)).toBe(1)+ t.revoke(false)+ t.send()+ await seconds(t, host, 30)+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)+ })+it('reads the agent\'s list at once when the server says work waits, and types it', async () => {const t = setup(), host = t.open()t.idle()@@ -5182,17 +5218,20 @@ describe('deliveries the server pushes', () => {await vi.waitFor(() => expect(t.core.turns.deliver).toHaveBeenCalledTimes(1))})- // The Lead's rule for this change: a lost push never loses work.- it('still types work whose push was lost, within 30 s', async () => {+ // The Lead's rule for this change: a lost push never loses work. The server tells again within 25 s (deliveryRepush.ts);+ // the host types it at once then, and reads nothing on a timer meanwhile.+ it('types work whose push was lost as soon as the server tells again', async () => {const t = setup(), host = t.open()t.idle()t.push(announced)await host.tick()t.wait(500)t.send()- await seconds(t, host, 29)+ await seconds(t, host, 60)expect(t.core.turns.deliver).not.toHaveBeenCalled()- await seconds(t, host, 1)+ expect(reads(t)).toBe(1)+ t.push(waiting)+ await host.tick()expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)})@@ -5212,17 +5251,32 @@ describe('deliveries the server pushes', () => {expect(reads(t)).toBe(settled)})- it('goes back to reading each second once the server has not said it pushes for 10 minutes', async () => {+ // Review of #2977 (Important 1): with Redis silent no push comes, and an idle worker is read only when told, so the lease+ // must lapse within minutes. The server renews it each minute (backend lib/swarmDeliveryPushes.ts).+ it('goes back to reading each second, and says so once, when the server has not renewed its lease for 2.5 minutes', async () => {const t = setup(), host = t.open()t.idle()t.push(announced)await host.tick()- t.wait(10 * 60_000)+ t.wait(150_000)await host.tick()await seconds(t, host, 2)expect(reads(t)).toBe(4)+ expect(t.log.mock.calls.filter(([line]) => String(line).includes('stopped saying it pushes deliveries'))).toHaveLength(1)})+ it('keeps the lease on the server\'s minute word without reading any list', async () => {+ const t = setup(), host = t.open()+ t.idle()+ t.push(announced)+ await host.tick()+ for (let minute = 0; minute < 10; minute++) {+ await seconds(t, host, 60)+ t.push({ type: '__deliveries_lease' })+ }+ expect(reads(t)).toBe(1)+ }, 20_000)+it('reads nothing more for a push naming an agent that does not run here', async () => {const t = setup(), host = t.open()t.idle()@@ -5308,7 +5362,8 @@ describe('a delivery held by a busy pane', () => {await seconds(t, host, 1)await seconds(t, host, 60)expect(writes(t)).toBe(30)- expect(reads(t)).toBe(4)+ // Held, its list was read every 30 s; once the cancel is read it is idle, read only when told (task #2800).+ expect(reads(t)).toBe(2)})it('an acked message costs no extra list read', async () => {@@ -5576,3 +5631,38 @@ describe('the account a Buddy\'s grant holds for', () => {expect(account()).toBeNull()})})++// Task #2800's measure: what one idle agent and its machine ask the backend per minute over 10 minutes while the server+// pushes, nothing waiting. Printed for the pull request; run against main's host.ts and terminal.ts for the before numbers.+describe('requests per idle agent and machine per minute while the server pushes (task #2800)', () => {+ async function measure(lead: boolean) {+ const t = setup()+ Object.assign(t.core, { superTabs: { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), input: vi.fn(),+ screen: vi.fn(async () => ({ ok: true as const, text: '> ', hold: null })) } })+ t.row.lead = lead+ const host = t.open()+ t.idle()+ t.push({ type: 'super_tab_deliveries' })+ await host.tick()+ vi.mocked(t.call).mockClear()+ // The server's minute lease and its 4-minute word that it pushes (backend lib/swarmDeliveryPushes.ts). A daemon from+ // before #2800 drops the `__` lease frame.+ for (let second = 1; second <= 600; second++) {+ t.wait(1_000)+ if (second % 60 === 0) t.push({ type: '__deliveries_lease' } as BackendNotice)+ if (second % 240 === 0) t.push({ type: 'super_tab_deliveries' })+ await host.tick()+ }+ const calls = vi.mocked(t.call).mock.calls+ const perMinute = (match: (method: string, path: string) => boolean) => calls.filter(([method, path]) => match(method, path)).length / 10+ return { lists: perMinute((method, path) => method === 'GET' && path.endsWith('/deliveries')),+ pickups: perMinute((method, path) => method === 'POST' && path.endsWith('/terminal')) }+ }++ it('an idle worker: list reads only on the repeat, no terminal pickups; a Lead: a list read every 30 s', async () => {+ const worker = await measure(false), lead = await measure(true)+ process.stderr.write(`[#2800 measure] per minute: worker list GETs ${worker.lists}, Lead list GETs ${lead.lists}, machine terminal pickups ${worker.pickups}\n`)+ expect(worker).toEqual({ lists: 0.2, pickups: 0 })+ expect(lead.lists).toBe(2)+ }, 60_000)+})diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex cd7e34a77..68c8cf8ca 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -352,12 +352,16 @@ const DELIVERY_RETRY_MAX_MS = 30_000const CLAIM_FAILURE_LOG_MS = 5 * 60_000/** Stability roadmap 2.4 (2026-10-28): every host read each running agent's delivery list each second, almost always to find* nothing. A server that says it pushes (a `super_tab_deliveries` notice over the daemon socket, backend lib/adapterWs.ts)- * names the agent when work waits; an idle agent's list is then read only this often, as the safety net for a lost push.- * It matches the backend's quiet poll (liveness.ts SWEEP_EVERY_MS), so each read still runs a Lead's time checks. */-const DELIVERY_FALLBACK_MS = 30_000-/** The server repeats that it pushes every 4 minutes on each socket: without it for this long (an older server, a rollback,- * this process started after the last one), every list is read each second again. */-const PUSH_LEASE_MS = 10 * 60_000+ * names the agent when work waits, and tells again of a delivery still queued after 10 s (backend superTabs/deliveryRepush.ts,+ * task #2800: GET deliveries was 84% empty, mostly these reads). An idle worker's list is then read only when told; a Lead's+ * still this often, matching the backend's quiet poll (liveness.ts SWEEP_EVERY_MS), so each read runs its time checks. */+const LEAD_LIST_MS = 30_000+/** The server renews this lease each minute through Redis (`__deliveries_lease`, backend lib/swarmDeliveryPushes.ts), and+ * says it pushes every 4 minutes. An idle worker's list is read only when told (task #2800), so a channel gone silent (Redis+ * away, a server rolled back) must end the lease within minutes, not the 10 it was: past this, every list is read each second+ * again, and the log says so once (review of #2977, Important 1). It allows one lost renewal. Against a server from before+ * the minute renewal, it lapses for 1.5 of every 4 minutes, reading each second then: the cost of an old server only. */+const PUSH_LEASE_MS = 150_000/** Spec 2026-11-02-poll-cost Part 3: a delivery the core refused to write (a running turn, a draft, a dialog) was claimed again* every second for as long as it was held, up to a day (prod 2026-11-02: 414 claim POSTs a minute). The claimed message is* kept and written again on each tick; the claim is renewed only this often, well inside the backend's 10-minute claim quiet@@ -501,6 +505,8 @@ export class SuperTabHost {private readonly stopNotices: () => void/** Until when the server is known to push deliveries (PUSH_LEASE_MS). */private pushUntil = 0+ /** Whether the log has said the lease lapsed since it was last held: said once per lapse, not each second. */+ private leaseSaid = true/** The agents' lists the server said have work since the last poll took them, by list key; `pushAll` reads every one. */private readonly pushes = new Set<string>()private pushAll = false@@ -756,8 +762,10 @@ export class SuperTabHost {return}if (notice.type === '__terminal_waiting') { void this.terminal.waiting(); return }+ if (notice.type === '__deliveries_lease') { this.pushUntil = this.now() + PUSH_LEASE_MS; this.leaseSaid = false; return }if (notice.type !== 'super_tab_deliveries') returnthis.pushUntil = this.now() + PUSH_LEASE_MS+ this.leaseSaid = falseif (identifier(notice.tabId) && identifier(notice.agentId)) this.pushes.add(`list:${notice.tabId}:${notice.agentId}`)else this.pushAll = truevoid this.tick()@@ -1056,7 +1064,12 @@ export class SuperTabHost {const read = await this.sources.feed.due(), data = read.rosterif (this.stopped) return// Taken once the roster is in: a push heard from here on is read by the next poll, which follows this one at once.- const pushes = new Set(this.pushes), pushAll = this.pushAll || this.now() >= this.pushUntil+ const lapsed = this.now() >= this.pushUntil+ if (lapsed && !this.leaseSaid) {+ this.leaseSaid = true+ this.log('The server stopped saying it pushes deliveries (Redis away or an older server): reading every agent\'s list each second until it does again.')+ }+ const pushes = new Set(this.pushes), pushAll = this.pushAll || lapsedthis.pushes.clear()this.pushAll = false// Multiply was closed by the ordinary 30-minute idle cleanup while still a@@ -1147,7 +1160,10 @@ export class SuperTabHost {const listKey = `list:${target.tabId}:${target.agent.id}`if (this.backedOff(listKey)) continueconst last = this.lists.get(listKey)- const due = !last || pushAll || last.busy || pushes.has(listKey) || this.now() - last.readAt >= (last.held ? HELD_LIST_MS : DELIVERY_FALLBACK_MS)+ // A read that failed is due again once its backoff (checked above) ends, told or not: it was no list read.+ const every = last?.held ? HELD_LIST_MS : row.lead === true ? LEAD_LIST_MS : null+ const due = !last || pushAll || last.busy || pushes.has(listKey) || this.deliveryRetries.has(listKey)+ || (every !== null && this.now() - last.readAt >= every)if (!due) {// Unread this time, its deliveries are as the last read left them: none is taken as gone.for (const id of last.ids) seen.add(id)@@ -1224,7 +1240,8 @@ export class SuperTabHost {}}// Taken after the pass's acknowledgements and writes: an acknowledged delivery and one the pane holds need no read next- // second, and the 30 s read below still catches a cancel whose push was lost.+ // second. A held list (and a Lead's) is still read every 30 s, which catches a cancel whose push was lost; an idle one+ // is read when told.const read = this.lists.get(listKey)if (listRead && read) {const refused = (item: Json) => identifier(item.id) && !!this.claims.get(item.id)?.refuseddiff --git a/cli/src/superTabs/terminal.spec.ts b/cli/src/superTabs/terminal.spec.tsindex e3749b6f0..8adead8e1 100644--- a/cli/src/superTabs/terminal.spec.ts+++ b/cli/src/superTabs/terminal.spec.ts@@ -140,32 +140,26 @@ describe('a host serving its Lead\'s terminal requests', () => {// Spec 2026-11-02-poll-cost Part 4.2: every host of a Swarm agent asked every 3 s, almost always for nothing (prod 2026-11-02:// 305 a minute, each a transaction). A server that pushes deliveries also says when a terminal request waits for this-// machine (`__terminal_waiting`); the backend still gives up on a pickup after 10 s, so the fallback stays under it.+// machine (`__terminal_waiting`). Task #2800: the 8 s fallback that followed was still almost all empty; the sender's wait now+// tells the machine again at each re-check while the request waits (backend store.ts terminalResult), inside the 10 s pickup,+// so with the push lease the host asks only when told.describe('terminal requests the server pushes', () => {- it('with the push lease, polls every 8 s and picks up at once on __terminal_waiting', async () => {+ it('with the push lease, asks only when told, and at once on __terminal_waiting', async () => {let pushing = trueconst t = setup(), host = new TerminalHost(t.core, 'm1', { now: t.now, log: vi.fn(), pushes: () => pushing })- await host.tick([row()])- expect(t.polls()).toBe(1)- for (let second = 1; second < 8; second++) { t.wait(1_000); await host.tick([row()]) }- expect(t.polls()).toBe(1)- t.wait(1_000); await host.tick([row()])- expect(t.polls()).toBe(2)+ for (let second = 0; second < 60; second++) { await host.tick([row()]); t.wait(1_000) }+ expect(t.polls()).toBe(0)// Told a request waits: answered now, before the backend's 10 s are out.t.request(screenRequest())- t.wait(1_000)await host.waiting()- expect(t.polls()).toBe(3)+ expect(t.polls()).toBe(1)expect(t.sent.map(s => s.body.command.type)).toEqual(['agent.screenResult'])- // The next fallback poll counts from that pickup.- for (let second = 1; second < 8; second++) { t.wait(1_000); await host.tick([row()]) }- expect(t.polls()).toBe(3)- t.wait(1_000); await host.tick([row()])- expect(t.polls()).toBe(4)+ for (let second = 0; second < 60; second++) { t.wait(1_000); await host.tick([row()]) }+ expect(t.polls()).toBe(1)// The lease lapses: every 3 s again.pushing = falset.wait(3_000); await host.tick([row()])- expect(t.polls()).toBe(5)+ expect(t.polls()).toBe(2)})it('without it, polls every 3 s', async () => {@@ -184,7 +178,8 @@ describe('terminal requests the server pushes', () => {it('picks up once more after a push that came during a pickup', async () => {const t = setup(), host = new TerminalHost(t.core, 'm1', { now: t.now, log: vi.fn(), pushes: () => true })- const first = host.tick([row()])+ await host.tick([row()])+ const first = host.waiting()const pushed = host.waiting()await first; await pushedawait vi.waitFor(() => expect(t.polls()).toBe(2))diff --git a/cli/src/superTabs/terminal.ts b/cli/src/superTabs/terminal.tsindex 6590336bd..638030790 100644--- a/cli/src/superTabs/terminal.ts+++ b/cli/src/superTabs/terminal.ts@@ -19,12 +19,12 @@ import { identifier, object } from './wire.js'type Json = Record<string, unknown>interface Own { tabId: string; agentId: string; harnessId: string }-/** Every host of every Swarm asks, so not every second (Lead, 2026-10-23); the backend gives up on a pickup after 10 s. */+/** Every host of every Swarm asks, so not every second (Lead, 2026-10-23); the backend gives up on a pickup after 10 s.+ * Only without the push lease: while the server pushes deliveries it also says when a request waits for this machine+ * (`__terminal_waiting`, spec 2026-11-02-poll-cost Part 4.2), and says it again at each of the sender's re-checks while the+ * request still waits (backend store.ts terminalResult). Task #2800: the 8 s fallback poll kept then was still almost all+ * empty pickups, each a transaction; the host now asks only when told. */export const SERVE_EVERY_MS = 3_000-/** While the server pushes deliveries (the host's push lease), it also says when a request waits for this machine- * (`__terminal_waiting`, spec 2026-11-02-poll-cost Part 4.2): this poll is then only the net for a lost push, still inside the- * backend's 10 s. Prod 2026-11-02: 305 empty pickups a minute, each a transaction. */-export const SERVE_PUSHED_EVERY_MS = 8_000/** A screen read per agent; the 3-minute prompt wait does not need it finer. */const WATCH_EVERY_MS = 15_000const PROMPT_WAIT_MS = 3 * 60_000@@ -167,8 +167,8 @@ type Episode = { since: number; alerted: boolean } | nullinterface Watched { prompt: Episode; limit: Episode; model: Episode; retried?: number; skips?: number }export class TerminalHost {- /** When the last pickup started: the next is due after the interval the push lease allows now, so a lapsed lease is- * back to every 3 s at once. */+ /** When the last pickup started: without the push lease the next is due 3 s after it, so a lapsed lease is back to every+ * 3 s at once. */private servedAt = -Infinityprivate nextWatchAt = 0private serving: Promise<void> | null = null@@ -200,7 +200,7 @@ export class TerminalHost {if (!here.length) { this.watched.clear(); this.progress.clear(); return Promise.resolve() }const own = here.filter(agent => agent.running)const now = this.now()- if (!this.serving && now - this.servedAt >= (this.pushes() ? SERVE_PUSHED_EVERY_MS : SERVE_EVERY_MS)) this.startServing()+ if (!this.serving && !this.pushes() && now - this.servedAt >= SERVE_EVERY_MS) this.startServing()if (!this.watching && now >= this.nextWatchAt) {this.nextWatchAt = now + WATCH_EVERY_MSthis.watching = this.watch(own).catch(error => this.log(error instanceof Error ? error.message : String(error))).finally(() => { this.watching = null })diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 488ddc0ba..4dac02f4f 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -7416,42 +7416,7 @@ class _SwarmScreenState extends State<SwarmScreen> {topInset: _native ? 0 : _tabBarHeight,onOpened: onOpened,ownsPointer: (position) => _owns(_notificationsButtonKey, position),- onOpen: (row) async {- final destination = swarmDestinations(app)- .where(- (item) =>- item.machineId == row.machineId &&- item.agentId == row.agentId,- )- .firstOrNull;- if (destination == null) return false;- final readToken = app.agentUnread.readTokenFor(- row.machineId,- row.agentId,- );- final questionId = app- .questionFor(row.machineId, row.agentId)- ?.requestId;- final opened = await activateSwarmDestination(- app,- destination,- destinationSwarmId: app.activeSwarmId,- );- // Opening acknowledges this notification. Its question stays pending- // until the daemon confirms an answer, independently of unread state.- if (opened &&- app.agentUnread.readTokenFor(row.machineId, row.agentId) ==- readToken &&- app.questionFor(row.machineId, row.agentId)?.requestId ==- questionId) {- app.readAgentNotification(- row.machineId,- row.agentId,- readToken: readToken,- );- }- return opened;- },+ onOpen: (row) => openInboxNotification(app, row),),);}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 18a2b95f2..4ef238cc1 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -14908,8 +14908,12 @@ class AppNotifier extends ChangeNotifier {),);if (revealAgentView(machineId, agentId)) return;+ if (openSwarmAgentTerminal(machineId, agentId)) return;+ // A Swarm tab shows only its chats' terminals: a pane added to it would+ // be closed by its view, and the click would open nothing (#2792).if (activeSwarm.isUtility ||activeSwarm.isOrchestrator ||+ activeSwarm.isSuperTab ||activeSwarm.panes.length >= maxPanes) {newSwarm();}@@ -14917,6 +14921,24 @@ class AppNotifier extends ChangeNotifier {revealAgentView(machineId, agentId);}+ /// A loaded Swarm's agent running on [machineId] as [harnessId]: its Swarm+ /// comes forward and opens its terminal beside the chat it waits in (Huy,+ /// #2792). False when no Swarm this reader has loaded holds it.+ bool openSwarmAgentTerminal(String machineId, String harnessId) {+ for (final controller in superTabs.loadedControllers) {+ if (controller.accessRevoked) continue;+ final agent = controller.snapshot?.agents+ .where((a) => a.machineId == machineId && a.harnessId == harnessId)+ .firstOrNull;+ final name = superTabName(controller.tabId);+ if (agent == null || name == null) continue;+ openSuperTab(controller.tabId, name);+ controller.openAgentTerminal(agent.id);+ return true;+ }+ return false;+ }+/// The person has gone to this agent — by clicking its row, its banner, or/// anything else that puts it in front of them. Whatever it was carrying has/// been seen.diff --git a/desktop/lib/state/notification_inbox.dart b/desktop/lib/state/notification_inbox.dartindex 8443844ee..e53ca59c8 100644--- a/desktop/lib/state/notification_inbox.dart+++ b/desktop/lib/state/notification_inbox.dart@@ -2,6 +2,7 @@ import '../notify/alert_sounds.dart';import 'app_state.dart';import 'harness_activity.dart';import 'harness_sessions.dart';+import 'swarm_navigation.dart';/// A current question or an unread result, using the existing alert ledger.class InboxNotification {@@ -76,3 +77,38 @@ InboxNotification? _notification(unavailable: harnessSessionUnavailable(machine, agent),);}++/// Opens [row]'s harness where it is, a Swarm agent's terminal beside the chat+/// it waits in (#2792), and acknowledges the notification it opened. True when+/// something opened.+Future<bool> openInboxNotification(+ AppNotifier app,+ InboxNotification row,+) async {+ final readToken = app.agentUnread.readTokenFor(row.machineId, row.agentId);+ final questionId = app.questionFor(row.machineId, row.agentId)?.requestId;+ // A Swarm agent is also one of this machine's harnesses, but opened as one+ // it lands in a tab whose Swarm view closes it: it opens in its Swarm.+ final destination = swarmDestinations(app)+ .where(+ (item) =>+ item.machineId == row.machineId && item.agentId == row.agentId,+ )+ .firstOrNull;+ final opened =+ app.openSwarmAgentTerminal(row.machineId, row.agentId) ||+ (destination != null &&+ await activateSwarmDestination(+ app,+ destination,+ destinationSwarmId: app.activeSwarmId,+ ));+ // Opening acknowledges this notification. Its question stays pending+ // until the daemon confirms an answer, independently of unread state.+ if (opened &&+ app.agentUnread.readTokenFor(row.machineId, row.agentId) == readToken &&+ app.questionFor(row.machineId, row.agentId)?.requestId == questionId) {+ app.readAgentNotification(row.machineId, row.agentId, readToken: readToken);+ }+ return opened;+}diff --git a/desktop/lib/super_tabs/activity.dart b/desktop/lib/super_tabs/activity.dartindex 27eeda698..db82c65ec 100644--- a/desktop/lib/super_tabs/activity.dart+++ b/desktop/lib/super_tabs/activity.dart@@ -25,6 +25,7 @@ class SuperTabNeed {this.at,this.decision,this.question,+ this.agentId,});final SuperTabNeedKind kind;@@ -40,6 +41,10 @@ class SuperTabNeed {/// What an agent row asks: the question the task is waiting on, else the/// task's title. Null for a decision, which has its own.final String? question;++ /// The agent waiting on the reader, for an agent row: its terminal opens+ /// beside the task (#2792).+ final String? agentId;}/// The reader's Activity in one Swarm: the one place for everything new for@@ -110,6 +115,7 @@ class SuperTabActivity extends ChangeNotifier {'${_agentName(snapshot, group.assignment!['agentId'] as String)} is waiting on you',conversationId: group.id,question: _askedBy(group),+ agentId: group.assignment!['agentId'] as String,),];}diff --git a/desktop/lib/super_tabs/activity_view.dart b/desktop/lib/super_tabs/activity_view.dartindex 243afb00a..31a07a006 100644--- a/desktop/lib/super_tabs/activity_view.dart+++ b/desktop/lib/super_tabs/activity_view.dart@@ -484,7 +484,16 @@ class _SuperTabActivityViewState extends State<SuperTabActivityView> {privateWhere: project?.isPrivate == true,trailing: 'Open',preview: _oneLine(need.question ?? ''),- onTap: () => widget.onOpenConversation(need.conversationId),+ onTap: () {+ widget.onOpenConversation(need.conversationId);+ // At its prompt, beside the task (Huy, #2792).+ if (need.agentId case final agentId?) {+ _activity.controller.openAgentTerminal(+ agentId,+ conversationId: need.conversationId,+ );+ }+ },);}final now = widget.now(), created = decision.createdAt;diff --git a/desktop/lib/super_tabs/attention.dart b/desktop/lib/super_tabs/attention.dartindex 63fdef865..1cb052c65 100644--- a/desktop/lib/super_tabs/attention.dart+++ b/desktop/lib/super_tabs/attention.dart@@ -171,6 +171,40 @@ class SuperTabAttention extends ChangeNotifier {].join(', ');}+ /// The reader's unread tags in replies that live only in their thread, in+ /// [conversationId], oldest first: what the chat's top row names and opens+ /// (#2814). The same tags, read the same way, as [tagsIn] counts for the+ /// sidebar, so reading one drops it from both.+ List<SuperTabMention> threadTagsIn(String conversationId) {+ if (controller.accessRevoked ||+ controller.notifyOf(conversationId) == SuperTabNotify.muted) {+ return const [];+ }+ return [+ for (final m in mentions.waiting)+ if (m.conversationId == conversationId &&+ m.threadId != null &&+ (m.messageSequence ?? _unknown) >+ controller.threadReadMark(m.threadId!))+ m,+ ]..sort(+ (a, b) => (a.messageSequence ?? _unknown).compareTo(+ b.messageSequence ?? _unknown,+ ),+ );+ }++ /// How many replies of [root]'s thread in [conversationId] are new to the+ /// reader, as Activity lists it; 0 when it does not list it as new.+ int newRepliesIn(String conversationId, String root) {+ for (final thread in unread) {+ if (thread.conversationId == conversationId && thread.rootId == root) {+ return newCount(thread);+ }+ }+ return 0;+ }+/// Whether [threadId] contains an unread tag of the reader.bool hasUnreadTagInThread(String conversationId, String threadId) {if (controller.accessRevoked ||diff --git a/desktop/lib/super_tabs/backend_transport.dart b/desktop/lib/super_tabs/backend_transport.dartindex 43d40e538..77a46c888 100644--- a/desktop/lib/super_tabs/backend_transport.dart+++ b/desktop/lib/super_tabs/backend_transport.dart@@ -21,6 +21,8 @@ final _swarmRoute = RegExp('|routing-policy|groups|groups/$_id|join|join/preview|native''|activity|activity/read|threads|inbox|proposals''|reminders'+ // A voice message's clip, read once before it is sent (#2887; the mic, #2665).+ '|attachments/$_id/voice''|conversations/$_id/(?:messages|catch-up|read|unread|notifications''|threads/$_id/(?:read|follow)''|messages/$_id/attachments/$_id|messages/$_id/reminder)'diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 8b9b812e1..5709aa057 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -896,6 +896,10 @@ class SuperTabController extends ChangeNotifier {/// The thread open beside the chat.({String conversationId, String root})? openedThread;+ /// The reply the open thread was opened at, to bring into view lit once+ /// its panel holds it ([SuperTabThreadPanel] takes it); null otherwise.+ ({String root, String messageId})? threadTarget;+/// A thread restored open, whose replies its first read of the Swarm brings.bool _reopenThread = false;@@ -1632,9 +1636,11 @@ class SuperTabController extends ChangeNotifier {/// Opens [root]'s thread of the selected conversation beside the chat./// [shown] false opens it with its pane not on screen (the dial opened it/// in a background tab): nothing reads until [threadPaneShown].- void openThread(String root, {bool shown = true}) {+ /// [at] names a reply to open the thread at, lit, as a link to it does.+ void openThread(String root, {bool shown = true, String? at}) {if (accessRevoked) return;openedThread = (conversationId: selectedId, root: root);+ threadTarget = at == null ? null : (root: root, messageId: at);_threadUnshown = !shown;_pruneThreadFiles();_seeThread(root);@@ -1646,6 +1652,7 @@ class SuperTabController extends ChangeNotifier {void closeThread() {if (openedThread == null) return;openedThread = null;+ threadTarget = null;_pruneThreadFiles();_saveSoon();_changed();@@ -3294,6 +3301,18 @@ class SuperTabController extends ChangeNotifier {notifyListeners();}+ /// The agent whose terminal a Waiting on you notice asked to open+ /// ([openAgentTerminal]), until the Swarm workspace on screen takes it.+ ({String agentId, String? conversationId})? agentTerminalRequest;++ /// Opens [agentId]'s terminal, focused, beside the chat it waits in+ /// ([conversationId] when the notice names one), in the workspace on screen+ /// or the one shown next.+ void openAgentTerminal(String agentId, {String? conversationId}) {+ agentTerminalRequest = (agentId: agentId, conversationId: conversationId);+ notifyListeners();+ }+/// A message the reader asked to open by its link ([openMessageLink]), until/// the Swarm view on screen takes it.({String conversationId, String messageId})? messageRequest;diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex e783c9765..ce57966d4 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -89,6 +89,7 @@ class SuperTabMessageRow extends StatefulWidget {this.thread,this.threadUnread = false,this.threadTagged = false,+ this.threadFresh = 0,this.onOpenThread,this.threadTrailing,this.threadEnd,@@ -120,6 +121,10 @@ class SuperTabMessageRow extends StatefulWidget {/// Whether an unread reply in [thread] tags the reader.final bool threadTagged;+ /// How many of [thread]'s replies are new to the reader; 0 when none, or+ /// not known.+ final int threadFresh;+/// Opens [message]'s thread: from its reply line, or from an also-sent/// reply's mark.final VoidCallback? onOpenThread;@@ -898,6 +903,7 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {thread: thread,unread: widget.threadUnread,tagged: widget.threadTagged,+ fresh: widget.threadFresh,onOpen: open,member: widget.member,trailing: widget.threadTrailing,@@ -1136,6 +1142,7 @@ class SuperTabThreadLine extends StatelessWidget {required this.unread,required this.onOpen,this.tagged = false,+ this.fresh = 0,this.member,this.trailing,this.end,@@ -1143,6 +1150,10 @@ class SuperTabThreadLine extends StatelessWidget {final SuperTabThread thread;+ /// How many replies are new to the reader, said after the count while+ /// [unread]; 0 says nothing.+ final int fresh;+/// Drawn after the line's link, outside it: a thread session's mark.final Widget? trailing;@@ -1195,13 +1206,18 @@ class SuperTabThreadLine extends StatelessWidget {);}final count = thread.replies == 1 ? '1 reply' : '${thread.replies} replies';+ final newWords = unread && fresh > 0 ? '$fresh new' : null;final last = thread.lastAt;final lastReply = last == null? null: 'Last reply ${superTabAgo(DateTime.now().difference(last))}';final link = _SuperTabThreadBar(key: ValueKey('super-thread-bar-${thread.id}'),- label: [count, if (unread) 'unread', if (tagged) '@ you'].join(', '),+ label: [+ count,+ if (unread) newWords ?? 'unread',+ if (tagged) '@ you',+ ].join(', '),onTap: onOpen,builder: (active) => Row(children: [@@ -1227,6 +1243,15 @@ class SuperTabThreadLine extends StatelessWidget {),),),+ if (newWords != null) ...[+ const SizedBox(width: grid.AppDesktop.controlGap),+ Text(+ newWords,+ key: ValueKey('super-thread-new-${thread.id}'),+ style: DesktopChrome.metadata(color: DesktopChrome.accent)+ .copyWith(fontWeight: grid.AppFont.semibold),+ ),+ ],if (tagged) ...[const SizedBox(width: grid.AppDesktop.controlGap),Text(diff --git a/desktop/lib/super_tabs/personal_lead.dart b/desktop/lib/super_tabs/personal_lead.dartindex 713d76764..5466650ce 100644--- a/desktop/lib/super_tabs/personal_lead.dart+++ b/desktop/lib/super_tabs/personal_lead.dart@@ -103,10 +103,16 @@ class PersonalLeadStarter extends ChangeNotifier {return project != null && snapshot.leadOf(project.id) == null;}- /// Starts [conversationId]'s Lead after a message there, once: a start+ /// Starts [conversationId]'s Lead after a message there, or from the empty+ /// chat's card on [machineId] with [engine] (task #2815), once: a start/// already running here, or one another of the person's machines claimed,/// is the one.- Future<void> start(SuperTabController c, String conversationId) async {+ Future<void> start(+ SuperTabController c,+ String conversationId, {+ String? machineId,+ String? engine,+ }) async {final key = _key(c, conversationId);if (statusOf(c, conversationId) case final status? when !status.failed) {return;@@ -120,7 +126,12 @@ class PersonalLeadStarter extends ChangeNotifier {'this project is no longer available',);}- final plan = planFor(c, conversationId);+ final plan = planFor(+ c,+ conversationId,+ machineId: machineId,+ engine: engine,+ );final claim = await c.request('POST','/api/super-tabs/${Uri.encodeComponent(c.tabId)}/commands',@@ -145,16 +156,31 @@ class PersonalLeadStarter extends ChangeNotifier {}}+ bool _usable(MachineState? m) =>+ m != null &&+ !m.belongsToOtherAccount &&+ !m.machine.isTeamAccount &&+ !m.isOffline;++ /// The person's own computers a Lead can start on: connected, this one+ /// first.+ List<MachineState> machinesFor(SuperTabController c) => [+ ...app.machineStates.values.where((m) => _usable(m) && m.isLocalMachine),+ ...app.machineStates.values.where((m) => _usable(m) && !m.isLocalMachine),+ ];+/// Where [conversationId]'s Lead starts, or throws why it cannot: the repo's/// folder on this computer, else on the person's computer whose pane holds- /// it; with no repo, this computer, else another of theirs connected.- PersonalLeadPlan planFor(SuperTabController c, String conversationId) {+ /// it; with no repo, this computer, else another of theirs connected. A+ /// [machineId] the card picked is that computer, in the repo's folder when+ /// a pane there holds it; an [engine] it picked is that engine.+ PersonalLeadPlan planFor(+ SuperTabController c,+ String conversationId, {+ String? machineId,+ String? engine,+ }) {final project = c.snapshot!.projectFor(conversationId)!;- bool usable(MachineState? m) =>- m != null &&- !m.belongsToOtherAccount &&- !m.machine.isTeamAccount &&- !m.isOffline;String? repoFolder(String machineId, String? agentId) {final agent = app.stateOf(machineId)@@ -171,30 +197,39 @@ class PersonalLeadStarter extends ChangeNotifier {return where.root ?? where.cwd;}- final machines = app.machineStates.values.where(usable).toList();+ final machines = machinesFor(c);final local = machines.where((m) => m.isLocalMachine).firstOrNull;final repos = [for (final pane in PersonalProjects.of(app).panesFor(c, conversationId))- if (usable(app.stateOf(pane.machineId)))+ if (_usable(app.stateOf(pane.machineId)))if (repoFolder(pane.machineId, pane.agentId) case final folder?)(machineId: pane.machineId, folder: folder),];- final repo =- repos- .where((r) => r.machineId == local?.machine.machineId)- .firstOrNull ??- repos.firstOrNull;- final machine = repo != null- ? app.stateOf(repo.machineId)!- : local ?? machines.firstOrNull;+ final picked = machineId == null+ ? null+ : machines.where((m) => m.machine.machineId == machineId).firstOrNull;+ if (machineId != null && picked == null) {+ throw const SuperTabFailure('NO_MACHINE', 'that computer isn’t online');+ }+ final repo = picked != null+ ? repos.where((r) => r.machineId == machineId).firstOrNull+ : repos+ .where((r) => r.machineId == local?.machine.machineId)+ .firstOrNull ??+ repos.firstOrNull;+ final machine =+ picked ??+ (repo != null+ ? app.stateOf(repo.machineId)!+ : local ?? machines.firstOrNull);if (machine == null) {throw const SuperTabFailure('NO_MACHINE','none of your computers is online',);}- final engine = _engineOn(machine);- if (engine == null) {+ final chosen = engine ?? _engineOn(machine);+ if (chosen == null) {throw SuperTabFailure('NO_ENGINE','Claude Code and Codex aren’t signed in on '@@ -203,7 +238,7 @@ class PersonalLeadStarter extends ChangeNotifier {}return (machineId: machine.machine.machineId,- engine: engine,+ engine: chosen,folder: repo?.folder,projectName: project.name,);diff --git a/desktop/lib/super_tabs/personal_lead_card.dart b/desktop/lib/super_tabs/personal_lead_card.dartnew file mode 100644index 000000000..c0474abfb--- /dev/null+++ b/desktop/lib/super_tabs/personal_lead_card.dart@@ -0,0 +1,170 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_select_field.dart';+import '../state/app_state.dart';+import '../widgets/desktop_chrome.dart';+import 'controller.dart';+import 'personal_lead.dart';++/// The engines a Lead starts with, in the Naming System's words.+const _leadEngines = {'claude': 'Claude Code', 'codex': 'Codex'};++/// A Personal project chat with no Lead, empty: one click starts its Lead,+/// on the person's own computer, with Claude Code and in the repo's folder+/// unless they pick otherwise (Huy 11-04, task #2815). It is #2633's start+/// (personal_lead.dart), which a first message also runs, laid out as a+/// Buddy chat's start card is (buddies.dart).+class PersonalLeadStartCard extends StatefulWidget {+ const PersonalLeadStartCard({+ super.key = const ValueKey('super-lead-start'),+ required this.controller,+ required this.conversationId,+ required this.app,+ });++ final SuperTabController controller;+ final String conversationId;+ final AppNotifier app;++ @override+ State<PersonalLeadStartCard> createState() => _PersonalLeadStartCardState();+}++class _PersonalLeadStartCardState extends State<PersonalLeadStartCard> {+ SuperTabController get c => widget.controller;+ PersonalLeadStarter get starter => PersonalLeadStarter.of(widget.app);++ /// What the person picked; null keeps the starter's own choice.+ String? _machine, _engine;++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: starter,+ builder: (context, _) {+ final status = starter.statusOf(c, widget.conversationId);+ final starting = status != null && !status.failed;+ PersonalLeadPlan? plan;+ String? unavailable;+ try {+ plan = starter.planFor(+ c,+ widget.conversationId,+ machineId: _machine,+ engine: _engine,+ );+ } on SuperTabFailure catch (failure) {+ unavailable = failure.message;+ }+ final machines = starter.machinesFor(c);+ final busy = starting || c.saving;+ return DecoratedBox(+ decoration: BoxDecoration(+ color: DesktopChrome.surface,+ borderRadius: BorderRadius.circular(grid.AppCard.radius),+ border: Border.all(color: DesktopChrome.rim),+ ),+ child: Padding(+ padding: const EdgeInsets.all(grid.AppDesktop.groupGap),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ 'This project has no Lead yet',+ style: DesktopChrome.control(medium: true),+ ),+ const SizedBox(height: grid.AppDesktop.controlGap),+ if (plan case final plan?) ...[+ Row(+ children: [+ Expanded(+ flex: 3,+ child: AppSelectField<String>(+ key: const ValueKey('super-lead-start-machine'),+ value: plan.machineId,+ semanticLabel: 'Computer',+ textStyle: DesktopChrome.control(),+ options: [+ for (final m in machines)+ SelectOption(+ value: m.machine.machineId,+ label: m.machine.displayName,+ ),+ ],+ onChanged: (value) {+ if (!busy) setState(() => _machine = value);+ },+ ),+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Expanded(+ flex: 2,+ child: AppSelectField<String>(+ key: const ValueKey('super-lead-start-engine'),+ value: plan.engine,+ semanticLabel: 'Agent',+ textStyle: DesktopChrome.control(),+ options: [+ for (final MapEntry(:key, :value)+ in _leadEngines.entries)+ SelectOption(value: key, label: value),+ ],+ onChanged: (value) {+ if (!busy) setState(() => _engine = value);+ },+ ),+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ FilledButton(+ onPressed: busy+ ? null+ : () => unawaited(+ starter.start(+ c,+ widget.conversationId,+ machineId: plan.machineId,+ engine: plan.engine,+ ),+ ),+ child: Text(starting ? 'Starting…' : 'Start Lead'),+ ),+ ],+ ),+ const SizedBox(height: grid.AppDesktop.controlGap),+ Text(+ switch (plan.folder) {+ final folder? => 'Folder: $folder',+ null => 'A new folder in your Harness projects folder',+ },+ key: const ValueKey('super-lead-start-folder'),+ style: DesktopChrome.metadata(),+ ),+ ] else+ Text(+ 'Can’t start a Lead: $unavailable',+ key: const ValueKey('super-lead-start-unavailable'),+ style: DesktopChrome.control(),+ ),+ if (status?.reason case final reason?) ...[+ const SizedBox(height: grid.AppDesktop.controlGap),+ Text(+ 'Couldn’t start a Lead: $reason',+ key: const ValueKey('super-lead-start-error'),+ style: DesktopChrome.control(),+ ),+ ],+ const SizedBox(height: grid.AppDesktop.controlGap),+ Text(+ 'Or send a message below: that starts the Lead too.',+ style: DesktopChrome.metadata(),+ ),+ ],+ ),+ ),+ );+ },+ );+}diff --git a/desktop/lib/super_tabs/reply_box.dart b/desktop/lib/super_tabs/reply_box.dartindex 0f970f133..c539641b4 100644--- a/desktop/lib/super_tabs/reply_box.dart+++ b/desktop/lib/super_tabs/reply_box.dart@@ -36,6 +36,8 @@ class SuperTabReplyBox extends StatelessWidget {this.options,this.onTag,this.onMic,+ this.voiceRow,+ this.voiceNotice,this.onKey,this.inputFormatters = const [],this.surfaceKey = const ValueKey('super-thread-composer-surface'),@@ -64,6 +66,13 @@ class SuperTabReplyBox extends StatelessWidget {/// @ Tag's press, and the mic's: no mic without one; @ Tag greyed.final VoidCallback? onTag, onMic;+ /// A voice message under way in this thread: drawn in the row's place.+ final Widget? voiceRow;++ /// The line about its voice message under the row (voice_row.dart), with+ /// its own padding: it takes no room when it has nothing to say.+ final Widget? voiceNotice;+/// Sees each key first, such as an open @ completion list's arrows and/// Enter; a non-null answer is the key's.final KeyEventResult? Function(KeyEvent event)? onKey;@@ -181,53 +190,58 @@ class SuperTabReplyBox extends StatelessWidget {),Padding(padding: composerRowInsets(target: grid.AppControl.height),- child: Row(- children: [- FocusTraversalOrder(- order: toolsOrder,- child: NewHarnessAttachButton(- attachments: files,- enabled: writable && !busy,- icon: AppIcons.plus,- ),- ),- FocusTraversalOrder(- order: toolsOrder,- child: SuperTabComposerTagButton(- key: tagKey,- onPressed: writable ? onTag : null,+ // A voice message under way takes the row's place (#2665).+ child: voiceRow != null+ ? FocusTraversalOrder(order: sendOrder, child: voiceRow!)+ : Row(+ children: [+ FocusTraversalOrder(+ order: toolsOrder,+ child: NewHarnessAttachButton(+ attachments: files,+ enabled: writable && !busy,+ icon: AppIcons.plus,+ ),+ ),+ FocusTraversalOrder(+ order: toolsOrder,+ child: SuperTabComposerTagButton(+ key: tagKey,+ onPressed: writable ? onTag : null,+ ),+ ),+ Expanded(child: options ?? const SizedBox.shrink()),+ if (onMic case final onMic?)+ FocusTraversalOrder(+ order: sendOrder,+ child: SuperTabComposerMic(+ key: micKey,+ onPressed: writable ? onMic : null,+ ),+ ),+ FocusTraversalOrder(+ order: sendOrder,+ child: ListenableBuilder(+ listenable: Listenable.merge([files, text]),+ builder: (context, _) => AppIconButton(+ key: sendKey,+ icon: AppIcons.arrowUp,+ tooltip: 'Send reply',+ color: DesktopChrome.accent,+ onPressed:+ writable &&+ !busy &&+ (text.text.trim().isNotEmpty ||+ !files.isEmpty)+ ? onSend+ : null,+ ),+ ),+ ),+ ],),- ),- Expanded(child: options ?? const SizedBox.shrink()),- if (onMic case final onMic?)- FocusTraversalOrder(- order: sendOrder,- child: SuperTabComposerMic(- key: micKey,- onPressed: writable ? onMic : null,- ),- ),- FocusTraversalOrder(- order: sendOrder,- child: ListenableBuilder(- listenable: Listenable.merge([files, text]),- builder: (context, _) => AppIconButton(- key: sendKey,- icon: AppIcons.arrowUp,- tooltip: 'Send reply',- color: DesktopChrome.accent,- onPressed:- writable &&- !busy &&- (text.text.trim().isNotEmpty || !files.isEmpty)- ? onSend- : null,- ),- ),- ),- ],- ),),+ ?voiceNotice,],),),diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dartindex d581a9601..fc0c7059e 100644--- a/desktop/lib/super_tabs/thread_panel.dart+++ b/desktop/lib/super_tabs/thread_panel.dart@@ -14,13 +14,14 @@ import 'composer_toggle.dart';import 'day_pill.dart';import 'reply_box.dart';import 'controller.dart';-import 'message_row.dart' show SuperTabMessageRow;+import 'message_row.dart' show SuperTabMessageHighlight, SuperTabMessageRow;import 'jump_to_latest.dart';import 'model.dart';import 'thread_scroll.dart';import '../widgets/laid_out_list.dart';import 'swarm_type.dart';-import 'voice_recorder.dart';+import 'voice_row.dart';+import 'voice_take.dart';/// One thread beside the chat (Dee, 2026-10-29): its root, a "N replies"/// divider, the replies, and a composer whose reply goes to the root.@@ -34,7 +35,7 @@ class SuperTabThreadPanel extends StatefulWidget {this.sessionActivity,this.machineName,this.onScroll,- this.voiceRecorder,+ this.voice,});final SuperTabController controller;@@ -57,8 +58,9 @@ class SuperTabThreadPanel extends StatefulWidget {/// so a device scrolling this Swarm scrolls the thread, not the chat.final ValueChanged<ScrollController?>? onScroll;- /// What the reply box's mic records with; without it, no mic shows.- final SuperTabVoiceRecorder? voiceRecorder;+ /// The composers' voice message (the view's one take); without it, no mic+ /// shows. Its row takes the reply box's row while it is this thread's.+ final SuperTabVoiceTake? voice;@overrideState<SuperTabThreadPanel> createState() => _SuperTabThreadPanelState();@@ -94,14 +96,66 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {SuperTabController get c => widget.controller;+ // The reply the thread was opened at (#2814): its row, and the one lit.+ final _targetKey = GlobalKey();+ String? _target, _lit;+ Timer? _litTimer;+ int _jumps = 0;+/// [row] with its message's time, for the day pill over the list. Keyed/// by the message, so the list keeps each row's place as replies arrive.Widget _dated(SuperTabMessage message, Widget row) => SuperTabDayMark(key: ValueKey('super-thread-day-${message.id}'),time: message.createdAt,- child: row,+ child: KeyedSubtree(+ key: message.id == _target ? _targetKey : null,+ child: SuperTabMessageHighlight(on: message.id == _lit, child: row),+ ),);+ /// The reply the thread was opened at ([SuperTabController.threadTarget]),+ /// once [messages] hold it: brought into view and lit for two seconds, and+ /// the list reads on from it rather than following the end.+ void _takeTarget(List<SuperTabMessage> messages) {+ final target = c.threadTarget;+ if (target == null || target.root != widget.root) return;+ final at = messages.indexWhere((m) => m.id == target.messageId);+ if (at < 0) return;+ c.threadTarget = null;+ final jump = ++_jumps;+ // After the frame: a panel just opened has no list to hold before it.+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || jump != _jumps) return;+ _scroll.holdPlace();+ _litTimer?.cancel();+ setState(() => _target = _lit = target.messageId);+ _litTimer = Timer(const Duration(seconds: 2), () {+ if (mounted) setState(() => _lit = null);+ });+ _reveal(jump, at / messages.length, 0);+ });+ }++ /// The list is lazy: jump near the target's place ([at], its share of the+ /// thread) until its row is built, then bring it into view.+ void _reveal(int jump, double at, int attempt) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || jump != _jumps || !_scroll.hasClients) return;+ if (_targetKey.currentContext case final row?) {+ unawaited(Scrollable.ensureVisible(row, alignment: .3));+ return;+ }+ if (attempt > 20) return;+ final position = _scroll.position;+ _scroll.jumpTo(+ position.minScrollExtent ++ at * (position.maxScrollExtent - position.minScrollExtent),+ );+ _reveal(jump, at, attempt + 1);+ });+ WidgetsBinding.instance.scheduleFrame();+ }+/// The conversation this thread is in.String get _conversationId => c.openedThread?.conversationId ?? c.selectedId;@@ -135,6 +189,7 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {@overridevoid dispose() {+ _litTimer?.cancel();widget.onScroll?.call(null);_scroll.dispose();_composer.dispose();@@ -338,6 +393,7 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {Widget build(BuildContext context) {grid.AppTheme.watch(context);final messages = c.threadMessages(widget.root);+ _takeTarget(messages);final root = messages.where((m) => m.id == widget.root).firstOrNull;final replies = messages.where((m) => m.id != widget.root).toList();final pending = c@@ -576,9 +632,34 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {onSend: () => unawaited(_send()),options: _choices(_writable),onTag: _promptTag,- onMic: switch (widget.voiceRecorder) {- final recorder? => () => unawaited(- recorder.start(conversationId: _conversationId, root: widget.root),+ onMic: switch (widget.voice) {+ final voice? => () => voice.start(+ conversationId: _conversationId,+ root: widget.root,+ ),+ null => null,+ },+ voiceRow: switch (widget.voice) {+ final voice? when voice.activeIn(_conversationId, widget.root) =>+ SuperTabVoiceRow(+ key: const ValueKey('super-thread-voice-row'),+ take: voice,+ discardKey: const ValueKey('super-thread-voice-discard'),+ sendKey: const ValueKey('super-thread-voice-send'),+ ),+ _ => null,+ },+ voiceNotice: switch (widget.voice) {+ final voice? => SuperTabVoiceNotice(+ take: voice,+ conversationId: _conversationId,+ root: widget.root,+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.composerSide,+ 0,+ grid.AppDesktop.composerSide,+ grid.AppDesktop.controlGap,+ ),),null => null,},diff --git a/desktop/lib/super_tabs/unread_line.dart b/desktop/lib/super_tabs/unread_line.dartindex 594986b26..66ce189e1 100644--- a/desktop/lib/super_tabs/unread_line.dart+++ b/desktop/lib/super_tabs/unread_line.dart@@ -318,6 +318,76 @@ class SuperTabUnreadBar extends StatelessWidget {}}+/// Shown while the chat holds unread tags of the reader in replies that live only in their thread (#2814): a flat row+/// across the top of the chat, like [SuperTabUnreadBar], that names them and opens the oldest one's thread at the+/// reply. The words carry it, not the colour.+class SuperTabThreadTagBar extends StatelessWidget {+ const SuperTabThreadTagBar({+ super.key,+ required this.count,+ required this.onOpen,+ });++ /// The unread tags in threads.+ final int count;+ final VoidCallback onOpen;++ static String label(int count) => count == 1+ ? '1 new reply mentions you · Open'+ : '$count new replies mention you · Open';++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final accent = DesktopChrome.accent;+ final words = label(count);+ return Material(+ key: const ValueKey('super-thread-tag-bar'),+ color: DesktopChrome.selection,+ child: DecoratedBox(+ decoration: BoxDecoration(+ border: Border(bottom: BorderSide(color: DesktopChrome.rim)),+ ),+ child: Semantics(+ button: true,+ label: '$words its thread',+ excludeSemantics: true,+ child: InkWell(+ onTap: onOpen,+ child: Padding(+ padding: SuperTabUnreadBar._padding,+ child: Row(+ children: [+ Icon(+ AppIcons.atSign,+ size: grid.AppDesktop.iconSize,+ color: accent,+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Expanded(+ child: Text(+ words,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(color: accent, medium: true),+ ),+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Icon(+ AppIcons.arrowRight,+ size: grid.AppDesktop.iconSize,+ color: accent,+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }+}+/// Shown while the New messages line, not yet seen this visit, is below the reader (a link opened the chat above/// it): takes the reader down to it.class SuperTabJumpToUnread extends StatelessWidget {diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 128d8d969..2d072e235 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -33,6 +33,7 @@ import 'recording_notice.dart';import 'profile_actions.dart';import 'live_card.dart';import 'personal_lead.dart';+import 'personal_lead_card.dart';import 'personal_projects.dart';import 'private_project_lock.dart';import 'pull_request_facts.dart';@@ -85,6 +86,9 @@ import 'pane_layout.dart';import 'composer_actions.dart';import 'view_room.dart';import 'voice_recorder.dart';+import 'voice_row.dart';+import 'voice_send.dart';+import 'voice_take.dart';import 'swarm_type.dart';import 'visible_tick.dart';import 'buddy_rows.dart';@@ -142,8 +146,9 @@ class SuperTabView extends StatefulWidget {/// without an [app], a link into another Swarm is not followed.final SwarmLinkSwarms? linkSwarms;- /// What the composer's mic records with; without it, no mic shows.- final SuperTabVoiceRecorder? voiceRecorder;+ /// Makes the microphone the composers' mic records with+ /// ([superTabVoiceRecorder]: macOS and the web); without it, no mic shows.+ final SuperTabVoiceRecorder Function()? voiceRecorder;@overrideState<SuperTabView> createState() => _SuperTabViewState();@@ -300,6 +305,7 @@ class _SuperTabViewState extends State<SuperTabView>WidgetsBinding.instance.addObserver(this);_composer.addListener(_composerMoved);c.addListener(_changed);+ c.addListener(_holdVoiceAway);c.buddyChatOpener = _openBuddyChat;SuperTabChatNotices.of(c).chatShown = _chatShown;_registerDial();@@ -308,6 +314,49 @@ class _SuperTabViewState extends State<SuperTabView>bool _chatShown() => _chatIsVisible;+ /// The composers' one voice message (voice_take.dart), the main chat's or+ /// a thread's, for the chat it was recorded in; none without a recorder.+ late final SuperTabVoiceTake? _voice = switch (widget.voiceRecorder) {+ final recorder? => SuperTabVoiceTake(+ recorder: recorder,+ post: _postVoice,+ )..addListener(_voiceChanged),+ null => null,+ };++ Future<SuperTabVoicePosted> _postVoice(+ String conversationId,+ String? root,+ SuperTabVoiceClip clip,+ ) => c.sendVoice(+ conversationId: conversationId,+ root: root,+ wav: clip.wav,+ // The computer's own language; the server hears English in one it does+ // not serve.+ lang: WidgetsBinding.instance.platformDispatcher.locale.languageCode,+ );++ void _voiceChanged() {+ if (mounted) setState(() {});+ }++ /// A take recording for a chat or thread no longer shown stops and is kept+ /// for it, Send still there: never sent into the one opened instead.+ void _holdVoiceAway() {+ final voice = _voice;+ if (voice == null ||+ (voice.state != SuperTabVoiceState.recording &&+ voice.state != SuperTabVoiceState.starting)) {+ return;+ }+ final root = voice.root;+ final away = root == null+ ? c.selectedId != voice.conversationId+ : c.openedThread?.root != root;+ if (away) voice.hold();+ }+@overridevoid didChangeDependencies() {super.didChangeDependencies();@@ -352,10 +401,14 @@ class _SuperTabViewState extends State<SuperTabView>_board = SuperTabProjectBoard(c);oldWidget.controller.threadPaneHidden();oldWidget.controller.removeListener(_changed);+ oldWidget.controller.removeListener(_holdVoiceAway);+ // A take belongs to the Swarm it was recorded in.+ _voice?.discard();if (oldWidget.controller.buddyChatOpener == _openBuddyChat) {oldWidget.controller.buddyChatOpener = null;}c.addListener(_changed);+ c.addListener(_holdVoiceAway);c.buddyChatOpener = _openBuddyChat;for (final scroll in _scroll.values) {scroll.dispose();@@ -619,6 +672,31 @@ class _SuperTabViewState extends State<SuperTabView>Timer? _historyRetry;static const _historyRetryAfter = Duration(seconds: 5);+ /// The band's [today] (the unread bar or the jump pill, or nothing), under+ /// the row naming [id]'s unread tags in threads when it has any (#2814).+ Widget? _withThreadTags(String id, Widget? today) {+ final tags = SuperTabAttention.of(c).threadTagsIn(id);+ if (tags.isEmpty) return today;+ final bar = SuperTabThreadTagBar(+ count: tags.length,+ onOpen: () => _openThreadTag(tags.first),+ );+ if (today == null) return bar;+ return Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [bar, today],+ );+ }++ /// Opens [tag]'s thread at its reply, lit; opening it reads it, which+ /// clears the tag from the row and the red number.+ void _openThreadTag(SuperTabMention tag) {+ final root = tag.threadId;+ if (root == null) return;+ c.openThread(root, at: tag.messageId);+ }+/// Brings [id]'s New messages line into view near the top, and stops/// following the end there: what came since the reader's mark is below./// The bar or the pill clicked: the line, with typing back in the composer,@@ -912,6 +990,8 @@ class _SuperTabViewState extends State<SuperTabView>_board.dispose();_facts.dispose();c.removeListener(_changed);+ c.removeListener(_holdVoiceAway);+ _voice?.dispose();for (final source in _linkSources) {source.removeListener(_linkSourceChanged);}@@ -1934,7 +2014,7 @@ class _SuperTabViewState extends State<SuperTabView>// A thread reply opens its thread; one shown only there has no row in the// chat to scroll to.if (message.threadReply) {- c.openThread(message.thread!);+ c.openThread(message.thread!, at: message.id);if (!message.inMainStream) return;}final shownBy = _rowShowing(id, messageId) ?? messageId;@@ -2092,7 +2172,7 @@ class _SuperTabViewState extends State<SuperTabView>// A tag in a thread opens the thread; one in a thread reply shown only// there is not in the chat to scroll to.if (message.thread case final root?) {- c.openThread(root);+ c.openThread(root, at: message.inMainStream ? null : message.id);if (!message.inMainStream) return;}setState(() {@@ -2636,6 +2716,7 @@ class _SuperTabViewState extends State<SuperTabView>required List<Widget> options,required List<Widget> trailing,required Widget send,+ Widget? voice,}) {// Too little height for a second row (a phone on its side with its keyboard// up): the actions take the row's end. A narrow phone with so little@@ -2643,7 +2724,7 @@ class _SuperTabViewState extends State<SuperTabView>// has no room for @ Tag there, and an @ typed still opens the list.final target = _phone ? kFingerTarget : grid.AppControl.height;final row = composerRowInsets(target: target);- if (_phone && room < _phoneComposerTwoRowsFrom) {+ if (_phone && room < _phoneComposerTwoRowsFrom && voice == null) {return Padding(padding: EdgeInsets.only(left: grid.AppDesktop.composerSide,@@ -2676,21 +2757,24 @@ class _SuperTabViewState extends State<SuperTabView>),Padding(padding: row,- child: Row(- key: const ValueKey('super-message-composer-actions'),- children: [- attach,- tag,- Expanded(- child: Wrap(- crossAxisAlignment: WrapCrossAlignment.center,- children: options,- ),+ // A voice message under way takes the row's place (#2665).+ child:+ voice ??+ Row(+ key: const ValueKey('super-message-composer-actions'),+ children: [+ attach,+ tag,+ Expanded(+ child: Wrap(+ crossAxisAlignment: WrapCrossAlignment.center,+ children: options,+ ),+ ),+ ...trailing,+ send,+ ],),- ...trailing,- send,- ],- ),),],);@@ -2747,6 +2831,50 @@ class _SuperTabViewState extends State<SuperTabView>);}+ /// Whether [group]'s empty chat offers to start its Lead: a Personal+ /// project with none, read by someone who may write (task #2815).+ bool _offersLead(SuperTabConversation group) => switch (widget.app) {+ final app? => c.canWrite && PersonalLeadStarter.of(app).wants(c, group.id),+ null => false,+ };++ /// A Personal project's empty chat with no Lead: the card that starts one+ /// (Huy 11-04, task #2815), and under it what the chat says without it: its+ /// panes when it holds any, else its plain line.+ Widget _leadWaiting(SuperTabConversation group) => Center(+ child: SingleChildScrollView(+ padding: const EdgeInsets.all(grid.AppDesktop.panelPadding),+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: grid.AppDesktop.formWidth),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ PersonalLeadStartCard(+ controller: c,+ conversationId: group.id,+ app: widget.app!,+ ),+ if (_personalPaneCount(group) > 0)+ _panesWaiting(group)+ else+ Padding(+ padding: const EdgeInsets.only(+ top: grid.AppDesktop.panelPadding,+ ),+ child: Text(+ 'Discuss the plan with '+ '${c.snapshot!.coordinatorNameOf(group.projectId)}.',+ textAlign: TextAlign.center,+ style: DesktopChrome.text(color: DesktopChrome.muted),+ ),+ ),+ ],+ ),+ ),+ ),+ );+/// Opens the group's terminals beside the chat; null when it has none this/// reader may open (a read-only viewer's terminal reads are refused).VoidCallback? _openTerminals(SuperTabConversation group) =>@@ -3631,6 +3759,9 @@ class _SuperTabViewState extends State<SuperTabView>threadTagged:thread != null &&SuperTabAttention.of(c).hasUnreadTagInThread(c.selectedId, thread.id),+ threadFresh: thread == null+ ? 0+ : SuperTabAttention.of(c).newRepliesIn(c.selectedId, thread.id),// A thread its own Buddy session answers says so on its line.threadTrailing: switch (thread == null || inThread? null@@ -3722,7 +3853,7 @@ class _SuperTabViewState extends State<SuperTabView>superTabSessionActivity(c, widget.app, session),machineName: widget.machineName,onScroll: (list) => _threadScroll = list,- voiceRecorder: widget.voiceRecorder,+ voice: _voice,),);}@@ -4185,6 +4316,12 @@ class _SuperTabViewState extends State<SuperTabView>? const Center(child: CircularProgressIndicator()): unread && c.error != null? _firstReadFailed(c.error!)+ : messages.isEmpty &&+ outgoing.isEmpty &&+ !c.accessRevoked &&+ group != null &&+ _offersLead(group)+ ? _leadWaiting(group): messages.isEmpty &&outgoing.isEmpty &&!c.accessRevoked &&@@ -4220,29 +4357,33 @@ class _SuperTabViewState extends State<SuperTabView>SuperTabUnreadBand(key: ValueKey('super-unread-band-${c.selectedId}'),scroll: _scroll[c.selectedId],- child: _showsBar(c.selectedId)- ? SuperTabUnreadBar(- count: _newFromLine(c.selectedId),- more: c.hasNewer(c.selectedId),- onPressed: () => _jumpToUnreadLine(c.selectedId),- onMarkRead: _markReadFromBar,- )- : _unread.offersDown(c.selectedId)- ? Padding(- padding: const EdgeInsets.fromLTRB(- grid.AppDesktop.panelPadding,- grid.AppDesktop.controlGap,- grid.AppDesktop.panelPadding,- 0,- ),- child: Center(- child: SuperTabJumpToUnread(- onPressed: () =>- _jumpToUnreadLine(c.selectedId),+ child: _withThreadTags(+ c.selectedId,+ _showsBar(c.selectedId)+ ? SuperTabUnreadBar(+ count: _newFromLine(c.selectedId),+ more: c.hasNewer(c.selectedId),+ onPressed: () =>+ _jumpToUnreadLine(c.selectedId),+ onMarkRead: _markReadFromBar,+ )+ : _unread.offersDown(c.selectedId)+ ? Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.panelPadding,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.panelPadding,+ 0,),- ),- )- : null,+ child: Center(+ child: SuperTabJumpToUnread(+ onPressed: () =>+ _jumpToUnreadLine(c.selectedId),+ ),+ ),+ )+ : null,+ ),),Expanded(child: Stack(@@ -4761,21 +4902,27 @@ class _SuperTabViewState extends State<SuperTabView>),],trailing: [- if (widget.voiceRecorder case final recorder?)+ if (_voice case final voice?)fingerTarget(enabled: _phone,SuperTabComposerMic(key: const ValueKey('super-composer-mic'),onPressed: writable- ? () => unawaited(- recorder.start(- conversationId: chatId,- ),+ ? () => voice.start(+ conversationId: chatId,): null,),),],+ voice: switch (_voice) {+ final voice? when voice.activeIn(chatId, null) =>+ SuperTabVoiceRow(+ key: const ValueKey('super-voice-row'),+ take: voice,+ ),+ _ => null,+ },send: ListenableBuilder(listenable: Listenable.merge([_composer, _files]),builder: (context, _) => fingerTarget(@@ -4799,6 +4946,17 @@ class _SuperTabViewState extends State<SuperTabView>),),),+ if (_voice case final voice?)+ SuperTabVoiceNotice(+ take: voice,+ conversationId: chatId,+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.composerSide,+ 0,+ grid.AppDesktop.composerSide,+ grid.AppDesktop.controlGap,+ ),+ ),],),),@@ -4898,6 +5056,22 @@ class _SuperTabViewState extends State<SuperTabView>// A thread opened since Members takes its side and closes it.if (thread != null) _rosterOpen = false;final threadDrawer = thread != null && !wide;+ // A terminal on screen keeps its chat beside it, in the right pane, as+ // a thread sits; a thread or Members takes that side, and a narrow+ // window shows one at a time (Huy, 11-04, #2792).+ final chatBeside =+ wide &&+ thread == null &&+ !_rosterOpen &&+ terminal != null &&+ _terminalsVisible &&+ !_manageVisible &&+ !_notificationsVisible &&+ c.snapshot?.projects.isEmpty != true;+ final chat = SuperTabImageGallery(+ images: () => _images(_shownMessages(c.selectedId)),+ child: _conversation(narrow),+ );final chatCovered =(narrow && _sidebarOpen) || (!wide && _rosterOpen) || threadDrawer;if (_chatCovered && !chatCovered) {@@ -4948,8 +5122,15 @@ class _SuperTabViewState extends State<SuperTabView>onLeave: _leaveResize,left: narrow ? null : _sidebar(),// An open thread takes the roster's side, as in Slack.- right: !wide ? null : thread ?? (_rosterOpen ? roster : null),- rightDefault: thread == null+ right: !wide+ ? null+ : thread ??+ (_rosterOpen+ ? roster+ : chatBeside+ ? chat+ : null),+ rightDefault: thread == null && !chatBeside? SuperTabPaneLayout.rightWidth: SuperTabPaneLayout.threadWidth,// Over the chat, beside an open thread, as in Slack.@@ -4986,10 +5167,7 @@ class _SuperTabViewState extends State<SuperTabView>? 5: 0,children: [- SuperTabImageGallery(- images: () => _images(_shownMessages(c.selectedId)),- child: _conversation(narrow),- ),+ chatBeside ? const SizedBox.shrink() : chat,terminal ?? const SizedBox.shrink(),_showPullRequests? SuperTabPullRequests(diff --git a/desktop/lib/super_tabs/voice_recorder.dart b/desktop/lib/super_tabs/voice_recorder.dartindex 3fbe16d29..dc74b3ccc 100644--- a/desktop/lib/super_tabs/voice_recorder.dart+++ b/desktop/lib/super_tabs/voice_recorder.dart@@ -1,9 +1,176 @@-/// Records a voice message from the composer's mic: sent as audio, people hear-/// it and agents read its words (Dee, 11-04; #2887), never typed into the box.-/// The composer shows its mic only with one, so no button that does nothing-/// shows: none is given until recording comes, with the `record` package and-/// the macOS microphone entitlement (River, 11-04: its own task after #2662).+import 'dart:async';+import 'dart:typed_data';++import 'package:flutter/foundation.dart';+import 'package:record/record.dart';++import 'voice_wav.dart';++/// One finished take: the WAV to upload and how long it ran.+typedef SuperTabVoiceClip = ({Uint8List wav, Duration length});++/// The microphone behind the composer's mic (voice_take.dart): sent as audio,+/// people hear it and agents read its words (Dee, 11-04; #2887), never typed+/// into the box. The phone's recorder seam (mobile/lib/phone/voice_recorder.dart).+///+/// A seam rather than `AudioRecorder` itself: the plugin is a platform channel,+/// and a widget test that reached it would hang on a call no recorder answers.abstract interface class SuperTabVoiceRecorder {- /// Starts a take for [conversationId], in the thread [root] when one is open.- Future<void> start({required String conversationId, String? root});+ /// Asks for the microphone the first time it runs. False once refused.+ Future<bool> allowed();++ /// Starts a take. Throws when the microphone cannot be opened.+ Future<void> start();++ /// Ends the take, or null when not one buffer was captured.+ Future<SuperTabVoiceClip?> stop();++ /// Ends the take and throws it away.+ Future<void> cancel();++ Future<void> dispose();++ /// How loud the microphone is now, 0…1 (`pcm16Level`); 0 between takes.+ ValueListenable<double> get level;+}++/// The recorder for this build, or null where none works: macOS (AVFoundation)+/// and the web (getUserMedia). Linux and Windows get none, so their composer+/// draws no mic (#2665: a mic that cannot record is a button that does nothing).+SuperTabVoiceRecorder Function()? superTabVoiceRecorder({+ bool web = kIsWeb,+ TargetPlatform? platform,+}) => web || (platform ?? defaultTargetPlatform) == TargetPlatform.macOS+ ? SuperTabMicRecorder.new+ : null;++/// [SuperTabVoiceRecorder] over the computer's or browser's microphone.+///+/// Streams 16 kHz mono PCM and wraps it in a WAV here, as the phone does: the+/// server's voice read is tuned on it, and a minute is under 2 MB to upload.+class SuperTabMicRecorder implements SuperTabVoiceRecorder {+ static const _requested = RecordConfig(+ encoder: AudioEncoder.pcm16bits,+ sampleRate: 16000,+ numChannels: 1,+ );++ /// How long a stop lets audio already captured arrive before the+ /// microphone closes, and how long it waits for the stream to end.+ static const _tailSettle = Duration(milliseconds: 120);+ static const _drainLimit = Duration(seconds: 2);++ final AudioRecorder _recorder = AudioRecorder();+ final BytesBuilder _pcm = BytesBuilder(copy: false);+ StreamSubscription<Uint8List>? _subscription;+ Completer<void>? _drained;++ /// What the platform records at: a device may refuse 16 kHz and say so,+ /// and a header with the wrong rate transcribes at the wrong speed.+ int _sampleRate = _requested.sampleRate;+ int _channels = _requested.numChannels;++ /// Never disposed: the row's wave may still listen as this is torn down.+ final ValueNotifier<double> _level = ValueNotifier(0);++ @override+ ValueListenable<double> get level => _level;++ /// One plugin call at a time: a discard not awaited must never land on+ /// the next take.+ Future<void> _tail = Future.value();++ Future<T> _serially<T>(Future<T> Function() operation) {+ final result = _tail.then((_) => operation());+ _tail = result.then((_) {}, onError: (Object _) {});+ return result;+ }++ @override+ Future<bool> allowed() => _recorder.hasPermission();++ @override+ Future<void> start() => _serially(() async {+ await _discard();+ _sampleRate = _requested.sampleRate;+ _channels = _requested.numChannels;+ await _recorder.setOnConfigChanged((config) {+ _sampleRate = config.sampleRate;+ _channels = config.numChannels;+ });+ // A broadcast stream drops what arrives before a listener: subscribe in+ // the same step, with nothing awaited between.+ final stream = await _recorder.startStream(_requested);+ final drained = Completer<void>();+ _drained = drained;+ void finish([Object? _]) {+ if (!drained.isCompleted) drained.complete();+ }++ _subscription = stream.listen(+ (buffer) {+ _pcm.add(buffer);+ _level.value = pcm16Level(buffer);+ },+ onDone: finish,+ onError: finish,+ );+ });++ @override+ Future<SuperTabVoiceClip?> stop() => _serially(() async {+ final drained = _drained;+ if (drained == null) return null;+ await _settleTail();+ await _recorder.stop();+ await drained.future.timeout(_drainLimit, onTimeout: () {});+ await _subscription?.cancel();+ _subscription = null;+ _drained = null;+ _level.value = 0;+ final pcm = _pcm.takeBytes();+ if (pcm.isEmpty) return null;+ final samples = pcm.length ~/ (2 * _channels);+ return (+ wav: wavFromPcm16(pcm, sampleRate: _sampleRate, channels: _channels),+ length: Duration(microseconds: samples * 1000000 ~/ _sampleRate),+ );+ });++ @override+ Future<void> cancel() => _serially(() async {+ if (_drained == null) return;+ await _recorder.cancel();+ await _discard();+ });++ @override+ Future<void> dispose() => _serially(() async {+ await _discard();+ await _recorder.dispose();+ });++ /// Waits until a stretch passes with no buffer, at most [_tailSettle].+ Future<void> _settleTail() async {+ const step = Duration(milliseconds: 20);+ final deadline = DateTime.now().add(_tailSettle);+ var seen = _pcm.length, quiet = 0;+ while (_subscription != null && DateTime.now().isBefore(deadline)) {+ await Future<void>.delayed(step);+ if (_pcm.length != seen) {+ seen = _pcm.length;+ quiet = 0;+ } else if (++quiet >= 2) {+ return;+ }+ }+ }++ Future<void> _discard() async {+ await _subscription?.cancel();+ _subscription = null;+ _drained = null;+ _pcm.clear();+ _level.value = 0;+ }}diff --git a/desktop/lib/super_tabs/voice_row.dart b/desktop/lib/super_tabs/voice_row.dartnew file mode 100644index 000000000..ba69b9e1b--- /dev/null+++ b/desktop/lib/super_tabs/voice_row.dart@@ -0,0 +1,351 @@+import 'dart:async';+import 'dart:math' as math;++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/scheduler.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_icon_button.dart';+import '../widgets/desktop_chrome.dart';+import 'voice_length.dart';+import 'voice_take.dart';++/// Where macOS lets a person give Harness the microphone.+final superTabMicrophoneSettings = Uri.parse(+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone',+);++/// Opens [superTabMicrophoneSettings]; a test puts its own here.+@visibleForTesting+Future<bool> Function(Uri url) superTabOpenSettings = launchUrl;++/// What the composer says when the microphone was refused: on macOS with a+/// way to System Settings, in a browser where to allow it (no page can open+/// a browser's settings).+const superTabMicRefusedMac = "Harness can't use the microphone";+const superTabMicRefusedWeb =+ "This site can't use the microphone · allow it in your browser's site settings";++/// The composer's row while a voice message is under way (Dee, 11-04; the+/// phone's SwarmVoiceRow):+///+/// [X] ● 0:14 ıllıllıııllıı.ılı [↑]+///+/// X throws the take away; the red dot and the time run while it records,+/// and the wave follows the microphone. A kept take shows its length with+/// the dot and the wave at rest. Send posts it, spinning until it has gone.+class SuperTabVoiceRow extends StatelessWidget {+ const SuperTabVoiceRow({+ super.key,+ required this.take,+ this.discardKey = const ValueKey('super-voice-discard'),+ this.sendKey = const ValueKey('super-voice-send'),+ });++ final SuperTabVoiceTake take;+ final Key discardKey, sendKey;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return ListenableBuilder(+ listenable: take,+ builder: (context, _) {+ final sending = take.state == SuperTabVoiceState.sending;+ final recording = take.state == SuperTabVoiceState.recording;+ return Row(+ children: [+ AppIconButton(+ key: discardKey,+ icon: AppIcons.close,+ tooltip: 'Discard voice message',+ onPressed: sending ? null : take.discard,+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Container(+ key: const ValueKey('super-voice-dot'),+ width: grid.AppDesktop.controlGap,+ height: grid.AppDesktop.controlGap,+ decoration: BoxDecoration(+ color: recording+ ? grid.AppPalette.dangerFill+ : DesktopChrome.hint,+ shape: BoxShape.circle,+ ),+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ _TakeClock(take: take),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Expanded(+ child: _VoiceWave(+ key: const ValueKey('super-voice-wave'),+ level: recording ? take.level : null,+ ),+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ AppIconButton(+ key: sendKey,+ icon: AppIcons.arrowUp,+ tooltip: 'Send voice message',+ color: DesktopChrome.accent,+ spinning: sending,+ onPressed: take.canSend ? take.send : null,+ ),+ ],+ );+ },+ );+ }+}++/// The one line under a composer about its voice message: a refused+/// microphone, with the way to allow it, or what the last take came to.+/// Nothing when there is nothing to say.+class SuperTabVoiceNotice extends StatelessWidget {+ const SuperTabVoiceNotice({+ super.key,+ required this.take,+ required this.conversationId,+ this.root,+ this.web = kIsWeb,+ this.padding = EdgeInsets.zero,+ });++ final SuperTabVoiceTake take;+ final String conversationId;+ final String? root;+ final bool web;++ /// Around the line when there is one; nothing takes room when there is not.+ final EdgeInsets padding;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return ListenableBuilder(+ listenable: take,+ builder: (context, _) {+ final here = take.conversationId == conversationId && take.root == root;+ final style = DesktopChrome.metadata(color: DesktopChrome.muted);+ if (here && take.denied) {+ return Padding(+ key: const ValueKey('super-voice-refused'),+ padding: padding,+ child: web+ ? Text(superTabMicRefusedWeb, style: style)+ : Wrap(+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ Text('$superTabMicRefusedMac · ', style: style),+ InkWell(+ key: const ValueKey('super-voice-settings'),+ onTap: () => unawaited(+ superTabOpenSettings(superTabMicrophoneSettings),+ ),+ child: Text(+ 'Open System Settings',+ style: DesktopChrome.metadata(+ color: DesktopChrome.accent,+ ),+ ),+ ),+ ],+ ),+ );+ }+ final notice = take.notice;+ if (here && notice != null) {+ return Padding(+ key: const ValueKey('super-voice-notice'),+ padding: padding,+ child: Text(notice, style: style),+ );+ }+ return const SizedBox.shrink();+ },+ );+ }+}++/// The take's time beside the red dot: it runs, a second at a time, only+/// while the take records.+class _TakeClock extends StatefulWidget {+ const _TakeClock({required this.take});++ final SuperTabVoiceTake take;++ @override+ State<_TakeClock> createState() => _TakeClockState();+}++class _TakeClockState extends State<_TakeClock> {+ Timer? _tick;++ @override+ Widget build(BuildContext context) {+ final recording = widget.take.state == SuperTabVoiceState.recording;+ if (recording && _tick == null) {+ _tick = Timer.periodic(const Duration(seconds: 1), (_) {+ if (mounted) setState(() {});+ });+ } else if (!recording) {+ _tick?.cancel();+ _tick = null;+ }+ return Text(+ superTabVoiceLength(widget.take.length),+ key: const ValueKey('super-voice-time'),+ style: DesktopChrome.control().copyWith(+ fontFeatures: const [FontFeature.tabularFigures()],+ ),+ );+ }++ @override+ void dispose() {+ _tick?.cancel();+ super.dispose();+ }+}++/// The row's wave: the microphone's [level] scrolling in from the right, one+/// bar 2 wide every 4. At rest (no [level]) the bars lie flat. Under Reduce+/// Motion nothing scrolls. Painted behind a [RepaintBoundary], so the+/// composer is not rebuilt at every frame.+class _VoiceWave extends StatefulWidget {+ const _VoiceWave({super.key, required this.level});++ final ValueListenable<double>? level;++ static const double bar = 2, pitch = 4, low = 2;++ /// How often a new bar comes in on the right.+ static const step = Duration(milliseconds: 70);++ /// The most bars kept: enough for any composer's width.+ static const keep = 240;++ @override+ State<_VoiceWave> createState() => _VoiceWaveState();+}++class _VoiceWaveState extends State<_VoiceWave>+ with SingleTickerProviderStateMixin {+ late final Ticker _ticker = createTicker(_tick);+ final List<double> _history = [];+ final ValueNotifier<int> _moved = ValueNotifier(0);+ Duration _last = Duration.zero;+ double _shown = 0;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _sync();+ }++ @override+ void didUpdateWidget(_VoiceWave old) {+ super.didUpdateWidget(old);+ if (widget.level == null && old.level != null) {+ _history.clear();+ _moved.value++;+ }+ _sync();+ }++ void _sync() {+ final run =+ widget.level != null && !MediaQuery.disableAnimationsOf(context);+ if (run && !_ticker.isActive) {+ _last = Duration.zero;+ unawaited(_ticker.start());+ } else if (!run && _ticker.isActive) {+ _ticker.stop();+ }+ }++ void _tick(Duration elapsed) {+ if (elapsed - _last < _VoiceWave.step) return;+ _last = elapsed;+ final target = (widget.level?.value ?? 0).clamp(0.0, 1.0);+ _shown += (target - _shown) * 0.6;+ // A breath in silence: never a frozen line while listening.+ final breath = 0.06 + 0.05 * math.sin(elapsed.inMilliseconds / 180.0).abs();+ _history.add(math.max(_shown, breath));+ if (_history.length > _VoiceWave.keep) _history.removeAt(0);+ _moved.value++;+ }++ @override+ void dispose() {+ _ticker.dispose();+ _moved.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => RepaintBoundary(+ child: SizedBox(+ height: grid.AppControl.heightFieldScaled,+ child: CustomPaint(+ size: Size.infinite,+ painter: _WavePainter(+ history: _history,+ moved: _moved,+ color: DesktopChrome.muted,+ still: MediaQuery.disableAnimationsOf(context) ? widget.level : null,+ ),+ ),+ ),+ );+}++class _WavePainter extends CustomPainter {+ _WavePainter({+ required this.history,+ required Listenable moved,+ required this.color,+ required this.still,+ }) : super(repaint: still == null ? moved : Listenable.merge([moved, still]));++ final List<double> history;+ final Color color;++ /// Under Reduce Motion: the level the one still shape follows.+ final ValueListenable<double>? still;++ @override+ void paint(Canvas canvas, Size size) {+ final count = (size.width / _VoiceWave.pitch).floor();+ if (count <= 0) return;+ final paint = Paint()..color = color;+ final mid = size.height / 2;+ final high = size.height * .6;+ for (var i = 0; i < count; i++) {+ final double amount;+ if (still case final still?) {+ final shape = 0.35 + 0.65 * math.sin(math.pi * (i + 0.5) / count);+ amount = (0.08 + 0.92 * still.value.clamp(0.0, 1.0)) * shape;+ } else {+ final at = history.length - count + i;+ amount = at < 0 ? 0 : history[at];+ }+ final h = _VoiceWave.low + (high - _VoiceWave.low) * amount;+ final x = size.width - (count - i) * _VoiceWave.pitch;+ canvas.drawRRect(+ RRect.fromRectAndRadius(+ Rect.fromLTWH(x, mid - h / 2, _VoiceWave.bar, h),+ const Radius.circular(_VoiceWave.bar / 2),+ ),+ paint,+ );+ }+ }++ @override+ bool shouldRepaint(_WavePainter old) =>+ old.color != color || old.still != still || old.history != history;+}diff --git a/desktop/lib/super_tabs/voice_send.dart b/desktop/lib/super_tabs/voice_send.dartnew file mode 100644index 000000000..3f03cde73--- /dev/null+++ b/desktop/lib/super_tabs/voice_send.dart@@ -0,0 +1,129 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import '../state/harness_attachments.dart';+import 'controller.dart';+import 'model.dart';+import 'voice_take.dart';++/// The name a voice message's clip is uploaded under: what an older app shows+/// for it, as a file (the phone's swarmVoiceFileName).+const superTabVoiceFileName = 'Voice message.wav';++/// What the composer says when a voice message went without its words.+const superTabVoiceOverLimit =+ "Sent without words: today's voice limit is used";+const superTabVoiceNotTranscribed =+ "Sent without words: they couldn't be heard";++/// What it says when the clip's read got no answer; the take is kept.+const superTabVoiceNoAnswer = "Not sent · couldn't reach the server";++/// What it says to a server from before voice messages; the take is kept.+const superTabVoiceNeedsServer = 'Voice messages need a newer server';++/// What it says while another message holds the send lane; the take is kept.+const superTabVoiceBusy = 'Another message is on its way · try Send again';++/// How long to wait before asking again while the server still reads a clip+/// another try started.+@visibleForTesting+Duration superTabVoiceRetry = const Duration(seconds: 1);++/// How many times to ask before giving up on a clip still being read.+const _voiceAsks = 30;++/// A take from the composer's mic, sent as the phone sends one (#2887): the+/// clip goes up as an ordinary file, the server reads it once as a voice+/// message (its length, waveform and words, on the sender's voice quota), and+/// `message.send` names that file with no text: the server makes the words+/// the message's text, for agents to read.+extension SuperTabVoiceSend on SuperTabController {+ /// Sends [wav] in [conversationId], as a reply to [root] when there is one,+ /// its words heard in [lang]. Not sent, the take is the composer's to keep;+ /// once the send is on its way it is the chat's, kept there with Retry if+ /// its answer is lost or refused, like any other message.+ Future<SuperTabVoicePosted> sendVoice({+ required String conversationId,+ required String? root,+ required Uint8List wav,+ required String lang,+ }) async {+ if (!canWrite) return (sent: false, notice: null);+ if (saving || hasPendingAction) {+ return (sent: false, notice: superTabVoiceBusy);+ }+ final String id;+ try {+ final answer = await uploadFile(+ conversationId,+ HarnessAttachment(superTabVoiceFileName, wav),+ );+ id = superTabMap(answer['attachment'])['id'] as String;+ } on SuperTabFailure catch (failure) {+ return (sent: false, notice: failure.message);+ } on TimeoutException {+ return (sent: false, notice: 'The upload stopped moving. Try again.');+ } on Object {+ return (sent: false, notice: superTabVoiceNoAnswer);+ }+ final read = await _readVoice(id, lang);+ final voice = read.voice;+ if (voice == null) return (sent: false, notice: read.refused);+ if (saving || hasPendingAction) {+ return (sent: false, notice: superTabVoiceBusy);+ }+ // Answered or not, the message is now the chat's: a lost answer or a+ // refusal shows it there with Retry, under the same receipt.+ await command({+ 'type': 'message.send',+ 'conversationId': conversationId,+ 'text': '',+ 'replyTo': root,+ 'recipientIds': const <String>[],+ 'attachmentIds': [id],+ if (oneBuddy) 'oneBuddy': true,+ });+ return (+ sent: true,+ notice: voice.transcribed+ ? null+ : voice.failure == 'limit'+ ? superTabVoiceOverLimit+ : superTabVoiceNotTranscribed,+ );+ }++ /// Has the server read the uploaded clip [attachmentId] as a voice message,+ /// once (backend store.ts readVoice). Answers the refusal to show when it+ /// could not.+ Future<({SuperTabVoice? voice, String? refused})> _readVoice(+ String attachmentId,+ String lang,+ ) async {+ final path =+ '/api/super-tabs/$tabId/attachments/$attachmentId/voice'+ '?lang=${Uri.encodeQueryComponent(lang)}';+ for (var ask = 1; ; ask++) {+ try {+ final answer = await request('POST', path, body: const {});+ final voice = SuperTabVoice.read(answer['voice']);+ return voice == null+ ? (voice: null, refused: superTabVoiceNeedsServer)+ : (voice: voice, refused: null);+ } on SuperTabFailure catch (failure) {+ if (failure.code == 'VOICE_TRANSCRIBING' && ask < _voiceAsks) {+ await Future<void>.delayed(superTabVoiceRetry);+ continue;+ }+ if (failure.statusCode == 404) {+ return (voice: null, refused: superTabVoiceNeedsServer);+ }+ return (voice: null, refused: failure.message);+ } on Object {+ return (voice: null, refused: superTabVoiceNoAnswer);+ }+ }+ }+}diff --git a/desktop/lib/super_tabs/voice_take.dart b/desktop/lib/super_tabs/voice_take.dartnew file mode 100644index 000000000..b0849985a--- /dev/null+++ b/desktop/lib/super_tabs/voice_take.dart@@ -0,0 +1,261 @@+import 'dart:async';++import 'package:clock/clock.dart';+import 'package:flutter/foundation.dart';++import 'voice_recorder.dart';++/// Whether a take went, and what to say about it either way.+typedef SuperTabVoicePosted = ({bool sent, String? notice});++/// Posts [clip] as a voice message in [conversationId], in the thread [root]+/// when there is one (voice_send.dart).+typedef SuperTabVoicePost = Future<SuperTabVoicePosted> Function(+ String conversationId,+ String? root,+ SuperTabVoiceClip clip,+);++/// Where a composer's voice message is.+enum SuperTabVoiceState {+ /// No take: the composer shows its row and mic.+ off,++ /// The microphone is asked for, or opening.+ starting,++ /// Recording.+ recording,++ /// Stopped and kept, with Send and X: at [SuperTabVoiceTake.maxTake], or as+ /// its chat or thread was left.+ held,++ /// Its audio is on its way.+ sending,+}++/// One composer's voice message, as the phone's `SwarmVoice` (Dee, 11-04:+/// "just send the full audio"). The mic records for a chat (and a thread's+/// [root]); the composer then shows the voice row in place of its own: X+/// throws the take away, Send posts it as audio ([post]), and the server+/// reads its words for agents. Nothing goes into the message box.+///+/// A take is never sent by itself. It stops and is kept, Send still there, at+/// [maxTake] and when its chat or thread is left ([hold]); it stays with the+/// chat it was recorded for.+class SuperTabVoiceTake extends ChangeNotifier {+ SuperTabVoiceTake({required this.recorder, required this.post});++ /// The longest take; it stops there with Send ready.+ static const maxTake = Duration(minutes: 10);++ static const nothingRecorded = "Couldn't record anything · try the mic again";+ static const couldNotStart = "The microphone couldn't start · try again";+ static const notSent = 'Not sent · try Send again';++ /// Makes the microphone on the first tap, which this owns and disposes: a+ /// recorder opens a platform channel, and a chat nobody talks in should not.+ final SuperTabVoiceRecorder Function() recorder;+ final SuperTabVoicePost post;++ SuperTabVoiceRecorder? _recorder;+ SuperTabVoiceState _state = SuperTabVoiceState.off;+ String? _conversationId, _root, _notice;+ SuperTabVoiceClip? _clip;+ bool _denied = false, _disposed = false;++ /// Bumped by everything that ends a take, so what an earlier one still+ /// awaits lands nowhere.+ int _turn = 0;+ Timer? _limit;+ Stopwatch? _clock;++ SuperTabVoiceState get state => _state;++ /// The chat and thread the take is for.+ String? get conversationId => _conversationId;+ String? get root => _root;++ /// What went wrong with the last take or send; null otherwise.+ String? get notice => _notice;++ /// The microphone was refused at the last tap: the composer says where to+ /// allow it.+ bool get denied => _denied;++ /// A take is under way or kept: the composer shows the voice row.+ bool get active => _state != SuperTabVoiceState.off;++ /// Whether the voice row belongs in the composer of [conversationId]'s+ /// [root] (null: the main chat).+ bool activeIn(String conversationId, String? root) =>+ active && _conversationId == conversationId && _root == root;++ /// Send can be pressed: a take is recording or kept.+ bool get canSend =>+ _state == SuperTabVoiceState.recording ||+ _state == SuperTabVoiceState.held && _clip != null;++ /// How long the take has run, or the kept take's length.+ Duration get length => _clip?.length ?? _clock?.elapsed ?? Duration.zero;++ /// How loud the microphone is, for the row's wave.+ ValueListenable<double> get level => _recorder?.level ?? _silence;+ static final ValueListenable<double> _silence = ValueNotifier(0);++ /// Starts a take for [conversationId], in the thread [root] when one is+ /// open. A take kept for another chat is thrown away first.+ void start({required String conversationId, String? root}) {+ if (_disposed || _state == SuperTabVoiceState.sending) return;+ if (_state != SuperTabVoiceState.off) discard();+ _conversationId = conversationId;+ _root = root;+ unawaited(_start());+ }++ /// Stops the take and keeps it, with Send and X: its chat or thread was+ /// left. A take still opening is called off.+ void hold() {+ if (_state == SuperTabVoiceState.starting) discard();+ if (_state == SuperTabVoiceState.recording) unawaited(_stop());+ }++ /// Throws the take away, recorded or kept, and sends nothing.+ void discard() {+ if (_disposed || _state == SuperTabVoiceState.sending) return;+ final recording =+ _state == SuperTabVoiceState.recording ||+ _state == SuperTabVoiceState.starting;+ _end();+ if (recording) unawaited(_recorder?.cancel());+ _notice = null;+ _set(SuperTabVoiceState.off);+ }++ /// Posts the take, stopping it first while it records.+ void send() {+ if (!canSend) return;+ unawaited(_send());+ }++ Future<void> _start() async {+ final turn = ++_turn;+ _notice = null;+ _set(SuperTabVoiceState.starting);+ final mic = _recorder ??= recorder();+ final bool allowed;+ try {+ allowed = await mic.allowed();+ } on Object {+ if (turn == _turn) _fail(couldNotStart);+ return;+ }+ if (turn != _turn) return;+ _denied = !allowed;+ if (!allowed) {+ _end();+ _set(SuperTabVoiceState.off);+ return;+ }+ try {+ await mic.start();+ } on Object {+ if (turn == _turn) _fail(couldNotStart);+ return;+ }+ // Called off while the microphone opened.+ if (turn != _turn) {+ unawaited(mic.cancel());+ return;+ }+ _clip = null;+ _clock = clock.stopwatch()..start();+ _limit = Timer(maxTake, hold);+ _set(SuperTabVoiceState.recording);+ }++ void _fail(String notice) {+ _end();+ _notice = notice;+ _set(SuperTabVoiceState.off);+ }++ /// Ends the recording and keeps it; true once there is a take to send.+ Future<bool> _stop() async {+ if (_state != SuperTabVoiceState.recording) return _clip != null;+ final turn = _turn;+ _limit?.cancel();+ _clock?.stop();+ // Held while the recorder finishes: no second stop, X or Send meanwhile.+ _set(SuperTabVoiceState.held);+ SuperTabVoiceClip? clip;+ try {+ clip = await _recorder!.stop();+ } on Object {+ clip = null;+ }+ if (turn != _turn || _disposed) return false;+ if (clip == null) {+ _fail(nothingRecorded);+ return false;+ }+ _clip = clip;+ notifyListeners();+ return true;+ }++ Future<void> _send() async {+ if (!await _stop()) return;+ final clip = _clip!, turn = _turn;+ final conversationId = _conversationId!, root = _root;+ _notice = null;+ _set(SuperTabVoiceState.sending);+ SuperTabVoicePosted posted;+ try {+ posted = await post(conversationId, root, clip);+ } on Object {+ // Whatever failed, the take stays with Send and X.+ posted = (sent: false, notice: notSent);+ }+ if (turn != _turn || _disposed) return;+ _notice = posted.notice;+ if (!posted.sent) {+ _set(SuperTabVoiceState.held);+ return;+ }+ _end();+ _set(SuperTabVoiceState.off);+ }++ void _end() {+ _turn++;+ _limit?.cancel();+ _limit = null;+ _clock = null;+ _clip = null;+ }++ void _set(SuperTabVoiceState state) {+ if (_disposed) return;+ _state = state;+ notifyListeners();+ }++ @override+ void dispose() {+ _disposed = true;+ final recording =+ _state == SuperTabVoiceState.recording ||+ _state == SuperTabVoiceState.starting;+ _end();+ final mic = _recorder;+ if (mic != null) {+ unawaited(() async {+ if (recording) await mic.cancel();+ await mic.dispose();+ }());+ }+ super.dispose();+ }+}diff --git a/desktop/lib/super_tabs/voice_wav.dart b/desktop/lib/super_tabs/voice_wav.dartnew file mode 100644index 000000000..314264109--- /dev/null+++ b/desktop/lib/super_tabs/voice_wav.dart@@ -0,0 +1,79 @@+/// The phone's WAV helpers (mobile/lib/phone/voice_wav.dart), for the+/// composer's mic: the server reads a voice message's length and words from+/// a PCM16 WAV (#2887). Kept in step with the phone's by hand.+library;++import 'dart:math' as math;+import 'dart:typed_data';++/// How loud a buffer of 16-bit little-endian PCM sounds, from 0 (silence) to 1+/// (near full scale) — what the waveform beside the mic draws.+///+/// RMS rather than [pcm16Peak]: one click would otherwise read as a shout. And+/// on a decibel scale, because that is how loudness is heard — linear RMS puts+/// ordinary speech in the bottom tenth of the range and the bars barely move.+/// A quiet room sits near −60 dBFS and a voice at the phone near −30 to −20,+/// so [_quietDb]…[_loudDb] is spread over 0…1.+double pcm16Level(Uint8List pcm) {+ final count = pcm.length ~/ 2;+ if (count == 0) return 0;+ final data = ByteData.sublistView(pcm);+ var sum = 0.0;+ for (var offset = 0; offset + 1 < pcm.length; offset += 2) {+ final sample = data.getInt16(offset, Endian.little);+ sum += sample * sample;+ }+ final rms = math.sqrt(sum / count);+ if (rms < 1) return 0;+ final db = 20 * math.log(rms / 32768) / math.ln10;+ return ((db - _quietDb) / (_loudDb - _quietDb)).clamp(0.0, 1.0);+}++const double _quietDb = -55;+const double _loudDb = -10;++/// The loudest sample in 16-bit little-endian PCM, as a magnitude.+int pcm16Peak(Uint8List pcm) {+ final data = ByteData.sublistView(pcm);+ var peak = 0;+ for (var offset = 0; offset + 1 < pcm.length; offset += 2) {+ final sample = data.getInt16(offset, Endian.little).abs();+ if (sample > peak) peak = sample;+ }+ return peak;+}++/// Wraps raw 16-bit little-endian PCM in a 44-byte WAV header.+///+/// A self-describing container rather than bare samples, and the backend+/// depends on it: `/api/voice/stt` forwards the file under its own+/// Content-Type with NO rate or encoding hints, so the header is the only+/// place the sample rate is stated. Headerless PCM would be read as if its+/// first 44 bytes were a header. The twin of `wav()` in the CLI's+/// `cable/cableHost.ts`, which does the same for the dial's recordings.+Uint8List wavFromPcm16(+ Uint8List pcm, {+ required int sampleRate,+ required int channels,+}) {+ const headerLength = 44;+ final blockAlign = channels * 2;+ final header = ByteData(headerLength)+ ..setUint32(0, 0x52494646) // "RIFF"+ ..setUint32(4, 36 + pcm.length, Endian.little)+ ..setUint32(8, 0x57415645) // "WAVE"+ ..setUint32(12, 0x666d7420) // "fmt "+ ..setUint32(16, 16, Endian.little) // fmt chunk size+ ..setUint16(20, 1, Endian.little) // PCM+ ..setUint16(22, channels, Endian.little)+ ..setUint32(24, sampleRate, Endian.little)+ ..setUint32(28, sampleRate * blockAlign, Endian.little)+ ..setUint16(32, blockAlign, Endian.little)+ ..setUint16(34, 16, Endian.little) // bits per sample+ ..setUint32(36, 0x64617461) // "data"+ ..setUint32(40, pcm.length, Endian.little);+ return (BytesBuilder(copy: false)+ ..add(header.buffer.asUint8List())+ ..add(pcm))+ .takeBytes();+}diff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dartindex c825c311e..11c045b95 100644--- a/desktop/lib/super_tabs/workspace.dart+++ b/desktop/lib/super_tabs/workspace.dart@@ -17,6 +17,7 @@ import 'sharing.dart';import 'swarm_switcher.dart' show PersonalSwarm;import 'terminal_unavailable.dart';import 'view.dart';+import 'voice_recorder.dart';/// Keeps the app's one native canvas alive in the group's middle area./// Switching chat/terminals never constructs a second terminal renderer.@@ -464,6 +465,36 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {setState(() {});}+ /// What a Waiting on you notice asked to open+ /// ([SuperTabController.openAgentTerminal]): the agent's terminal, focused,+ /// beside the chat it waits in, where its card's Open terminal can open it+ /// (#2951's rules); or a line saying why it can't (Huy, #2792).+ void _takeAgentTerminal(SuperTabController controller, String tabId) {+ final request = controller.agentTerminalRequest;+ if (!mounted || request == null || controller.snapshot == null) return;+ controller.agentTerminalRequest = null;+ final agent = controller.snapshot!.agent(request.agentId);+ if (agent == null) return;+ final groups = superTabAgentTerminalGroups(controller, agent.id);+ if (groups.isEmpty) {+ final reason = superTabOpenTerminalBlocked(controller, agent.id);+ if (reason != null) {+ ScaffoldMessenger.maybeOf(context)+ ?.showSnackBar(SnackBar(content: Text(reason)));+ }+ return;+ }+ bool waitsThere(SuperTabConversation group) =>+ group.assignment?['agentId'] == agent.id &&+ superTabWorkWaits(group.assignment?['status']);+ final group =+ groups.where((g) => g.id == request.conversationId).firstOrNull ??+ groups.where(waitsThere).firstOrNull ??+ groups.where((g) => g.id == controller.selectedId).firstOrNull ??+ groups.first;+ _focusAgent(controller, tabId, agent, group.id);+ }+Future<void> _chooseAgentGroup(SuperTabController controller,String tabId,@@ -536,6 +567,11 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {}});}+ if (controller.agentTerminalRequest != null) {+ WidgetsBinding.instance.addPostFrameCallback(+ (_) => _takeAgentTerminal(controller, tab.id),+ );+ }_syncTerminal(controller, tab.id);final agents = controller.terminalAgents(controller.selectedId);final local = _localPanes(controller);@@ -614,6 +650,8 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {SuperTabView(key: ValueKey('${controller.accountId}:$id'),controller: controller,+ // macOS and the web record; Linux and Windows draw no mic.+ voiceRecorder: superTabVoiceRecorder(),onInvite: () =>unawaited(showSuperTabPeople(context, controller)),onAddAgent: widget.onAddAgent,diff --git a/desktop/linux/flutter/generated_plugin_registrant.cc b/desktop/linux/flutter/generated_plugin_registrant.ccindex 81af9798c..1e3d22fb6 100644--- a/desktop/linux/flutter/generated_plugin_registrant.cc+++ b/desktop/linux/flutter/generated_plugin_registrant.cc@@ -8,6 +8,7 @@#include <desktop_drop/desktop_drop_plugin.h>#include <file_selector_linux/file_selector_plugin.h>+#include <record_linux/record_linux_plugin.h>#include <screen_retriever_linux/screen_retriever_linux_plugin.h>#include <url_launcher_linux/url_launcher_plugin.h>#include <webview_all_linux/webview_all_linux_plugin.h>@@ -20,6 +21,9 @@ void fl_register_plugins(FlPluginRegistry* registry) {g_autoptr(FlPluginRegistrar) file_selector_linux_registrar =fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin");file_selector_plugin_register_with_registrar(file_selector_linux_registrar);+ g_autoptr(FlPluginRegistrar) record_linux_registrar =+ fl_plugin_registry_get_registrar_for_plugin(registry, "RecordLinuxPlugin");+ record_linux_plugin_register_with_registrar(record_linux_registrar);g_autoptr(FlPluginRegistrar) screen_retriever_linux_registrar =fl_plugin_registry_get_registrar_for_plugin(registry, "ScreenRetrieverLinuxPlugin");screen_retriever_linux_plugin_register_with_registrar(screen_retriever_linux_registrar);diff --git a/desktop/linux/flutter/generated_plugins.cmake b/desktop/linux/flutter/generated_plugins.cmakeindex e60b8fdf4..e1780669c 100644--- a/desktop/linux/flutter/generated_plugins.cmake+++ b/desktop/linux/flutter/generated_plugins.cmake@@ -5,6 +5,7 @@list(APPEND FLUTTER_PLUGIN_LISTdesktop_dropfile_selector_linux+ record_linuxscreen_retriever_linuxurl_launcher_linuxwebview_all_linuxdiff --git a/desktop/macos/Flutter/GeneratedPluginRegistrant.swift b/desktop/macos/Flutter/GeneratedPluginRegistrant.swiftindex 21d01c51a..0c9bbb56d 100644--- a/desktop/macos/Flutter/GeneratedPluginRegistrant.swift+++ b/desktop/macos/Flutter/GeneratedPluginRegistrant.swift@@ -8,6 +8,7 @@ import Foundationimport desktop_dropimport file_selector_macosimport package_info_plus+import record_macosimport screen_retriever_macosimport url_launcher_macosimport video_player_avfoundation@@ -18,6 +19,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {DesktopDropPlugin.register(with: registry.registrar(forPlugin: "DesktopDropPlugin"))FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin"))FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin"))+ RecordMacOsPlugin.register(with: registry.registrar(forPlugin: "RecordMacOsPlugin"))ScreenRetrieverMacosPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverMacosPlugin"))UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))VideoPlayerPlugin.register(with: registry.registrar(forPlugin: "VideoPlayerPlugin"))diff --git a/desktop/macos/Runner/DebugProfile.entitlements b/desktop/macos/Runner/DebugProfile.entitlementsindex 5f4ca18c4..8f498fdd5 100644--- a/desktop/macos/Runner/DebugProfile.entitlements+++ b/desktop/macos/Runner/DebugProfile.entitlements@@ -2,6 +2,10 @@<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>+ <!-- The composer's mic records voice messages (#2665): the hardened runtime opens the+ microphone only with this. -->+ <key>com.apple.security.device.audio-input</key>+ <true/><key>com.apple.security.network.client</key><true/><key>com.apple.security.cs.allow-jit</key>diff --git a/desktop/macos/Runner/Info.plist b/desktop/macos/Runner/Info.plistindex 17a74764d..e6efb2341 100644--- a/desktop/macos/Runner/Info.plist+++ b/desktop/macos/Runner/Info.plist@@ -71,6 +71,8 @@</dict></dict></dict>+ <key>NSMicrophoneUsageDescription</key>+ <string>Harness records the voice messages you send in a Swarm chat.</string><key>NSLocalNetworkUsageDescription</key><string>Harness finds and connects to Autonomous robots on your local network.</string><key>NSBonjourServices</key>diff --git a/desktop/macos/Runner/Release.entitlements b/desktop/macos/Runner/Release.entitlementsindex 8090a1eee..b211567c8 100644--- a/desktop/macos/Runner/Release.entitlements+++ b/desktop/macos/Runner/Release.entitlements@@ -2,6 +2,10 @@<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>+ <!-- The composer's mic records voice messages (#2665): the hardened runtime opens the+ microphone only with this. -->+ <key>com.apple.security.device.audio-input</key>+ <true/><key>com.apple.security.network.client</key><true/><key>com.apple.security.network.server</key>diff --git a/desktop/pubspec.lock b/desktop/pubspec.lockindex b31c4f35d..f3f5f72ca 100644--- a/desktop/pubspec.lock+++ b/desktop/pubspec.lock@@ -551,6 +551,70 @@ packages:url: "https://pub.dev"source: hostedversion: "0.0.3"+ record:+ dependency: "direct main"+ description:+ name: record+ sha256: "7c4467dec63435c9206db183f8a4672cf8a62f5e5579e45803ceada8330756e7"+ url: "https://pub.dev"+ source: hosted+ version: "7.1.2"+ record_android:+ dependency: transitive+ description:+ name: record_android+ sha256: f5080279259c4ad769590f1c165762eaa4e414178adc2e2fab137103228e07ac+ url: "https://pub.dev"+ source: hosted+ version: "2.2.0"+ record_ios:+ dependency: transitive+ description:+ name: record_ios+ sha256: "21d189f49a598af4697dac4cc9e48389ac0a1fb3e916622b5504a58d9b96313e"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.1"+ record_linux:+ dependency: transitive+ description:+ name: record_linux+ sha256: "00c847ba25684572674dacfbd4bcabee6c5d9a1fa948778ff34091c71c19250f"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.3"+ record_macos:+ dependency: transitive+ description:+ name: record_macos+ sha256: ced7495abf3d683e8a7dbe8fc96df8ea5722837a26f922b7cb7c5de11661bb46+ url: "https://pub.dev"+ source: hosted+ version: "2.1.1"+ record_platform_interface:+ dependency: transitive+ description:+ name: record_platform_interface+ sha256: d94b37cadb8fe203e64b0e9893271c0b71b34f2550ee7fb0c6105d650e00c1f5+ url: "https://pub.dev"+ source: hosted+ version: "2.1.0"+ record_web:+ dependency: transitive+ description:+ name: record_web+ sha256: "7f6950be87abacb05cf77eb6ca200b60f2c2a6af5d50236b5f4baf53f92e755e"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.3"+ record_windows:+ dependency: transitive+ description:+ name: record_windows+ sha256: "8195489a47b5e8246985d6213ff65aae1b14e32a0ca45dc5f680e8d503296e1b"+ url: "https://pub.dev"+ source: hosted+ version: "2.3.0"riverpod:dependency: transitivedescription:diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yamlindex 6df180808..f94069f45 100644--- a/desktop/pubspec.yaml+++ b/desktop/pubspec.yaml@@ -115,6 +115,9 @@ dependencies:# It has no Linux or Windows implementation, so there the bubble's play# opens the file as a file chip does. See CLAUDE.md on what a plugin costs.video_player: ^2.14.0+ # The composer's mic on macOS and the web, as the phone records (#2665):+ # 16 kHz mono PCM16 streamed into a WAV. Linux and Windows draw no mic.+ record: ^7.1.1dev_dependencies:flutter_test:diff --git a/desktop/test/macos_microphone_permission_test.dart b/desktop/test/macos_microphone_permission_test.dartnew file mode 100644index 000000000..5f9d025eb--- /dev/null+++ b/desktop/test/macos_microphone_permission_test.dart@@ -0,0 +1,35 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';++/// #2665: the composer's mic records on macOS. The app runs with the hardened+/// runtime, which opens the microphone only with the audio-input entitlement,+/// and macOS asks the person only with a usage text (without one it kills the+/// app at the first take).+void main() {+ String plist(String path) => File(path).readAsStringSync();++ bool hasTrue(String plist, String key) => RegExp(+ '<key>${RegExp.escape(key)}</key>\\s*<true/>',+ ).hasMatch(plist);++ for (final file in [+ 'macos/Runner/Release.entitlements',+ 'macos/Runner/DebugProfile.entitlements',+ ]) {+ test('$file lets the app use the microphone', () {+ expect(+ hasTrue(plist(file), 'com.apple.security.device.audio-input'),+ isTrue,+ );+ });+ }++ test('Info.plist says why Harness asks for the microphone', () {+ final usage = RegExp(+ r'<key>NSMicrophoneUsageDescription</key>\s*<string>([^<]+)</string>',+ ).firstMatch(plist('macos/Runner/Info.plist'));+ expect(usage, isNotNull);+ expect(usage!.group(1), contains('voice message'));+ });+}diff --git a/desktop/test/notification_inbox_swarm_test.dart b/desktop/test/notification_inbox_swarm_test.dartnew file mode 100644index 000000000..344a3ca5f--- /dev/null+++ b/desktop/test/notification_inbox_swarm_test.dart@@ -0,0 +1,64 @@+// Huy (11-04, #2792): the bell's Notifications row for a Swarm agent waiting+// on him opened nothing, like its toast: it opens the agent's terminal+// beside the chat it waits in.+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/notify/alert_sounds.dart';+import 'package:harness/state/notification_inbox.dart';+import 'package:harness/super_tabs/workspace.dart';++import 'super_tab_launch_test.dart' show SuperTabLaunchFixture;+import 'super_tab_waiting_notice_test.dart' show waitingSwarm;++void main() {+ testWidgets('the bell\'s row for a Swarm agent opens its terminal beside '+ 'the task it waits in', (tester) async {+ await tester.binding.setSurfaceSize(const Size(1440, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final f = SuperTabLaunchFixture();+ final c = await waitingSwarm(f);+ final swarm = f.app.activeSwarmId;+ f.app.newSwarm();+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: ListenableBuilder(+ listenable: f.app,+ builder: (_, _) => SuperTabWorkspace(+ app: f.app,+ canvas: const SizedBox.expand(),+ onAddAgent: (_) {},+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ final opened = await openInboxNotification(+ f.app,+ const InboxNotification(+ machineId: 'm',+ agentId: 'native-nova',+ title: 'nova',+ detail: '',+ kind: AlertKind.needsYou,+ unavailable: null,+ ),+ );+ await tester.pumpAndSettle();+ expect(opened, isTrue);+ expect(f.app.activeSwarmId, swarm);+ expect(c.selectedId, 'task');+ expect(f.app.focusedPane?.agentId, 'native-nova');+ // Beside the task's chat, which stays on screen.+ expect(+ find.byKey(const ValueKey('super-message-composer')),+ findsOneWidget,+ );+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ });+}diff --git a/desktop/test/screenshots/personal-lead-card/after/personal-lead-card-empty-dark.png b/desktop/test/screenshots/personal-lead-card/after/personal-lead-card-empty-dark.pngnew file mode 100644index 000000000..e1a450bb6Binary files /dev/null and b/desktop/test/screenshots/personal-lead-card/after/personal-lead-card-empty-dark.png differdiff --git a/desktop/test/screenshots/personal-lead-card/after/personal-lead-card-empty-light.png b/desktop/test/screenshots/personal-lead-card/after/personal-lead-card-empty-light.pngnew file mode 100644index 000000000..4aef80debBinary files /dev/null and b/desktop/test/screenshots/personal-lead-card/after/personal-lead-card-empty-light.png differdiff --git a/desktop/test/screenshots/personal-lead-card/after/personal-lead-card-failed-dark.png b/desktop/test/screenshots/personal-lead-card/after/personal-lead-card-failed-dark.pngnew file mode 100644index 000000000..0bd6d8e35Binary files /dev/null and b/desktop/test/screenshots/personal-lead-card/after/personal-lead-card-failed-dark.png differdiff --git a/desktop/test/screenshots/personal-lead-card/after/personal-lead-card-failed-light.png b/desktop/test/screenshots/personal-lead-card/after/personal-lead-card-failed-light.pngnew file mode 100644index 000000000..1aeb3ed27Binary files /dev/null and b/desktop/test/screenshots/personal-lead-card/after/personal-lead-card-failed-light.png differdiff --git a/desktop/test/screenshots/personal-lead-card/before/personal-lead-card-empty-dark.png b/desktop/test/screenshots/personal-lead-card/before/personal-lead-card-empty-dark.pngnew file mode 100644index 000000000..3778e8667Binary files /dev/null and b/desktop/test/screenshots/personal-lead-card/before/personal-lead-card-empty-dark.png differdiff --git a/desktop/test/screenshots/personal-lead-card/before/personal-lead-card-empty-light.png b/desktop/test/screenshots/personal-lead-card/before/personal-lead-card-empty-light.pngnew file mode 100644index 000000000..4f88cca62Binary files /dev/null and b/desktop/test/screenshots/personal-lead-card/before/personal-lead-card-empty-light.png differdiff --git a/desktop/test/super_tab_composer_mic_test.dart b/desktop/test/super_tab_composer_mic_test.dartnew file mode 100644index 000000000..e51d54152--- /dev/null+++ b/desktop/test/super_tab_composer_mic_test.dart@@ -0,0 +1,196 @@+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/view.dart';+import 'package:harness/super_tabs/voice_row.dart';++import 'support/fake_voice_recorder.dart';+import 'support/voice_server.dart';++/// #2665: on macOS and the web the composer's mic records a voice message and+/// sends it as audio through #2887's path (people hear it, agents read its+/// words). While a take is under way its row takes the composer row's place:+/// X, the red dot and time, the wave, and Send. A refused microphone says so+/// in one line, with the way to allow it.+void main() {+ late VoiceServer server;+ late FakeVoiceRecorder mic;+ late SuperTabController c;++ Future<void> close(WidgetTester tester) async {+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ Future<SuperTabController> show(+ WidgetTester tester, {+ String chat = 'lead',+ String? thread,+ }) async {+ server = VoiceServer()..threads = true;+ server.append('The build fails on the second run.');+ server.append('Measure prod CPU', conversationId: 'offline');+ mic = FakeVoiceRecorder();+ c = server.controller();+ await c.refresh();+ await tester.binding.setSurfaceSize(const Size(1280, 720));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ voiceRecorder: () => mic,+ ),+ ),+ ),+ );+ await c.select(chat);+ await tester.pumpAndSettle();+ if (thread != null) {+ c.openThread(thread);+ await tester.pumpAndSettle();+ }+ return c;+ }++ group('the main chat', () {+ testWidgets('the mic records in place of the row and keeps the text', (+ tester,+ ) async {+ await show(tester);+ await tester.enterText(key('super-message-composer'), 'half a thought');+ await tester.tap(key('super-composer-mic'));+ await tester.pump();+ expect(key('super-voice-row'), findsOneWidget);+ expect(key('super-message-composer-actions'), findsNothing);+ expect(key('super-voice-dot'), findsOneWidget);+ expect(find.text('0:00'), findsOneWidget);+ await tester.pump(const Duration(seconds: 3));+ expect(find.text('0:03'), findsOneWidget);+ expect(+ tester+ .widget<TextField>(key('super-message-composer'))+ .controller!+ .text,+ 'half a thought',+ );+ await tester.tap(key('super-voice-discard'));+ await tester.pumpAndSettle();+ await close(tester);+ });++ testWidgets('X throws the take away and sends nothing', (tester) async {+ await show(tester);+ await tester.tap(key('super-composer-mic'));+ await tester.pump();+ await tester.tap(key('super-voice-discard'));+ await tester.pumpAndSettle();+ expect(mic.calls.last, 'cancel');+ expect(key('super-voice-row'), findsNothing);+ expect(key('super-message-composer-actions'), findsOneWidget);+ expect(server.uploads, isEmpty);+ expect(server.lastSend(), isNull);+ await close(tester);+ });++ testWidgets('Send posts one voice message to the chat', (tester) async {+ await show(tester);+ await tester.tap(key('super-composer-mic'));+ await tester.pump();+ await tester.tap(key('super-voice-send'));+ await tester.pumpAndSettle();+ expect(server.uploads.single['name'], 'Voice message.wav');+ final send = server.lastSend()!;+ expect(send['conversationId'], 'lead');+ expect(send['text'], '');+ expect(send['attachmentIds'], [server.uploads.single['id']]);+ expect(send['replyTo'], isNull);+ expect(key('super-voice-row'), findsNothing);+ expect(key('super-message-composer-actions'), findsOneWidget);+ await close(tester);+ });++ testWidgets('another chat holds the take for its own chat', (tester) async {+ await show(tester);+ await tester.tap(key('super-composer-mic'));+ await tester.pump();+ await c.select('offline');+ await tester.pumpAndSettle();+ expect(mic.calls.last, 'stop');+ expect(key('super-voice-row'), findsNothing);+ expect(key('super-message-composer-actions'), findsOneWidget);+ expect(server.lastSend(), isNull);+ await c.select('lead');+ await tester.pumpAndSettle();+ expect(key('super-voice-row'), findsOneWidget);+ await tester.tap(key('super-voice-send'));+ await tester.pumpAndSettle();+ expect(server.lastSend()!['conversationId'], 'lead');+ await close(tester);+ });++ testWidgets('a refused microphone says so, with System Settings', (+ tester,+ ) async {+ final opened = <Uri>[];+ final before = superTabOpenSettings;+ superTabOpenSettings = (url) async {+ opened.add(url);+ return true;+ };+ addTearDown(() => superTabOpenSettings = before);+ await show(tester);+ mic.allow = false;+ await tester.tap(key('super-composer-mic'));+ await tester.pumpAndSettle();+ expect(key('super-voice-row'), findsNothing);+ expect(key('super-voice-refused'), findsOneWidget);+ expect(+ find.textContaining("Harness can't use the microphone"),+ findsOneWidget,+ );+ await tester.tap(key('super-voice-settings'));+ expect(opened, [superTabMicrophoneSettings]);+ await close(tester);+ });+ });++ group('a thread', () {+ testWidgets("the thread's mic sends a reply to its root", (tester) async {+ await show(tester, thread: 'message-1');+ await tester.tap(key('super-thread-mic'));+ await tester.pump();+ expect(key('super-thread-voice-row'), findsOneWidget);+ // The main chat's composer keeps its own row.+ expect(key('super-voice-row'), findsNothing);+ await tester.tap(key('super-thread-voice-send'));+ await tester.pumpAndSettle();+ final send = server.lastSend()!;+ expect(send['conversationId'], 'lead');+ expect(send['replyTo'], 'message-1');+ expect(key('super-thread-voice-row'), findsNothing);+ await close(tester);+ });++ testWidgets('closing the thread holds its take', (tester) async {+ await show(tester, thread: 'message-1');+ await tester.tap(key('super-thread-mic'));+ await tester.pump();+ c.closeThread();+ await tester.pumpAndSettle();+ expect(mic.calls.last, 'stop');+ expect(server.lastSend(), isNull);+ await close(tester);+ });+ });+}diff --git a/desktop/test/super_tab_composer_padding_test.dart b/desktop/test/super_tab_composer_padding_test.dartindex 66c627dd1..ded507a14 100644--- a/desktop/test/super_tab_composer_padding_test.dart+++ b/desktop/test/super_tab_composer_padding_test.dart@@ -4,15 +4,10 @@ import 'package:harness/shared/theme/app_icons.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/state/workspace_chrome.dart';import 'package:harness/super_tabs/view.dart';-import 'package:harness/super_tabs/voice_recorder.dart';+import 'support/fake_voice_recorder.dart';import 'support/super_tab_fixture.dart';-class _Recorder implements SuperTabVoiceRecorder {- @override- Future<void> start({required String conversationId, String? root}) async {}-}-/// Huy, 11-04: the composer was too tight, its hint and its row of actions/// against the box's edge. As on the phone and in Slack, the text sits 12 below/// the top and 16 in from each side, the + and the arrow's glyphs keep those@@ -89,7 +84,7 @@ void main() {onAddAgent: (_) {},onOpenTerminal: (_) {},machineName: (_) => 'Mac Studio',- voiceRecorder: _Recorder(),+ voiceRecorder: FakeVoiceRecorder.new,),),),diff --git a/desktop/test/super_tab_composer_row_shots_test.dart b/desktop/test/super_tab_composer_row_shots_test.dartindex 6f67efac5..0f18455b9 100644--- a/desktop/test/super_tab_composer_row_shots_test.dart+++ b/desktop/test/super_tab_composer_row_shots_test.dart@@ -7,24 +7,20 @@ import 'package:flutter_test/flutter_test.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/state/workspace_chrome.dart';import 'package:harness/super_tabs/view.dart';-import 'package:harness/super_tabs/voice_recorder.dart';import 'box_render_preview_test.dart' show loadPreviewFonts;+import 'support/fake_voice_recorder.dart';import 'support/super_tab_fixture.dart';/// Set to a folder to write the PR's screenshots there.final shots = Platform.environment['SUPER_TAB_COMPOSER_ROW_SHOTS'];-/// A recorder for the mic's place only: no take is recorded.-class _Preview implements SuperTabVoiceRecorder {- @override- Future<void> start({required String conversationId, String? root}) async {}-}-/// The composer as the PR shows it (Huy and Scholes, 11-04): the reader's/// Buddy chat with New session on offer, a project chat's thread with Also-/// send, the mic's place once recording comes (`chat-mic`), and the web at a-/// phone's width (`web-phone`), each with a draft, in both appearances.+/// send, the mic (`chat-mic`), a voice message recording in the chat and in a+/// thread (`chat-recording`, `thread-recording`, #2665), a refused microphone+/// (`chat-refused`), and the web at a phone's width (`web-phone`), each with a+/// draft, in both appearances.void main() {setUpAll(() async {if (shots != null) await loadPreviewFonts();@@ -68,10 +64,21 @@ void main() {}for (final brightness in Brightness.values) {- for (final scene in ['chat', 'thread', 'chat-mic', 'web-phone']) {+ for (final scene in [+ 'chat',+ 'thread',+ 'chat-mic',+ 'chat-recording',+ 'thread-recording',+ 'chat-refused',+ 'web-phone',+ ]) {testWidgets('screenshot: $scene (${brightness.name})', (tester) async {final picture = GlobalKey();- final thread = scene == 'thread';+ final thread = scene.startsWith('thread');+ final mic = scene.startsWith('chat-') || scene == 'thread-recording'+ ? (FakeVoiceRecorder()..allow = scene != 'chat-refused')+ : null;final c = (thread ? projectThread() : buddyChat()).controller();addTearDown(c.dispose);await c.refresh();@@ -97,7 +104,7 @@ void main() {onAddAgent: (_) {},onOpenTerminal: (_) {},machineName: (_) => 'Mac Studio',- voiceRecorder: scene == 'chat-mic' ? _Preview() : null,+ voiceRecorder: mic == null ? null : () => mic,),),),@@ -118,6 +125,19 @@ void main() {thread ? 'Here is the trace.' : 'Can you check the release notes?',);await tester.pumpAndSettle();+ if (scene.endsWith('-recording') || scene == 'chat-refused') {+ await tester.tap(+ find.byKey(+ ValueKey(thread ? 'super-thread-mic' : 'super-composer-mic'),+ ),+ );+ // The wave keeps moving while it records: pumped, never settled.+ for (var i = 0; i < 14; i++) {+ await tester.pump(const Duration(seconds: 1));+ }+ mic?.level.value = .6;+ await tester.pump(const Duration(milliseconds: 700));+ }await tester.runAsync(() async {final boundary =diff --git a/desktop/test/super_tab_composer_row_test.dart b/desktop/test/super_tab_composer_row_test.dartindex defdc5852..900b92648 100644--- a/desktop/test/super_tab_composer_row_test.dart+++ b/desktop/test/super_tab_composer_row_test.dart@@ -5,19 +5,10 @@ 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';import 'package:harness/super_tabs/view.dart';-import 'package:harness/super_tabs/voice_recorder.dart';+import 'support/fake_voice_recorder.dart';import 'support/super_tab_fixture.dart';-/// The takes a mic started, as (conversation, thread root).-class _Recorder implements SuperTabVoiceRecorder {- final takes = <(String, String?)>[];-- @override- Future<void> start({required String conversationId, String? root}) async =>- takes.add((conversationId, root));-}-/// Huy and Scholes, 11-04: the Desktop and web composer is the phone's. One/// rounded box, the text on top and one row under it: + (attach), @ Tag, the/// New session chip, the mic and send. Also send is a small checkbox under a@@ -72,7 +63,7 @@ void main() {WidgetTester tester, {String chat = 'offline',String? thread,- SuperTabVoiceRecorder? recorder,+ FakeVoiceRecorder? recorder,}) async {final c = server().controller();addTearDown(c.dispose);@@ -89,7 +80,7 @@ void main() {onAddAgent: (_) {},onOpenTerminal: (_) {},machineName: (_) => 'Mac Studio',- voiceRecorder: recorder,+ voiceRecorder: recorder == null ? null : () => recorder,),),),@@ -179,7 +170,7 @@ void main() {testWidgets('puts the mic left of send, and a click starts a take for the ''chat', (tester) async {- final recorder = _Recorder();+ final recorder = FakeVoiceRecorder();await show(tester, recorder: recorder);final mic = tester.getRect(key('super-composer-mic'));expect(mic.right, lessThanOrEqualTo(tester.getRect(send()).left));@@ -189,7 +180,8 @@ void main() {);await tester.tap(key('super-composer-mic'));await tester.pump();- expect(recorder.takes, [('offline', null)]);+ expect(recorder.calls, ['allowed', 'start']);+ expect(key('super-voice-row'), findsOneWidget);// A take is never dictation: the box stays as it was.expect(tester@@ -222,7 +214,7 @@ void main() {testWidgets('Tab goes from the text to +, @ Tag, New session, the mic and ''send, in the row\'s order', (tester) async {- await show(tester, recorder: _Recorder());+ await show(tester, recorder: FakeVoiceRecorder());await tester.enterText(key('super-message-composer'), 'Ready');await tester.pump();expect(focusedIn(tester, key('super-message-composer')), isTrue);@@ -299,7 +291,7 @@ void main() {testWidgets('puts the mic left of send, and a click starts a take for the ''thread', (tester) async {- final recorder = _Recorder();+ final recorder = FakeVoiceRecorder();await show(tester, thread: 'message-3', recorder: recorder);expect(tester.getRect(key('super-thread-mic')).right,@@ -307,7 +299,8 @@ void main() {);await tester.tap(key('super-thread-mic'));await tester.pump();- expect(recorder.takes, [('offline', 'message-3')]);+ expect(recorder.calls, ['allowed', 'start']);+ expect(key('super-thread-voice-row'), findsOneWidget);});testWidgets('@ Tag types @ at the caret and opens the tag list', (diff --git a/desktop/test/super_tab_personal_lead_card_test.dart b/desktop/test/super_tab_personal_lead_card_test.dartnew file mode 100644index 000000000..63389627b--- /dev/null+++ b/desktop/test/super_tab_personal_lead_card_test.dart@@ -0,0 +1,381 @@+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/swarm.dart';+import 'package:harness/state/terminal_pane.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/personal_lead.dart';+import 'package:harness/super_tabs/personal_projects.dart';+import 'package:harness/super_tabs/swarm_switcher.dart';+import 'package:harness/super_tabs/workspace.dart';++import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;+import 'support/capture.dart';++// Huy, 11-04 (task #2815, a follow-up to #2633): in his Personal Swarm,+// # Harness Monitor had no Lead, and its empty chat said only "1 pane in this+// project · Discuss the plan with Product Manager · Show panes". A message+// there starts its Lead (#2633), but nothing said so. Now the empty chat+// offers the start itself, as a Buddy chat's start card does.++/// Set to a folder to write the PR's pictures of the empty chat.+final _shots = Platform.environment['PERSONAL_LEAD_CARD_SHOTS'];++var _paneIds = 9000;++/// The person's desk on this Mac: one tab, # Harness Monitor, with one pane,+/// in a checkout of the project's repo or, without [repo], a plain folder.+void _desk(SuperTabLaunchFixture f, {bool repo = true}) {+ f.app.machineStates['m']!.agents = [+ Agent(+ id: 'n1',+ name: 'Agent n1',+ engine: 'codex',+ terminalAvailable: true,+ project: AgentProject(+ name: 'harness-monitor',+ cwd: '/Users/huy/harness-monitor',+ root: repo ? '/Users/huy/harness-monitor' : null,+ remote: repo ? '[email protected]:huy/harness-monitor.git' : null,+ ),+ ),+ ];+ f.app.swarms.add(+ Swarm(id: 'desk', name: 'Harness Monitor')+ ..panes.add(TerminalPane(id: _paneIds++, machineId: 'm', agentId: 'n1')),+ );+}++/// The fixture's Swarm made the person's Personal one ([personal] false leaves+/// it a Team Swarm), its projects made for the desk, # Harness Monitor shown.+Future<(SuperTabController, String)> _swarm(+ SuperTabLaunchFixture f, {+ bool personal = true,+ String role = 'owner',+}) async {+ for (final state in f.app.machineStates.values) {+ state.localOnly = true;+ }+ f.connection.server.state+ ..['name'] = personal ? 'Personal' : 'Team'+ ..['ownerId'] = 'owner'+ ..['people'] = [+ {'id': 'owner', 'email': '[email protected]', 'role': role},+ if (!personal)+ {'id': 'peer', 'email': '[email protected]', 'role': 'collaborator'},+ ];+ if (personal) {+ await f.app.superTabs.storage.write('super_tab.personal.owner', tabId);+ }+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Personal');+ PersonalSwarm.of(f.app).id;+ for (var i = 0; i < 20; i++) {+ await Future<void>.microtask(() {});+ }+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ if (personal) await PersonalProjects.of(f.app).sync(c);+ // The desk's project; the Swarm's first one holds none of its panes.+ final chat = personal+ ? c.snapshot!.projects+ .firstWhere((p) => p.leadConversationId != 'lead')+ .leadConversationId+ : 'lead';+ c.select(chat);+ return (c, chat);+}++Future<void> _show(+ WidgetTester tester,+ SuperTabLaunchFixture f, {+ Brightness brightness = Brightness.light,+}) async {+ await tester.binding.setSurfaceSize(const Size(1280, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: ListenableBuilder(+ listenable: f.app,+ builder: (_, _) => SuperTabWorkspace(+ app: f.app,+ canvas: const Text('Native terminals'),+ onAddAgent: (_) {},+ ),+ ),+ ),+ ),+ );+ await _settle(tester);+}++Future<void> _settle(WidgetTester tester) async {+ for (var i = 0; i < 20; i++) {+ await tester.pump(const Duration(milliseconds: 20));+ }+}++Future<void> _close(+ WidgetTester tester,+ SuperTabLaunchFixture f,+ SuperTabController c,+) async {+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+}++Finder _key(String value) => find.byKey(ValueKey(value));+final _card = _key('super-lead-start');++List<Map> _claims(SuperTabLaunchFixture f) => [+ for (final post in f.connection.server.posts)+ if ((post['command'] as Map?)?['type'] == 'lead.claim')+ post['command'] as Map,+];++void main() {+ setUpAll(() => loadCaptureFonts(_shots));+ tearDown(() => PersonalLeadStarter.launchForTest = null);++ testWidgets('a Personal project with no Lead offers to start one, on this '+ 'Mac with Claude Code in the repo\'s folder, above Show panes', (+ tester,+ ) async {+ final f = SuperTabLaunchFixture();+ _desk(f);+ final (c, _) = await _swarm(f);+ await _show(tester, f);+ expect(_card, findsOneWidget);+ expect(+ find.descendant(+ of: _card,+ matching: find.text('This project has no Lead yet'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: _key('super-lead-start-machine'),+ matching: find.text('Test host'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: _key('super-lead-start-engine'),+ matching: find.text('Claude Code'),+ ),+ findsOneWidget,+ );+ expect(+ tester.widget<Text>(_key('super-lead-start-folder')).data,+ 'Folder: /Users/huy/harness-monitor',+ );+ expect(find.widgetWithText(FilledButton, 'Start Lead'), findsOneWidget);+ // Show panes stays, under the card.+ final panes = _key('super-project-show-panes');+ expect(panes, findsOneWidget);+ expect(+ tester.getRect(panes).top,+ greaterThan(tester.getRect(_card).bottom),+ );+ await _close(tester, f, c);+ });++ testWidgets('with no repo, the card says the Lead starts in a new folder '+ 'of the Harness projects folder', (tester) async {+ final f = SuperTabLaunchFixture();+ _desk(f, repo: false);+ final (c, _) = await _swarm(f);+ final plans = <PersonalLeadPlan>[];+ PersonalLeadStarter.launchForTest = (_, _, plan) async => plans.add(plan);+ await _show(tester, f);+ expect(+ tester.widget<Text>(_key('super-lead-start-folder')).data,+ 'A new folder in your Harness projects folder',+ );+ await tester.tap(find.widgetWithText(FilledButton, 'Start Lead'));+ await _settle(tester);+ expect(plans.single.folder, isNull);+ await _close(tester, f, c);+ });++ testWidgets('Start Lead starts one Lead where the card says, however often '+ 'it is pressed', (tester) async {+ final f = SuperTabLaunchFixture();+ _desk(f);+ final (c, chat) = await _swarm(f);+ final plans = <PersonalLeadPlan>[];+ PersonalLeadStarter.launchForTest = (_, id, plan) async {+ expect(id, chat);+ plans.add(plan);+ };+ await _show(tester, f);+ final start = find.widgetWithText(FilledButton, 'Start Lead');+ await tester.tap(start);+ await tester.tap(start, warnIfMissed: false);+ await _settle(tester);+ expect(_claims(f), hasLength(1));+ expect(plans, hasLength(1));+ expect(plans.single.machineId, 'm');+ expect(plans.single.engine, 'claude');+ expect(plans.single.folder, '/Users/huy/harness-monitor');+ await _close(tester, f, c);+ });++ testWidgets('the engine picked on the card is the one the Lead starts with', (+ tester,+ ) async {+ final f = SuperTabLaunchFixture();+ _desk(f);+ final (c, _) = await _swarm(f);+ final plans = <PersonalLeadPlan>[];+ PersonalLeadStarter.launchForTest = (_, _, plan) async => plans.add(plan);+ await _show(tester, f);+ await tester.tap(_key('super-lead-start-engine'));+ await _settle(tester);+ await tester.tap(find.text('Codex').last);+ await _settle(tester);+ await tester.tap(find.widgetWithText(FilledButton, 'Start Lead'));+ await _settle(tester);+ expect(plans.single.engine, 'codex');+ await _close(tester, f, c);+ });++ testWidgets('a project with a Lead shows no card', (tester) async {+ final f = SuperTabLaunchFixture();+ _desk(f);+ final (c, chat) = await _swarm(f);+ final state = f.connection.server.state;+ final project = (state['projects'] as List).cast<Map>().firstWhere(+ (p) => p['leadConversationId'] == chat,+ );+ (state['agents'] as List).add({+ 'id': 'monitor-lead',+ 'name': 'Lead',+ 'machineId': 'm',+ 'harnessId': 'h-lead',+ 'contributorId': 'owner',+ 'projectId': project['id'],+ 'configuration': {'engine': 'claude'},+ });+ project['leadId'] = 'monitor-lead';+ (state['conversations'] as List).cast<Map>().firstWhere(+ (g) => g['id'] == chat,+ )+ ..['leadId'] = 'monitor-lead'+ ..['agentIds'] = ['monitor-lead'];+ await c.refresh();+ await _show(tester, f);+ expect(c.snapshot!.leadOf(project['id'] as String), isNotNull);+ expect(_card, findsNothing);+ expect(find.text('1 pane in this project'), findsOneWidget);+ await _close(tester, f, c);+ });++ testWidgets('with none of the person\'s computers online, the card says '+ 'why and offers no Start Lead', (tester) async {+ final f = SuperTabLaunchFixture();+ _desk(f);+ final (c, _) = await _swarm(f);+ f.app.machineStates['m']!.nodeOnline = false;+ await _show(tester, f);+ expect(+ tester.widget<Text>(_key('super-lead-start-unavailable')).data,+ 'Can’t start a Lead: none of your computers is online',+ );+ expect(find.widgetWithText(FilledButton, 'Start Lead'), findsNothing);+ await _close(tester, f, c);+ });++ testWidgets('a reader who can\'t write sees no card', (tester) async {+ final f = SuperTabLaunchFixture();+ _desk(f);+ final (c, _) = await _swarm(f, role: 'viewer');+ await _show(tester, f);+ expect(c.canWrite, isFalse);+ expect(find.text('1 pane in this project'), findsOneWidget);+ expect(_card, findsNothing);+ await _close(tester, f, c);+ });++ testWidgets('a Team Swarm shows no card', (tester) async {+ final f = SuperTabLaunchFixture();+ _desk(f);+ final state = f.connection.server.state;+ (state['conversations'] as List).cast<Map>().first['leadId'] = null;+ final (c, _) = await _swarm(f, personal: false);+ await _show(tester, f);+ expect(_card, findsNothing);+ await _close(tester, f, c);+ });++ testWidgets('a failed start says why on the card, and Start Lead tries '+ 'again', (tester) async {+ final f = SuperTabLaunchFixture();+ _desk(f);+ final (c, _) = await _swarm(f);+ var calls = 0;+ PersonalLeadStarter.launchForTest = (_, _, _) async {+ calls++;+ if (calls == 1) {+ throw const SuperTabFailure(+ 'CREATE_FAILED',+ 'Claude Code isn’t signed in on Test host.',+ );+ }+ };+ await _show(tester, f);+ await tester.tap(find.widgetWithText(FilledButton, 'Start Lead'));+ await _settle(tester);+ expect(+ find.descendant(+ of: _card,+ matching: find.text(+ 'Couldn’t start a Lead: Claude Code isn’t signed in on Test host',+ ),+ ),+ findsOneWidget,+ );+ await tester.tap(find.widgetWithText(FilledButton, 'Start Lead'));+ await _settle(tester);+ expect(calls, 2);+ await _close(tester, f, c);+ });++ for (final brightness in Brightness.values) {+ for (final failed in [false, true]) {+ final name =+ 'personal-lead-card-${failed ? 'failed' : 'empty'}-'+ '${brightness.name}';+ testWidgets(name, (tester) async {+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ final f = SuperTabLaunchFixture();+ _desk(f);+ final (c, chat) = await _swarm(f);+ await _show(tester, f, brightness: brightness);+ if (failed) {+ PersonalLeadStarter.of(f.app).setStatusForTest(+ c,+ chat,+ const PersonalLeadStatus.failed(+ 'Claude Code isn’t signed in on Test host',+ ),+ );+ await _settle(tester);+ }+ await captureWindow(tester, _shots, name);+ await _close(tester, f, c);+ }, skip: _shots == null);+ }+ }+}diff --git a/desktop/test/super_tab_personal_lead_test.dart b/desktop/test/super_tab_personal_lead_test.dartindex 3b2dbed85..fdf229241 100644--- a/desktop/test/super_tab_personal_lead_test.dart+++ b/desktop/test/super_tab_personal_lead_test.dart@@ -183,6 +183,22 @@ void main() {expect(starter.statusOf(c, games)?.failed, isFalse);});+ // Task #2815: the empty chat's Start a Lead card picks them.+ test('a start the card asked for uses its machine and engine', () async {+ final f = SuperTabLaunchFixture();+ _desk(f, remote: 'https://github.com/huy/games', cwd: '/Users/huy/games');+ final c = await _swarm(f);+ final games = _games(c);+ final starter = PersonalLeadStarter.of(f.app);+ expect(+ [for (final m in starter.machinesFor(c)) m.machine.machineId],+ ['m'],+ );+ await starter.start(c, games, machineId: 'm', engine: 'codex');+ expect(_create(f)['engine'], 'codex');+ expect(_create(f)['cwd'], '/Users/huy/games');+ });+test('a Team Swarm starts no Lead', () async {final f = SuperTabLaunchFixture();_desk(f, remote: 'https://github.com/huy/games', cwd: '/Users/huy/games');diff --git a/desktop/test/super_tab_teammate_terminal_test.dart b/desktop/test/super_tab_teammate_terminal_test.dartindex d17b045dd..61731fbdb 100644--- a/desktop/test/super_tab_teammate_terminal_test.dart+++ b/desktop/test/super_tab_teammate_terminal_test.dart@@ -446,7 +446,18 @@ void main() {expect(api.reads, greaterThanOrEqualTo(9));expect(tester.state(find.byType(SharedHarnessPanel)), same(panel));expect(f.app.panes.single, same(pane));- expect(find.text('Retry'), findsNothing);+ // No Retry where the terminal is; its chat beside it, in the right pane+ // (#2792), answers for its own connection.+ expect(+ find.text('Retry').evaluate().length,+ find+ .descendant(+ of: find.byKey(const ValueKey('super-right-pane')),+ matching: find.text('Retry'),+ )+ .evaluate()+ .length,+ );await _close(tester, f, c);},);diff --git a/desktop/test/super_tab_thread_tag_bar_shots_test.dart b/desktop/test/super_tab_thread_tag_bar_shots_test.dartnew file mode 100644index 000000000..640dcb9a4--- /dev/null+++ b/desktop/test/super_tab_thread_tag_bar_shots_test.dart@@ -0,0 +1,122 @@+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/attention.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/capture.dart';+import 'support/super_tab_fixture.dart';++/// Set to a folder to write the PR's screenshots there.+final shots = Platform.environment['SUPER_TAB_THREAD_TAG_SHOTS'];++const _lead = {'kind': 'agent', 'id': 'lead-agent', 'name': 'River'};+const _peer = {'kind': 'person', 'id': 'peer', 'name': '[email protected]'};++/// A chat with tags of the reader in two threads: its top row, then Open at+/// the oldest reply, lit (#2814).+void main() {+ setUpAll(() => loadCaptureFonts(shots));++ for (final brightness in Brightness.values) {+ testWidgets('screenshots for review (${brightness.name})', (tester) async {+ final server = ConversationServer()..threads = true;+ (server.state['people'] as List).add({+ 'id': 'peer',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ void say(String text, Map<String, Object> author, {String? root}) {+ server.append(text);+ server.messages.last['author'] = author;+ if (root != null) {+ server.messages.last+ ..['thread'] = root+ ..['replyTo'] = root;+ }+ }++ say('Build the import fix for compressed uploads.', _lead);+ say(+ 'On it: the upload keeps its gzip header now.',+ _peer,+ root: 'message-1',+ );+ say(+ '@owner can you try the import with your archive?',+ _peer,+ root: 'message-1',+ );+ say('Release notes for 1.4.2 are up.', _lead);+ say('The phone fixture cleanup race is fixed.', _lead);+ say(+ '@owner the race is in your screen too, please look.',+ _peer,+ root: 'message-5',+ );+ // The server counts a tagged person among a thread's people.+ for (final m in server.messages) {+ if ((m['text'] as String).startsWith('@owner')) {+ m['mentions'] = ['owner'];+ }+ }+ server.tag('message-3', threadId: 'message-1', messageSequence: 3);+ server.tag('message-6', threadId: 'message-5', messageSequence: 6);+ server.followedThreads = {+ 'unread': [+ for (final (root, last, fresh) in [+ ('message-1', 3, 2),+ ('message-5', 6, 1),+ ])+ {+ 'conversationId': 'lead',+ 'rootId': root,+ 'root': {'id': root, 'sequence': 1, 'author': _lead, 'text': ''},+ 'lastReplySequence': last,+ 'lastReplier': _peer,+ 'unreadReplies': fresh,+ 'follow': null,+ },+ ],+ 'read': <Object>[],+ 'more': false,+ };+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ await tester.binding.setSurfaceSize(const Size(1280, 720));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ final bar = find.byKey(const ValueKey('super-thread-tag-bar'));+ expect(find.text('2 new replies mention you · Open'), findsOneWidget);+ await captureWindow(tester, shots, 'thread-tag-bar-${brightness.name}');++ await tester.tap(bar);+ await tester.pump();+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 300));+ expect(c.openedThread?.root, 'message-1');+ await captureWindow(tester, shots, 'thread-tag-open-${brightness.name}');+ await tester.pump(SuperTabAttention.quietGap);+ await tester.pumpAndSettle();+ });+ }+}diff --git a/desktop/test/super_tab_thread_tag_bar_test.dart b/desktop/test/super_tab_thread_tag_bar_test.dartnew file mode 100644index 000000000..f97cd3a0a--- /dev/null+++ b/desktop/test/super_tab_thread_tag_bar_test.dart@@ -0,0 +1,250 @@+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/attention.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/message_row.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';++/// A tag of the reader inside a thread, when they open its chat: the top of+/// the chat names it and opens the thread at the reply (Lê Lộc, #2814).+void main() {+ Future<SuperTabController> show(+ WidgetTester tester,+ ConversationServer server, {+ Brightness brightness = Brightness.dark,+ }) async {+ await tester.binding.setSurfaceSize(const Size(1400, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final c = server.controller();+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ return c;+ }++ const peer = {'kind': 'person', 'id': 'peer', 'name': '[email protected]'};++ /// [roots] top-level messages in the lead chat, each with one reply from+ /// a teammate that lives only in its thread: message-1 (root) and+ /// message-2 (its reply), message-3 and message-4, and so on.+ ConversationServer threads(int roots) {+ final server = ConversationServer()..threads = true;+ (server.state['people'] as List).add({+ 'id': 'peer',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ for (var i = 0; i < roots; i++) {+ server.append('Topic ${i + 1}');+ final root = server.messages.last['id'] as String;+ server.append('Reply to topic ${i + 1}, @owner please look');+ server.messages.last+ ..['thread'] = root+ ..['replyTo'] = root+ ..['author'] = peer;+ }+ return server;+ }++ /// The reader is tagged in [reply], a reply only in [root]'s thread.+ void tagIn(ConversationServer server, String reply, String root) {+ final sequence = server.messages.firstWhere(+ (m) => m['id'] == reply,+ )['sequence'];+ server.tag(reply, threadId: root, messageSequence: sequence as int);+ }++ /// Lets Activity's next re-read run out, so no timer outlives the test.+ Future<void> settle(WidgetTester tester) async {+ await tester.pump(SuperTabAttention.quietGap);+ await tester.pumpAndSettle();+ }++ Finder bar() => find.byKey(const ValueKey('super-thread-tag-bar'));+ Finder panel() => find.byKey(const ValueKey('super-thread-panel'));+ Finder line(String root) => find.byKey(ValueKey('super-thread-line-$root'));++ /// Whether [text]'s row in the thread panel is lit.+ bool litInPanel(WidgetTester tester, String text) {+ final highlight = find.ancestor(+ of: find.descendant(of: panel(), matching: find.text(text)),+ matching: find.byType(SuperTabMessageHighlight),+ );+ return tester+ .widgetList<SuperTabMessageHighlight>(highlight)+ .any((h) => h.on);+ }++ group('the thread tags of a chat', () {+ testWidgets('list oldest first, and leave out read ones, main-stream '+ 'tags and other chats', (tester) async {+ final server = threads(2);+ tagIn(server, 'message-4', 'message-3');+ tagIn(server, 'message-2', 'message-1');+ server.tag('message-1', messageSequence: 1);+ final c = await show(tester, server);+ final attention = SuperTabAttention.of(c);+ expect(attention.threadTagsIn('lead').map((m) => m.messageId), [+ 'message-2',+ 'message-4',+ ]);+ c.markThreadRead('lead', 'message-1', 2);+ await tester.pumpAndSettle();+ expect(attention.threadTagsIn('lead').map((m) => m.messageId), [+ 'message-4',+ ]);+ expect(attention.threadTagsIn('other'), isEmpty);+ await settle(tester);+ });+ });++ group('the chat names a thread tag at its top', () {+ testWidgets('1 new reply mentions you · Open opens the thread at the '+ 'reply, lit; then the row and the red number go', (tester) async {+ final server = threads(1);+ server.append('Later news in the chat.');+ tagIn(server, 'message-2', 'message-1');+ final c = await show(tester, server);+ final attention = SuperTabAttention.of(c);+ expect(attention.mentionsIn('lead'), 1);+ expect(+ find.descendant(+ of: bar(),+ matching: find.text('1 new reply mentions you · Open'),+ ),+ findsOneWidget,+ );+ expect(panel(), findsNothing);++ await tester.tap(bar());+ await tester.pump();+ expect(c.openedThread?.root, 'message-1');+ await tester.pump();+ await tester.pump();+ expect(panel(), findsOneWidget);+ expect(litInPanel(tester, 'Reply to topic 1, @owner please look'), true);+ await tester.pumpAndSettle();+ expect(bar(), findsNothing);+ expect(attention.mentionsIn('lead'), 0);+ await settle(tester);+ });++ testWidgets('two threads: Open goes to the oldest first, then the next', (+ tester,+ ) async {+ final server = threads(2);+ tagIn(server, 'message-4', 'message-3');+ tagIn(server, 'message-2', 'message-1');+ final c = await show(tester, server);+ expect(+ find.descendant(+ of: bar(),+ matching: find.text('2 new replies mention you · Open'),+ ),+ findsOneWidget,+ );+ await tester.tap(bar());+ await tester.pumpAndSettle();+ expect(c.openedThread?.root, 'message-1');+ expect(+ find.descendant(+ of: bar(),+ matching: find.text('1 new reply mentions you · Open'),+ ),+ findsOneWidget,+ );+ await tester.tap(bar());+ await tester.pumpAndSettle();+ expect(c.openedThread?.root, 'message-3');+ expect(bar(), findsNothing);+ await settle(tester);+ });++ testWidgets('a thread read from the Threads view clears the row', (+ tester,+ ) async {+ final server = threads(1);+ tagIn(server, 'message-2', 'message-1');+ final c = await show(tester, server);+ expect(bar(), findsOneWidget);+ c.markThreadRead('lead', 'message-1', 2);+ await tester.pumpAndSettle();+ expect(bar(), findsNothing);+ await settle(tester);+ });++ testWidgets('a tag in the main chat adds no thread row', (tester) async {+ final server = threads(1);+ server.append('A note for @owner in the chat.');+ server.messages.last['author'] = peer;+ server.tag('message-3', messageSequence: 3);+ await show(tester, server);+ expect(bar(), findsNothing);+ await settle(tester);+ });+ });++ group("a thread's row in the chat", () {+ testWidgets('says how many of its replies are new, until read', (+ tester,+ ) async {+ final server = threads(1);+ server.append('Second reply, @owner');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-2'+ ..['author'] = peer;+ tagIn(server, 'message-3', 'message-1');+ server.followedThreads = {+ 'unread': [+ {+ 'conversationId': 'lead',+ 'rootId': 'message-1',+ 'root': {+ 'id': 'message-1',+ 'sequence': 1,+ 'author': {'kind': 'person', 'id': 'owner', 'name': 'owner'},+ 'text': 'Topic 1',+ 'createdAt': '2026-11-04T08:00:00Z',+ },+ 'lastReplyAt': '2026-11-04T08:10:00Z',+ 'lastReplySequence': 3,+ 'lastReplier': peer,+ 'unreadReplies': 2,+ 'replies': 2,+ 'follow': null,+ },+ ],+ 'read': <Object>[],+ 'more': false,+ };+ final c = await show(tester, server);+ final fresh = find.descendant(+ of: line('message-1'),+ matching: find.text('2 new'),+ );+ expect(fresh, findsOneWidget);+ c.markThreadRead('lead', 'message-1', 3);+ await tester.pumpAndSettle();+ expect(fresh, findsNothing);+ await settle(tester);+ });+ });+}diff --git a/desktop/test/super_tab_view_test.dart b/desktop/test/super_tab_view_test.dartindex e5ab66b9d..3d8909764 100644--- a/desktop/test/super_tab_view_test.dart+++ b/desktop/test/super_tab_view_test.dart@@ -637,7 +637,8 @@ void main() {);testWidgets(- 'native terminals fill the middle, preserve both sidebars, and return to chat',+ 'native terminals fill the middle with their chat beside them, preserve '+ 'both sidebars, and return to chat',(tester) async {await tester.binding.setSurfaceSize(const Size(1100, 700));addTearDown(() => tester.binding.setSurfaceSize(null));@@ -662,9 +663,17 @@ void main() {);await tester.pumpAndSettle();expect(find.text('Native terminal fixture'), findsOneWidget);- expect(find.text('Review this result.'), findsNothing);+ // Wide, the chat stays beside the terminal (Huy, #2792), in the right+ // pane where a thread sits.+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('super-right-pane')),+ matching: find.text('Review this result.'),+ ),+ findsOneWidget,+ );expect(find.byKey(const ValueKey('super-group-lead')), findsOneWidget);- // The right column stays closed at rest beside the terminals too.+ // Members stays closed at rest beside the terminals too.expect(find.byType(SuperTabRoster), findsNothing);expect(tester@@ -685,6 +694,8 @@ void main() {await tester.binding.setSurfaceSize(const Size(800, 700));await tester.pumpAndSettle();expect(find.text('Native terminal fixture'), findsOneWidget);+ // Narrow, one at a time: the terminal holds the middle alone.+ expect(find.text('Review this result.'), findsNothing);await tester.tap(find.byTooltip('Chat'));expect(closed, isTrue);expect(diff --git a/desktop/test/super_tab_voice_send_test.dart b/desktop/test/super_tab_voice_send_test.dartnew file mode 100644index 000000000..61dc7e488--- /dev/null+++ b/desktop/test/super_tab_voice_send_test.dart@@ -0,0 +1,137 @@+// Sending a take from the Desktop and web composer's mic (#2665) through+// #2887's path, as the phone's sendVoice does: the clip goes up as an+// ordinary file, the server reads it once as a voice message, and the send+// names that file with no text (its words become the text on the server).+import 'dart:typed_data';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/voice_send.dart';++import 'support/voice_server.dart';++final _wav = Uint8List.fromList(List.filled(44 + 3200, 1));++void main() {+ late VoiceServer server;+ late SuperTabController c;++ setUp(() async {+ server = VoiceServer()..append('Hello');+ c = server.controller();+ await c.refresh();+ });++ tearDown(() async {+ await c.flush();+ c.dispose();+ });++ Map<String, dynamic>? sent() => server.lastSend();++ test(+ 'a take goes up as a voice file, is read once, and is sent alone',+ () async {+ final posted = await c.sendVoice(+ conversationId: 'lead',+ root: null,+ wav: _wav,+ lang: 'vi',+ );+ expect(posted.sent, isTrue);+ expect(posted.notice, isNull);+ expect(server.uploads.single['name'], 'Voice message.wav');+ expect(server.uploads.single['file'], _wav);+ final id = server.uploads.single['id'];+ expect(server.voiceReads, [+ '/api/super-tabs/tab/attachments/$id/voice?lang=vi',+ ]);+ final send = sent()!;+ expect(send['conversationId'], 'lead');+ expect(send['text'], '');+ expect(send['attachmentIds'], [id]);+ expect(send['replyTo'], isNull);+ },+ );++ test("a thread's take is a reply to its root", () async {+ await c.sendVoice(+ conversationId: 'lead',+ root: 'message-1',+ wav: _wav,+ lang: 'en',+ );+ expect(sent()!['replyTo'], 'message-1');+ });++ test('a clip still being read is asked about again', () async {+ server.voiceAnswers = [+ const SuperTabFailure(+ 'VOICE_TRANSCRIBING',+ 'Still reading.',+ statusCode: 409,+ ),+ ...server.voiceAnswers,+ ];+ superTabVoiceRetry = Duration.zero;+ final posted = await c.sendVoice(+ conversationId: 'lead',+ root: null,+ wav: _wav,+ lang: 'en',+ );+ expect(posted.sent, isTrue);+ expect(server.voiceReads, hasLength(2));+ });++ test('a server from before voice messages keeps the take', () async {+ server.voiceAnswers = [+ const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404),+ ];+ final posted = await c.sendVoice(+ conversationId: 'lead',+ root: null,+ wav: _wav,+ lang: 'en',+ );+ expect(posted.sent, isFalse);+ expect(posted.notice, superTabVoiceNeedsServer);+ expect(sent(), isNull);+ });++ test('over the daily voice limit it sends and says so', () async {+ server.voiceAnswers = [+ {+ 'voice': {+ 'durationMs': 1000,+ 'waveform': List.filled(48, 3),+ 'transcribed': false,+ 'failure': 'limit',+ },+ },+ ];+ final posted = await c.sendVoice(+ conversationId: 'lead',+ root: null,+ wav: _wav,+ lang: 'en',+ );+ expect(posted.sent, isTrue);+ expect(posted.notice, superTabVoiceOverLimit);+ expect(sent(), isNotNull);+ });++ test('a refused upload keeps the take and says why', () async {+ server.failUpload = 'Voice message.wav';+ final posted = await c.sendVoice(+ conversationId: 'lead',+ root: null,+ wav: _wav,+ lang: 'en',+ );+ expect(posted.sent, isFalse);+ expect(posted.notice, 'The file is too large.');+ expect(server.voiceReads, isEmpty);+ expect(sent(), isNull);+ });+}diff --git a/desktop/test/super_tab_voice_take_test.dart b/desktop/test/super_tab_voice_take_test.dartnew file mode 100644index 000000000..a5b01850f--- /dev/null+++ b/desktop/test/super_tab_voice_take_test.dart@@ -0,0 +1,189 @@+import 'package:flutter/foundation.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/voice_recorder.dart';+import 'package:harness/super_tabs/voice_take.dart';+import 'package:harness/super_tabs/voice_wav.dart';++import 'support/fake_voice_recorder.dart';++void main() {+ group('a take', () {+ late FakeVoiceRecorder mic;+ late List<({String conversationId, String? root, Uint8List wav})> posted;+ late SuperTabVoicePosted answer;+ late SuperTabVoiceTake take;++ setUp(() {+ mic = FakeVoiceRecorder();+ posted = [];+ answer = (sent: true, notice: null);+ take = SuperTabVoiceTake(+ recorder: () => mic,+ post: (conversationId, root, clip) async {+ posted.add((+ conversationId: conversationId,+ root: root,+ wav: clip.wav,+ ));+ return answer;+ },+ );+ });++ tearDown(() => take.dispose());++ testWidgets('starts recording for its chat and thread', (tester) async {+ take.start(conversationId: 'c1', root: 'r1');+ await tester.pump();+ expect(take.state, SuperTabVoiceState.recording);+ expect(take.conversationId, 'c1');+ expect(take.root, 'r1');+ expect(mic.calls, ['allowed', 'start']);+ take.discard();+ });++ testWidgets('send stops the take and posts its clip once', (tester) async {+ take.start(conversationId: 'c1');+ await tester.pump();+ take.send();+ await tester.pump();+ expect(mic.calls, ['allowed', 'start', 'stop']);+ expect(posted, hasLength(1));+ expect(posted.single.conversationId, 'c1');+ expect(posted.single.root, isNull);+ expect(posted.single.wav, mic.clip.wav);+ expect(take.state, SuperTabVoiceState.off);+ take.send();+ await tester.pump();+ expect(posted, hasLength(1));+ });++ testWidgets('discard cancels the recording and posts nothing', (+ tester,+ ) async {+ take.start(conversationId: 'c1');+ await tester.pump();+ take.discard();+ await tester.pump();+ expect(mic.calls.last, 'cancel');+ expect(posted, isEmpty);+ expect(take.state, SuperTabVoiceState.off);+ });++ testWidgets('a send that fails keeps the take with its notice', (+ tester,+ ) async {+ answer = (sent: false, notice: 'Voice messages need a newer server');+ take.start(conversationId: 'c1');+ await tester.pump();+ take.send();+ await tester.pump();+ expect(take.state, SuperTabVoiceState.held);+ expect(take.notice, 'Voice messages need a newer server');+ answer = (sent: true, notice: null);+ take.send();+ await tester.pump();+ expect(posted, hasLength(2));+ expect(take.state, SuperTabVoiceState.off);+ expect(take.notice, isNull);+ });++ testWidgets('a refused microphone says so and records nothing', (+ tester,+ ) async {+ mic.allow = false;+ take.start(conversationId: 'c1');+ await tester.pump();+ expect(take.state, SuperTabVoiceState.off);+ expect(take.denied, isTrue);+ expect(mic.calls, ['allowed']);+ expect(posted, isEmpty);+ // Allowed later in the system's settings: the next tap asks again.+ mic.allow = true;+ take.start(conversationId: 'c1');+ await tester.pump();+ expect(take.denied, isFalse);+ expect(take.state, SuperTabVoiceState.recording);+ take.discard();+ });++ testWidgets('a mic that cannot start says so', (tester) async {+ mic.failStart = true;+ take.start(conversationId: 'c1');+ await tester.pump();+ expect(take.state, SuperTabVoiceState.off);+ expect(take.notice, SuperTabVoiceTake.couldNotStart);+ });++ testWidgets('stops at ten minutes and waits with Send ready', (+ tester,+ ) async {+ take.start(conversationId: 'c1');+ await tester.pump();+ await tester.pump(SuperTabVoiceTake.maxTake);+ await tester.pump();+ expect(take.state, SuperTabVoiceState.held);+ expect(take.canSend, isTrue);+ expect(mic.calls.last, 'stop');+ expect(posted, isEmpty);+ });++ testWidgets('hold stops the take and keeps it for its chat', (+ tester,+ ) async {+ take.start(conversationId: 'c1', root: 'r1');+ await tester.pump();+ take.hold();+ await tester.pump();+ expect(take.state, SuperTabVoiceState.held);+ expect(take.conversationId, 'c1');+ expect(take.length, mic.clip.length);+ expect(posted, isEmpty);+ take.send();+ await tester.pump();+ expect(posted.single.root, 'r1');+ });++ testWidgets('nothing recorded says so and keeps nothing', (tester) async {+ mic.empty = true;+ take.start(conversationId: 'c1');+ await tester.pump();+ take.send();+ await tester.pump();+ expect(posted, isEmpty);+ expect(take.state, SuperTabVoiceState.off);+ expect(take.notice, SuperTabVoiceTake.nothingRecorded);+ });+ });++ test('a recorder only where recording works: macOS and the web', () {+ expect(+ superTabVoiceRecorder(web: false, platform: TargetPlatform.macOS),+ isNotNull,+ );+ expect(+ superTabVoiceRecorder(web: true, platform: TargetPlatform.linux),+ isNotNull,+ );+ expect(+ superTabVoiceRecorder(web: false, platform: TargetPlatform.linux),+ isNull,+ );+ expect(+ superTabVoiceRecorder(web: false, platform: TargetPlatform.windows),+ isNull,+ );+ });++ test('a clip is PCM16 in a WAV header stating its rate and length', () {+ final pcm = Uint8List.fromList(List.filled(3200, 1));+ final wav = wavFromPcm16(pcm, sampleRate: 16000, channels: 1);+ final data = ByteData.sublistView(wav);+ expect(wav.length, 44 + 3200);+ expect(String.fromCharCodes(wav.sublist(0, 4)), 'RIFF');+ expect(String.fromCharCodes(wav.sublist(8, 12)), 'WAVE');+ expect(data.getUint32(24, Endian.little), 16000);+ expect(data.getUint16(22, Endian.little), 1);+ expect(data.getUint32(40, Endian.little), 3200);+ });+}diff --git a/desktop/test/super_tab_waiting_notice_shots_test.dart b/desktop/test/super_tab_waiting_notice_shots_test.dartnew file mode 100644index 000000000..d4e77b0e0--- /dev/null+++ b/desktop/test/super_tab_waiting_notice_shots_test.dart@@ -0,0 +1,274 @@+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart' show FontLoader;+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/notify/agent_alerts.dart';+import 'package:harness/notify/alert_sounds.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart' show AgentLoadStatus;+import 'package:harness/state/notification_inbox.dart';+import 'package:harness/super_tabs/workspace.dart';+import 'package:harness/terminal/terminal_binary.dart';+import 'package:harness/terminal/terminal_font_store.dart';+import 'package:xterm/xterm.dart' show TerminalStyle;+import 'package:harness/widgets/agent_alert_banners.dart';+import 'package:harness/widgets/pane_grid.dart';+import 'package:harness/ws/local_cli_discovery.dart' show LocalCliEndpoint;++import 'super_tab_launch_test.dart'+ show SuperTabFixtureConnection, SuperTabLaunchFixture;+import 'super_tab_waiting_notice_test.dart' show waitingSwarm;+import 'support/capture.dart';++/// Set to a folder to write the PR's screenshots there.+final _shots = Platform.environment['HARNESS_WAITING_NOTICE_CAPTURE_DIR'];++/// What Nova's terminal holds: Claude Code stopped at a permission prompt,+/// as Egret3 was when Huy clicked its toast.+const _prompt =+ '⏺ I will run the Desktop widget tests for the notice click.\r\n'+ '\r\n'+ '╭───────────────────────────────────────────────────────────────────╮\r\n'+ '│ Bash command │\r\n'+ '│ │\r\n'+ '│ flutter test test/super_tab_waiting_notice_test.dart │\r\n'+ '│ Run the waiting-notice widget tests │\r\n'+ '│ │\r\n'+ '│ Do you want to proceed? │\r\n'+ '│ ❯ 1. Yes │\r\n'+ "│ 2. Yes, and don't ask again for flutter test commands │\r\n"+ '│ 3. No, and tell Claude what to do differently (esc) │\r\n'+ '╰───────────────────────────────────────────────────────────────────╯\r\n';++/// The machine's daemon, answering Nova's terminal with its screen.+class _PromptConnection extends SuperTabFixtureConnection {+ _PromptConnection(super.store);++ @override+ Future<bool> sendTerminalFrame(+ String type,+ Map<String, dynamic> payload,+ ) async {+ if (type != 'terminal_open') return true;+ const stream = SuperTabFixtureConnection.streamId;+ await event('terminal_ready', {+ 'requestId': payload['requestId'],+ 'protocolVersion': 3,+ 'streamId': stream,+ 'agentId': payload['agentId'],+ });+ await app.handleTerminalBinaryForTest(+ 'm',+ encodeTerminalLocal(+ TerminalBinaryFrame(+ kind: TerminalBinaryKind.keyframe,+ streamId: stream,+ seq: 0,+ bytes: Uint8List.fromList(utf8.encode(_prompt)),+ compressed: false,+ cols: 100,+ rows: 30,+ ),+ )!,+ );+ return true;+ }+}++/// Each way a Waiting on you notice opens Nova's terminal at its prompt, and+/// the reason for Finn, whom no chat holds (#2792). The Team account this+/// runs in has no screen, so the pane is drawn here against a daemon fixture+/// that holds a real prompt.+void main() {+ setUpAll(() async {+ await loadCaptureFonts(_shots);+ // The terminal's own font, so the prompt reads as it does on a Mac.+ const mono = '/System/Library/Fonts/SFNSMono.ttf';+ if (_shots != null && File(mono).existsSync()) {+ final bytes = ByteData.sublistView(await File(mono).readAsBytes());+ await (FontLoader('SF Mono')..addFont(Future.value(bytes))).load();+ }+ });++ for (final brightness in Brightness.values) {+ testWidgets('screenshots for review (${brightness.name})', (tester) async {+ await tester.binding.setSurfaceSize(const Size(1280, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ final f = SuperTabLaunchFixture(+ connectionFactory: (store) => _PromptConnection(store),+ );+ final c = await waitingSwarm(f);+ // Nova's word in its task, beside the prompt it stopped at.+ final server = f.connection.server+ ..append(+ 'Running the waiting-notice widget tests next. Claude Code needs '+ 'your OK for the command; it is in my terminal.',+ conversationId: 'task',+ );+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'nova',+ 'name': 'Nova',+ };+ await c.refresh();+ // No threads followed: Activity lists only what needs the reader.+ f.connection.server.followedThreads = {+ 'unread': <dynamic>[],+ 'read': <dynamic>[],+ 'more': false,+ };+ // Nova runs in Claude Code and waits at its prompt, on a connected Mac.+ for (final agent in f.connection.server.state['agents'] as List) {+ agent['configuration'] = {'engine': 'claude'};+ }+ await c.refresh();+ f.app.stateOf('m')!+ // This Mac, reached over its own daemon as the reader's is.+ ..localEndpoint = LocalCliEndpoint(+ computerId: 'fixture',+ wsUri: Uri.parse('ws://fixture.invalid'),+ protocolVersion: 1,+ terminalProtocolVersion: 3,+ )+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..terminalCapabilityAvailable = true+ ..agents = [+ for (final (id, name) in [('nova', 'Nova'), ('finn', 'Finn')])+ Agent.fromJson({+ 'id': 'native-$id',+ 'name': name,+ 'engine': 'claude',+ 'status': 'running',+ 'sessionId': 'session-$id',+ 'terminal': {'available': true},+ }),+ ];+ f.app.agentAlerts.store.value = true;+ addTearDown(() => f.app.agentAlerts.store.value = false);+ final font = terminalFontStore.value;+ terminalFontStore.value = const TerminalStyle(+ fontFamily: 'SF Mono',+ fontSize: 13,+ );+ addTearDown(() => terminalFontStore.value = font);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: Stack(+ children: [+ ListenableBuilder(+ listenable: f.app,+ builder: (_, _) => SuperTabWorkspace(+ app: f.app,+ canvas: PaneGrid(notifier: f.app, swarmMode: true),+ onAddAgent: (_) {},+ ),+ ),+ AgentAlertBanners(notifier: f.app),+ ],+ ),+ ),+ ),+ );+ // A terminal keeps drawing (its cursor), so frames rather than a settle.+ Future<void> frames([int count = 20]) async {+ for (var frame = 0; frame < count; frame++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ Future<void> shot(String name) =>+ captureWindow(tester, _shots, 'waiting-$name-${brightness.name}');++ /// Nova's terminal is open beside the task, focused, at its prompt.+ void atPrompt() {+ expect(c.selectedId, 'task');+ expect(c.terminalAgents('task').single.id, 'nova');+ final pane = f.app.focusedPane;+ expect(pane?.agentId, 'native-nova');+ // The prompt the daemon sent is on the pane's own terminal.+ expect(+ pane?.session?.terminal.buffer.getText(),+ contains('Do you want to proceed?'),+ );+ }++ /// Back to the project chat with no terminal, for the next way in.+ Future<void> back() async {+ c.selectTerminal('task', null);+ await c.select('lead');+ await frames();+ expect(c.terminalAgents('task'), isEmpty);+ }++ Future<void> toast(String agent) async {+ f.app.agentAlerts.post(+ AgentAlert(+ machineId: 'm',+ agentId: 'native-$agent',+ title: agent == 'nova' ? 'Nova' : 'Finn',+ kind: AlertKind.needsYou,+ at: DateTime.now(),+ ),+ );+ await frames(5);+ }++ await frames();+ await toast('nova');+ await shot('toast');+ await tester.tap(find.byKey(const Key('agent-alert-banner')));+ await frames();+ atPrompt();+ await shot('toast-opened');++ await back();+ await tester.tap(find.byKey(const ValueKey('super-activity')));+ await frames();+ await shot('activity');+ await tester.tap(find.text('Nova is waiting on you'));+ await frames();+ atPrompt();+ await shot('activity-opened');++ await back();+ // The bell's row, as its dropdown opens it.+ await openInboxNotification(+ f.app,+ const InboxNotification(+ machineId: 'm',+ agentId: 'native-nova',+ title: 'Nova',+ detail: '',+ kind: AlertKind.needsYou,+ unavailable: null,+ ),+ );+ await frames();+ atPrompt();+ await shot('bell-opened');++ await toast('finn');+ await tester.tap(find.byKey(const Key('agent-alert-banner')));+ await frames(10);+ expect(find.byType(SnackBar), findsOneWidget);+ await shot('no-chat');+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ // Its terminals keep timers until the app goes.+ f.dispose();+ await tester.pump();+ });+ }+}diff --git a/desktop/test/super_tab_waiting_notice_test.dart b/desktop/test/super_tab_waiting_notice_test.dartnew file mode 100644index 000000000..2a6762a46--- /dev/null+++ b/desktop/test/super_tab_waiting_notice_test.dart@@ -0,0 +1,219 @@+// Huy (11-04, #2792): the toast "Egret3 · Waiting on you" did nothing when+// clicked; he went through Manage to reach the agent's terminal and its+// prompt. A Waiting on you notice opens the agent's terminal beside the chat+// it waits in, or says why it can't.+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/notify/agent_alerts.dart';+import 'package:harness/notify/alert_sounds.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/workspace.dart';+import 'package:harness/widgets/agent_alert_banners.dart';++import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;+import 'support/super_tab_fixture.dart';++const _reason =+ 'Not in a task or chat now. Give it work or add it to a chat to open its terminal.';++/// A Swarm with Nova waiting on the reader in its task, and Finn in no chat.+Future<SuperTabController> waitingSwarm(SuperTabLaunchFixture f) async {+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');+ final state = f.connection.server.state;+ state['projects'] = [projectFixture('lead', 'Web', 'lead')];+ state['agents'] = [+ for (final (id, name) in [('nova', 'Nova'), ('finn', 'Finn')])+ {+ 'id': id,+ 'displayName': name,+ 'name': 'Engineer',+ 'projectId': 'lead',+ 'machineId': 'm',+ 'harnessId': 'native-$id',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'codex'},+ },+ ];+ (state['conversations'] as List).add({+ ...conversationFixture('task', 'Build the mobile app'),+ 'projectId': 'lead',+ 'agentIds': ['nova'],+ 'assignment': {+ 'id': 'as-nova',+ 'agentId': 'nova',+ 'status': 'needs_human',+ // Asked of the reader by name, as Activity lists it (#2929).+ 'askedOf': 'owner',+ },+ });+ f.app.stateOf('m')!.agents = [+ for (final name in ['nova', 'finn'])+ Agent.fromJson({+ 'id': 'native-$name',+ 'name': name,+ 'engine': 'codex',+ 'status': 'stopped',+ 'sessionId': 'saved-$name',+ 'terminal': {'available': false},+ }),+ ];+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ await c.select('lead');+ return c;+}++void main() {+ Future<void> show(WidgetTester tester, SuperTabLaunchFixture f) async {+ await tester.binding.setSurfaceSize(const Size(1440, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ // Banners are off until the person turns them on.+ f.app.agentAlerts.store.value = true;+ addTearDown(() => f.app.agentAlerts.store.value = false);+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Stack(+ children: [+ ListenableBuilder(+ listenable: f.app,+ builder: (_, _) => SuperTabWorkspace(+ app: f.app,+ canvas: const SizedBox.expand(),+ onAddAgent: (_) {},+ ),+ ),+ AgentAlertBanners(notifier: f.app),+ ],+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ Future<void> clickToast(+ WidgetTester tester,+ SuperTabLaunchFixture f,+ String agent,+ ) async {+ f.app.agentAlerts.post(+ AgentAlert(+ machineId: 'm',+ agentId: 'native-$agent',+ title: agent,+ kind: AlertKind.needsYou,+ at: DateTime.now(),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const Key('agent-alert-banner')));+ await tester.pumpAndSettle();+ }++ Future<void> done(+ WidgetTester tester,+ SuperTabLaunchFixture f,+ SuperTabController c,+ ) async {+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ }++ /// The task's chat stays on screen beside the terminal, its composer+ /// included (Huy, 11-04: side by side, "beside its task chat").+ void besideChat() => expect(+ find.byKey(const ValueKey('super-message-composer')),+ findsOneWidget,+ );++ testWidgets('a Waiting on you toast opens the agent\'s terminal beside the '+ 'task it waits in, focused', (tester) async {+ final f = SuperTabLaunchFixture();+ final c = await waitingSwarm(f);+ await show(tester, f);+ expect(c.selectedId, 'lead');+ await clickToast(tester, f, 'nova');+ expect(c.selectedId, 'task');+ expect(c.terminalAgents('task').single.id, 'nova');+ expect(f.app.panes.single.agentId, 'native-nova');+ expect(f.app.focusedPane?.agentId, 'native-nova');+ besideChat();+ await done(tester, f, c);+ });++ testWidgets('from another tab, the toast brings the agent\'s Swarm forward '+ 'with its terminal open', (tester) async {+ final f = SuperTabLaunchFixture();+ final c = await waitingSwarm(f);+ final swarm = f.app.activeSwarmId;+ f.app.newSwarm();+ await show(tester, f);+ expect(f.app.activeSwarmId, isNot(swarm));+ await clickToast(tester, f, 'nova');+ expect(f.app.activeSwarmId, swarm);+ expect(c.selectedId, 'task');+ expect(f.app.focusedPane?.agentId, 'native-nova');+ besideChat();+ await done(tester, f, c);+ });++ // Review of #2973 (Avocet): an agent no Swarm holds, clicked from a Swarm+ // tab, was added there and closed by the Swarm view, as Huy's was.+ testWidgets('from a Swarm tab, the toast for a harness no Swarm holds opens '+ 'it in a new tab, focused', (tester) async {+ final f = SuperTabLaunchFixture();+ final c = await waitingSwarm(f);+ final swarm = f.app.activeSwarmId;+ f.app.stateOf('m')!.agents = [+ ...f.app.stateOf('m')!.agents,+ Agent.fromJson({+ 'id': 'native-solo',+ 'name': 'solo',+ 'engine': 'codex',+ 'status': 'stopped',+ 'sessionId': 'saved-solo',+ 'terminal': {'available': false},+ }),+ ];+ await show(tester, f);+ await clickToast(tester, f, 'solo');+ expect(f.app.activeSwarmId, isNot(swarm));+ expect(f.app.activeSwarm.isSuperTab, isFalse);+ expect(f.app.focusedPane?.agentId, 'native-solo');+ expect(c.selectedId, 'lead');+ await done(tester, f, c);+ });++ testWidgets('Activity\'s "is waiting on you" opens the task with the '+ 'agent\'s terminal focused', (tester) async {+ final f = SuperTabLaunchFixture();+ final c = await waitingSwarm(f);+ await show(tester, f);+ await tester.tap(find.byKey(const ValueKey('super-activity')));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Nova is waiting on you'));+ await tester.pumpAndSettle();+ expect(c.selectedId, 'task');+ expect(c.terminalAgents('task').single.id, 'nova');+ expect(f.app.focusedPane?.agentId, 'native-nova');+ besideChat();+ await done(tester, f, c);+ });++ testWidgets('the toast for an agent no chat holds brings its Swarm forward '+ 'and says why its terminal cannot open', (tester) async {+ final f = SuperTabLaunchFixture();+ final c = await waitingSwarm(f);+ await show(tester, f);+ await clickToast(tester, f, 'finn');+ expect(find.text(_reason), findsOneWidget);+ expect(c.selectedId, 'lead');+ expect(f.app.panes.where((p) => p.agentId == 'native-finn'), isEmpty);+ await done(tester, f, c);+ });+}diff --git a/desktop/test/support/fake_voice_recorder.dart b/desktop/test/support/fake_voice_recorder.dartnew file mode 100644index 000000000..2e3a956fe--- /dev/null+++ b/desktop/test/support/fake_voice_recorder.dart@@ -0,0 +1,43 @@+import 'package:flutter/foundation.dart';+import 'package:harness/super_tabs/voice_recorder.dart';++/// A microphone for widget tests: no platform channel, and every call it+/// gets is in [calls]. [allow] answers the permission, [failStart] makes+/// start throw, [empty] makes stop hand back nothing.+class FakeVoiceRecorder implements SuperTabVoiceRecorder {+ final calls = <String>[];+ bool allow = true, failStart = false, empty = false;++ /// What every stop hands back: one second of 16 kHz mono silence.+ final SuperTabVoiceClip clip = (+ wav: Uint8List.fromList([...List.filled(44, 0), ...List.filled(32000, 0)]),+ length: const Duration(seconds: 1),+ );++ @override+ final ValueNotifier<double> level = ValueNotifier(0);++ @override+ Future<bool> allowed() async {+ calls.add('allowed');+ return allow;+ }++ @override+ Future<void> start() async {+ calls.add('start');+ if (failStart) throw Exception('no microphone');+ }++ @override+ Future<SuperTabVoiceClip?> stop() async {+ calls.add('stop');+ return empty ? null : clip;+ }++ @override+ Future<void> cancel() async => calls.add('cancel');++ @override+ Future<void> dispose() async => calls.add('dispose');+}diff --git a/desktop/test/support/voice_server.dart b/desktop/test/support/voice_server.dartnew file mode 100644index 000000000..8ff4f125a--- /dev/null+++ b/desktop/test/support/voice_server.dart@@ -0,0 +1,49 @@+import 'package:harness/super_tabs/controller.dart';++import 'super_tab_fixture.dart';++/// A server with #2887's voice route (`POST …/attachments/:id/voice`):+/// [voiceAnswers] are given in turn, the last one again; a [SuperTabFailure]+/// in it is thrown.+class VoiceServer extends ConversationServer {+ final voiceReads = <String>[];+ List<Object> voiceAnswers = [+ {+ 'voice': {+ 'durationMs': 1000,+ 'waveform': List.filled(48, 3),+ 'transcribed': true,+ },+ },+ ];++ /// The last `message.send` the server was asked for.+ Map<String, dynamic>? lastSend() {+ for (final post in posts.reversed) {+ final command = post['command'];+ if (command is Map && command['type'] == 'message.send') {+ return Map<String, dynamic>.from(command);+ }+ }+ return null;+ }++ @override+ Future<Map<String, dynamic>> request(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) async {+ if (method == 'POST' && path.contains('/voice')) {+ voiceReads.add(path);+ final answer =+ voiceAnswers[(voiceReads.length - 1).clamp(+ 0,+ voiceAnswers.length - 1,+ )];+ if (answer is SuperTabFailure) throw answer;+ return answer as Map<String, dynamic>;+ }+ return super.request(method, path, body: body);+ }+}diff --git a/desktop/windows/flutter/generated_plugin_registrant.cc b/desktop/windows/flutter/generated_plugin_registrant.ccindex 4bbb60114..b889d641c 100644--- a/desktop/windows/flutter/generated_plugin_registrant.cc+++ b/desktop/windows/flutter/generated_plugin_registrant.cc@@ -8,6 +8,7 @@#include <desktop_drop/desktop_drop_plugin.h>#include <file_selector_windows/file_selector_windows.h>+#include <record_windows/record_windows_plugin_c_api.h>#include <screen_retriever_windows/screen_retriever_windows_plugin_c_api.h>#include <url_launcher_windows/url_launcher_windows.h>#include <window_manager/window_manager_plugin.h>@@ -17,6 +18,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) {registry->GetRegistrarForPlugin("DesktopDropPlugin"));FileSelectorWindowsRegisterWithRegistrar(registry->GetRegistrarForPlugin("FileSelectorWindows"));+ RecordWindowsPluginCApiRegisterWithRegistrar(+ registry->GetRegistrarForPlugin("RecordWindowsPluginCApi"));ScreenRetrieverWindowsPluginCApiRegisterWithRegistrar(registry->GetRegistrarForPlugin("ScreenRetrieverWindowsPluginCApi"));UrlLauncherWindowsRegisterWithRegistrar(diff --git a/desktop/windows/flutter/generated_plugins.cmake b/desktop/windows/flutter/generated_plugins.cmakeindex 031c11180..f5f638fcc 100644--- a/desktop/windows/flutter/generated_plugins.cmake+++ b/desktop/windows/flutter/generated_plugins.cmake@@ -5,6 +5,7 @@list(APPEND FLUTTER_PLUGIN_LISTdesktop_dropfile_selector_windows+ record_windowsscreen_retriever_windowsurl_launcher_windowswindow_managerdiff --git a/docs/plans/2026-11-04-changes-poll-reads-plan.md b/docs/plans/2026-11-04-changes-poll-reads-plan.mdnew file mode 100644index 000000000..25c6b62f0--- /dev/null+++ b/docs/plans/2026-11-04-changes-poll-reads-plan.md@@ -0,0 +1,128 @@+# GET changes reads only what moved, once per pod — Implementation Plan++> Written by the writing-plans skill. The Engineer implements it task by task, test first (test-driven-development):+> each task's failing test is committed before its code. One review on the pull request.++**Goal:** `GET /api/super-tabs/:tabId/changes` costs a fraction of today's database time and bytes per poll (task #2783,+Watch Production #2773: 32% of DB time, 30% of DB bytes after v1.4.1; all part reads bursting to ~570 ms together).++**Architecture:** the poll already reads parts through the per-pod read cache (`cache.ts`, `cachedReads.ts`): a bump marks+entries stale and one shared delta per Swarm and stamp patches them. Measured on the bench (below), three things in that+path make every poll's refresh read far more than moved, and one makes slower pollers read alone:++1. The change feed (`feed`, `cachedReads.ts readChanged`) holds all seven kinds under the `all` scope, so every machine+ reading (every 15 s per machine) makes the pod's next delta read all seven part collections. A reading moved one+ machine part.+2. The shared delta (`cache.ts deltaFor`) reaches back to the oldest stale entry of the Swarm refreshed in the last two+ minutes (`DELTA_MAX_GAP_MS`), whether or not anyone is reading it. One first load's dormant entries drag every later+ delta back: on the bench, ~190 whole conversations (1.2 MB) per machine reading.+3. Each delta reads every part changed in its window (30 s overlap and more) with its whole data, though the pod received+ most of them, at the same versions, in the delta before.+4. A cursor older than the feed's start reads the change collections itself, one poller at a time.++The fixes, one per task: the feed splits by stamp scope; a delta joins only entries refreshed recently; a delta reads keys+and versions first and whole rows only for versions the pod has not held; the feed starts far enough back for slow pollers.+Answers stay identical: every change is checked against today's loaders.++**Tech Stack:** TypeScript, Fastify, Prisma on MongoDB (`aggregateRaw`), vitest; the bench on mongodb-memory-server.++**Spec:** task #2783's brief; [2026-11-02 poll cost](../superpowers/specs/2026-11-02-poll-cost-design.md) Part 1 (the feed+rule) and [2026-11-02 cache delta](../superpowers/specs/2026-11-02-swarm-cache-delta-design.md), whose rules stay.++## Global Constraints++- Answers identical: every changed read equals what today's loader returns (`integration/superTabCacheDelta.test.ts`+ equivalence after seeded writes; unit tests per rule).+- No env switches: everything ships on. No production access: Ken's numbers and the bench.+- Red-first: each task commits its failing test before its code.+- Backend only; nothing in `cli/src/core`. Temp files only in `mktemp -d` folders.++## Review Focus++- `deltaFor`'s join window: an entry left out of a shared delta must still be refreshed correctly on its own read.+- The version-gated delta: a part is reused from memory only at the same kind, key and version; every part whose version+ the pod has not held is read whole. The memo is bounded and per Swarm.+- The split feed: a reply's parts are the same set, in kind order, as the single feed's.+- The integration plan test for the by-id read (backend AGENTS.md rule 3).++## Design (AGENTS.md checklist)++- **Growth:** the delta memo holds each Swarm's parts seen in its last deltas, pruned to the reach of the next delta+ (everything older than the earliest live entry's refresh, less the overlap) and to `DELTA_MAX_PARTS` per Swarm; dropped+ with the Swarm's entries. The feed's earlier start adds at most two minutes of changes to a held feed.+- **Concurrency:** no locks, as the cache today: one delta per Swarm and stamp, joined by every entry it covers.+- **Read cost:** a machine reading reads machine parts only; a delta reads keys and versions, then whole rows only of what+ moved since the pod's last delta.+- **Scale:** at 10x pollers per pod the part reads stay per bump, not per poll. First warning: the `swarm cache` minute+ log's patch bytes and full loads per entry, and `route latency` for changes.+- **Compatibility:** no API or stored shape changes; old and new pods share Redis stamps as today.+- **Migration + rollback:** none stored; roll back with the previous release.+- **Audience:** permissions still apply after the cache (`read/views.ts readerView`, `read/changes.ts changesFor`).+- **Identity:** nothing keyed by or sent as the machine owner's login.+- **Failure:** a delta or by-id read that fails loads the entry in full, as a failed delta does today.+- **Platforms:** backend on Linux pods.++## Measuring++`backend/integration/bench/changesPollCost.ts`: the bench's seeded Swarm (200 groups, 6 machines, 20 workers) on one+backend process, 18 person windows and 20 agents polling; rounds where all poll at once after nothing, one machine+reading, every machine reading and one post. Per poll: operations, part reads, MongoDB bytes out, profiler ms, wall ms,+reply bytes; per round: operations and bytes by collection. Run before (main) and after, and with `--light`.++## Task 1: machine readings refresh only the machine part of the feed++**Files:** `backend/src/superTabs/cachedReads.ts` (`readChanged`), `backend/src/superTabs/cachePatch.ts` (`feedRule` →+by kinds), `backend/src/superTabs/parts/load.ts` (`loadChanged` takes kinds already), tests in+`cachedReads.test.ts`, `cachePatch.test.ts`.++**Interfaces:** `feedRuleOf(kinds)`; entries `feed` (scope `main`, the six non-machine kinds) and `machine-feed` (scope+`all`, kind `machine`). `readChanged` returns the same parts as before, the six kinds then machines.++- [ ] Failing test: after a machine-only bump, a feed read asks the delta for `machine` only, and its answer equals+ `loadChanged` (red today: the delta asks for all seven kinds).+- [ ] Split the feed; keep the direct path when the cursor is older than either part's start.+- [ ] Run `cachedReads.test.ts`, `cachePatch.test.ts`, `cache.test.ts`, `read/*.test.ts`.++## Task 2: a shared delta joins only entries refreshed recently++**Files:** `backend/src/superTabs/cache.ts` (`deltaFor`, new `DELTA_JOIN_MS`), `cache.test.ts`.++**Interfaces:** an entry joins another's delta only when it was refreshed at most `DELTA_JOIN_MS` (15 s, Desktop's+background cadence) before the entry being refreshed. A cold entry, read later, gets its own delta from its own time.++- [ ] Failing test: an entry refreshed 60 s ago and not read since does not move a hot entry's delta back (red today: the+ delta starts at the cold entry's time less the overlap); read later, it is still patched right.+- [ ] Implement; existing "entries refreshed together still share one delta" stays green.+- [ ] Run `cache.test.ts`, `cachedReads.test.ts`.++## Task 3: a delta reads whole rows only for versions the pod has not held++**Files:** `backend/src/superTabs/parts/load.ts` (`loadDelta` in two steps: keys and versions, then whole rows by `_id`),+`backend/src/superTabs/cachedReads.ts` (`readDelta` with a per-Swarm memo), tests in `cachedReads.test.ts`, the plan in+`backend/integration/` (rule 3).++**Interfaces:** `loadDelta(tx, tabId, since, kinds, held?)`: `held(kind, key, version)` returns a part the pod holds at+that version, or none; the answer is the same `SwarmDelta`. The memo keeps each Swarm's delta parts, pruned by time.++- [ ] Failing test: a second delta over the same window reads no whole row it already read (red today: it reads every+ row again), and its answer equals a fresh `loadDelta`.+- [ ] Implement; by-id read is a plain `$match` on `_id` with `tabId`.+- [ ] Integration test of the by-id read's plan (IXSCAN on `_id`).+- [ ] Run `cachedReads.test.ts`, `cache.test.ts`, `parts/*.test.ts`.++## Task 4: slower pollers share the pod's feed++**Files:** `backend/src/superTabs/cachedReads.ts` (`readChanged`, `FEED_REACH_MS`), `cachedReads.test.ts`.++**Interfaces:** a feed loaded on a miss starts at the earlier of its reader's cursor less 15 s and two minutes before the+read, so a phone (5 s), a background window (15 s) or a CLI reading a minute later reads the held feed.++- [ ] Failing test: a cursor 60 s older than the poller that loaded the feed reads no collection (red today: it reads all+ seven itself).+- [ ] Implement.+- [ ] Run `cachedReads.test.ts`.++## Task 5: measure and hand over++- [ ] Bench before (main) and after, plain and `--light`; numbers and red/green evidence in a PR comment.+- [ ] `npm test` (backend unit suite) and typecheck; PR ready; review step.diff --git a/docs/plans/2026-11-04-desktop-composer-mic-plan.md b/docs/plans/2026-11-04-desktop-composer-mic-plan.mdnew file mode 100644index 000000000..338c15341--- /dev/null+++ b/docs/plans/2026-11-04-desktop-composer-mic-plan.md@@ -0,0 +1,100 @@+# Desktop and Web Composer Mic Implementation Plan++> **For agentic workers:** The assigned Engineer implements this plan task by task in this session, test first, by the project's instructions (plan first in a draft PR; each failing test committed before its code; one independent review step on the pull request). No subagents: the tasks share the recorder seam.++**Goal:** On macOS and the web, the Swarm composer's mic (main chat and thread) records a voice message and sends it as audio through #2887's path: people hear it, agents read its words. Linux and Windows show no mic. A refused microphone says so in one short line, with a way to the system setting.++**Architecture:** `voice_recorder.dart` becomes the phone's recorder seam (`allowed`, `start`, `stop`, `cancel`, `dispose`, `level`), with `SuperTabMicRecorder` over the `record` package streaming 16 kHz mono PCM16, wrapped in a WAV header (`voice_wav.dart`, the phone's `wavFromPcm16` and `pcm16Level`). `voice_take.dart` holds one take, as the phone's `SwarmVoice` does (off, starting, recording, held, sending; at most 10:00, then held with Send ready). `voice_send.dart` sends a take as the phone's `sendVoice` does: `uploadFile` of `Voice message.wav`, `POST …/attachments/:id/voice?lang=` (retrying `VOICE_TRANSCRIBING`), then `message.send` with empty text, the file, and the thread's root as `replyTo`. While a take is under way, `voice_row.dart` takes the place of the composer's row: `[X] ● 0:14 ıllıllıııllıı.ılı [↑]`. The view gets a recorder factory only where recording works (`superTabVoiceRecorder()`: macOS and the web), so Linux and Windows draw no mic (the #2918 rule: no mic without a recorder).++**Tech Stack:** Flutter (Desktop, web build of the same code), `record` ^7.1.1 (as the phone), flutter_test widget tests with the `ConversationServer` fixture (memory store, fake sign-in) and a fake recorder.++**Spec:** Swarm task #2665, conversation 359ddf4db0057d3048910c4d (River, 11-04; Huy and Scholes' composer #2918, Dee's voice messages #2887).++## Global Constraints++- The take is never sent by itself and nothing goes into the text box. What is typed stays in the box.+- A take stops at exactly 10:00 and is held with Send ready. Changing chat or thread stops and holds the take for its own chat; its row shows only in that chat. A mic tap in another chat discards a held take first.+- X discards the take; Send stops it (when recording) and posts it; a failed send keeps the take with its notice.+- Microphone refused: one line under the box. macOS: "Harness can't use the microphone · Open System Settings", the link opening `x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone`. Web: "This site can't use the microphone · allow it in your browser's site settings" (no page can open a browser's settings).+- The language the words are heard in is the computer's own language (`PlatformDispatcher.locale.languageCode`); the server falls back to English for one it does not serve. No picker (beyond the brief).+- macOS: `com.apple.security.device.audio-input` in both entitlements (the app runs with the hardened runtime, which needs it for the microphone), and `NSMicrophoneUsageDescription` in Info.plist.+- Harness Design Language: tokens only (`grid.AppDesktop`, `DesktopChrome`, `AppIcons`), icons through `AppIcons` at weight 400, no hard-coded colours or sizes, nothing explanatory added.+- Every button is reachable with Tab, X and Send in the row's order.+- Never run a test that signs the Mac out of the real CLI; Desktop tests use a memory store and a fake sign-in.+- A real microphone can't be tested on a Team account: the PR says so; the Desktop release candidate check covers it.+- PR body first line: "Requested by [email protected] through Harness."++## Design++- **Growth:** a take lives in memory (1.9 MB a minute, 19 MB at 10:00) until it is sent or discarded; the uploaded file is #2887's attachment row, deleted by the unsent-file sweep or with its message.+- **Concurrency:** one take per composer; the recorder serializes its operations as the phone's does. The voice read's claim is the server's (#2887).+- **Read cost:** one upload, one voice read, one send per take; nothing new is polled.+- **Scale:** N/A because it is one person's clip at a time; the server's voice quota and memory budget (#2887) bound it.+- **Compatibility:** an old server answers 404 to the voice read: the take is kept and the row says "Voice messages need a newer server". Old clients see #2887's fallback (the words as text, a file chip).+- **Migration + rollback:** N/A because nothing is stored; rolling back removes the mic.+- **Audience:** the server's voice route (#2887) allows only the uploader, in a conversation it may post in.+- **Identity:** the signed-in person's own upload and voice quota, as on the phone.+- **Failure:** every failure is a line beside the take, which is kept: refused mic, a mic that could not start, nothing recorded, upload or read failed, old server, over the daily voice limit (sent without words, said).+- **Platforms:** macOS (AVFoundation through `record_macos`) and the web (`record_web`, getUserMedia, HTTPS only). Linux and Windows get no recorder and show no mic.++## Review Focus++1. A take recording while the person switches chat: it is held for its own chat, never sent into the newly opened one.+2. Send pressed twice, or a send whose answer was lost: one message (the file is used once; the second send is refused by the server, as today).+3. The microphone refused on macOS: the line names the setting and opens it; the mic stays usable after access is given (the next tap asks again).+4. The entitlement and usage text pass the Desktop release's signing and notarization (prepare run linked in the PR).+5. Linux and Windows: no mic, and the build still compiles with the `record` package.++---++### Task 1: The recorder seam and the take++**Files:**+- Modify: `desktop/lib/super_tabs/voice_recorder.dart` (the seam, `SuperTabMicRecorder`, `superTabVoiceRecorder()`)+- Create: `desktop/lib/super_tabs/voice_wav.dart`, `desktop/lib/super_tabs/voice_take.dart`+- Modify: `desktop/pubspec.yaml` (`record: ^7.1.1`), `desktop/pubspec.lock`+- Test: `desktop/test/super_tab_voice_take_test.dart`++**Interfaces:**+- Produces: `typedef SuperTabVoiceClip = ({Uint8List wav, Duration length})`; `abstract interface class SuperTabVoiceRecorder { Future<bool> allowed(); Future<void> start(); Future<SuperTabVoiceClip?> stop(); Future<void> cancel(); Future<void> dispose(); ValueListenable<double> get level; }`; `SuperTabVoiceRecorder Function()? superTabVoiceRecorder({bool web, TargetPlatform platform})`; `class SuperTabVoiceTake extends ChangeNotifier` with `state`, `conversationId`, `root`, `notice`, `denied`, `length`, `level`, `start({conversationId, root})`, `hold()`, `discard()`, `send()`; `SuperTabVoiceTake.maxTake = Duration(minutes: 10)`.++- [ ] **Step 1: Write the failing tests**: with a fake recorder, start records (state recording, for its chat and root); send stops then posts the clip once and returns to off; discard cancels the recorder and posts nothing; a failed post keeps the take held with its notice; refused mic sets `denied` and the notice, posts nothing; at 10:00 (fake clock) the take is held with Send ready, nothing posted; `hold()` while recording keeps the take; `superTabVoiceRecorder` gives a recorder for macOS and the web, none for Linux and Windows; `wavFromPcm16` writes a 44-byte header with the rate and length.+- [ ] **Step 2: Run** `flutter test test/super_tab_voice_take_test.dart` and watch it fail (missing files).+- [ ] **Step 3: Commit the failing tests.**+- [ ] **Step 4: Implement**; `flutter pub get`.+- [ ] **Step 5: Run** the test file; expect PASS. Commit.++### Task 2: Sending a take through #2887's path++**Files:**+- Create: `desktop/lib/super_tabs/voice_send.dart` (`extension SuperTabVoiceSend on SuperTabController { Future<SuperTabVoicePosted> sendVoice(...) }`)+- Test: `desktop/test/super_tab_voice_send_test.dart`++**Interfaces:**+- Consumes: `SuperTabController.uploadFile`, `request`, `command`, `oneBuddy`.+- Produces: `typedef SuperTabVoicePosted = ({bool sent, String? notice})`; `Future<SuperTabVoicePosted> sendVoice({required String conversationId, String? root, required Uint8List wav, required String lang})`.++- [ ] **Step 1: Write the failing tests** against the `ConversationServer` fixture: a take uploads `Voice message.wav`, reads it at `…/voice?lang=vi`, and sends `message.send` with text '', the file and `replyTo` = the thread's root; `VOICE_TRANSCRIBING` is asked again; a 404 keeps the take with "Voice messages need a newer server"; over the limit sends and says "Sent without words: today's voice limit is used".+- [ ] **Step 2: Run and watch them fail. Step 3: Commit.**+- [ ] **Step 4: Implement. Step 5: Run; PASS. Commit.**++### Task 3: The composer's mic, the recording row and the refused line++**Files:**+- Create: `desktop/lib/super_tabs/voice_row.dart` (`SuperTabVoiceRow`, `SuperTabVoiceRefused`)+- Modify: `desktop/lib/super_tabs/view.dart` (`voiceRecorder` becomes a factory; one `SuperTabVoiceTake` for the main composer; `_composerLayout` takes the row), `desktop/lib/super_tabs/reply_box.dart` (`voiceRow`, `voiceNotice`), `desktop/lib/super_tabs/thread_panel.dart` (its own take), `desktop/lib/super_tabs/composer_actions.dart`, `desktop/lib/super_tabs/workspace.dart` (passes `superTabVoiceRecorder()`), `desktop/lib/shared/theme/app_icons.dart` if a new icon is needed+- Test: `desktop/test/super_tab_composer_mic_test.dart`; update `super_tab_composer_row_test.dart`++- [ ] **Step 1: Write the failing tests** at 1280x720 with a fake recorder: tapping the mic shows `super-voice-row` in place of the row (X, red dot, time, wave, send) and leaves the typed text; X returns the row and posts nothing; Send posts one voice message to the chat (and to the thread's root from the thread's mic); switching chat holds the take and the other chat shows its normal row; a refused mic shows `super-voice-refused` with "Open System Settings" on macOS; closing a thread holds its take.+- [ ] **Step 2: Run and watch them fail. Step 3: Commit.**+- [ ] **Step 4: Implement. Step 5: Run** the new file, `super_tab_composer_row_test`, `super_tab_reply_box_test`, `super_tab_composer_layout_test`, `super_tab_phone_composer_test`, `super_tab_voice_message_test`, and the guards (`python3 scripts/check-ui-style.py --only desktop/lib/super_tabs`, `python3 desktop/scripts/audit-icons.py`, `icon_catalog_render_test`, `lucide_weight_test`, `laid_out_list_test`). Commit.++### Task 4: macOS microphone permission++**Files:**+- Modify: `desktop/macos/Runner/Release.entitlements`, `desktop/macos/Runner/DebugProfile.entitlements`, `desktop/macos/Runner/Info.plist`+- Test: `desktop/test/macos_microphone_permission_test.dart` (reads the plists: both entitlements carry `com.apple.security.device.audio-input` true; Info.plist carries `NSMicrophoneUsageDescription`)++- [ ] **Step 1: Write the failing test. Step 2: Watch it fail. Step 3: Commit.**+- [ ] **Step 4: Add the keys. Step 5: PASS. Commit.**+- [ ] **Step 6:** light and dark screenshots of the recording row and the refused line (`super_tab_composer_mic_shots_test.dart`), red/green evidence comment, `make release-desktop ARGS="--prepare"` on the pushed branch, linked in the PR.diff --git a/docs/plans/2026-11-04-empty-polls-wait-plan.md b/docs/plans/2026-11-04-empty-polls-wait-plan.mdnew file mode 100644index 000000000..25f36f55e--- /dev/null+++ b/docs/plans/2026-11-04-empty-polls-wait-plan.md@@ -0,0 +1,120 @@+# Empty polls stop: deliveries and terminal pickups wait for the server's word — plan++> Worked by the project's Engineer way of working: this plan first, then each task test first (failing test committed,+> then the code that passes it), one pull request, one independent review. No Execution Handoff.++**Goal:** Watch Production (#2773, task #2800). Ken's targets of 11-04: Atlas CPU peak hour ≤ 40% (now ~68%), per-minute+p95 ≤ 60% (now 88%). About 13% of requests are empty: `GET deliveries` is 84% empty and the hosts' terminal pickups are+almost all empty. Each of those empty answers costs DB reads. Stop asking on a timer where the server already says when+something waits, and keep a message reaching its reader at least as fast as now.++**Architecture:** The server already pushes, over each machine's daemon socket, when a delivery or a terminal request waits+for one of its agents (`super_tab_deliveries`, `__terminal_waiting`; spec 2026-11-02-poll-cost). The daemon still asks on a+timer as the net for a lost push: every idle agent's list every 30 s, and a terminal pickup every 8 s per machine. This plan+moves that net to the server, where it costs one read for all machines instead of one per agent:++1. The server repeats a push that may have been lost: a pass in the singleton worker every 15 s reads the queued deliveries+ (one indexed read for every Swarm) and tells each machine whose agent has one waiting 10 s or more; a sender waiting on+ a terminal request tells the machine again on each of its rechecks while the request is still pending.+2. The "this server pushes" repeat goes through the machine's Redis channel, as the host-changes repeat does: a lease renewal+ each minute (`__deliveries_lease`, which older daemons drop) and the old word every 4 minutes. The daemon's lease is 2.5+ minutes, so a silent Redis puts it back to reading each second within minutes, and it logs that once.+3. While the server pushes, the daemon reads an idle worker's list only when told (a push, a repeat, a reconnect, a retry+ after a failed read) and picks up terminal requests only when told. The Lead's list keeps its 30 s read: its poll runs the+ project's time checks (liveness.ts). Without the push lease everything stays as today (each second, every 3 s).++**Tech Stack:** backend TypeScript (Fastify, Prisma on MongoDB, ioredis bus), CLI TypeScript daemon (vitest specs).++**Spec:** task #2800's brief; follows docs/superpowers/specs/2026-11-02-poll-cost-design.md (Parts 3 and 4.2).++## Global Constraints++- No env switches; red-first tests where behavior changes; Swarm code stays out of `cli/src/core`.+- A message reaches its reader no slower: a delivered push is read in the same tick as today; a lost push is repeated by the+ server within 25 s (today the daemon's own 30 s read); a lost terminal push is repeated within the sender's 5 s recheck,+ inside the 10 s pickup deadline (today the 8 s poll).+- Old daemons are unchanged: they ignore nothing new and keep their timers. Release order: backend first, then CLI. A new+ daemon against an old backend still reads every list on each 4-minute repeat and on reconnect.++## Design++- **Growth:** nothing stored. The pass reads; terminal requests keep their TTL index (TERMINAL_EXPIRY_MS).+- **Concurrency:** no locks; the pass runs in the singleton worker, one run at a time (`running` flag). Pushes are+ idempotent: a host told twice reads once per tick.+- **Read cost:** one indexed read of queued deliveries `(status, _id)` every 15 s for all Swarms, at most one 500-row page;+ the terminal re-push adds no read (the sender's recheck already reads the row).+- **Scale:** at 10x agents the pass still makes 4 reads a minute; the publishes grow with machines that have queued work.+ The first metric to warn is the rows read per pass in the `[swarm-deliveries] re-announced` log (logged when non-zero)+ nearing the page size of 500: queues of machines that are away grow it while the agents told stay few.+- **Compatibility:** frame shapes unchanged (`super_tab_deliveries` with or without ids, `__terminal_waiting`). The Redis+ repeat message `{ pushes: true }` is new on the server's own channel and only the server reads it.+- **Migration + rollback:** none. Rolling the backend back to before this change brings back its in-process 4-minute word:+ new daemons hold their 2.5-minute lease for part of each 4 minutes and read each second for the rest, and a lost push waits+ for that word (up to 4 minutes) instead of the re-push pass.+- **Audience:** a push names only ids and reaches only the machine's own socket; the host reads through the checked poll.+- **Identity:** unchanged; the pass publishes per machine id from the delivery row.+- **Failure:** Redis away → no minute renewal → the daemon's lease (2.5 minutes) lapses → each-second reads, and the daemon+ logs the lapse once (review of #2977, Important 1: with the old 10-minute lease an idle worker's delivery could wait 10+ minutes). A failed list read is retried after its backoff without waiting for a push. A delivery the host keeps withholding+ stays queued and is told every 15 s, so that agent's list is read every 15 s instead of 30 s.+- **Platforms:** CLI daemon on macOS, Linux and Windows alike; no platform code.++## Review Focus++1. A push lost on the way: a queued delivery and a pending terminal request each reach the machine again without any+ daemon timer (server pass, sender recheck).+2. Paths that leave a delivery open without a push: covered by the pass (queued) or by the daemon's held/busy reads.+3. The Lead's list keeps its 30 s read (time checks), and a failed read retries after its backoff.++## Task 1: the push repeat goes through Redis (backend)++**Files:** `backend/src/lib/swarmDeliveryPushes.ts`, `backend/src/lib/bus.ts` (message type), test+`backend/src/lib/swarmDeliveryPushes.test.ts`.+**Interfaces:** `SwarmDeliveriesMsg` gains `| { pushes: true }`; `relaySwarmDeliveries` unchanged in signature.++- [x] Failing test: after 4 minutes the repeat reaches the socket only through the machine's channel; a channel that+ delivers nothing stops the repeat (and it is logged).+- [x] Code: publish `{ pushes: true }` on the machine's channel every 4 minutes; the subscriber turns it into `tell({})`.++## Task 2: the server repeats pushes for queued deliveries (backend)++**Files:** `backend/src/superTabs/deliveryRepush.ts` (new), `backend/src/worker.ts`, test+`backend/src/superTabs/deliveryRepush.test.ts`.+**Interfaces:** `repushQueuedDeliveries(db, tell, now): Promise<number>`; `startDeliveryRepush(db, tell, everyMs = 15_000)`.++- [x] Failing test: queued deliveries waiting ≥ 10 s are told once per machine and agent; fresh, claimed and other rows are not.+- [x] Code: one `(status, _id)` read of queued rows (500 max), filter by `updatedAt`, tell `deliveriesWaiting` per pair;+ started in the singleton worker next to the settle pass.++## Task 3: a sender's wait repeats the terminal push (backend)++**Files:** `backend/src/superTabs/store.ts` (`terminalResult`), test `backend/integration/superTabs.test.ts`.++- [x] Failing test: a request still pending at the sender's recheck is announced again to its machine; a claimed or+ answered one is not.+- [x] Code: on each recheck of a pending request (not the first read), call `terminalWaiting` for its machine and agent.++## Task 4: an idle worker's list is read only when told (CLI)++**Files:** `cli/src/superTabs/host.ts`, test `cli/src/superTabs/host.spec.ts`.++- [x] Failing test: with the push lease, an idle worker's list is read once over 3 minutes; the Lead's every 30 s; a pushed+ delivery is read and typed in the same tick; a failed read is retried after its backoff.+- [x] Code: `due` keeps the timer only for Lead rows; a list with a pending read retry is due once its backoff ends.++## Task 5: terminal pickups only when told (CLI)++**Files:** `cli/src/superTabs/terminal.ts`, test `cli/src/superTabs/terminal.spec.ts`.++- [x] Failing test: with the push lease, no pickup over a minute unless `__terminal_waiting` arrives, then at once; without+ the lease every 3 s as today.+- [x] Code: drop the 8 s pushed poll.++## Task 6: measure++**Files:** `backend/integration/superTabEmptyPolls.test.ts` (new), `cli/src/superTabs/emptyPolls.spec.ts` (new).++- [x] DB operations per empty worker list read (full and quiet), per empty terminal pickup, and per repush pass, under+ MongoDB's profiler on a seeded Swarm.+- [x] Requests per idle worker, per Lead and per machine per minute over 10 simulated minutes, before (main) and after.+- [x] Before/after table in the pull request.diff --git a/docs/plans/2026-11-04-personal-lead-start-card-plan.md b/docs/plans/2026-11-04-personal-lead-start-card-plan.mdnew file mode 100644index 000000000..06746ea34--- /dev/null+++ b/docs/plans/2026-11-04-personal-lead-start-card-plan.md@@ -0,0 +1,99 @@+# Start a Lead card Implementation Plan++> This plan follows the project's own way of working (project instructions, Engineer): each plan task commits its+> failing test before its code, and the pull request's one review step is the independent review. There is no+> execution handoff; the Engineer implements it.++**Goal:** In a Personal Swarm project with no Lead, the empty chat offers to start one right away: a card like the+Buddy's start card, with the machine, engine and folder it will use and Start Lead, above Show panes.++**Architecture:** #2633's `PersonalLeadStarter` (desktop/lib/super_tabs/personal_lead.dart) already decides whether a+chat wants a Lead (`wants`), where it starts (`planFor`), starts it once with one claim (`start`), and keeps its+failure. The card is a view over that: `planFor` and `start` take the machine and engine the card picked, and the+card reads the starter's status for its button and failure line. `view.dart`'s empty project chat shows the card+while `wants` holds, above the panes block it already draws.++**Tech Stack:** Flutter (Desktop and web, one code base), widget tests with the Super Tab fixture server, a memory+store and a fake sign-in.++**Spec:** Swarm task #2815's brief (Huy, 11-04, follow-up to #2633), quoted in the pull request.++## Global Constraints++- Only a Personal Swarm project with no Lead shows the card. Team Swarms are unchanged.+- Defaults: the machine is this Mac (the person's own), else another of their computers that's connected. The engine+ is Claude Code, else Codex (#2633's own choice; the Swarm has no other default engine). The folder is the project's+ repo on that machine, else a new folder in the Harness projects folder.+- Copy: "This project has no Lead yet", "Start Lead", "Starting…", "Couldn’t start a Lead: <reason>" (the receipt's+ own words), and "Or send a message below: that starts the Lead too."+- One start per project, through #2633's claim. A message sent before starting still starts it as #2633 does.+- Harness design language: tokens only, no new numeric `EdgeInsets`, `Color` or radius in `super_tabs`+ (`scripts/check-ui-style.py`).+- Desktop guard tests (`check-ui-style`, `laid_out_list_test`) pass before Ready.++## Review Focus++- A machine picked that has no repo checkout: the folder line and the start both fall back to a new Harness folder.+- Start Lead pressed twice, or a message sent while the card's start runs: one claim and one start.+- The Lead appears while the card is shown, for example after another of the person's machines started it: the card+ goes away on the next snapshot.+- None of the person's computers is online, or neither engine is signed in: the card says why and offers no Start.+- A viewer who can't write: no card, as the Buddy start shows none.++---++### Task 1: The starter takes the card's machine and engine++**Files:**+- Modify: `desktop/lib/super_tabs/personal_lead.dart`+- Test: `desktop/test/super_tab_personal_lead_test.dart`++**Interfaces:**+- Produces: `List<MachineState> PersonalLeadStarter.machinesFor(SuperTabController c)`: the person's own connected+ computers, this one first.+- Produces: `PersonalLeadPlan planFor(SuperTabController c, String conversationId, {String? machineId, String? engine})`:+ with `machineId`, that machine and its repo folder (null when it has none there); with `engine`, that engine.+- Produces: `Future<void> start(SuperTabController c, String conversationId, {String? machineId, String? engine})`.++- [ ] **Step 1: Write the failing test** `a start the card asked for uses its engine` in+ `super_tab_personal_lead_test.dart`: `start(c, games, engine: 'codex')` creates the agent with `engine == 'codex'`.+- [ ] **Step 2: Run it and watch it fail:** `flutter test test/super_tab_personal_lead_test.dart` fails because `start`+ takes no engine.+- [ ] **Step 3: Implement** the three interfaces above. `planFor` keeps its fallback order when given nothing.+- [ ] **Step 4: Run it and watch it pass:** the same command passes, along with #2633's existing cases.+- [ ] **Step 5: Commit** the test first, then the code.++### Task 2: The empty project chat shows the card++**Files:**+- Create: `desktop/lib/super_tabs/personal_lead_card.dart`+- Modify: `desktop/lib/super_tabs/view.dart` (the empty-chat branch that calls `_panesWaiting`)+- Test: `desktop/test/super_tab_personal_lead_card_test.dart`++**Interfaces:**+- Consumes: Task 1's `machinesFor`, `planFor` and `start`, plus `statusOf` and `wants`.+- Produces: `PersonalLeadStartCard({required SuperTabController controller, required String conversationId,+ required AppNotifier app})`, keyed `super-lead-start`. Its machine field is `super-lead-start-machine`, its engine+ field `super-lead-start-engine`, its folder line `super-lead-start-folder` and its failure line+ `super-lead-start-error`.++- [ ] **Step 1: Write the failing tests** in `super_tab_personal_lead_card_test.dart`:+ - The card shows with its defaults (`Test host`, `Claude Code`, the repo's folder) above Show panes.+ - With no repo, the folder line reads "A new folder in your Harness projects folder".+ - Start Lead pressed twice makes one claim and one start, on `m` with `claude` in the repo's folder.+ - The engine picked on the card is the one the start uses.+ - A project with a Lead shows no card.+ - A Team Swarm shows no card.+ - A failed start shows "Couldn’t start a Lead: <reason>" on the card, and Start Lead tries again.+- [ ] **Step 2: Run them and watch them fail:** `flutter test test/super_tab_personal_lead_card_test.dart` fails with+ no `super-lead-start`.+- [ ] **Step 3: Implement** the card after the Buddy start card's layout (`buddies.dart` `_BuddyStart`: a medium+ title, one row of fields and a filled button, lines under it). In `view.dart`, show it above the panes block, or+ above the plain "Discuss the plan" line when the project has no panes, while `wants` holds and the reader can+ write.+- [ ] **Step 4: Run them and watch them pass,** then the files that draw the empty chat or start a Lead:+ `super_tab_personal_projects_test.dart`, `super_tab_personal_lead_test.dart`, `super_tab_receipt_test.dart`,+ `super_tab_view_test.dart`. Then the guard tests: `python3 scripts/check-ui-style.py`,+ `flutter test test/laid_out_list_test.dart`.+- [ ] **Step 5: Commit** the tests first, then the code. Light and dark screenshots come from+ `PERSONAL_LEAD_CARD_SHOTS=<dir> flutter test test/super_tab_personal_lead_card_test.dart`.diff --git a/docs/plans/2026-11-04-phone-account-profile-plan.md b/docs/plans/2026-11-04-phone-account-profile-plan.mdnew file mode 100644index 000000000..cb445df4b--- /dev/null+++ b/docs/plans/2026-11-04-phone-account-profile-plan.md@@ -0,0 +1,60 @@+# Profile on the phone Implementation Plan++> **For agentic workers:** Written by the writing-plans skill as the project's instructions adapt it (Engineer role).+> The Engineer implements it task by task, test first, in this session; the pull request's Review step is the one+> independent review. No execution handoff.++**Goal:** From the phone's account row (its avatar, at the top of Settings), Profile opens a sheet where the person+changes their account Name (everywhere) and their @username in each Swarm they are in, with Desktop's words.++**Architecture:** `ApiClient.updateMe` sends `PATCH /api/auth/me` straight to the backend with the phone's sign-in (the+route #2917 added, which validates the name); `AppNotifier.setAccountName` shows the saved name at once and answers a+refusal in one line, as Desktop's does. The sheet (`phone/account_profile_dialog.dart`) is the phone's dialog look+(`widgets/rename_agent_dialog.dart`): Name, then one Username field per Swarm ("@name in Pilot") from the account's+Swarm inbox, through `SwarmProfile.setUsername` (`member.username`). Save sends only what changed, in order (name,+usernames, then a Swarm's own name where it followed the account name), stops at the first refusal and shows it under+its field. Settings' account sheet gets Profile above Sign out.++**Tech Stack:** Flutter (mobile), flutter_test, offscreen screenshots.++**Spec:** task #2655's brief; #2917's Desktop sheet (`desktop/lib/widgets/account_profile_sheet.dart`) and backend rule+(`backend/src/lib/accountName.ts`).++## Global Constraints++- Desktop's words: Profile, Name, Username, `in <Swarm>`, Cancel, Save; "Use 1 to 60 characters, with no hidden ones.",+ "Update Harness to change your name." (a backend from before the route), "Your name was not saved. Try again.".+- Mobile tokens and flat rows; light and dark screenshots; phone tests headless; never install on a phone.+- The per-Swarm "Your profile" sheet stays as it is (Tony's #2919 changes its row).++## Review Focus++- A name saved and a username refused: the name stays saved, the username's refusal shows under it, Save again sends+ only the username.+- An empty or too-long name is refused here, before any call.+- A Swarm the person may not rename in (access revoked) offers no Username field.+- A refusal from the backend is shown in its words, under the Name field.++## Design++N/A for storage: nothing new is stored; it calls the routes #2917 and the Swarm already serve. Failure: every refusal is+shown under its field; a call lost on the way says so.++### Task 1: The account name from the phone++**Files:** `lib/api/api_client.dart` (`updateMe`), `lib/state/app_state.dart` (`setAccountName`); test+`test/api/api_client_test.dart`, `test/phone_edge/account_profile_test.dart`.++- [ ] Failing tests: `updateMe` sends `PATCH /api/auth/me {name}`; `setAccountName` updates `currentUser`, answers a 400's+ message, and 404 as "Update Harness to change your name.".+- [ ] Implement; run.++### Task 2: The Profile sheet and its entry++**Files:** create `lib/phone/account_profile_dialog.dart`; modify `lib/phone/settings_page.dart`; test+`test/phone_edge/account_profile_test.dart`, screenshots.++- [ ] Failing widget tests: Profile above Sign out opens the sheet with the name; Save sends only what changed; empty+ name refused here; a refusal under its field; one Username per Swarm with `@` and `in <Swarm>`; a revoked Swarm offers+ none.+- [ ] Implement; run; light and dark screenshots.diff --git a/docs/plans/2026-11-04-thread-tag-unread-bar-plan.md b/docs/plans/2026-11-04-thread-tag-unread-bar-plan.mdnew file mode 100644index 000000000..994caae18--- /dev/null+++ b/docs/plans/2026-11-04-thread-tag-unread-bar-plan.md@@ -0,0 +1,73 @@+# Thread tag in the unread bar: implementation plan++> Way of working: the project's Engineer role (plan first, then each task test first, one review on the pull request).++**Goal:** When the chat you open holds an unread tag of you inside a thread, the chat says so at its top ("1 new reply+mentions you · Open"), and Open opens that thread at the reply, lit. The thread's root row says how many replies are new.+Reading it clears the row and the sidebar's red number. Today's main-chat unread bar is unchanged. (Task #2814, Lê Lộc.)++**Architecture:** The tags already reach Desktop (`SuperTabMentions.waiting`, with `threadId` and `messageSequence`), and+`SuperTabAttention.tagsIn` already counts those past the thread's read mark for the sidebar. A new+`SuperTabAttention.threadTagsIn` lists those tags in thread replies, oldest first. The chat draws a new+`SuperTabThreadTagBar` row above today's bar while that list is not empty. Open calls `openThread(root, at: reply)`; the+controller keeps the reply as the thread's target and the thread panel lights it once held. Opening the thread reads it+(`_seeThread`), which already moves the thread mark, so the tag stops counting in the bar and the sidebar. The thread+line takes the followed thread's `unreadReplies` as "N new".++**Tech stack:** Flutter (desktop/lib/super_tabs), widget tests with the memory `ConversationServer` fixture and a fake+sign-in. No backend change.++**Spec:** the task's brief (#2814) and the mockup posted to Lê Lộc in the project chat.++## Global constraints++- Desktop and web share this code; the phone app has its own chat code and is out of scope.+- Harness design language: flat row, words carry the meaning (never colour alone), tokens from `DesktopChrome`/`grid`.+- Desktop tests use the memory store and a fake sign-in; nothing signs the real CLI out.+- No backend or cli/src/core change.++## Review focus++- The bar counts exactly what the sidebar's red number counts for thread tags (same mark, same muted rule).+- Open lands on the oldest tag; the panel lights the reply once it is held, without following the end over it.+- A main-chat unread keeps today's bar, its Jump and Mark as read.++## Design++N/A because this stores, syncs and exposes no new data: it reads the tags and thread marks Desktop already holds.++## Task 1: thread tags of a chat, oldest first++**Files:** `desktop/lib/super_tabs/attention.dart`, `desktop/test/super_tab_thread_tag_bar_test.dart`++**Interfaces:** `List<SuperTabMention> SuperTabAttention.threadTagsIn(String conversationId)`++- [ ] Failing test: two thread tags in one chat list oldest first; one read past its thread mark drops out; a main-stream+ tag and a muted chat list nothing.+- [ ] Code that passes it.++## Task 2: the bar, and Open at the reply++**Files:** `desktop/lib/super_tabs/unread_line.dart`, `view.dart`, `controller.dart`, `thread_panel.dart`, the test above++**Interfaces:** `SuperTabThreadTagBar({count, onOpen})`; `SuperTabController.openThread(root, {shown, String? at})`;+`SuperTabController.threadTarget` (the reply to light, by root).++- [ ] Failing widget tests: a thread tag shows "1 new reply mentions you · Open"; Open opens the thread with the reply+ lit; the bar and the sidebar count go once read; two threads say "2 new replies mention you" and Open goes to+ the oldest first, then the bar says 1; a main-chat unread shows today's bar and no thread row.+- [ ] Code that passes them.++## Task 3: the thread row's new replies++**Files:** `desktop/lib/super_tabs/message_row.dart`, `view.dart`, the test above++**Interfaces:** `SuperTabThreadLine.fresh` (new replies, 0 for none)++- [ ] Failing test: an unread followed thread's row says "2 new"; once read it does not.+- [ ] Code that passes it.++## Task 4: screenshots and guard tests++- [ ] Light and dark screenshots of the chat with the bar and the row (`SUPER_TAB_THREAD_TAG_SHOTS=<dir>`).+- [ ] Desktop guard tests: `check-ui-style`, `laid_out_list_test`, the changed files' tests.diff --git a/docs/plans/2026-11-04-waiting-notice-opens-terminal-plan.md b/docs/plans/2026-11-04-waiting-notice-opens-terminal-plan.mdnew file mode 100644index 000000000..58cbbf4c1--- /dev/null+++ b/docs/plans/2026-11-04-waiting-notice-opens-terminal-plan.md@@ -0,0 +1,81 @@+# Waiting on you opens the agent's terminal Implementation Plan++> Implemented by the task's Engineer task by task, each failing test committed before its code (project instructions,+> Engineer). One independent review on the pull request.++**Goal:** One click on a "Waiting on you" notice for a Swarm agent opens that agent's terminal beside its task chat,+focused on the prompt it waits on. The notice can be the toast, the bell's Notifications list, or Activity's+"<agent> is waiting on you" row. When no chat can hold the terminal, the Swarm view says why (task #2792, Huy,+2026-11-04).++**Architecture:** Today the toast (`AgentAlertBanners` → `AppNotifier.revealAgentFromAlert`) reveals a pane, or adds+the agent to the active tab. When that tab is a Swarm tab, `SuperTabWorkspace._syncTerminal` closes any pane that is not+one of its chat's terminals, so the click undoes itself and nothing opens.++- `revealAgentFromAlert` first looks for a Swarm agent with that machine and harness id in the loaded Swarms+ (`superTabs.loadedControllers`). When it finds one, it brings that Swarm's tab forward (`openSuperTab`) and asks the+ controller to open the agent's terminal (`SuperTabController.openAgentTerminal`, a request the view on screen takes,+ like `openNotice`). An agent no Swarm holds keeps the old path, which now opens a new tab when the current one is a+ Swarm tab.+- `SuperTabWorkspace` takes the request with #2951's rules (`superTabAgentTerminalGroups`). It picks the chat where the+ agent's work waits on the reader, else the one on screen, else the first, then opens and focuses the terminal there+ (`_focusAgent`). With no chat, it shows `superTabOpenTerminalBlocked`'s reason.+- Activity's agent row opens its task and asks for the assignee's terminal the same way.+- The bell's Notifications list falls back to `revealAgentFromAlert` for an agent that is not one of this window's+ panes, which is a Swarm agent.++**Tech Stack:** Flutter (Desktop and web share this code), widget tests on `SuperTabLaunchFixture` (memory store, fake+sign-in).++**Spec:** task #2792's brief.++## Global Constraints++- Red first for each click and for the not-allowed case.+- Reuse #2951's `superTabAgentTerminalGroups` and `superTabOpenTerminalBlocked`; no second rule for where a terminal+ can open.+- No backend change: the backend already opens a terminal only in a chat that holds the agent.+- Desktop tests use a memory store and a fake sign-in; screenshots offscreen, light and dark.++## Design++- growth: N/A because nothing is stored; the request is one field cleared when taken.+- concurrency: N/A because it is UI state on the main isolate.+- read cost: N/A because no read is added; it looks only at the loaded Swarms' snapshots.+- scale: N/A because it scans the loaded Swarms' agents once per click.+- compatibility: N/A because no wire or saved format changes.+- migration + rollback: N/A because nothing is stored; revert the commit.+- audience: the server decides which agents and chats the reader's snapshot holds, and which terminals open.+- identity: N/A because no login is used.+- failure: a chat that can't hold the terminal says why, and a terminal that fails to attach shows the workspace's+ existing error with Retry.+- platforms: macOS, Linux, Windows and web (shared Flutter code).++## Review Focus++- The Swarm agent is matched by machine id and harness id, the same pair the workspace's panes use.+- An agent no loaded Swarm holds keeps today's behaviour, and no longer adds a pane to a Swarm tab that would close it.+- Which chat is chosen when several hold the agent.++## Task 1: the toast opens a Swarm agent's terminal at its prompt++**Files:** desktop/lib/state/app_state.dart, desktop/lib/super_tabs/controller.dart,+desktop/lib/super_tabs/workspace.dart, desktop/test/super_tab_waiting_notice_test.dart++**Interfaces:** `SuperTabController.openAgentTerminal(String agentId, {String? conversationId})` and its+`agentTerminalRequest`.++- [ ] Test: a Swarm tab on another chat; a toast for Nova (waiting in its task) is clicked; the task is selected and+ Nova's terminal is the focused pane.+- [ ] Test: the toast for an agent no chat holds brings its Swarm forward and shows the reason; no pane is added.+- [ ] Run red, commit; implement; run green, commit.++## Task 2: Activity's row and the bell's list do the same++**Files:** desktop/lib/super_tabs/activity.dart, desktop/lib/super_tabs/activity_view.dart,+desktop/lib/screens/swarm_screen.dart, desktop/test/super_tab_waiting_notice_test.dart++- [ ] Test: Activity's "Nova is waiting on you" opens the task with Nova's terminal focused.+- [ ] Test: the bell's row for a Swarm agent opens its terminal there.+- [ ] Shots: the task with the terminal open, and the reason, light and dark.+- [ ] Run red, commit; implement; run green, commit.diff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dartindex dec4a3e16..617ae5075 100644--- a/mobile/lib/api/api_client.dart+++ b/mobile/lib/api/api_client.dart@@ -105,6 +105,14 @@ class ApiClient {return unwrapApiResponse(res) as Map<String, dynamic>?;}+ /// Saves the signed-in person's own account name (`PATCH /api/auth/me`, task #2655, the route #2917 added) and+ /// answers the profile as [me] does. The backend checks the name and says why it refused in words; one from before+ /// the route answers 404.+ Future<Map<String, dynamic>?> updateMe({required String name}) async {+ final res = await _dio.patch('/api/auth/me', data: {'name': name});+ return unwrapApiResponse(res) as Map<String, dynamic>?;+ }+// -- machines --Future<List<Machine>> machines() async {final res = await _dio.get('/api/machines');diff --git a/mobile/lib/phone/account_profile_dialog.dart b/mobile/lib/phone/account_profile_dialog.dartnew file mode 100644index 000000000..37c9a8546--- /dev/null+++ b/mobile/lib/phone/account_profile_dialog.dart@@ -0,0 +1,282 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../state/app_state.dart';+import '../swarm/swarm_face.dart';+import '../swarm/swarm_profile.dart';+import '../swarm/swarm_session.dart';++/// One Swarm the person is in, as Profile changes their @username there (`member.username`) and, when it followed+/// their account name, the Swarm's own name for them (`member.name`).+class AccountProfileSwarm {+ const AccountProfileSwarm({+ required this.name,+ required this.username,+ required this.personName,+ required this.setUsername,+ required this.setName,+ });++ /// The Swarm's name, as "in Pilot" says it.+ final String name;+ final String? username;++ /// The name this Swarm shows for them.+ final String? personName;++ /// Null once saved, else the Swarm's refusal in its words.+ final Future<String?> Function(String username) setUsername;+ final Future<String?> Function(String name) setName;+}++/// The Swarms of [session] the person may still rename themselves in (`SwarmProfile.canRename`), in the inbox's+/// order: each a Username field in Profile.+List<AccountProfileSwarm> accountProfileSwarms(SwarmSession? session) {+ if (session == null) return const [];+ final targets = <AccountProfileSwarm>[];+ for (final listing in session.inbox.swarms) {+ final reader = session.inbox.reader(listing.id);+ if (reader == null) continue;+ final profile = SwarmProfile(reader: reader);+ if (!profile.canRename) continue;+ final me = reader.snapshot?.person(reader.accountId);+ targets.add(AccountProfileSwarm(+ name: listing.name,+ username: me?.username,+ personName: me?.name,+ setUsername: profile.setUsername,+ setName: profile.setName,+ ));+ }+ return targets;+}++/// Profile (task #2655), from the account row's sheet in Settings: the account's name, everywhere, and the @username+/// in each Swarm of [swarms]. The desktop's Profile (#2917) in the phone's dialog look (`rename_agent_dialog.dart`).+Future<void> showAccountProfile(+ BuildContext context,+ AppNotifier notifier, {+ List<AccountProfileSwarm> swarms = const [],+}) => showAppDialog<void>(+ context: context,+ builder: (_) => _AccountProfileDialog(notifier: notifier, swarms: swarms),+);++/// The backend's rule (backend/src/lib/accountName.ts), said before sending when it is plain here.+const _invalidName = 'Use 1 to 60 characters, with no hidden ones.';+const _maxName = 60;+const _maxUsername = 32;++class _AccountProfileDialog extends StatefulWidget {+ const _AccountProfileDialog({required this.notifier, required this.swarms});++ final AppNotifier notifier;+ final List<AccountProfileSwarm> swarms;++ @override+ State<_AccountProfileDialog> createState() => _AccountProfileDialogState();+}++class _AccountProfileDialogState extends State<_AccountProfileDialog> {+ /// The name when the sheet opened: a Swarm's own name follows only a name changed here, and only where it was+ /// that name, so one set on purpose in a Swarm stays.+ late final String _openedName = widget.notifier.currentUser?.name ?? '';+ late final _name = TextEditingController(text: _openedName);+ late final _usernames = [for (final s in widget.swarms) TextEditingController(text: s.username ?? '')];++ /// What each Swarm holds now: updated as each save lands, so Save again sends only what is left.+ late final _savedUsernames = [for (final s in widget.swarms) s.username ?? ''];+ late final _swarmNames = [for (final s in widget.swarms) s.personName];+ late String _savedName = _openedName;++ bool _busy = false;+ String? _nameError;+ late final _usernameErrors = List<String?>.filled(widget.swarms.length, null);++ @override+ void dispose() {+ _name.dispose();+ for (final c in _usernames) {+ c.dispose();+ }+ super.dispose();+ }++ /// One space between words, as the backend keeps it.+ static String _tidy(String text) => text.replaceAll(RegExp(r'\s+'), ' ').trim();++ /// Sends only what differs from what is saved, in order: the account name, each username, then each Swarm's own+ /// name where it followed the old one. Stops at the first refusal and says why under its field.+ Future<void> _save() async {+ if (_busy) return;+ final name = _tidy(_name.text);+ if (name.isEmpty || name.runes.length > _maxName) {+ setState(() => _nameError = _invalidName);+ return;+ }+ setState(() {+ _busy = true;+ _nameError = null;+ _usernameErrors.fillRange(0, _usernameErrors.length, null);+ });+ String? failure;+ int? failedSwarm;+ if (name != _tidy(_savedName)) {+ failure = await widget.notifier.setAccountName(name);+ if (failure == null) _savedName = name;+ }+ for (var i = 0; failure == null && i < widget.swarms.length; i++) {+ final username = _usernames[i].text.trim();+ if (username.isEmpty || username == _savedUsernames[i]) continue;+ failure = await widget.swarms[i].setUsername(username);+ if (failure == null) {+ _savedUsernames[i] = username;+ } else {+ failedSwarm = i;+ }+ }+ final renamed = name != _tidy(_openedName);+ for (var i = 0; failure == null && renamed && i < widget.swarms.length; i++) {+ final own = _swarmNames[i];+ if (own == null || _tidy(own) != _tidy(_openedName)) continue;+ failure = await widget.swarms[i].setName(name);+ if (failure == null) {+ _swarmNames[i] = name;+ } else {+ failedSwarm = null;+ }+ }+ if (!mounted || !(ModalRoute.of(context)?.isActive ?? false)) return;+ if (failure == null) {+ Navigator.of(context).pop();+ return;+ }+ setState(() {+ _busy = false;+ if (failedSwarm case final i?) {+ _usernameErrors[i] = failure;+ } else {+ _nameError = failure;+ }+ });+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final danger = Theme.of(context).colorScheme.error;+ void submit(String _) => unawaited(_save());+ return Dialog(+ insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),+ child: Semantics(+ scopesRoute: true,+ namesRoute: true,+ explicitChildNodes: true,+ label: 'Profile',+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 360),+ child: SingleChildScrollView(+ padding: const EdgeInsets.all(20),+ child: Column(+ key: const ValueKey('account-profile-sheet'),+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(+ 'Profile',+ style: TextStyle(color: grid.AppPalette.textPrimary, fontSize: 17, fontWeight: grid.AppFont.semibold),+ ),+ const SizedBox(height: 18),+ _label('Name'),+ TextField(+ key: const ValueKey('account-profile-name'),+ controller: _name,+ autofocus: true,+ enabled: !_busy,+ maxLength: _maxName,+ textInputAction: TextInputAction.done,+ textCapitalization: TextCapitalization.words,+ decoration: const InputDecoration(counterText: ''),+ onChanged: (_) => setState(() => _nameError = null),+ onSubmitted: submit,+ ),+ if (_nameError case final error?) _error('account-profile-name-error', error, danger),+ for (var i = 0; i < widget.swarms.length; i++) ...[+ const SizedBox(height: 16),+ Row(+ children: [+ _label('Username'),+ const SizedBox(width: 8),+ Expanded(+ child: Text(+ 'in ${widget.swarms[i].name}',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(color: grid.AppPalette.textSecondary, fontSize: 13),+ ),+ ),+ ],+ ),+ TextField(+ key: ValueKey('account-profile-username-$i'),+ controller: _usernames[i],+ enabled: !_busy,+ maxLength: _maxUsername,+ autocorrect: false,+ textInputAction: TextInputAction.done,+ decoration: const InputDecoration(counterText: '', prefixText: '@'),+ onChanged: (_) => setState(() => _usernameErrors[i] = null),+ onSubmitted: submit,+ ),+ if (_usernameErrors[i] case final error?) _error('account-profile-username-$i-error', error, danger),+ ],+ const SizedBox(height: 20),+ Row(+ mainAxisAlignment: MainAxisAlignment.end,+ children: [+ TextButton(+ key: const ValueKey('account-profile-cancel'),+ onPressed: () => Navigator.of(context).pop(),+ child: const Text('Cancel'),+ ),+ const SizedBox(width: 8),+ FilledButton(+ key: const ValueKey('account-profile-save'),+ onPressed: _busy ? null : () => unawaited(_save()),+ child: const Text('Save'),+ ),+ ],+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }++ Widget _label(String text) => Padding(+ padding: const EdgeInsets.only(bottom: 6),+ child: Text(text, style: TextStyle(color: grid.AppPalette.textPrimary, fontSize: 14, fontWeight: grid.AppFont.medium)),+ );++ /// A refusal under its field, read out when it appears, in the dialog's red ink.+ Widget _error(String key, String text, Color danger) => Semantics(+ liveRegion: true,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(2, 8, 2, 0),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Padding(padding: const EdgeInsets.only(top: 1), child: Icon(LucideIcons.circleAlert300, size: 15, color: danger)),+ const SizedBox(width: 6),+ Expanded(child: Text(text, key: ValueKey(key), style: TextStyle(color: danger, fontSize: 13, height: 1.35))),+ ],+ ),+ ),+ );+}diff --git a/mobile/lib/phone/settings_page.dart b/mobile/lib/phone/settings_page.dartindex 82d7da6dd..ea4cafdd4 100644--- a/mobile/lib/phone/settings_page.dart+++ b/mobile/lib/phone/settings_page.dart@@ -52,6 +52,8 @@ import 'tty.dart';import 'usage_entry.dart';import 'voice_language.dart';import 'voice_language_store.dart';+import '../swarm/swarm_session.dart' show SwarmScope;+import 'account_profile_dialog.dart';/// The phone's Settings tab.///@@ -557,10 +559,18 @@ class _Body extends StatelessWidget {}void _showAccountSheet(BuildContext context, AppNotifier notifier) {+ // The Swarms read under the sheet's own context, before it opens: a Username field each (#2655).+ final swarms = accountProfileSwarms(SwarmScope.of(context));showPhoneSheet(context,title: notifier.currentUser?.email ?? 'Signed in',actions: [+ // Your name, and your @username in each Swarm: the desktop's avatar menu Profile (#2917).+ PhoneSheetAction(+ icon: LucideIcons.user300,+ label: 'Profile',+ onTap: () => unawaited(showAccountProfile(context, notifier, swarms: swarms)),+ ),PhoneSheetAction(icon: LucideIcons.logOut300,label: 'Sign out',diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 8f5b06e0e..36b30b0a6 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -1977,6 +1977,28 @@ class AppNotifier extends ChangeNotifier {return load;}+ /// Saves the signed-in person's own account name (Profile, task #2655) and shows it at once; answers why it was+ /// refused, in one short line, or null once saved. As the desktop's (`setAccountName`, #2917).+ Future<String?> setAccountName(String name) async {+ final revision = _authRevision;+ try {+ final me = await api.updateMe(name: name);+ if (me == null || !_authWorkCurrent(revision)) return null;+ final profile = CurrentUserProfile.fromMe(me);+ // Another account's answer is not this one's name: the next profile read settles it.+ if (currentUser?.id != null && profile.id != currentUser?.id) return null;+ currentUser = profile;+ notifyListeners();+ return null;+ } on ApiException catch (error) {+ // A backend from before the route.+ if (error.status == 404) return 'Update Harness to change your name.';+ return error.message;+ } catch (_) {+ return 'Your name was not saved. Try again.';+ }+ }+Future<void> _readProfile(int revision) async {try {final me = await api.me();diff --git a/mobile/test/api/api_client_test.dart b/mobile/test/api/api_client_test.dartindex 90a7d8f5c..16dfa40c3 100644--- a/mobile/test/api/api_client_test.dart+++ b/mobile/test/api/api_client_test.dart@@ -150,6 +150,33 @@ void main() {Map<String, Object?> ok(Object? data) => {'success': true, 'data': data};+ group('the account name (#2655)', () {+ test('PATCHes /api/auth/me with the name, signed as the phone, and answers the profile', () async {+ backend.answer = (_, _) => (+ status: 200,+ body: ok({'user': {'id': 'u', 'name': 'Ada King', 'email': '[email protected]'}}),+ );+ final me = await client(_Tokens(['phone-token'])).updateMe(name: 'Ada King');+ expect((me?['user'] as Map)['name'], 'Ada King');+ final request = backend.requests.single;+ expect(request.method, 'PATCH');+ expect(request.path, '/api/auth/me');+ expect(request.headers.value('authorization'), 'Bearer phone-token');+ expect(jsonDecode(utf8.decode(request.body)), {'name': 'Ada King'});+ });++ test("a refusal comes back in the backend's words, with its status", () async {+ backend.answer = (_, _) => (+ status: 400,+ body: {'success': false, 'error': {'code': 'INVALID_NAME', 'message': 'Use a name, not an email address.'}},+ );+ await expectLater(+ client(_Tokens(['t'])).updateMe(name: '[email protected]'),+ throwsA(isA<ApiException>().having((e) => e.message, 'message', 'Use a name, not an email address.').having((e) => e.status, 'status', 400)),+ );+ });+ });+group('a Swarm read', () {test('answers the value, signed with this sign-in, its query kept', () async {backend.answer = (_, _) => (status: 200, body: ok({'tabs': <Object>[]}));diff --git a/mobile/test/phone_edge/account_profile_shots_test.dart b/mobile/test/phone_edge/account_profile_shots_test.dartnew file mode 100644index 000000000..518a6d5f8--- /dev/null+++ b/mobile/test/phone_edge/account_profile_shots_test.dart@@ -0,0 +1,95 @@+import 'dart:convert';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/phone/account_profile_dialog.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/color_palette.dart';++import 'edge_fixture.dart';++/// Profile's screenshots for review (#2655): the sheet with two Swarms, and a refusal under a username, in both+/// phone themes. Set ACCOUNT_PROFILE_SHOTS to a folder to write them.+final shots = Platform.environment['ACCOUNT_PROFILE_SHOTS'];+void main() {+ setUpAll(() async {+ if (shots == null || !Platform.isMacOS) return;+ final sf = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),+ );+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {+ await (FontLoader(family)..addFont(Future.value(sf))).load();+ }+ final mono = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),+ );+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {+ await (FontLoader(family)..addFont(Future.value(mono))).load();+ }+ final manifest =+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;+ for (final entry in manifest.cast<Map<String, dynamic>>()) {+ final loader = FontLoader(entry['family'] as String);+ for (final font in (entry['fonts'] as List).cast<Map>()) {+ loader.addFont(rootBundle.load(font['asset'] as String));+ }+ await loader.load();+ }+ });++ for (final brightness in Brightness.values) {+ testWidgets('Profile, ${brightness.name}', (tester) async {+ await tester.binding.setSurfaceSize(const Size(390, 844));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);+ addTearDown(tester.view.resetPadding);+ final palette = brightness == Brightness.light ? HarnessPalette.paper : HarnessPalette.graphite;+ final before = (AppTheme.palette.value, AppTheme.brightness.value);+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = brightness;+ addTearDown(() {+ AppTheme.palette.value = before.$1;+ AppTheme.brightness.value = before.$2;+ });+ final app = edgeApp();+ app.api = EdgeApi(app, AuthSession());+ app.currentUser = const CurrentUserProfile(id: 'u', name: 'Ada Lovelace', email: '[email protected]');+ final boundary = GlobalKey();+ AccountProfileSwarm swarm(String name, String username, {String? refuse}) => AccountProfileSwarm(+ name: name, username: username, personName: 'Ada Lovelace',+ setUsername: (_) async => refuse, setName: (_) async => null);+ final swarms = [swarm('Pilot', 'ada', refuse: 'That username is taken in this Swarm.'), swarm('Scout', 'ada-l')];+ await tester.pumpWidget(RepaintBoundary(key: boundary, child: phoneApp(+ Builder(builder: (context) => Scaffold(body: Center(child: TextButton(+ onPressed: () => showAccountProfile(context, app, swarms: swarms), child: const Text('open'))))),+ brightness: brightness)));+ await tester.tap(find.text('open'));+ await frames(tester);+ Future<void> shot(String name) => tester.runAsync(() async {+ final image = await (boundary.currentContext!.findRenderObject()! as RenderRepaintBoundary).toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/account-profile-$name-${brightness.name}.png').writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ FocusManager.instance.primaryFocus?.unfocus();+ await frames(tester);+ await shot('open');+ await tester.enterText(find.byKey(const ValueKey('account-profile-username-0')), 'ada2');+ FocusManager.instance.primaryFocus?.unfocus();+ await tester.tap(find.text('Save'));+ await frames(tester);+ await shot('refused');+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 3));+ app.dispose();+ await tester.pump(const Duration(seconds: 30));+ }, skip: shots == null);+ }+}diff --git a/mobile/test/phone_edge/account_profile_test.dart b/mobile/test/phone_edge/account_profile_test.dartnew file mode 100644index 000000000..e200fe6c4--- /dev/null+++ b/mobile/test/phone_edge/account_profile_test.dart@@ -0,0 +1,213 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/api/api_client.dart';+import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/phone/account_profile_dialog.dart';+import 'package:harness_mobile/phone/settings_page.dart';+import 'package:harness_mobile/state/app_state.dart';++import 'edge_fixture.dart';++/// The account's name as the backend answers `PATCH /api/auth/me` (#2917): saved, or refused in its words.+class _ProfileApi extends EdgeApi {+ _ProfileApi(super.app, super.session);++ final names = <String>[];+ Object? refuse;++ @override+ Future<Map<String, dynamic>?> updateMe({required String name}) async {+ names.add(name);+ final refusal = refuse;+ if (refusal != null) throw refusal;+ return {+ 'user': {'id': 'u', 'name': name, 'email': '[email protected]'},+ };+ }+}++/// One Swarm's username, and its own name, as the sheet changes them (`SwarmProfile.setUsername`, `setName`).+class _Swarm {+ _Swarm(this.name, {this.username, this.personName});++ final String name;+ String? username, personName;+ final sent = <String>[];+ String? refuseUsername;++ AccountProfileSwarm get target => AccountProfileSwarm(+ name: name,+ username: username,+ personName: personName,+ setUsername: (value) async {+ sent.add('username $value');+ if (refuseUsername case final refusal?) return refusal;+ username = value;+ return null;+ },+ setName: (value) async {+ sent.add('name $value');+ personName = value;+ return null;+ },+ );+}++void main() {+ late AppNotifier app;+ late _ProfileApi api;++ AppNotifier signedIn() {+ final notifier = edgeApp();+ api = _ProfileApi(notifier, AuthSession());+ notifier.api = api;+ notifier.currentUser = const CurrentUserProfile(id: 'u', name: 'Ada Lovelace', email: '[email protected]');+ return notifier;+ }++ Future<void> open(WidgetTester tester, {List<_Swarm> swarms = const [], Brightness brightness = Brightness.dark}) async {+ setPhone(tester, largePhone);+ app = signedIn();+ await tester.pumpWidget(phoneApp(+ Builder(builder: (context) => TextButton(+ onPressed: () => showAccountProfile(context, app, swarms: [for (final s in swarms) s.target]),+ child: const Text('open'),+ )),+ brightness: brightness,+ ));+ await tester.tap(find.text('open'));+ await frames(tester);+ }++ Future<void> close(WidgetTester tester) async {+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 3));+ app.dispose();+ await tester.pump(const Duration(seconds: 30));+ }++ Finder field(String key) => find.byKey(ValueKey(key));+ Future<void> save(WidgetTester tester) async {+ await tester.tap(find.text('Save'));+ await frames(tester);+ }++ group('the account name (#2655)', () {+ test('setAccountName saves it, shows it at once, and answers a refusal in its words', () async {+ final notifier = signedIn();+ expect(await notifier.setAccountName('Ada King'), isNull);+ expect(notifier.currentUser?.name, 'Ada King');+ api.refuse = ApiException('Use a name, not an email address.', status: 400);+ expect(await notifier.setAccountName('[email protected]'), 'Use a name, not an email address.');+ api.refuse = ApiException('Not found', status: 404);+ expect(await notifier.setAccountName('Ada'), 'Update Harness to change your name.');+ api.refuse = StateError('socket closed');+ expect(await notifier.setAccountName('Ada'), 'Your name was not saved. Try again.');+ expect(notifier.currentUser?.name, 'Ada King');+ notifier.dispose();+ });+ });++ group('Profile (#2655)', () {+ testWidgets('opens on the name; Save sends a changed name and closes', (tester) async {+ await open(tester);+ expect(find.text('Profile'), findsOneWidget);+ expect(find.text('Name'), findsOneWidget);+ expect(tester.widget<TextField>(field('account-profile-name')).controller!.text, 'Ada Lovelace');+ // No Swarm: no username.+ expect(find.text('Username'), findsNothing);+ await tester.enterText(field('account-profile-name'), ' Ada King ');+ await save(tester);+ expect(api.names, ['Ada King']);+ expect(app.currentUser?.name, 'Ada King');+ expect(find.text('Profile'), findsNothing);+ await close(tester);+ });++ testWidgets('an empty name is refused here, a long one is held to 60, and nothing is sent', (tester) async {+ await open(tester);+ await tester.enterText(field('account-profile-name'), ' ');+ await save(tester);+ expect(find.text('Use 1 to 60 characters, with no hidden ones.'), findsOneWidget);+ expect(api.names, isEmpty);+ await tester.enterText(field('account-profile-name'), 'x' * 61);+ await frames(tester);+ expect(tester.widget<TextField>(field('account-profile-name')).controller!.text.length, 60);+ await close(tester);+ });++ testWidgets("the backend's refusal shows under Name, and an edit takes it back", (tester) async {+ await open(tester);+ api.refuse = ApiException('Use a name, not an email address.', status: 400);+ await tester.enterText(field('account-profile-name'), '[email protected]');+ await save(tester);+ expect(find.byKey(const ValueKey('account-profile-name-error')), findsOneWidget);+ expect(find.text('Use a name, not an email address.'), findsOneWidget);+ expect(find.text('Profile'), findsOneWidget, reason: 'it stays open');+ await tester.enterText(field('account-profile-name'), 'Ada');+ await frames(tester);+ expect(find.text('Use a name, not an email address.'), findsNothing);+ await close(tester);+ });++ testWidgets('one Username per Swarm, with @ and the Swarm\'s name; only what changed is sent', (tester) async {+ final pilot = _Swarm('Pilot', username: 'ada', personName: 'Ada Lovelace');+ final scout = _Swarm('Scout', username: 'ada-l', personName: 'Ada');+ await open(tester, swarms: [pilot, scout]);+ expect(find.text('Username'), findsNWidgets(2));+ expect(find.text('in Pilot'), findsOneWidget);+ expect(find.text('in Scout'), findsOneWidget);+ expect(tester.widget<TextField>(field('account-profile-username-0')).decoration?.prefixText, '@');+ expect(tester.widget<TextField>(field('account-profile-username-1')).controller!.text, 'ada-l');+ await tester.enterText(field('account-profile-username-1'), 'lovelace');+ await save(tester);+ // The name did not change: no account call, and no Swarm name follows it.+ expect(api.names, isEmpty);+ expect(pilot.sent, isEmpty);+ expect(scout.sent, ['username lovelace']);+ expect(find.text('Profile'), findsNothing);+ await close(tester);+ });++ testWidgets('a new name is followed by the Swarm name where it was the same; a refused username stays '+ 'under its field, and Save again sends only it', (tester) async {+ final pilot = _Swarm('Pilot', username: 'ada', personName: 'Ada Lovelace')..refuseUsername = 'That username is taken in this Swarm.';+ final scout = _Swarm('Scout', username: 'ada-l', personName: 'Countess');+ await open(tester, swarms: [pilot, scout]);+ await tester.enterText(field('account-profile-name'), 'Ada King');+ await tester.enterText(field('account-profile-username-0'), 'ada2');+ await save(tester);+ expect(api.names, ['Ada King']);+ expect(pilot.sent, ['username ada2']);+ expect(find.byKey(const ValueKey('account-profile-username-0-error')), findsOneWidget);+ expect(find.text('That username is taken in this Swarm.'), findsOneWidget);+ pilot.refuseUsername = null;+ await save(tester);+ // The name is saved already: not sent again. Pilot's own name followed the change; Scout's, set on purpose, did not.+ expect(api.names, ['Ada King']);+ expect(pilot.sent, ['username ada2', 'username ada2', 'name Ada King']);+ expect(scout.sent, isEmpty);+ expect(find.text('Profile'), findsNothing);+ await close(tester);+ });+ });++ group('the entry (#2655)', () {+ testWidgets('Profile sits above Sign out in the account sheet, and opens the sheet', (tester) async {+ setPhone(tester, largePhone);+ app = signedIn();+ await tester.pumpWidget(phoneApp(SettingsPage(notifier: app, large: true)));+ await frames(tester);+ await tester.tap(find.text('Ada Lovelace'));+ await frames(tester);+ final profile = tester.getTopLeft(find.text('Profile'));+ final signOut = tester.getTopLeft(find.text('Sign out'));+ expect(profile.dy, lessThan(signOut.dy));+ await tester.tap(find.text('Profile'));+ await frames(tester);+ expect(find.byKey(const ValueKey('account-profile-name')), findsOneWidget);+ await close(tester);+ });+ });+}