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 b1817: #2985 #2992 #2993 #2995 #2996 #2997 #2998 #2999 #3000 #3004 (#3009)
0xken15644e0765c645
diff --git a/backend/integration/bench/README.md b/backend/integration/bench/README.mdindex f724a37b8..2c3d11d49 100644--- a/backend/integration/bench/README.md+++ b/backend/integration/bench/README.md@@ -71,6 +71,15 @@ NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADATABASE_URL=mongodb://127.0.0.1:1/bench-never-used npx tsx integration/bench/changesPollCost.ts```+To see what each hot call costs MongoDB once a Swarm has grown (task #2839): the benchmark's Swarm gets `--starts` finished+starts (3000) and `--dormant` quiet Lead conversations (1500) as rows, then each call runs once after a post, and the+profiler counts its commands and getMores by collection. `GROWN_SHAPES=1` prints each large part read and its plan:++```bash+NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= \+ DATABASE_URL=mongodb://127.0.0.1:1/bench-never-used npx tsx integration/bench/grownFeedOps.ts+```+The bench's own tests (helpers, plus a short run of the whole scenario), and its typecheck:```bashdiff --git a/backend/integration/bench/grownFeedOps.ts b/backend/integration/bench/grownFeedOps.tsnew file mode 100644index 000000000..f7a3bf343--- /dev/null+++ b/backend/integration/bench/grownFeedOps.ts@@ -0,0 +1,126 @@+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 { startProfiling } from './profile.js'+import { seedSwarm } from './seed.js'+import { benchStamps } from './stamps.js'++/**+ * Database operations per call once a Swarm's starts and quiet conversations have grown (task #2839: Atlas ops per request+ * rose 38% at flat traffic, with SwarmStart and SwarmGroup getMores growing). The benchmark's seeded Swarm gets `--starts`+ * finished starts (kept 7 days) and `--dormant` quiet conversations of its Lead, written as rows; then each call runs once+ * after a post, the way production runs them after any change, and the profiler counts its commands and getMores by+ * collection. 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/grownFeedOps.ts [--starts 3000] [--dormant 1500]+ */+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 starts = flag('--starts', 3000), dormant = flag('--dormant', 1500)+ const { config } = parseArgs(argv.filter((arg, i) => !['--starts', '--dormant'].includes(arg) && !['--starts', '--dormant'].includes(argv[i - 1]!)))+ 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)+ await grow(database.db, swarm.tabId, swarm.leadId, starts, dormant)+ const owner = people[0]!, host = people[1]!+ const worker = swarm.workers.find(w => w.machine === 1) ?? swarm.workers[0]!+ let cursor = (await call<{ cursor: string }>(owner, 'GET', `/api/super-tabs/${swarm.tabId}/parts`)).data!.cursor+ const hostReader = driver.hostReader(host, machineId(1))+ await hostReader.poll()+ let n = 0+ const post = async () => {+ const { code } = await driver.execute(swarm.tabId, owner, `grown-${n++}`, { type: 'message.send', conversationId: worker.group, text: 'One post.', replyTo: null, recipientIds: [] })+ if (code) throw new Error(`post: ${code}`)+ }+ const calls: Array<[string, () => Promise<unknown>]> = [+ ['GET changes (Desktop poll)', async () => {+ const reply = await call<Changes>(owner, 'GET', `/api/super-tabs/${swarm.tabId}/changes?cursor=${cursor}`)+ if (!reply.data || 'reload' in reply.data && reply.data.reload) throw new Error(`changes: ${reply.code ?? 'reload'}`)+ cursor = (reply.data as { cursor: string }).cursor+ }],+ ['host poll (its rows by change)', () => hostReader.poll()],+ ['GET parts (first load)', () => call(owner, 'GET', `/api/super-tabs/${swarm.tabId}/parts`)],+ ['GET deliveries (the Lead)', () => driver.deliveries(swarm.tabId, owner, swarm.leadId)],+ ['GET lead messages', () => call(owner, 'GET', `/api/super-tabs/${swarm.tabId}/conversations/lead/messages`)],+ ['POST commands (message.send)', post],+ ]+ process.stdout.write(`Grown Swarm: ${starts} finished starts, ${dormant} quiet Lead conversations, ${config.groups} groups\n\n`)+ process.stdout.write('| Call, after one post | Commands | getMores | Docs returned | KB from MongoDB | SwarmStart (cmd+getMore) | SwarmGroup (cmd+getMore) |\n|---|---|---|---|---|---|---|\n')+ for (const [label, run] of calls) {+ for (let i = 0; i < 2; i++) { await post(); await run() } // warm the cache as production's is+ await post()+ await startProfiling(database.db)+ await run()+ const rows = await profiled(database.db)+ const kind = (name: string) => rows.filter(r => r.collection === name)+ const ops = (list: Row[]) => `${list.filter(r => r.op !== 'getmore').length}+${list.filter(r => r.op === 'getmore').length}`+ process.stdout.write(`| ${label} | ${rows.filter(r => r.op !== 'getmore').length} | ${rows.filter(r => r.op === 'getmore').length} | ` ++ `${rows.reduce((s, r) => s + r.returned, 0)} | ${(rows.reduce((s, r) => s + r.bytes, 0) / 1024).toFixed(1)} | ${ops(kind('SwarmStart'))} | ${ops(kind('SwarmGroup'))} |\n`)+ if (process.env.GROWN_SHAPES) for (const r of rows.filter(r => r.collection.startsWith('Swarm') && r.returned > 50)) process.stdout.write(` ${r.collection} ${r.op} n=${r.returned} ${r.plan}\n`)+ }+ await close()+ await driver.close()+ } finally {+ await stamps.close()+ await database.stop()+ }+}++interface Row { collection: string; op: string; returned: number; bytes: number; plan: string }++/** Every operation profiled since startProfiling, the profiler's own and system collections left out. */+async function profiled(db: PrismaClient): Promise<Row[]> {+ await db.$runCommandRaw({ profile: 0 })+ const found = (await db.$runCommandRaw({ aggregate: 'system.profile', cursor: { batchSize: 100_000 }, pipeline: [+ { $match: { op: { $in: ['command', 'query', 'getmore'] }, ns: { $not: { $regex: String.raw`\.(system\.|\$cmd)` } } } },+ { $project: { _id: 0, ns: 1, op: 1, nreturned: 1, responseLength: 1, planSummary: 1, aggregate: '$command.aggregate', find: '$command.find' } }] }) as unknown as+ { cursor: { firstBatch: Array<{ ns: string; op: string; nreturned?: number; responseLength?: number; planSummary?: string; aggregate?: unknown; find?: unknown }> } }).cursor.firstBatch+ return found.filter(r => r.op !== 'command' || r.aggregate || r.find).map(r => ({ collection: r.ns.slice(r.ns.indexOf('.') + 1), op: r.op,+ returned: Number(r.nreturned ?? 0), bytes: Number(r.responseLength ?? 0), plan: r.planSummary ?? '' }))+}++/** Rows as the Swarm's own writes leave them: finished starts (each failed before it had a harness, finished within the last+ * week) and quiet conversations of the Lead, copies of a seeded conversation. */+async function grow(db: PrismaClient, tabId: string, leadId: string, starts: number, dormant: number) {+ const now = Date.now(), template = (await db.swarmGroup.findFirst({ where: { tabId, dormant: false, kind: null } }))!+ const at = (i: number) => new Date(now - 3_600_000 - i * 60_000)+ for (let i = 0; i < starts; i += 500) {+ await db.swarmStart.createMany({ data: Array.from({ length: Math.min(500, starts - i) }, (_, j) => {+ const key = `grown-start-${i + j}`, conversationId = template.key+ return { id: `${tabId}:${key}`, tabId, key, version: 2, changedAt: at(i + j), deleted: false, ordinal: 1, machineId: machineId(1), conversationId,+ agentId: null, finishedAt: at(i + j), data: { id: key, creationId: key, actorKey: 'bench', contributorId: 'bench', membershipGeneration: 'bench',+ machineOwnerId: 'bench', hostGrant: null, harnessId: null, dispatched: false, error: 'bench: failed before a harness', requestedAt: at(i + j).getTime(),+ request: { conversationId, machineId: machineId(1), engine: 'codex', name: `Grown ${i + j}`, cwd: '/bench/repo', worktree: false,+ requirements: { memoryBytes: 1, diskBytes: 1, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } } }+ }) })+ }+ const data = template.data as Record<string, unknown>+ for (let i = 0; i < dormant; i += 500) {+ await db.swarmGroup.createMany({ data: Array.from({ length: Math.min(500, dormant - i) }, (_, j) => {+ const key = `grown-group-${i + j}`+ const { id: _id, ...row } = template as Record<string, unknown> & { id: string }+ return { ...row, id: `${tabId}:${key}`, key, version: 2, changedAt: at(i + j), lastActivityAt: at(i + j), dormant: true, agentIds: [leadId],+ executionMachineId: null, data: { ...data, id: key, title: `Grown ${i + j}`, agentIds: [leadId], dormant: true, assignment: null } } as never+ }) })+ }+}++main().catch(error => {+ process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`)+ process.exitCode = 1+})diff --git a/backend/integration/bench/profile.ts b/backend/integration/bench/profile.tsindex 8c61b55ac..aab1c333b 100644--- a/backend/integration/bench/profile.ts+++ b/backend/integration/bench/profile.ts@@ -10,6 +10,8 @@ export interface ProfileEntry {docsExamined?: numberkeysExamined?: numbernreturned?: number+ /** The bytes of the operation's reply to the backend: what queryStats' result bytes count per route. */+ responseLength?: numbermillis: number}@@ -100,7 +102,7 @@ export function renderProfile(profile: ProfileSummary & { peakConnections: numbe/** A `system.profile` aggregation that keeps of each operation only what `ProfileEntry` reads: its filter (a find's, an update's,* or the first `$match` of a pipeline, as `match`) and never its whole command. Session ids, cluster times and a pipeline's* own `$type` expressions are more than Prisma's raw reply can decode. */-export const PROFILE_STAGES = [{ $project: { _id: 0, op: 1, ns: 1, planSummary: 1, docsExamined: 1, keysExamined: 1, nreturned: 1, millis: 1,+export const PROFILE_STAGES = [{ $project: { _id: 0, op: 1, ns: 1, planSummary: 1, docsExamined: 1, keysExamined: 1, nreturned: 1, responseLength: 1, millis: 1,'command.aggregate': 1, 'command.find': 1, 'command.filter': 1, 'command.q': 1, 'command.query': 1,match: { $first: { $map: { input: { $filter: { input: { $ifNull: ['$command.pipeline', []] },cond: { $ne: [{ $type: { $getField: { field: { $literal: '$match' }, input: '$$this' } } }, 'missing'] } } },@@ -109,7 +111,7 @@ export const PROFILE_STAGES = [{ $project: { _id: 0, op: 1, ns: 1, planSummary:/** A row of PROFILE_STAGES as the ProfileEntry it stands for. */export function profileEntry(row: ProfileEntry & { match?: unknown }): ProfileEntry {const { match, ...entry } = row- return { ...entry, millis: Number(entry.millis),+ return { ...entry, millis: Number(entry.millis), ...entry.responseLength !== undefined ? { responseLength: Number(entry.responseLength) } : {},...match !== undefined || entry.command?.aggregate ? { command: { ...entry.command, pipeline: [{ $match: match ?? {} }] } } : {} }}diff --git a/backend/integration/superTabFollowedThreads.test.ts b/backend/integration/superTabFollowedThreads.test.tsindex d4a46002b..0fc10a40a 100644--- a/backend/integration/superTabFollowedThreads.test.ts+++ b/backend/integration/superTabFollowedThreads.test.ts@@ -1,3 +1,4 @@+import { appendFileSync } from 'node:fs'import { randomUUID } from 'node:crypto'import { execFile } from 'node:child_process'import { promisify } from 'node:util'@@ -471,6 +472,35 @@ describe('a person\'s followed threads (GET /threads)', () => {expect(body.data.more).toBe(true)})+ // Darren (11-04, task #2835): Activity's Threads lists every thread, 50 at a time; the read answers as many as asked.+ it('answers as many read threads as asked, the newest replies first, and says when there are more', async () => {+ const s = await scene()+ const many = await insert(s.tabId, s.web, Array.from({ length: 60 }, (_, i) => ({ text: `Paged root ${i}`, author: personAuthor(peer) })))+ await markRead(s.tabId, s.web, await sequenceOf(many.at(-1)!), peer)+ await insert(s.tabId, s.web, many.map(thread => ({ text: 'Reply', author: agentAuthor(s.worker), thread })))+ await markRead(s.tabId, s.web, await newestIn(s.tabId, s.web), peer)+ const top = await newestIn(s.tabId, s.web)+ for (const root of many) await writeThreadMark(db, { tabId: s.tabId, personId: peer.sub, conversationId: s.web, threadId: root, sequence: top, now: Date.now() })+ const page = async (query: string) => {+ resetThreadsReads()+ return call('GET', `/api/super-tabs/${s.tabId}/threads${query}`, peer)+ }+ const first = (await page('?read=50')).body.data+ expect(first.unread).toEqual([])+ expect(first.read).toHaveLength(50)+ expect(first.more).toBe(true)+ const all = (await page('?read=100')).body.data+ expect(all.read).toHaveLength(60)+ expect(all.more).toBe(false)+ // The next page goes on where the first stopped: the same 50 first, newest reply first throughout.+ expect(all.read.slice(0, 50).map((t: { rootId: string }) => t.rootId)).toEqual(first.read.map((t: { rootId: string }) => t.rootId))+ const times = all.read.map((t: { lastReplyAt: string }) => Date.parse(t.lastReplyAt))+ expect(times).toEqual(times.toSorted((a: number, b: number) => b - a))+ // A client that asks for no number gets what it always did.+ expect((await page('')).body.data.read).toHaveLength(MAX_READ_THREADS)+ for (const bad of ['0', '251', '2.5', 'many']) expect((await page(`?read=${bad}`)).status, bad).toBe(400)+ })+it('refuses a Team session and an agent', async () => {const s = await followScene()const team = await threads(s.tabId, 'team')@@ -514,7 +544,8 @@ describe('a person\'s followed threads (GET /threads)', () => {return { ...s, long }}/** One threads read under the profiler, after a warm read: its reply, and the operations each collection served. */- async function profiledThreads(tabId: string) {+ async function profiledThreads(tabId: string, query = '') {+ const threads = (id: string, as: AuthUser) => call('GET', `/api/super-tabs/${id}/threads${query}`, as)await threads(tabId, peer)await db.$runCommandRaw({ profile: 0 })await db.$runCommandRaw({ drop: 'system.profile' }).catch(() => {})@@ -561,6 +592,28 @@ describe('a person\'s followed threads (GET /threads)', () => {expect(reply.body.data.more).toBe(true)}, 120_000)+ // Task #2835: a page of N read threads reads 2N candidates' roots by id and summaries by root id, nothing more.+ it('reads each page of read threads by index, its cost bounded by the threads asked for', async () => {+ const s = await longScene()+ await backfillThreads(db, Date.now())+ for (const [n, candidates] of [[50, 70], [100, 70]] as const) {+ resetThreadsReads()+ const { reply, rows } = await profiledThreads(s.tabId, `?read=${n}`)+ const messages = rows.filter(r => r.ns.endsWith('.SuperTabMessage')), summaries = rows.filter(r => r.ns.endsWith('.SuperTabThread'))+ expect(rows.filter(r => r.planSummary === 'COLLSCAN')).toEqual([])+ expect(messages.filter(r => /thread/.test(r.planSummary ?? '')), JSON.stringify(messages)).toEqual([])+ expect(summaries.filter(r => r.op !== 'getmore')).toHaveLength(1)+ expect(summaries[0]!.planSummary).toMatch(/^IXSCAN \{ _id: 1 \}/)+ // At most 2N candidates, and here all 70 of the person's marks.+ expect(summaries.reduce((x, r) => x + (r.docsExamined ?? 0), 0)).toBeLessThanOrEqual(Math.min(2 * n, candidates))+ expect(messages.reduce((x, r) => x + (r.docsExamined ?? 0), 0)).toBeLessThanOrEqual(candidates)+ expect(reply.body.data.read).toHaveLength(Math.min(n, candidates))+ // What each page read, for the pull request: THREADS_COST_OUT=<file> writes it there.+ if (process.env.THREADS_COST_OUT) appendFileSync(process.env.THREADS_COST_OUT, `read=${n} ${JSON.stringify(rows.map(r => ({+ collection: r.ns.split('.').at(-1), op: r.op, plan: r.planSummary, docs: r.docsExamined, keys: r.keysExamined, returned: r.nreturned })))}\n`)+ }+ }, 120_000)+// Ken's scan of 11-04 (task #2768): the unread threads' member check read each thread's newest 100 rows before the mark in// one $or branch per thread, and long threads sent it to one $unionWith branch per thread. It reads their summaries now./** Web: 60 roots of the owner's; the first 10 hold 300 worker replies. Peer replied early in every third thread (i % 3 == 0)@@ -611,6 +664,45 @@ describe('a person\'s followed threads (GET /threads)', () => {expect(reply.body.data.unread).toHaveLength(s.member.length)}, 120_000)+ // Ken's scan of 11-04 16:40 (task #2838): since #2962 the threads route returned 2.8x the database bytes per call (203 KB to+ // ~580 KB). The member check read each candidate's whole summary: the root's source, and the first and newest row of every+ // author with their names, though it asks only whether one person wrote or was tagged there.+ /** Web: 60 roots of an agent's, each with a source as large as a route's; 6 agents with display names reply in each, and the+ * owner and outsider are tagged. Peer replied early in every third thread (i % 3 == 0), is tagged early in the next+ * (i % 3 == 1), and is not in the rest. Peer read the chat, then each thread got one new worker reply. */+ async function crowdedScene() {+ const s = await scene()+ const named = (id: string): Author => ({ ...agentAuthor(id), displayName: `${id} the agent on Elvis-MacBook-Pro.local` })+ const source = { kind: 'route-fixture', candidates: Array.from({ length: 12 }, (_, i) => ({ agent: `candidate-${i}`, why: 'x'.repeat(80) })) }+ const roots = await insert(s.tabId, s.web, Array.from({ length: 60 }, (_, i) => ({ text: `Crowded root ${i}`, author: named('lead'), source })))+ await insert(s.tabId, s.web, roots.flatMap((thread, i) => [+ ...i % 3 === 0 ? [{ text: `Peer early ${i}`, author: personAuthor(peer), thread }] : [],+ ...i % 3 === 1 ? [{ text: `Tags peer ${i}`, author: named('agent-0'), thread, mentions: [peer.sub] }] : [],+ ...Array.from({ length: 6 }, (_, a) => ({ text: `Agent ${a} on ${i}`, author: named(`agent-${a}`), thread, mentions: [owner.sub, outsider.sub] })),+ ]))+ await markRead(s.tabId, s.web, await newestIn(s.tabId, s.web), peer)+ await insert(s.tabId, s.web, roots.map(thread => ({ text: 'New reply', author: agentAuthor(s.worker), thread })))+ await backfillThreads(db, Date.now())+ return { ...s, roots, member: roots.filter((_, i) => i % 3 !== 2) }+ }++ it('reads of each candidate\'s summary only the rows that name the person: the bytes follow their threads, not every author', async () => {+ const s = await crowdedScene()+ const { reply, rows } = await profiledThreads(s.tabId)+ const summaries = rows.filter(r => r.ns.endsWith('.SuperTabThread'))+ const bytes = (of: typeof rows) => of.reduce((n, r) => n + (r.responseLength ?? 0), 0)+ console.info(`threads read, 60 unread candidates, 40 naming the person: ${bytes(rows)} database bytes in all, ${bytes(summaries)} of them summaries\n` ++ rows.map(r => ` ${r.ns.split('.').at(-1)} ${r.op} ${(r.planSummary ?? '').slice(0, 60)} docs=${r.docsExamined ?? 0} returned=${r.nreturned ?? 0} bytes=${r.responseLength ?? 0}`).join('\n'))+ expect(reply.body.data.unread.map((t: any) => t.rootId).sort()).toEqual([...s.member].sort())+ // Still one read by id, examining one summary per candidate (#2962's gain).+ expect(summaries.filter(r => r.op !== 'getmore')).toHaveLength(1)+ expect(summaries[0]!.planSummary).toMatch(/^IXSCAN \{ _id: 1 \}/)+ expect(summaries.reduce((n, r) => n + (r.docsExamined ?? 0), 0)).toBeLessThanOrEqual(60)+ // Only the 40 summaries that name the person come back, each with only the parts that do: a few hundred bytes each.+ expect(summaries.reduce((n, r) => n + (r.nreturned ?? 0), 0)).toBe(s.member.length)+ expect(bytes(summaries)).toBeLessThanOrEqual(s.member.length * 400)+ }, 120_000)+it('keeps reading a Swarm Buddy chat\'s rows to learn whether the person is in a thread: its summary cannot hide a lost project\'s row', async () => {let chat = ''const s = await scene(f => f.edit(state => { chat = openSwarmBuddyChat(state, state.people.find(p => p.id === peer.sub)!).id }))diff --git a/backend/integration/superTabGroupPlans.test.ts b/backend/integration/superTabGroupPlans.test.tsindex 37b071536..bcc687b46 100644--- a/backend/integration/superTabGroupPlans.test.ts+++ b/backend/integration/superTabGroupPlans.test.ts@@ -220,6 +220,18 @@ describe('hot SwarmGroup reads name their index and read only what they return (expectOnlyReturned(where(changed, ['_id']))})+ it('a read past 101 conversations comes in one reply, with no getMore, however many a Swarm has (#2839)', async () => {+ let keys: string[] = []+ const reads = await profiled(async () => {+ keys = (await parts.loadGroups(db, s.tabId, 'project', { projectId: { $in: ['lead', null] }, dormant: true })).map(g => g.key)+ })+ expect(keys.length).toBeGreaterThan(101)+ expectIndexed(reads)+ const ops = (await db.$runCommandRaw({ aggregate: 'system.profile', cursor: {}, pipeline: [{ $match: { ns: { $regex: '\\.SwarmGroup$' } } },+ { $group: { _id: '$op', n: { $sum: 1 } } }] }) as unknown as { cursor: { firstBatch: Array<{ _id: string; n: number }> } }).cursor.firstBatch+ expect(Object.fromEntries(ops.map(o => [o._id, o.n]))).toEqual({ command: 1 })+ })+it('a command loads the Swarm\'s open conversations and those it names, each read through its index', async () => {const quiet = s.quietLead[5]!.keyfor (const [named, expected] of [diff --git a/backend/integration/superTabHostGroups.test.ts b/backend/integration/superTabHostGroups.test.tsindex d61406cc6..08ec597b8 100644--- a/backend/integration/superTabHostGroups.test.ts+++ b/backend/integration/superTabHostGroups.test.ts@@ -257,3 +257,56 @@ describe('a host check', () => {expect(entries.filter(e => e.planSummary?.includes('hostDigest'))).toEqual([])})})++describe('the host signature\'s member, agent and start stamps through the patched cache (#2839)', () => {+ /** A start that failed before it had a harness: finished, and kept live for 7 days as a Swarm's history of starts is. */+ const startData = (key: string, error: string | null = 'failed before a harness') => ({ id: key, creationId: key, actorKey: 'test', contributorId: 'test',+ membershipGeneration: 'g', machineOwnerId: 'o', hostGrant: null, harnessId: null, dispatched: false, error, request: { conversationId: 'lead',+ machineId: 'm-test', engine: 'codex', name: key, cwd: '/repo', worktree: false,+ requirements: { memoryBytes: 1, diskBytes: 1, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } })+ /** STARTS starts, last changed ten minutes ago: more than one batch's 101, past the cache's overlap. */+ const STARTS = 150+ async function withStarts() {+ const { tabId, web } = await scene()+ await swarmTransaction(db, async tx => {+ for (let i = 0; i < STARTS; i++) await guardedWrite(tx, tabId, { op: 'insert', kind: 'start', key: `start-${i}`, ordinal: 40_000 + i, data: startData(`start-${i}`) }, Date.now())+ })+ await db.swarmStart.updateMany({ where: { tabId }, data: { changedAt: new Date(Date.now() - 600_000) } })+ return { tabId, web }+ }+ const start = (all: parts.SwarmParts, key: string) => all.starts.find(s => s.key === key && !s.deleted)!++ it('a change reads no live start whose stamp did not move, and the signature stays the pipeline\'s', { timeout: 60_000 }, async () => {+ const { tabId, web } = await withStarts()+ const cache = new SwarmCache(stamps, { delta: readDelta(db) })+ expect(await cachedInputs(cache, tabId)).toBe(await pipeline(tabId))+ await write(tabId, update(web, g => ({ ...g, archived: true })))+ const expected = await pipeline(tabId)+ let got: string | null = null+ const patched = await profiled(db, async () => { got = await cachedInputs(cache, tabId) })+ expect(got).toBe(expected)+ // Starts read only by what changed since the last check, never every live one.+ expect(reads(patched, 'SwarmStart', ['tabId'], ['changedAt'])).toEqual([])+ })++ it('gives the pipeline\'s string after start, agent and member writes, and a touch', { timeout: 120_000 }, async () => {+ const { tabId } = await withStarts()+ const cache = new SwarmCache(stamps, { delta: readDelta(db) })+ const steps: Array<[string, (all: parts.SwarmParts) => parts.PartWrite | null]> = [+ ['a start added', () => ({ op: 'insert', kind: 'start', key: 'late-start', ordinal: 50_000, data: startData('late-start', null) })],+ ['a start finished', all => ({ op: 'update', kind: 'start', key: 'late-start', seen: start(all, 'late-start').version, data: startData('late-start', 'failed') })],+ ['a start removed', all => ({ op: 'remove', kind: 'start', key: 'start-3', seen: start(all, 'start-3').version, data: start(all, 'start-3').data })],+ ['a start added again under its key', () => ({ op: 'insert', kind: 'start', key: 'start-3', ordinal: 50_001, data: startData('start-3') })],+ ['an agent renamed', all => { const a = all.agents.find(x => !x.deleted)!; return { op: 'update', kind: 'agent', key: a.key, seen: a.version, data: { ...a.data!, name: 'Renamed' } } }],+ ['a member changed', all => { const m = all.members.find(x => !x.deleted)!; return { op: 'update', kind: 'member', key: m.key, seen: m.version, data: { ...m.data! as object } } }],+ ['a start touched', all => ({ op: 'touch', kind: 'start', key: 'start-4', seen: start(all, 'start-4').version })],+ ]+ expect(await cachedInputs(cache, tabId)).toBe(await pipeline(tabId))+ for (const [name, step] of steps) {+ await write(tabId, step)+ const expected = await pipeline(tabId)+ expect(await cachedInputs(cache, tabId), `${name}, patched`).toBe(expected)+ expect(await hostInputs(db, DIRECT, tabId), `${name}, no cache`).toBe(expected)+ }+ })+})diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex facfc5687..dfc1c4561 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 { startMessageReachStats } from '../src/superTabs/messageReachStats.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.@@ -1344,6 +1345,73 @@ describe('Super Tabs on a real Mongo replica set', () => {expect(await db.superTabConfiguration.count({ where: { tabId: tab } })).toBe(3)})+ // Task #2840: how long a message takes to reach its reader, per pod per minute (superTabs/messageReachStats.ts). The rows a+ // minute's line would carry for what [act] did.+ async function reaches(act: () => Promise<unknown>): Promise<Array<Record<string, unknown>>> {+ const log = vi.fn()+ const stop = startMessageReachStats({ everyMs: 3_600_000, pod: 'test', log })+ try { await act() } finally { stop() }+ return (log.mock.calls[0]?.[1] as { rows?: Array<Record<string, unknown>> } | undefined)?.rows ?? []+ }++ it('times an agent\'s delivery from its creation to its host\'s first acknowledgement, once', async () => {+ const { tab, lead } = await fixture()+ await run(tab, message('Please start.'))+ const delivery = (await store.deliveries(host, tab, lead))[0]!+ expect(await reaches(() => store.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: 'claim' }))).toEqual([])+ const typed = await reaches(() => store.delivery(host, tab, lead, delivery.id, { type: 'ack', claimId: 'claim', receipt: 'done', uncertain: false }))+ expect(typed).toEqual([{ reader: 'agent', via: 'delivery', n: 1, p50: expect.any(Number), p95: expect.any(Number), max: expect.any(Number) }])+ expect(typed[0]!.max as number).toBeLessThan(60_000)+ // The same acknowledgement again, as a host retries one it did not hear answered: the message reached it once.+ expect(await reaches(() => store.delivery(host, tab, lead, delivery.id, { type: 'ack', claimId: 'claim', receipt: 'done', uncertain: false }))).toEqual([])+ })++ it('does not time a delivery its host could not confirm', async () => {+ const { tab, lead } = await fixture()+ await run(tab, message('Please start.'))+ const delivery = (await store.deliveries(host, tab, lead))[0]!+ await store.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: 'claim' })+ expect(await reaches(() => store.delivery(host, tab, lead, delivery.id, { type: 'ack', claimId: 'claim', receipt: 'unclear', uncertain: true }))).toEqual([])+ })++ it('times a person\'s read of new messages for each message someone else wrote, and nothing else', async () => {+ const { tab, lead } = await fixture()+ const tail = (await store.messages(owner, tab, 'lead', {})).messages.at(-1)!.sequence+ await run(tab, message('From the Lead.'), host, lead)+ await run(tab, message('My own.'))+ const read = await reaches(() => store.messages(owner, tab, 'lead', { after: tail }))+ expect(read).toEqual([{ reader: 'person', via: 'read', n: 1, p50: expect.any(Number), p95: expect.any(Number), max: expect.any(Number) }])+ // The page shown, a thread, or an agent's read is a re-read, not the message reaching its reader.+ expect(await reaches(() => store.messages(owner, tab, 'lead', {}))).toEqual([])+ expect(await reaches(() => store.messages(host, tab, 'lead', { after: tail }, lead))).toEqual([])+ })++ // Task #2840's measure: what timing costs a read of new messages and a delivery acknowledgement, per call, on a seeded+ // Swarm (run against main's store.ts for the before numbers), and the minute's line those calls make. Printed for the PR.+ it('measures an after read and a delivery ack per call, and prints the minute line', async () => {+ const { tab, lead } = await fixture()+ const tail = (await store.messages(owner, tab, 'lead', {})).messages.at(-1)!.sequence+ for (let i = 0; i < 20; i++) await run(tab, message(`Update ${i}.`), host, lead)+ const log = vi.fn()+ const stop = startMessageReachStats({ everyMs: 3_600_000, pod: 'api-7f9c-pod:1', log })+ const reads = 200+ for (let i = 0; i < 20; i++) await store.messages(owner, tab, 'lead', { after: tail })+ let started = performance.now()+ for (let i = 0; i < reads; i++) await store.messages(owner, tab, 'lead', { after: tail })+ const readMs = (performance.now() - started) / reads+ const acks = 20+ for (let i = 0; i < acks; i++) await run(tab, message(`Task ${i}.`))+ const open = await store.deliveries(host, tab, lead)+ for (const d of open) await store.delivery(host, tab, lead, d.id, { type: 'claim', claimId: `c-${d.id}` })+ started = performance.now()+ for (const d of open) await store.delivery(host, tab, lead, d.id, { type: 'ack', claimId: `c-${d.id}`, receipt: 'typed', uncertain: false })+ const ackMs = (performance.now() - started) / open.length+ stop()+ process.stderr.write(`[#2840 measure] per call: after read (20 rows) ${readMs.toFixed(2)} ms over ${reads}, delivery ack ${ackMs.toFixed(2)} ms over ${open.length}\n`)+ process.stderr.write(`[#2840 sample] message reach latency ${JSON.stringify(log.mock.calls[0]?.[1] ?? null)}\n`)+ expect(open.length).toBeGreaterThan(0)+ }, 120_000)+it('records a claimed delivery hold for the claim holder only and posts nothing in the conversation', async () => {const { tab, lead } = await fixture()await run(tab, message('Please start.'))diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 5480c44b1..c469f15fd 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -543,7 +543,8 @@ model ProductUsagePreference {@@map("product_usage_preferences")}-/// Only fleet-wide counters. Never add an account, machine, agent, location or event timestamp.+/// Only fleet-wide counters. Never add an account, machine, agent, location or event timestamp. So no index on `machineId`+/// either, as the Atlas advisor suggested on 2026-11-04 (task #2841): no row has one, and no backend read asks for it.model ProductUsageTotal {id String @id @default(auto()) @map("_id") @db.ObjectIddayUtc DateTime@@ -1912,6 +1913,9 @@ model SwarmGroup {/// written before it (markFinishedGroups).workFinished Boolean @default(false)+ /// Not indexed on `data.kind` (Atlas advisor, 2026-11-04, task #2841): no backend read filters by it, the only one that+ /// does is the rollback script scripts/buddy-sessions/end-all.ts, across every Swarm; and every hot read keeps its plan+ /// with such an index (the numbers are in task #2841's pull request). The top-level `kind` holds the same value.@@unique([tabId, key])@@index([tabId, changedAt])@@index([tabId, dormant, changedAt])diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 51c7fa738..fd79a3c43 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -31,7 +31,7 @@ import { githubTokensFromEnv, type GitHubTokens } from '../github/tokens.js'import { logger } from '../utils/logger.js'import { SwarmReads } from '../superTabs/read/service.js'import { inboxWait, readInbox } from '../superTabs/read/inbox.js'-import { readFollowedThreads, threadsWait } from '../superTabs/read/followedThreads.js'+import { READ_THREADS_ASKED_MAX, readFollowedThreads, threadsWait } from '../superTabs/read/followedThreads.js'import { activityWait } from '../superTabs/activity.js'import { reminderWait } from '../superTabs/reminders.js'import { NOTIFY_LEVELS } from '../superTabs/chatSettings.js'@@ -109,6 +109,9 @@ const threadParams = messageParams.extend({ threadId: id })const fileParams = messageParams.extend({ messageId: id, attachmentId: id })const reminderParams = messageParams.extend({ messageId: id })const noQuery = z.object({}).strict()+/** The followed-threads read's query (read/followedThreads.ts): how many read threads to answer. */+const threadsQuery = z.object({ read: z.string().regex(/^[1-9][0-9]{0,2}$/).transform(Number)+ .refine(n => n <= READ_THREADS_ASKED_MAX, `At most ${READ_THREADS_ASKED_MAX}.`).optional() }).strict()// The project whose open Buddy proposals a person reads (superTabs/proposals.ts).const proposalsQuery = z.object({ projectId: id }).strict()// The reader's own catch-up (superTabs/catchUp.ts): no asAgentId, since agents read every message as it comes.@@ -531,11 +534,12 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Sureturn respond(reply, () => readInbox(store, req.user!, req.params.tabId))})// A person's followed threads, unread first (read/followedThreads.ts): Desktop's Threads view, read as the inbox is.- app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof noQuery> }>('/api/super-tabs/:tabId/threads',- { preHandler: [validateParams(tabParams), validateQuery(noQuery)] }, async (req, reply) => {+ // `read`: how many read threads to answer (Activity's Threads asks 50 at a time, task #2835); 30 when not asked.+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof threadsQuery> }>('/api/super-tabs/:tabId/threads',+ { preHandler: [validateParams(tabParams), validateQuery(threadsQuery)] }, async (req, reply) => {const wait = await threadsWait(req.user!, req.params.tabId)if (wait) return sendError(reply.header('Retry-After', String(wait)), 'Too many thread reads. Try again in a moment.', 'RATE_LIMITED', 429)- return respond(reply, () => readFollowedThreads(store, req.user!, req.params.tabId))+ return respond(reply, () => readFollowedThreads(store, req.user!, req.params.tabId, req.query.read))})// One project's Buddy proposals its PM has not answered, oldest first (superTabs/proposals.ts): the Tasks view's Proposals.app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof proposalsQuery> }>('/api/super-tabs/:tabId/proposals',diff --git a/backend/src/server.ts b/backend/src/server.tsindex 54f9265b3..6727b75a1 100644--- a/backend/src/server.ts+++ b/backend/src/server.ts@@ -30,6 +30,7 @@ import { startMemoryStats } from './lib/memoryStats.js'import { readDelta } from './superTabs/cachedReads.js'import { watchGroupIndexes } from './superTabs/parts/indexed.js'import { startMessageReadStats } from './superTabs/messageReadStats.js'+import { startMessageReachStats } from './superTabs/messageReachStats.js'import { useSharedSsoProfileStore } from './lib/ssoAuth.js'import { useSharedRateCounter } from './lib/rateLimit.js'import { createRouteRateLimit } from './middlewares/routeRateLimit.js'@@ -167,6 +168,8 @@ async function start(): Promise<void> {const stopRouteLatency = startRouteLatency(registerRouteLatency(app))// Every minute: who reads messages how, with the rows each page decoded and showed (superTabs/messageReadStats.ts).const stopMessageReadStats = startMessageReadStats()+ // Every minute: how long messages took to reach their readers, p50/p95 per reader kind (superTabs/messageReachStats.ts).+ const stopMessageReachStats = startMessageReachStats()// Every minute: how each frame an adapter sends for one viewer reached it, and how many processes each publish woke.const stopRelayStats = startRelayStats()// Frames for one viewer go to the process holding it (lib/terminalRoute.ts), unless TERMINAL_POD_ROUTES=off.@@ -261,6 +264,7 @@ async function start(): Promise<void> {stopRouteLatency()stopMachineReportLog()stopMessageReadStats()+ stopMessageReachStats()stopRelayStats()stopPodRoutes()// The database stays connected through the drain, for the requests still being served (lib/prisma.ts).diff --git a/backend/src/superTabs/messageReachStats.test.ts b/backend/src/superTabs/messageReachStats.test.tsnew file mode 100644index 000000000..d32e88cbf--- /dev/null+++ b/backend/src/superTabs/messageReachStats.test.ts@@ -0,0 +1,90 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { LATE_MS, recordMessageReach, startMessageReachStats } from './messageReachStats.js'++// Task #2840 (Watch Production): Ken's guard "how fast a message reaches its reader" had no measurement in any production log.+describe('message reach latency', () => {+ afterEach(() => { vi.useRealTimers() })++ function started(options: Parameters<typeof startMessageReachStats>[0] = {}) {+ vi.useFakeTimers()+ const log = vi.fn()+ const stop = startMessageReachStats({ pod: 'pod-1', ...options, log })+ return { log, stop }+ }++ it('logs each minute, per reader and way, the count, p50, p95 and max in ms, with the pod and window', () => {+ const { log, stop } = started()+ for (let ms = 1; ms <= 100; ms++) recordMessageReach({ reader: 'agent', via: 'delivery' }, ms)+ recordMessageReach({ reader: 'person', via: 'read' }, 250)+ vi.advanceTimersByTime(60_000)+ expect(log).toHaveBeenCalledTimes(1)+ const [message, context] = log.mock.calls[0]!+ expect(message).toBe('message reach latency')+ expect(context).toEqual({ pod: 'pod-1', windowMs: 60_000, rows: [+ { reader: 'agent', via: 'delivery', n: 100, p50: 50, p95: 95, max: 100 },+ { reader: 'person', via: 'read', n: 1, p50: 250, p95: 250, max: 250 },+ ] })+ stop()+ })++ // A reader that was away and catches up is not a slow delivery: counted apart, so it cannot set the p95. A live app reads+ // new messages within seconds of a push or its poll (15 s at most, off screen), so a read a minute late is a catch-up (an+ // app brought back, review of #2995); an agent's delivery includes the time it was busy, so it gets 10 minutes.+ it('counts a read over a minute old and a delivery over 10 minutes old as late, outside the percentiles', () => {+ const { log, stop } = started()+ recordMessageReach({ reader: 'person', via: 'read' }, 400)+ recordMessageReach({ reader: 'person', via: 'read' }, LATE_MS.read + 1)+ recordMessageReach({ reader: 'person', via: 'read' }, 5 * 60_000)+ recordMessageReach({ reader: 'agent', via: 'delivery' }, 5 * 60_000)+ recordMessageReach({ reader: 'agent', via: 'delivery' }, LATE_MS.delivery + 1)+ recordMessageReach({ reader: 'buddy', via: 'read' }, 3 * 3_600_000)+ vi.advanceTimersByTime(60_000)+ expect(log.mock.calls[0]![1].rows).toEqual([+ { reader: 'person', via: 'read', n: 1, p50: 400, p95: 400, max: 400, late: 2 },+ { reader: 'agent', via: 'delivery', n: 1, p50: 300_000, p95: 300_000, max: 300_000, late: 1 },+ { reader: 'buddy', via: 'read', n: 0, late: 1 },+ ])+ expect(LATE_MS).toEqual({ read: 60_000, delivery: 600_000 })+ stop()+ })++ it('says nothing for a minute nothing reached anyone, and starts each window empty', () => {+ const { log, stop } = started()+ vi.advanceTimersByTime(60_000)+ expect(log).not.toHaveBeenCalled()+ recordMessageReach({ reader: 'agent', via: 'delivery' }, 10)+ vi.advanceTimersByTime(60_000)+ vi.advanceTimersByTime(60_000)+ expect(log).toHaveBeenCalledTimes(1)+ stop()+ })++ // Memory stays bounded however busy the pod: a fixed sample per row, while count and max cover every message.+ it('keeps a bounded sample per row, its count and max covering every message', () => {+ const { log, stop } = started({ maxSamples: 10, random: () => 0.99 })+ for (let i = 0; i < 1_000; i++) recordMessageReach({ reader: 'agent', via: 'delivery' }, i === 500 ? 9_000 : 5)+ vi.advanceTimersByTime(60_000)+ expect(log.mock.calls[0]![1].rows[0]).toMatchObject({ n: 1_000, max: 9_000 })+ stop()+ })++ it('logs what is left when stopped, and records nothing once stopped', () => {+ const { log, stop } = started()+ recordMessageReach({ reader: 'agent', via: 'delivery' }, 30)+ stop()+ expect(log).toHaveBeenCalledTimes(1)+ recordMessageReach({ reader: 'agent', via: 'delivery' }, 30)+ vi.advanceTimersByTime(120_000)+ expect(log).toHaveBeenCalledTimes(1)+ })++ it('carries no ids, text or emails: only reader kinds, ways and numbers', () => {+ const { log, stop } = started()+ recordMessageReach({ reader: 'person', via: 'read' }, 12)+ stop()+ const keys = new Set<string>()+ const walk = (value: unknown) => { if (value && typeof value === 'object') for (const [k, v] of Object.entries(value)) { keys.add(k); walk(v) } }+ walk(log.mock.calls[0]![1])+ expect([...keys].sort()).toEqual(['0', 'max', 'n', 'p50', 'p95', 'pod', 'reader', 'rows', 'via', 'windowMs'])+ })+})diff --git a/backend/src/superTabs/messageReachStats.ts b/backend/src/superTabs/messageReachStats.tsnew file mode 100644index 000000000..ce48358aa--- /dev/null+++ b/backend/src/superTabs/messageReachStats.ts@@ -0,0 +1,80 @@+import { hostname } from 'node:os'+import { logger } from '../utils/logger.js'++/**+ * How fast a message reaches its reader (task #2840, Watch Production): Ken's guard on the load work had no measurement in+ * any production log. Every minute, `message reach latency` logs per reader kind and way the count, p50, p95 and max in ms,+ * per pod, in the style of `route latency` (lib/routeLatency.ts) and `messages by reader` (messageReadStats.ts):+ * - `delivery`: an agent's host acknowledged it typed the message (store.ts delivery), from the delivery's creation, which+ * is written with its message. It includes any time the agent was busy before its host could type it: the reach as the+ * agent sees it, not the Swarm's latency alone (review of #2995).+ * - `read`: a person's app read new messages and was handed it (store.ts messages, `after`), from the message's creation.+ * Counted per reading app: a person with Desktop and the phone open counts each message twice.+ * Nothing is kept but kinds and numbers: no id, text or email. In memory, per pod, cleared each minute.+ */++export interface MessageReachKey {+ reader: 'person' | 'agent' | 'buddy'+ via: 'read' | 'delivery'+}++/** Older than this when it reached its reader, a message was waiting on a reader that was away, not on the Swarm: it is+ * counted as `late`, outside the percentiles, so a catch-up cannot set the p95. A live app reads new messages within seconds+ * of the push or its poll (every 15 s at most, off screen), so a read over a minute old is an app brought back or opened+ * (review of #2995: a phone reopened after 3 to 9 minutes would otherwise set the person p95). A delivery includes the time+ * its agent was busy, so it gets 10 minutes. */+export const LATE_MS: Readonly<Record<MessageReachKey['via'], number>> = { read: 60_000, delivery: 10 * 60_000 }++interface Row { key: MessageReachKey; n: number; late: number; max: number; samples: number[] }+interface Window { rows: Map<string, Row>; maxSamples: number; random: () => number }++let current: Window | undefined++export function recordMessageReach(key: MessageReachKey, ms: number): void {+ const window = current+ if (!window) return+ const id = `${key.reader}|${key.via}`+ let row = window.rows.get(id)+ if (!row) window.rows.set(id, row = { key: { reader: key.reader, via: key.via }, n: 0, late: 0, max: 0, samples: [] })+ if (ms > LATE_MS[key.via]) { row.late++; return }+ const value = Math.max(0, ms)+ row.n+++ if (value > row.max) row.max = value+ if (row.samples.length < window.maxSamples) row.samples.push(value)+ else {+ const slot = Math.floor(window.random() * row.n)+ if (slot < window.maxSamples) row.samples[slot] = value+ }+}++/** Nearest-rank percentile of sorted values. */+const percentile = (sorted: number[], p: number) => sorted[Math.max(0, Math.ceil(p / 100 * sorted.length) - 1)] ?? 0+const round = (ms: number) => Math.round(ms)++/** Logs each window, every `everyMs`, until stopped; stopping logs what is left. */+export function startMessageReachStats({ everyMs = 60_000, pod = `${hostname()}:${process.pid}`, maxSamples = 2000, random = Math.random,+ log = (m, c) => logger.info(m, c) }: { everyMs?: number; pod?: string; maxSamples?: number; random?: () => number+ log?: (message: string, context: Record<string, unknown>) => void } = {}): () => void {+ const window: Window = { rows: new Map(), maxSamples, random }+ current = window+ let since = Date.now()+ const flush = () => {+ const now = Date.now()+ if (window.rows.size) {+ const rows = [...window.rows.values()].map(({ key, n, late, max, samples }) => {+ const sorted = samples.sort((a, b) => a - b)+ return { ...key, n, ...n ? { p50: round(percentile(sorted, 50)), p95: round(percentile(sorted, 95)), max: round(max) } : {}, ...late ? { late } : {} }+ })+ log('message reach latency', { pod, windowMs: now - since, rows })+ }+ window.rows.clear()+ since = now+ }+ const timer = setInterval(flush, everyMs)+ timer.unref()+ return () => {+ clearInterval(timer)+ if (current === window) current = undefined+ flush()+ }+}diff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.tsindex 4b149146f..d1975cee6 100644--- a/backend/src/superTabs/pageReads.ts+++ b/backend/src/superTabs/pageReads.ts@@ -300,6 +300,41 @@ export async function threadsAcross(tx: Transaction, tabId: string, threads: Reareturn threadReplies(tx, tabId, { parts: stored.flatMap(t => t.parts), mentions: stored.flatMap(t => t.mentions) })}+/**+ * Of the threads rooted at `threads`, those whose summary shows `personId` writing or tagged in a row a person reads (what+ * threadReplies marks agentOnly is left out), as `${conversationId}\u0000${root}`. A backfilled Swarm's only (threadsBackfilled):+ * its summaries hold every reply. One read by `_id`, as threadsAcross, that returns only the summaries naming the person, and+ * of each only the parts and tags that do, without their rows' authors or the root's source: the member check needs no more+ * (inbox.ts namedInThreads). Reading them whole made the threads route return 2.8x the database bytes per call (task #2838).+ */+export async function threadsNaming(tx: Transaction, tabId: string, threads: ReadonlyArray<{ conversationId: string; root: string }>,+ personId: string): Promise<Set<string>> {+ if (!threads.length) return new Set()+ const named = new Set(threads.map(t => `${t.conversationId}\u0000${t.root}`))+ // A part's key fields that decide whether a reader skips its rows (threadReplies hidden).+ const key = (of: string) => ({ root: `${of}._id.root`, kind: `${of}._id.kind`, only: `${of}._id.only`, to: `${of}._id.to` })+ const stored = (await readBy(tx, 'SuperTabThread', 'id', [+ { $match: { _id: { $in: [...new Set(threads.map(t => t.root))] },+ $or: [{ parts: { $elemMatch: { '_id.author.kind': 'person', '_id.author.id': personId } } }, { 'mentions._id.person': personId }] } },+ { $project: { tabId: 1, conversationId: 1,+ parts: { $map: { input: { $filter: { input: '$parts', as: 'p',+ cond: { $and: [{ $eq: ['$$p._id.author.kind', 'person'] }, { $eq: ['$$p._id.author.id', personId] }] } } }, as: 'p', in: key('$$p') } },+ mentions: { $map: { input: { $filter: { input: '$mentions', as: 'm', cond: { $eq: ['$$m._id.person', personId] } } }, as: 'm', in: key('$$m') } },+ // The root's row, which deliveredCopies reads: only what it decides by.+ root: { $map: { input: { $filter: { input: '$parts', as: 'p', cond: { $eq: ['$$p._id.root', true] } } }, as: 'p',+ in: { kind: '$$p.root.source.kind', only: '$$p.root.source.recipientsOnly', to: { $gt: [{ $size: { $ifNull: ['$$p.root.recipientIds', []] } }, 0] } } } },+ } }]) as unknown as Array<{ _id: string; tabId: string; conversationId: string; parts: NamingPart[]; mentions: NamingPart[]+ root: Array<{ kind?: unknown; only?: unknown; to: boolean }> }>)+ .filter(t => t.tabId === tabId && named.has(`${t.conversationId}\u0000${t._id}`))+ const copies = await deliveredCopies(tx, tabId, stored.flatMap(t => t.root.slice(0, 1).map(r =>+ ({ id: t._id, source: { kind: r.kind, recipientsOnly: r.only }, recipientIds: r.to ? ['recipient'] : [] }))))+ const hidden = (thread: string, p: NamingPart) => (p.root === true && copies.has(thread))+ || agentOnly({ kind: p.kind, recipientsOnly: p.only }, p.to ? ['recipient'] : [])+ return new Set(stored.filter(t => [...t.parts, ...t.mentions].some(p => !hidden(t._id, p))).map(t => `${t.conversationId}\u0000${t._id}`))+}+/** What threadsNaming reads of a part or tag: what threadReplies decides agentOnly by. */+interface NamingPart { root?: boolean; kind?: unknown; only?: unknown; to?: boolean }+/*** Rewrites the summaries of the threads rooted at `roots` in one conversation from their rows now: one document per thread* with a reply, as threadFacet gives it, and none for a thread left with no reply. Run in the transaction that inserts a replydiff --git a/backend/src/superTabs/parts/indexed.test.ts b/backend/src/superTabs/parts/indexed.test.tsnew file mode 100644index 000000000..efe7ddf6e--- /dev/null+++ b/backend/src/superTabs/parts/indexed.test.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from 'vitest'+import { READ_BATCH, readBy } from './indexed.js'++describe('a named read (#2839)', () => {+ it('asks for every row in one batch: past 101 rows Mongo otherwise answers in getMores, more as a Swarm grows', async () => {+ const calls: Array<{ options?: { batchSize?: number } }> = []+ const tx = { swarmGroup: { aggregateRaw: async (args: { options?: { batchSize?: number } }) => { calls.push(args); return [] } } } as never+ await readBy(tx, 'SwarmGroup', 'agents', [{ $match: { tabId: 't', agentIds: 'a1' } }])+ expect(calls[0]!.options?.batchSize).toBe(READ_BATCH)+ expect(READ_BATCH).toBeGreaterThanOrEqual(10_000)+ })+})diff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.tsindex d77b77854..da75dd596 100644--- a/backend/src/superTabs/parts/indexed.ts+++ b/backend/src/superTabs/parts/indexed.ts@@ -171,6 +171,11 @@ export async function retryStaleIndex<T>(run: () => Promise<T>): Promise<T> {}}+/** The rows a named read asks for in its first reply: all of them, in one round trip, within Mongo's 16 MB reply. Its default+ * first batch is 101 documents, and each further batch a getMore: an agent's quiet conversations or a Swarm's week of+ * finished starts took more of them as the Swarm grew (#2839: Atlas ops per request up 38% at flat traffic). */+export const READ_BATCH = 100_000+/*** The rows of an `aggregateRaw` pipeline on `collection`, through its index `name` once the database is known to have it.* An index removed since the last listing (a rollback, an index replaced) fails the read: the listing is dropped, said, and@@ -180,7 +185,7 @@ export async function retryStaleIndex<T>(run: () => Promise<T>): Promise<T> {export async function readBy<C extends NamedCollection>(tx: Transaction, collection: C, name: NamedIndex<C>,pipeline: Prisma.InputJsonValue[]): Promise<Array<Record<string, unknown>>> {const model = (tx as unknown as Record<string, { aggregateRaw(args: unknown): Promise<unknown> }>)[collection[0]!.toLowerCase() + collection.slice(1)]!- const run = async (hint?: Record<string, number>) => await model.aggregateRaw({ pipeline, ...hint ? { options: { hint } } : {} }) as+ const run = async (hint?: Record<string, number>) => await model.aggregateRaw({ pipeline, options: { batchSize: READ_BATCH, ...hint ? { hint } : {} } }) asArray<Record<string, unknown>>if (rerun.getStore() || !present.get(collection)?.has(name)) return run()try {diff --git a/backend/src/superTabs/read/followedThreads.ts b/backend/src/superTabs/read/followedThreads.tsindex 2c832b150..736bb9a37 100644--- a/backend/src/superTabs/read/followedThreads.ts+++ b/backend/src/superTabs/read/followedThreads.ts@@ -32,10 +32,14 @@ import type { ThreadMarkRow } from '../readMarks.js'import { FIELDS, inboxRead, INBOX_READS, INBOX_WINDOW_MS, isReply, MEMBER_SCAN, newestFirst, perRange, preview, readable, row, SCAN_FIELDS, threadKey,type InboxMessage, type InboxThread, type Row } from './inbox.js'-/** Read threads answered, newest reply first. */+/** Read threads answered, newest reply first, when the client asks for no number (a Desktop before task #2835). */export const MAX_READ_THREADS = 30+/** The most read threads one read answers when asked (`?read=N`, Activity's Threads 50 at a time, task #2835). */+export const READ_THREADS_ASKED_MAX = 250/** Thread mark rows checked for read threads, most recently moved first: room for those the person turns out not to be in. */export const READ_CANDIDATES = 2 * MAX_READ_THREADS+/** Thread mark rows checked to answer [read] read threads: twice as many, as READ_CANDIDATES is for 30. */+export const readCandidates = (read: number) => 2 * read/** Threads found only by the person's tags that are checked as candidates, newest tag first, besides READ_CANDIDATES. */export const TAGGED_THREADS = 30/** Rows read per candidate thread, newest first. */@@ -58,7 +62,10 @@ export interface FollowedThread {}export interface FollowedThreads { unread: Array<InboxThread & { follow: boolean | null }>; read: FollowedThread[]; more: boolean }-export async function readFollowedThreads(store: SuperTabStore, user: AuthUser, tabId: string): Promise<FollowedThreads> {+/** [read]: how many read threads to answer (Activity asks 50, then 100, ... as the person scrolls); the cost grows only by the+ * candidates checked, 2 × read of the person's marks (at most THREAD_MARK_CAP, already read for the inbox), their roots by id and+ * their summaries by root id. */+export async function readFollowedThreads(store: SuperTabStore, user: AuthUser, tabId: string, read = MAX_READ_THREADS): Promise<FollowedThreads> {const db = store.db, personId = user.subconst { inbox, state, chats, marks, threadRows } = await inboxRead(store, user, tabId, { latest: false })const follows = new Map(threadRows.map(r => [threadKey(r.conversationId, r.threadId), r]))@@ -72,8 +79,9 @@ export async function readFollowedThreads(store: SuperTabStore, user: AuthUser,const tagged = await taggedThreads(db, tabId, state, { kind: 'person', userId: personId, email: user.email }, Date.now(), TAGGED_THREADS + 1,t => groups.has(t.conversationId) && !held.has(threadKey(t.conversationId, t.threadId)) && !listed.has(threadKey(t.conversationId, t.threadId)))const byTag: ThreadMarkRow[] = tagged.slice(0, TAGGED_THREADS).map(t => ({ conversationId: t.conversationId, threadId: t.threadId, sequence: 0, follow: null, updatedAt: t.at }))- const candidates = [...eligible.slice(0, READ_CANDIDATES), ...byTag]- let more = inbox.more || eligible.length > READ_CANDIDATES || tagged.length > TAGGED_THREADS+ const checked = readCandidates(read)+ const candidates = [...eligible.slice(0, checked), ...byTag]+ let more = inbox.more || eligible.length > checked || tagged.length > TAGGED_THREADSif (!candidates.length) return { unread, read: [], more }// Every root by its id, in one read; a root counts only in the chat its mark names, and only one the person reads.const found = (await readBy(db, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: candidates.map(c => c.threadId) }, tabId } },@@ -100,7 +108,7 @@ export async function readFollowedThreads(store: SuperTabStore, user: AuthUser,}const own = (a: Pick<Author, 'kind' | 'id'>) => a.kind === 'person' && a.id === personIdconst inIt = (m: Pick<Row, 'author' | 'mentions'>) => own(m.author) || m.mentions.includes(personId)- const read: Array<FollowedThread & { at: number }> = []+ const answered: Array<FollowedThread & { at: number }> = []for (const c of withRoot) {const key = threadKey(c.conversationId, c.threadId), root = roots.get(key)!// Newest first. A summary row stands for `count` rows of one author and kind, its newest and oldest among them: the newest@@ -118,12 +126,12 @@ export async function readFollowedThreads(store: SuperTabStore, user: AuthUser,createdAt: root.createdAt, agentOnly: false, routing: false }, ...replies.toReversed()]const [summary] = threadSummaries(state, groups.get(c.conversationId)!, rows)if (!summary) continue- read.push({ conversationId: c.conversationId, rootId: root.id, root: preview(root), replies: summary.replies, lastReplyAt: summary.lastAt.toISOString(),+ answered.push({ conversationId: c.conversationId, rootId: root.id, root: preview(root), replies: summary.replies, lastReplyAt: summary.lastAt.toISOString(),lastReplySequence: summary.lastSequence, lastReplier: summary.authors[0] ?? null, follow: c.follow, at: summary.lastAt.getTime() })}- read.sort((a, b) => newestFirst({ at: a.at, id: a.rootId }, { at: b.at, id: b.rootId }))- if (read.length > MAX_READ_THREADS) more = true- return { unread, read: read.slice(0, MAX_READ_THREADS).map(({ at: _at, ...thread }) => thread), more }+ answered.sort((a, b) => newestFirst({ at: a.at, id: a.rootId }, { at: b.at, id: b.rootId }))+ if (answered.length > read) more = true+ return { unread, read: answered.slice(0, read).map(({ at: _at, ...thread }) => thread), more }}const threadsReads = createRateLimiter('swarm-threads', THREADS_WINDOW_MS, THREADS_READS)diff --git a/backend/src/superTabs/read/hostInputs.ts b/backend/src/superTabs/read/hostInputs.tsindex aa04aaa01..fee9a0b7e 100644--- a/backend/src/superTabs/read/hostInputs.ts+++ b/backend/src/superTabs/read/hostInputs.ts@@ -12,7 +12,8 @@ import { createHash } from 'node:crypto'import type { Prisma } from '@prisma/client'import type { CacheView } from '../cache.js'import type { PatchRule } from '../cachePatch.js'-import { groupsBy } from '../parts/indexed.js'+import { groupsBy, readBy } from '../parts/indexed.js'+import { ms } from '../parts/light.js'type Transaction = Prisma.TransactionClient/** The row hash's length at the front of an etag (read/hostEtag.ts); the input signature follows it. */@@ -68,6 +69,50 @@ export const hostGroupsRule: PatchRule<HostGroups> = {},}+/** The kinds whose live rows the signature reads by their data stamp. */+const STAMP_KINDS = ['member', 'agent', 'start'] as const+type StampKind = typeof STAMP_KINDS[number]+/** Every live member, agent and start of a Swarm: its data stamp (`changedAt`, in ms), by kind and key. */+export type HostStamps = Readonly<Record<StampKind, Readonly<Record<string, number>>>>+const STAMP_COLLECTION = { member: 'SwarmMember', agent: 'SwarmAgent', start: 'SwarmStart' } as const++/** The stamps of every live member, agent and start, in one reply each. */+export async function loadHostStamps(tx: Transaction, tabId: string): Promise<HostStamps> {+ const [member, agent, start] = await Promise.all(STAMP_KINDS.map(async kind => Object.fromEntries((await readBy(tx, STAMP_COLLECTION[kind], 'changes',+ [{ $match: { tabId, deleted: false } }, { $project: { _id: 0, key: 1, changedAt: 1 } }])).map(row => [row.key as string, ms(row.changedAt)]))))+ return { member: member!, agent: agent!, start: start! }+}++/**+ * The `host:stamps` entry (#2839): a host's check after any change read every live start's stamp again, and finished starts+ * stay live for 7 days, so the read grew with the Swarm's history (Atlas ops per request up 38% at flat traffic). A changed+ * part comes as its row is now, so applying one twice does nothing; a tombstone takes its key out. A touch moves no+ * `changedAt`, so it is in no delta and changes no stamp, as it changed none of the rows read before.+ */+export const hostStampsRule: PatchRule<HostStamps> = {+ kinds: [...STAMP_KINDS],+ apply(held, delta) {+ let next: Record<StampKind, Record<string, number>> | null = null+ const copied = new Set<StampKind>()+ const writable = (kind: StampKind) => {+ next ??= { ...held } as Record<StampKind, Record<string, number>>+ if (!copied.has(kind)) { next[kind] = { ...held[kind] }; copied.add(kind) }+ return next[kind]+ }+ for (const part of delta.parts) {+ const kind = part.kind as StampKind+ if (!STAMP_KINDS.includes(kind)) continue+ const current = (next ?? held)[kind]+ if (part.deleted) {+ if (Object.hasOwn(current, part.key)) delete writable(kind)[part.key]+ continue+ }+ if (current[part.key] !== part.changedAt) writable(kind)[part.key] = part.changedAt+ }+ return next ?? held+ },+}+/** Every live conversation's row, through the live index alone: it holds the key, digest and dormancy, so no document is read. */export async function loadHostGroups(tx: Transaction, tabId: string): Promise<HostGroups> {const rows = await groupsBy(tx, 'live', [{ $match: { tabId, deleted: false } },@@ -76,17 +121,19 @@ export async function loadHostGroups(tx: Transaction, tabId: string): Promise<Ho}export async function hostInputs(tx: Transaction, view: CacheView, tabId: string): Promise<string | null> {- const live = { tabId, deleted: false }, stamp = { key: true, changedAt: true } as const- const [head, members, agents, starts, machines, held] = await Promise.all([+ const live = { tabId, deleted: false }+ const [head, stamps, machines, held] = await Promise.all([tx.swarmHead.findUnique({ where: { id: `${tabId}:head` }, select: { changedAt: true } }),- tx.swarmMember.findMany({ where: live, select: stamp }), tx.swarmAgent.findMany({ where: live, select: stamp }),- tx.swarmStart.findMany({ where: live, select: stamp }),+ view.get(tabId, 'host:stamps', 'main', () => loadHostStamps(tx, tabId), hostStampsRule),tx.swarmMachine.findMany({ where: live, select: { key: true, hostChangedAt: true } }),view.get(tabId, 'host:groups', 'main', () => loadHostGroups(tx, tabId), hostGroupsRule),])+ // As the rows read before gave them: key, then the stamp as a date.+ const rows = (kind: StampKind) => Object.entries(stamps[kind]).map(([key, at]) => ({ key, changedAt: new Date(at) }))+ const [members, agents, starts] = STAMP_KINDS.map(rows)const groups = hostGroupsSignature(held)if (!head || groups.missing) return nullconst keyed = <T extends { key: string }>(rows: T[]) => rows.sort((a, b) => byCodeUnit(a.key, b.key))- return createHash('sha256').update(JSON.stringify([head.changedAt, keyed(members), keyed(agents), keyed(starts), keyed(machines), groups.all]))+ return createHash('sha256').update(JSON.stringify([head.changedAt, keyed(members!), keyed(agents!), keyed(starts!), keyed(machines), groups.all])).digest('base64url').slice(0, ROW_HASH)}diff --git a/backend/src/superTabs/read/inbox.ts b/backend/src/superTabs/read/inbox.tsindex 2b5f086e8..2d032444b 100644--- a/backend/src/superTabs/read/inbox.ts+++ b/backend/src/superTabs/read/inbox.ts@@ -25,7 +25,7 @@ import { createRateLimiter } from '../../lib/rateLimit.js'import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../../lib/teamSession.js'import { agentOnly, author, fail, SuperTabError, type Actor, type Author, type Conversation, type SuperTabState } from '../model.js'import { readConversation } from '../projects.js'-import { deliveredCopies, threadsAcross, threadsBackfilled, type ThreadReply } from '../pageReads.js'+import { deliveredCopies, threadsBackfilled, threadsNaming, type ThreadReply } from '../pageReads.js'import { isSwarmBuddyChat } from '../buddies.js'import { threadSummaries } from '../threads.js'import { sessionReadsRow } from '../buddySessions.js'@@ -197,8 +197,8 @@ export async function newestInThreads(db: PrismaClient, tabId: string, ranges: T/*** The threads of `threads` the person wrote in or was tagged in, in rows a page shows them, as threadKey(conversationId, thread).- * Read from the threads' summaries (pageReads.ts threadsAcross): one small row per thread by root id in one read, whatever its- * length, holding each author's newest row and every person's first tag with what a reader skips marked, so a row of theirs any+ * Read from the threads' summaries (pageReads.ts threadsNaming): one read by root id, whatever the threads' length, of only the+ * summaries naming the person and only their parts and tags that do, with what a reader skips marked, so a row of theirs any* distance back counts, as the Threads view counts it. It read each thread's newest MEMBER_SCAN rows before the mark, one $or* branch per thread and one $unionWith branch past the cap: the threads route's slowest read in Ken's scan of 11-04 (task #2768).* A Swarm Buddy chat's threads still read those rows before `sequence`: its summary cannot tell a row of a project its person@@ -213,12 +213,8 @@ export async function namedInThreads(db: PrismaClient, tabId: string, state: Supconst scan = new Set(state.conversations.filter(g => !ready || isSwarmBuddyChat(g)).map(g => g.id))const scanned = threads.filter(t => scan.has(t.conversationId)), summed = threads.filter(t => !scan.has(t.conversationId))if (summed.length) {- const chatOf = new Map(summed.map(t => [t.thread, t.conversationId]))- for (const m of await threadsAcross(db, tabId, summed.map(t => ({ conversationId: t.conversationId, root: t.thread })))) {- if (!m.agentOnly && ((m.author.kind === 'person' && m.author.id === personId) || m.mentions.includes(personId))) {- named.add(threadKey(chatOf.get(m.thread)!, m.thread))- }- }+ const naming = await threadsNaming(db, tabId, summed.map(t => ({ conversationId: t.conversationId, root: t.thread })), personId)+ for (const t of summed) if (naming.has(`${t.conversationId}\u0000${t.thread}`)) named.add(threadKey(t.conversationId, t.thread))}if (scanned.length) {const rows = await newestInThreads(db, tabId, scanned.map(t => ({ conversationId: t.conversationId, thread: t.thread, sequence: { $lte: t.sequence } })),diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 9ce0ee17d..bfbaa52ab 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -97,6 +97,7 @@ import { OVERDUE_PER_PASS, overdueDecisions } from './overdueDecisions.js'import { answerable, askDecisions, MAX_OPEN_DECISIONS, REFLECTION_DECISION, reflectionDecisions, expireReflections, fullFor, listDecisions, type DecisionList, readAskedDecision, recordAnswer, repeatOf, waitingConversations, waitingFor, waitingInProject, withdrawIn, workEnded, workOver, writeDecisions } from './decisions.js'import { CATCH_UP_SCAN, catchUpSummary, type CatchUp } from './catchUp.js'import { recordMessageRead, type MessageReadKey } from './messageReadStats.js'+import { recordMessageReach } from './messageReachStats.js'import { DEFAULT_ROUTING_POLICY, type RoutingPolicy } from './routingPolicy.js'import { catalogRead } from './catalog.js'import { invitedSwarms } from './invitedSwarms.js'@@ -3003,6 +3004,16 @@ export class SuperTabStore {const context = own && !own.projectId && !forward && cursor.before === undefined && !cursor.messageId ? await this.sessionExcerpt(tx, tabId, conversationId, own.from, m => rowRead(m) && sessionReadsRow(undefined, group, state)(m)) : undefined// Only the rows this reader is shown get file links, each signed afresh for this read (fileLinks.ts).const linked = await this.linked(tabId, shown)+ // A person's read of new messages is where a message reaches them (task #2840): every app reads `after` once a push or its+ // poll says the conversation moved. Their own messages, and any other read (the page shown, a thread, a scroll back) are+ // not a message reaching its reader. Timed only once the read can no longer fail.+ if (forward && readerKind(actor, buddy) === 'person' && actor.kind === 'person') {+ const now = this.now()+ for (const m of shown) {+ const author = m.author as unknown as Author+ if (author.kind !== 'person' || author.id !== actor.userId) recordMessageReach({ reader: 'person', via: 'read' }, now - m.createdAt.getTime())+ }+ }const byMessage = deliveriesByMessage(deliveries)return { messages: linked.map(m => ({ ...m, mentions: m.mentions ?? [], reactions: reactions.get(m.id) ?? [],deliveries: (byMessage.get(m.id) ?? []).filter(d => shownTo(m, d)).sort(receiptOrder(m)) })), next, threads, ...(context ? { context } : {}),@@ -4035,6 +4046,13 @@ export class SuperTabStore {if (!live) await restoreDelivery(tx, delivery)// A claim that gets in ends the failing record. Unset, never null: a missing field is a real absence, which the first failure's// isSet: false branch matches and which leaves no keys in the document.+ // The message reached its agent (task #2840): its host's first acknowledgement that it was typed, timed from the delivery's+ // creation, which is written with its message. Once committed, so a retried transaction times it once; a repeated ack+ // finds deliveredAt set and times nothing.+ if (action.type === 'ack' && !action.uncertain && !delivery.deliveredAt) {+ const reader = isBuddy(agent(state, agentId)) ? 'buddy' as const : 'agent' as const, ms = this.now() - delivery.createdAt.getTime()+ afterCommit(tx, () => recordMessageReach({ reader, via: 'delivery' }, ms))+ }const updated = await tx.superTabDelivery.update({ where: { id: delivery.id }, data: { status, claimId: action.claimId,...(action.type === 'claim' ? { claimFailingSince: { unset: true }, claimFailedAt: { unset: true }, claimFailures: { unset: true },claimFailure: { unset: true } } : {}),diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dartindex 55f65245a..e8ad3c567 100644--- a/desktop/lib/shortcuts/keymap_commands.dart+++ b/desktop/lib/shortcuts/keymap_commands.dart@@ -30,9 +30,14 @@ class HarnessCommand {/// Workspace defaults come from the live shortcut table. A command cannot/// quietly propose different keys from the ones the user already uses.List<String> get keys {- if (id == 'swarm.quick_switcher') {+ // The Swarm chat's own letters are Cmd's on a Mac and Ctrl's elsewhere,+ // as in a browser: no terminal is there to take Ctrl.+ if (const {'swarm.quick_switcher': 'k', 'swarm.find_in_chat': 'f'}[id]+ case final letter?) {return [- defaultTargetPlatform == TargetPlatform.macOS ? 'cmd+k' : 'ctrl+k',+ defaultTargetPlatform == TargetPlatform.macOS+ ? 'cmd+$letter'+ : 'ctrl+$letter',];}// Cmd-Alt-T cannot collapse to Alt-T in a browser: that is New Tab.@@ -253,6 +258,15 @@ final harnessCommands = <HarnessCommand>[keywords: ['unread', 'chat', 'Swarm', 'Slack'],repeatable: true,),+ // Find in the open chat or thread (task #2826). A focused terminal keeps+ // the same key for its own find.+ const HarnessCommand(+ 'swarm.find_in_chat',+ 'Find in chat',+ ShortcutGroup.navigate,+ context: KeymapContext.swarmChat,+ keywords: ['find', 'search', 'chat', 'Swarm'],+ ),// The current project's Buddy chat, in a Swarm tab, where the PM's private// lines land since Buddies replaced Chat with PM: the id stays, so a key a// person bound to it keeps working. K for "talk": free on every platformdiff --git a/desktop/lib/super_tabs/activity.dart b/desktop/lib/super_tabs/activity.dartindex db82c65ec..be63076ea 100644--- a/desktop/lib/super_tabs/activity.dart+++ b/desktop/lib/super_tabs/activity.dart@@ -239,6 +239,13 @@ class SuperTabActivity extends ChangeNotifier {/// The followed threads with news today.List<SuperTabFollowedThread> get threadRows => newReplies;+ /// The followed threads the reader has read, newest reply first, below the+ /// new ones (Darren, task #2835).+ List<SuperTabFollowedThread> get readThreadRows => [+ for (final t in attention.shown)+ if (!attention.isNew(t)) t,+ ];+/// What the listed [decided] call their PM: the coordinator of their/// project, or `the PMs` when they come from several.String coordinatorFor(Iterable<SuperTabDecision> decided) {diff --git a/desktop/lib/super_tabs/activity_view.dart b/desktop/lib/super_tabs/activity_view.dartindex 31a07a006..918105f8d 100644--- a/desktop/lib/super_tabs/activity_view.dart+++ b/desktop/lib/super_tabs/activity_view.dart@@ -653,11 +653,13 @@ class _SuperTabActivityViewState extends State<SuperTabActivityView> {// ---- Threads ----- /// Every thread listed is unread (Activity lists today's new replies), so- /// there is no Unreads only here.+ /// Every thread the reader follows (Darren, task #2835): those with new+ /// replies first, bold, as before; then the ones they have read, plain,+ /// newest reply first, 50 at a time as they scroll. Only the new ones have+ /// Mark read.List<Widget> _threads() {final a = _activity;- final rows = a.threadRows;+ final rows = a.threadRows, read = a.readThreadRows;return [_bar([_markAll(@@ -669,51 +671,82 @@ class _SuperTabActivityViewState extends State<SuperTabActivityView> {},),]),- if (rows.isEmpty)- _empty('No threads with new replies')- else- ..._byDay<SuperTabFollowedThread>(rows, (t) => t.lastReplyAt, (t) {- // The data holds the root and the newest reply's author, not the- // reply's text: the preview is the root, said by the root's author.- final author = t.rootAuthor['name'] as String? ?? '';- final replier = t.lastReplier?['name'] as String? ?? '';- final project = _snapshot?.projectFor(t.conversationId);- final subject = threadSubject(t.rootText);- final root = _oneLine(t.rootText);- return _ActivityRow(- key: ValueKey('super-activity-row-thread:${t.key}'),- unread: a.attention.isNew(t),- avatarName: author.isEmpty ? subject : author,- who: subject.isEmpty ? 'Thread' : subject,- where: project?.name,- privateWhere: project?.isPrivate == true,- forThread: true,- repliedBy: replier.isEmpty ? null : replier,- trailing: '${a.attention.newCount(t)} new',- preview: author.isEmpty ? root : '$author: $root',- previewLead: author.isEmpty ? null : author.length + 1,- actions: [- (- label: 'Mark read',- run: () {- _settle();- a.attention.markRead(t);- },- ),- (- label: 'Unfollow',- run: () {- _settle();- unawaited(a.attention.setFollow(t, false));- },- ),- ],- onTap: () => widget.onOpenThread(t.conversationId, t.rootId),- );- }),+ if (rows.isEmpty && read.isEmpty)+ _empty('No threads yet')+ else ...[+ ..._byDay<SuperTabFollowedThread>(+ rows,+ (t) => t.lastReplyAt,+ (t) => _threadRow(t, unread: true),+ ),+ if (read.isNotEmpty) ...[+ KeyedSubtree(+ key: const ValueKey('super-activity-threads-read'),+ child: _heading('Read'),+ ),+ ..._byDay<SuperTabFollowedThread>(+ read,+ (t) => t.lastReplyAt,+ (t) => _threadRow(t, unread: false),+ ),+ if (a.attention.canReadMore)+ _ReadMore(+ key: const ValueKey('super-activity-threads-more'),+ onShown: a.attention.readMore,+ ),+ ],+ ],];}+ /// One followed thread's row: bold with its new count when [unread], plain+ /// with its last reply's time when read.+ Widget _threadRow(SuperTabFollowedThread t, {required bool unread}) {+ final a = _activity;+ // The data holds the root and the newest reply's author, not the+ // reply's text: the preview is the root, said by the root's author.+ final author = t.rootAuthor['name'] as String? ?? '';+ final replier = t.lastReplier?['name'] as String? ?? '';+ final project = _snapshot?.projectFor(t.conversationId);+ final subject = threadSubject(t.rootText);+ final root = _oneLine(t.rootText);+ return _ActivityRow(+ key: ValueKey('super-activity-row-thread:${t.key}'),+ unread: unread && a.attention.isNew(t),+ avatarName: author.isEmpty ? subject : author,+ who: subject.isEmpty ? 'Thread' : subject,+ where: project?.name,+ privateWhere: project?.isPrivate == true,+ forThread: true,+ repliedBy: replier.isEmpty ? null : replier,+ trailing: unread+ ? '${a.attention.newCount(t)} new'+ : t.lastReplyAt == null+ ? ''+ : _when(t.lastReplyAt!),+ preview: author.isEmpty ? root : '$author: $root',+ previewLead: author.isEmpty ? null : author.length + 1,+ actions: [+ if (unread)+ (+ label: 'Mark read',+ run: () {+ _settle();+ a.attention.markRead(t);+ },+ ),+ (+ label: 'Unfollow',+ run: () {+ _settle();+ unawaited(a.attention.setFollow(t, false));+ },+ ),+ ],+ onTap: () => widget.onOpenThread(t.conversationId, t.rootId),+ );+ }+@overrideWidget build(BuildContext context) => ListenableBuilder(// The threads are read only while this view shows them.@@ -1123,3 +1156,35 @@ class _ActivityRowState extends State<_ActivityRow> {);}}++/// The end of the read threads while there are more: built only once the list+/// scrolls to it, it asks for the next page.+class _ReadMore extends StatefulWidget {+ const _ReadMore({super.key, required this.onShown});++ final Future<void> Function() onShown;++ @override+ State<_ReadMore> createState() => _ReadMoreState();+}++class _ReadMoreState extends State<_ReadMore> {+ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) unawaited(widget.onShown());+ });+ }++ @override+ Widget build(BuildContext context) => const Padding(+ padding: EdgeInsets.all(grid.AppDesktop.groupGap),+ child: Center(+ child: SizedBox.square(+ dimension: 16,+ child: CircularProgressIndicator(strokeWidth: 2),+ ),+ ),+ );+}diff --git a/desktop/lib/super_tabs/attention.dart b/desktop/lib/super_tabs/attention.dartindex 1cb052c65..d09a3121e 100644--- a/desktop/lib/super_tabs/attention.dart+++ b/desktop/lib/super_tabs/attention.dart@@ -100,6 +100,35 @@ class SuperTabAttention extends ChangeNotifier {/// The server stopped short of everything (its bounds).bool more = false;+ /// Read threads asked for at a time, and at most (backend read/followedThreads.ts `READ_THREADS_ASKED_MAX`): Activity's+ /// Threads lists them 50 at a time as the reader scrolls (task #2835).+ static const readPage = 50, readMax = 250;++ /// How many read threads the next read asks for while Activity is open: the pages it shows. Closed, a read asks for+ /// none and gets the server's 30 as before, so the reads on every Swarm change cost what they did (review of #2993); the+ /// next visit starts at the first page again.+ int readWanted = readPage;++ /// The server takes `read`; false on one before it (it refuses the query), which answers its own number and cannot page.+ /// Not asked again in this session on purpose: it changes only with a backend release, and the next session asks.+ bool readPaging = true;++ /// Whether the end of the read threads can ask for more.+ bool get canReadMore =>+ _open &&+ loaded &&+ more &&+ readPaging &&+ read.length >= readWanted &&+ readWanted < readMax;++ /// Asks for the next [readPage] read threads, when there are more.+ Future<void> readMore() {+ if (_disposed || !canReadMore) return Future.value();+ readWanted = (readWanted + readPage).clamp(readPage, readMax);+ return load();+ }+/// Threads shown as new in this visit of Activity: they stay new/// until the view is left, though opening them marked them read.final Set<String> _newThisVisit = {};@@ -326,6 +355,7 @@ class SuperTabAttention extends ChangeNotifier {void closed() {_open = false;+ readWanted = readPage;_trailing?.cancel();_trailing = null;_newThisVisit.clear();@@ -335,6 +365,7 @@ class SuperTabAttention extends ChangeNotifier {void _clear() {unread = read = const [];+ readWanted = readPage;loaded = false;error = null;more = false;@@ -426,7 +457,20 @@ class SuperTabAttention extends ChangeNotifier {var full = followSupported;if (full) {try {- answer = await controller.request('GET', '$_path/threads');+ // Read pages only for the open view (see [readWanted]).+ final paged = readPaging && _open;+ try {+ answer = await controller.request(+ 'GET',+ paged ? '$_path/threads?read=$readWanted' : '$_path/threads',+ );+ } on SuperTabFailure catch (failure) {+ // A server before paging refuses `read`: read as it takes it.+ if (failure.statusCode != 400 || !paged) rethrow;+ readPaging = false;+ if (!current()) return;+ answer = await controller.request('GET', '$_path/threads');+ }} on SuperTabFailure catch (failure) {if (failure.statusCode != 404) rethrow;full = false;diff --git a/desktop/lib/super_tabs/backlog_view.dart b/desktop/lib/super_tabs/backlog_view.dartindex cf87b56e1..177184ee1 100644--- a/desktop/lib/super_tabs/backlog_view.dart+++ b/desktop/lib/super_tabs/backlog_view.dart@@ -89,9 +89,6 @@ class _SuperTabBacklogViewState extends State<SuperTabBacklogView> {String? _project;bool _mine = false;String _query = '';-- /// Mine with nothing open was asked to show what the reader shipped.- bool _mineShipped = false;bool _allShipped = false;final _folded = <SuperTabBacklogGroup>{};@@ -140,10 +137,7 @@ class _SuperTabBacklogViewState extends State<SuperTabBacklogView> {_watched = next;}- void _setMine(bool mine) => setState(() {- _mine = mine;- _mineShipped = false;- });+ void _setMine(bool mine) => setState(() => _mine = mine);/// Whether [task] answers the search: its title, its number, or the name/// of the agent on it.@@ -194,20 +188,12 @@ class _SuperTabBacklogViewState extends State<SuperTabBacklogView> {_matches(task, query))(task, group),];- // Mine with nothing open says so and links to what shipped (#2551). All- // of it is shipped here, or it would be open.- final noneOpen =- _mine &&- !_mineShipped &&- query.isEmpty &&- matching.every((e) => e.$2 == SuperTabBacklogGroup.shipped);- final shown = noneOpen- ? const <(SuperTabConversation, SuperTabBacklogGroup)>[]- : matching;+ // Shipped lists with nothing open too, as the mockup does (#2885): the+ // list is what the cards count.final byGroup = <SuperTabBacklogGroup, List<SuperTabConversation>>{for (final group in SuperTabBacklogGroup.values)group: [- for (final (task, g) in shown)+ for (final (task, g) in matching)if (g == group) task,],};@@ -241,8 +227,7 @@ class _SuperTabBacklogViewState extends State<SuperTabBacklogView> {}if (cut < tasks.length) entries.add(_More(tasks.length - cut));}- // The cards count what the filters match, Mine's shipped tasks too while- // its empty list links to them.+ // The cards count what the filters match.int count(SuperTabBacklogGroup group) =>matching.where((e) => e.$2 == group).length;final projects = c.snapshot?.projects ?? const <SuperTabProject>[];@@ -379,36 +364,17 @@ class _SuperTabBacklogViewState extends State<SuperTabBacklogView> {),Expanded(child: entries.isEmpty+ // Nothing open and nothing shipped.? Center(- child: Column(- mainAxisSize: MainAxisSize.min,- children: [- Text(- noneOpen- ? 'No open tasks of yours'- : query.isNotEmpty- ? 'No tasks match “${_query.trim()}”'- : _mine- ? 'No tasks you asked for'- : 'No tasks',- style: DesktopChrome.control(- color: DesktopChrome.muted,- ),- ),- if (noneOpen && matching.isNotEmpty)- DesktopPill(- key: const ValueKey(- 'super-backlog-mine-shipped',- ),- label:- 'Your shipped tasks from the last 7 days · '- '${matching.length}',- quiet: true,- compact: true,- onPressed: () =>- setState(() => _mineShipped = true),- ),- ],+ child: Text(+ query.isNotEmpty+ ? 'No tasks match “${_query.trim()}”'+ : _mine+ ? 'No open tasks of yours'+ : 'No tasks',+ style: DesktopChrome.control(+ color: DesktopChrome.muted,+ ),),): LaidOutListView.builder(diff --git a/desktop/lib/super_tabs/chat_find.dart b/desktop/lib/super_tabs/chat_find.dartnew file mode 100644index 000000000..c528b7aac--- /dev/null+++ b/desktop/lib/super_tabs/chat_find.dart@@ -0,0 +1,315 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:unorm_dart/unorm_dart.dart' as unorm;++import '../core/project_folder.dart' show foldDiacritics;+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 'message_row.dart' show SuperTabMessageRow;+import 'model.dart';++/// How many older pages one search reads at most, as far back as a tagged+/// message is opened from (task #2826).+const superTabFindPages = 50;++final _marks = RegExp('[̀-ͯ]');++/// [text] as find compares it: "Tiếng Việt" and "tieng viet" read the same,+/// whether its accents were typed composed or combining.+String superTabFindFold(String text) =>+ foldDiacritics(unorm.nfd(text).replaceAll(_marks, '')).toLowerCase();++/// Find in the open chat or thread: the loaded rows that match, which one is+/// current, and reading older pages, at most [superTabFindPages] a search,+/// when stepping up past the oldest loaded match. Matches are numbered from+/// the newest, so pages read in add matches above without moving the number.+class SuperTabChatFind extends ChangeNotifier {+ SuperTabChatFind({+ required this.rows,+ required this.hasOlder,+ required this.readOlder,+ });++ /// The rows the list shows, oldest first.+ final List<SuperTabMessage> Function() rows;+ final bool Function() hasOlder;++ /// Reads the page before those loaded; false when the read failed.+ final Future<bool> Function() readOlder;++ String query = '';+ List<String> matches = const [];+ Set<String> matching = const {};+ String? current;++ /// Pages read so far by the read-back under way, null when none is.+ int? reading;+ String? note;++ // Pages this search has read, and the search a read-back belongs to.+ int _pages = 0, _search = 0;+ final _folded = <String, (String, String)>{};++ int get total => matches.length;+ int? get number {+ final at = current == null ? -1 : matches.indexOf(current!);+ return at < 0 ? null : matches.length - at;+ }++ void search(String query) {+ this.query = query;+ _search++;+ _pages = 0;+ reading = null;+ note = null;+ current = null;+ _match();+ current = matches.lastOrNull;+ notifyListeners();+ }++ /// Matches the rows again as the list draws them, telling no one: what the+ /// list draws next reads them. The current match stays the same message.+ void refresh() {+ _match();+ if (!matching.contains(current)) current = matches.lastOrNull;+ }++ void clear() => search('');++ /// Steps to the newer match; a read-back under way stops, as the phone's+ /// does.+ void newer() {+ if (reading != null) {+ _search++;+ reading = null;+ }+ final at = current == null ? -1 : matches.indexOf(current!);+ if (at >= 0 && at < matches.length - 1) current = matches[at + 1];+ note = null;+ notifyListeners();+ }++ /// A read-back under way stops with it: its view or thread is gone.+ @override+ void dispose() {+ _search++;+ super.dispose();+ }++ Future<void> older() async {+ if (reading != null || query.trim().isEmpty) return;+ final at = current == null ? matches.length : matches.indexOf(current!);+ if (at > 0) {+ current = matches[at - 1];+ note = null;+ notifyListeners();+ return;+ }+ final search = _search, oldest = matches.firstOrNull;+ while (true) {+ if (!hasOlder()) {+ note = 'No more matches in this chat';+ break;+ }+ if (_pages >= superTabFindPages) {+ note = 'No more matches in the last $superTabFindPages pages';+ break;+ }+ // The page on its way counts: "1 of 50" while the first is read.+ reading = _pages + 1;+ notifyListeners();+ final read = await readOlder();+ if (search != _search) return;+ _pages++;+ if (!read) {+ note = 'Couldn’t read older messages';+ break;+ }+ _match();+ final first = matches.firstOrNull;+ if (first != null && first != oldest) {+ // The newest of the matches the pages brought, just above the old.+ final end = oldest == null ? matches.length : matches.indexOf(oldest);+ current = matches[end - 1];+ note = null;+ break;+ }+ }+ reading = null;+ notifyListeners();+ }++ void _match() {+ final folded = superTabFindFold(query.trim());+ if (folded.isEmpty) {+ matches = const [];+ matching = const {};+ return;+ }+ matches = [+ for (final row in rows())+ if (_fold(row).contains(folded)) row.id,+ ];+ matching = matches.toSet();+ }++ /// Each message is folded once while its text stays the same.+ String _fold(SuperTabMessage row) {+ final seen = _folded[row.id];+ if (seen != null && seen.$1 == row.text) return seen.$2;+ final folded = superTabFindFold(row.text);+ _folded[row.id] = (row.text, folded);+ return folded;+ }+}++/// The find field over a chat or thread: "n of N", older and newer, close.+/// Enter steps older, Shift+Enter newer, Esc closes.+class SuperTabFindBar extends StatefulWidget {+ const SuperTabFindBar({+ super.key,+ required this.find,+ required this.onClose,+ this.focus,+ });++ final SuperTabChatFind find;+ final VoidCallback onClose;+ final FocusNode? focus;++ @override+ State<SuperTabFindBar> createState() => _SuperTabFindBarState();+}++class _SuperTabFindBarState extends State<SuperTabFindBar> {+ late final _text = TextEditingController(text: widget.find.query);+ late final _focus = widget.focus ?? FocusNode(debugLabel: 'Find in chat');++ @override+ void initState() {+ super.initState();+ _focus.requestFocus();+ }++ @override+ void dispose() {+ _text.dispose();+ if (widget.focus == null) _focus.dispose();+ super.dispose();+ }++ KeyEventResult _key(FocusNode node, KeyEvent event) {+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {+ return KeyEventResult.ignored;+ }+ final composing = _text.value.composing;+ if (composing.isValid && !composing.isCollapsed) {+ return KeyEventResult.ignored;+ }+ final key = event.logicalKey;+ if (key == LogicalKeyboardKey.escape) {+ widget.onClose();+ return KeyEventResult.handled;+ }+ if (key == LogicalKeyboardKey.enter ||+ key == LogicalKeyboardKey.numpadEnter) {+ if (HardwareKeyboard.instance.isShiftPressed) {+ widget.find.newer();+ } else {+ widget.find.older();+ }+ return KeyEventResult.handled;+ }+ return KeyEventResult.ignored;+ }++ String _status(SuperTabChatFind find) {+ if (find.reading case final pages?) {+ return 'Reading older messages · $pages of $superTabFindPages';+ }+ if (find.note case final note?) return note;+ if (find.query.trim().isEmpty) return '';+ final number = find.number;+ return number == null ? 'No matches' : '$number of ${find.total}';+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return ListenableBuilder(+ listenable: widget.find,+ builder: (context, _) {+ final find = widget.find;+ final status = _status(find);+ return Container(+ key: const ValueKey('super-find-bar'),+ // The field lines up with the messages' text under it.+ padding: const EdgeInsets.fromLTRB(+ SuperTabMessageRow.horizontalInset,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ ),+ decoration: BoxDecoration(+ border: Border(bottom: BorderSide(color: DesktopChrome.rim)),+ ),+ child: Row(+ children: [+ Expanded(+ child: Focus(+ onKeyEvent: _key,+ child: TextField(+ key: const ValueKey('super-find-field'),+ controller: _text,+ focusNode: _focus,+ style: DesktopChrome.text(),+ onChanged: find.search,+ decoration: const InputDecoration(+ isDense: true,+ hintText: 'Find in chat',+ prefixIcon: Icon(AppIcons.search, size: 16),+ ),+ ),+ ),+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Semantics(+ liveRegion: true,+ child: Text(+ status,+ key: const ValueKey('super-find-count'),+ maxLines: 1,+ style: DesktopChrome.metadata(),+ ),+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ AppIconButton(+ key: const ValueKey('super-find-older'),+ icon: AppIcons.chevronUp,+ tooltip: 'Older match (Enter)',+ onPressed: find.query.trim().isEmpty || find.reading != null+ ? null+ : find.older,+ ),+ AppIconButton(+ key: const ValueKey('super-find-newer'),+ icon: AppIcons.chevronDown,+ tooltip: 'Newer match (Shift-Enter)',+ onPressed: (find.number ?? 1) > 1 ? find.newer : null,+ ),+ AppIconButton(+ key: const ValueKey('super-find-close'),+ icon: AppIcons.close,+ tooltip: 'Close find (Esc)',+ onPressed: widget.onClose,+ ),+ ],+ ),+ );+ },+ );+ }+}diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 5709aa057..a9c0be1d6 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -2058,7 +2058,7 @@ class SuperTabController extends ChangeNotifier {);static bool _listed(SuperTabMessage m) =>- m.source['kind'] != 'update-request';+ m.source['kind'] != 'update-request' && !m.terminalPrompt;/// [id]'s messages with its steps' rows merged in by time (task steps/// design): each step keeps its own conversation, shown inside its task.@@ -2332,18 +2332,24 @@ class SuperTabController extends ChangeNotifier {/// thread's reply line instead ([threadUnread]). The server's newest/// main-stream message covers a chat not held here; an older server's/// newest message, and the newest held, stand in for it.- bool unread(SuperTabConversation group) =>- max(- group.lastMainSequence ?? group.lastMessageSequence,- _messages[group.id]?.reversed- .where(- (m) => m.source['kind'] != 'update-request' && m.inMainStream,- )- .firstOrNull- ?.sequence ??- 0,- ) >- readMark(group.id);+ /// Held through the server's newest message, the rows held say it, so a+ /// row the chat does not list (a terminal's prompt) is nothing new.+ bool unread(SuperTabConversation group) {+ final held = _messages[group.id];+ final heldAll =+ held != null &&+ held.isNotEmpty &&+ held.last.sequence >= group.lastMessageSequence;+ return max(+ heldAll ? 0 : group.lastMainSequence ?? group.lastMessageSequence,+ held?.reversed+ .where((m) => _listed(m) && m.inMainStream)+ .firstOrNull+ ?.sequence ??+ 0,+ ) >+ readMark(group.id);+ }void start() {if (_disposed) return;@@ -3604,7 +3610,14 @@ class SuperTabController extends ChangeNotifier {return;}final loaded = _loadedMessageSequence(id);- final last = min(through ?? loaded, loaded);+ var last = min(through ?? loaded, loaded);+ // Rows the chat does not list (a terminal's prompt) just after what was+ // read are read with it, so another device does not show them unread.+ for (final m in _messages[id] ?? const <SuperTabMessage>[]) {+ if (m.sequence <= last || !m.inMainStream) continue;+ if (_listed(m) || m.sequence > loaded) break;+ last = m.sequence;+ }_serverMarks.mark(id, last, kept: snapshot?.readMarks[id] ?? 0);if ((_readAt[id] ?? 0) >= last) return;_readAt[id] = last;diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex ce57966d4..0e3351ab3 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -1043,22 +1043,29 @@ class SuperTabReplyPreview extends StatelessWidget {}}-/// Lights a message briefly, as the one a quote was followed to.+/// Lights a message briefly, as the one a quote was followed to, or while it+/// is find's current match; a [match] of find's others is lit more quietly.class SuperTabMessageHighlight extends StatelessWidget {const SuperTabMessageHighlight({super.key,required this.on,+ this.match = false,required this.child,});- final bool on;+ final bool on, match;final Widget child;@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);+ final selection = DesktopChrome.selection;return AnimatedContainer(duration: const Duration(milliseconds: 400),- color: on ? DesktopChrome.selection : Colors.transparent,+ color: on+ ? selection+ : match+ ? selection.withValues(alpha: selection.a / 2)+ : Colors.transparent,child: child,);}diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 502bc0f22..3381796d4 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -1520,6 +1520,10 @@ class SuperTabMessage {String get authorId => author['id'] as String? ?? '';bool get fromAgent => author['kind'] == 'agent';bool get fromTerminal => source['kind'] == 'native';++ /// What was typed into an agent's terminal, a scheduled prompt too: no chat+ /// row and nothing unread (Ken 11-04, task #2849). Its answer still is one.+ bool get terminalPrompt => fromTerminal && source['phase'] == 'prompt';SuperTabRoute? get route => SuperTabRoute.fromSource(source);bool get routeOverride => source['kind'] == 'route-override';diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dartindex fc0c7059e..12bfd1214 100644--- a/desktop/lib/super_tabs/thread_panel.dart+++ b/desktop/lib/super_tabs/thread_panel.dart@@ -9,6 +9,7 @@ import '../shared/widgets/app_icon_button.dart';import '../state/harness_attachments.dart';import '../widgets/desktop_chrome.dart';import 'buddy_sessions.dart';+import 'chat_find.dart';import 'composer_tags.dart';import 'composer_toggle.dart';import 'day_pill.dart';@@ -63,10 +64,10 @@ class SuperTabThreadPanel extends StatefulWidget {final SuperTabVoiceTake? voice;@override- State<SuperTabThreadPanel> createState() => _SuperTabThreadPanelState();+ State<SuperTabThreadPanel> createState() => SuperTabThreadPanelState();}-class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {+class SuperTabThreadPanelState extends State<SuperTabThreadPanel> {late final _composer = TextEditingController(text: c.threadDraft(widget.root),);@@ -101,6 +102,69 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {String? _target, _lit;Timer? _litTimer;int _jumps = 0;+ // Find in this thread (task #2826): its root and replies, the earlier+ // replies read as Show earlier replies reads them.+ SuperTabChatFind? _find;+ String? _foundMatch;+ final _findFocus = FocusNode(debugLabel: 'Find in thread');++ /// Whether what has focus is in this thread: Cmd+F finds here then.+ bool get focused =>+ FocusManager.instance.primaryFocus?.context+ ?.findAncestorStateOfType<SuperTabThreadPanelState>() ==+ this;++ void openFind() {+ if (_find != null) return _findFocus.requestFocus();+ final root = widget.root;+ setState(+ () => _find = SuperTabChatFind(+ // The root counts once no earlier replies are left to read: Up+ // from the oldest loaded reply reads them first.+ rows: () => [+ for (final m in c.threadMessages(root))+ if (m.id != root || !c.hasEarlierReplies(root)) m,+ ],+ hasOlder: () => c.hasEarlierReplies(root),+ readOlder: () async {+ final loaded = c.threadMessages(root).length;+ _scroll.holdPlace();+ await c.loadThread(earlier: true);+ return c.threadMessages(root).length > loaded ||+ !c.hasEarlierReplies(root);+ },+ )..addListener(_findMoved),+ );+ }++ void _closeFind({bool refocus = true}) {+ final find = _find;+ if (find == null) return;+ find+ ..removeListener(_findMoved)+ ..clear()+ ..dispose();+ _find = _foundMatch = null;+ if (!mounted) return;+ setState(() {});+ if (refocus) _focus.requestFocus();+ }++ /// A new current match is brought into view, as a followed link is.+ void _findMoved() {+ final match = _find?.current;+ if (!mounted) return;+ setState(() {});+ if (match == null || match == _foundMatch) return;+ _foundMatch = match;+ // Brought into view as the reply a thread opens at is.+ final messages = c.threadMessages(widget.root);+ final at = messages.indexWhere((m) => m.id == match);+ if (at < 0) return;+ final jump = ++_jumps;+ setState(() => _target = match);+ _reveal(jump, at / messages.length, 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.@@ -109,7 +173,13 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {time: message.createdAt,child: KeyedSubtree(key: message.id == _target ? _targetKey : null,- child: SuperTabMessageHighlight(on: message.id == _lit, child: row),+ // Lit as the reply opened at, or as find's current match; find's+ // other matches more quietly.+ child: SuperTabMessageHighlight(+ on: message.id == _lit || message.id == _find?.current,+ match: _find?.matching.contains(message.id) ?? false,+ child: row,+ ),),);@@ -184,6 +254,7 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {_newSession = false;_tagIndex.value = 0;_tagDismissed.value = null;+ _closeFind(refocus: false);}}@@ -191,6 +262,10 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {void dispose() {_litTimer?.cancel();widget.onScroll?.call(null);+ _find+ ?..removeListener(_findMoved)+ ..dispose();+ _findFocus.dispose();_scroll.dispose();_composer.dispose();_focus.dispose();@@ -394,6 +469,8 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {grid.AppTheme.watch(context);final messages = c.threadMessages(widget.root);_takeTarget(messages);+ // Find matches the rows as they are drawn now.+ _find?.refresh();final root = messages.where((m) => m.id == widget.root).firstOrNull;final replies = messages.where((m) => m.id != widget.root).toList();final pending = c@@ -438,6 +515,13 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {child: Text('Thread', style: SwarmType.name(context)),),),+ AppIconButton(+ key: const ValueKey('super-thread-find-button'),+ icon: AppIcons.search,+ tooltip: 'Find in thread',+ selected: _find != null,+ onPressed: openFind,+ ),AppIconButton(key: const ValueKey('super-thread-close'),icon: AppIcons.close,@@ -448,6 +532,13 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {),),Divider(height: 1, thickness: 1, color: DesktopChrome.rim),+ if (_find case final find?)+ SuperTabFindBar(+ key: ValueKey('super-thread-find-${widget.root}'),+ find: find,+ focus: _findFocus,+ onClose: _closeFind,+ ),SuperTabThreadSessionLine(key: ValueKey('super-thread-session-${widget.root}'),controller: c,@@ -656,7 +747,7 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {root: widget.root,padding: const EdgeInsets.fromLTRB(grid.AppDesktop.composerSide,- 0,+ grid.AppDesktop.controlGap,grid.AppDesktop.composerSide,grid.AppDesktop.controlGap,),diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 2d072e235..19ef0fd02 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -24,6 +24,7 @@ import '../state/harness_attachments.dart';import '../state/workspace_chrome.dart';import '../shortcuts/app_keymap.dart' show KeymapRegion;import '../shortcuts/keymap.dart' show KeymapContext;+import 'chat_find.dart';import 'chat_scroll.dart';import 'leaderboard/reader.dart';import 'jump_to_latest.dart';@@ -206,6 +207,12 @@ class _SuperTabViewState extends State<SuperTabView>({String conversationId, String messageId, double top})? _back;String? _lit;Timer? _litTimer;+ // Find in the open chat (task #2826): the search, the conversation it is+ // in, and the match last brought into view.+ SuperTabChatFind? _find;+ String? _findIn, _foundMatch;+ final _findFocus = FocusNode(debugLabel: 'Find in chat');+ final _threadFind = GlobalKey<SuperTabThreadPanelState>();bool _viewEnabled = true;bool _chatCovered = false;final _loadingOlder = <String>{};@@ -423,6 +430,7 @@ class _SuperTabViewState extends State<SuperTabView>_jumpRequest++;_finding = null;_back = null;+ _closeFind(refocus: false);_anchors.clear();_selected = null;_changed();@@ -487,6 +495,7 @@ class _SuperTabViewState extends State<SuperTabView>if (_selected != null) _jumpRequest++;_finding = null;_back = null;+ _closeFind(refocus: false);if (_anchors.remove(id) case final anchor?) {unawaited(_keepRow(id, anchor));}@@ -925,6 +934,7 @@ class _SuperTabViewState extends State<SuperTabView>...?region?.actions,'swarm.next_unread': () => _jumpUnread(1),'swarm.previous_unread': () => _jumpUnread(-1),+ 'swarm.find_in_chat': _findKey,},composing: region?.composing,keeps: region?.keeps,@@ -999,6 +1009,10 @@ class _SuperTabViewState extends State<SuperTabView>_unregisterDial?.call();_dial.cancel();_litTimer?.cancel();+ _find+ ?..removeListener(_findMoved)+ ..dispose();+ _findFocus.dispose();_historyRetry?.cancel();_composer.dispose();_mentionIndex.dispose();@@ -1500,6 +1514,7 @@ class _SuperTabViewState extends State<SuperTabView>void _readEarlierNearTop(String id, ScrollMetrics metrics) {if (metrics.extentBefore > 400 ||_finding != null ||+ _find?.reading != null ||_loadingOlder.contains(id) ||_olderFailed.contains(id) ||!c.hasOlder(id)) {@@ -2401,6 +2416,71 @@ class _SuperTabViewState extends State<SuperTabView>_focus.requestFocus();}+ /// Cmd+F: the thread's find while the thread has focus, else the chat's.+ void _findKey() {+ if (_threadFind.currentState case final thread? when thread.focused) {+ return thread.openFind();+ }+ _openFind();+ }++ void _openFind() {+ final id = c.selectedId;+ if (_find != null && _findIn == id) return _findFocus.requestFocus();+ _closeFind(refocus: false);+ final find = SuperTabChatFind(+ rows: () => [+ for (final entry in superTabTranscriptEntries(_shownMessages(id)))+ if (entry.interruptions == 0) entry.message,+ ],+ hasOlder: () => c.hasOlder(id),+ readOlder: () async {+ final loaded = c.messages(id).length;+ await _loadEarlier(id, keep: _find?.current);+ return c.messages(id).length > loaded || !c.hasOlder(id);+ },+ )..addListener(_findMoved);+ setState(() {+ _find = find;+ _findIn = id;+ });+ }++ void _closeFind({bool refocus = true}) {+ final find = _find;+ if (find == null) return;+ find+ ..removeListener(_findMoved)+ ..clear()+ ..dispose();+ _find = null;+ _findIn = _foundMatch = null;+ if (!mounted) return;+ setState(() {});+ if (refocus) _focus.requestFocus();+ }++ /// A new current match is brought into view, as a followed link is.+ void _findMoved() {+ final find = _find, id = _findIn;+ if (find == null || id == null || !mounted) return;+ final match = find.current;+ setState(() {});+ if (match == null || match == _foundMatch) return;+ _foundMatch = match;+ setState(() {+ _target = match;+ _scrollRequest++;+ _jumpingToEnd = false;+ _follow(id, false);+ });+ _revealTarget(+ id,+ 0,+ arrived: (row) => unawaited(Scrollable.ensureVisible(row, alignment: .3)),+ );+ }+void _light(String messageId) {_litTimer?.cancel();setState(() => _lit = messageId);@@ -3103,6 +3183,21 @@ class _SuperTabViewState extends State<SuperTabView>),),if (group != null && !_devicesVisible && !_listViewHoldsThePane) ...[+ if (!_terminalsVisible && !_showPullRequests && !_showTasks) ...[+ fingerTarget(+ enabled: _phone,+ AppIconButton(+ key: const ValueKey('super-find-button'),+ icon: AppIcons.search,+ size: AppIcons.inlineSize,+ tooltip: 'Find in chat',+ selected: _find != null,+ color: DesktopChrome.muted,+ onPressed: _openFind,+ ),+ ),+ const SizedBox(width: 4),+ ],// A project's chat is where its header rests: the button back// to it shows only from another view (Quiet Swarm, screen 1).if (!restsOnChat ||@@ -3843,6 +3938,7 @@ class _SuperTabViewState extends State<SuperTabView>images: () => _images(rows),thread: open.root,child: SuperTabThreadPanel(+ key: _threadFind,controller: c,root: open.root,row: (message, grouped) =>@@ -4152,6 +4248,8 @@ class _SuperTabViewState extends State<SuperTabView>_ => false,},);+ // Find matches the rows as they are drawn now.+ final search = _findIn == c.selectedId ? (_find?..refresh()) : null;Widget row(int index) {final entry = entries[index];final message = entry.message;@@ -4187,7 +4285,8 @@ class _SuperTabViewState extends State<SuperTabView>child: KeyedSubtree(key: message.id == _target ? _targetKey : null,child: SuperTabMessageHighlight(- on: message.id == _lit,+ on: message.id == _lit || message.id == search?.current,+ match: search?.matching.contains(message.id) ?? false,child: pendingById.containsKey(message.id)? _outgoingRow(pendingById[message.id]!,@@ -4264,6 +4363,13 @@ class _SuperTabViewState extends State<SuperTabView>: null;return Column(children: [+ if (search != null)+ SuperTabFindBar(+ key: ValueKey('super-find-$chatId'),+ find: search,+ focus: _findFocus,+ onClose: _closeFind,+ ),if (c.error != null && !unread)Padding(padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),@@ -4952,7 +5058,7 @@ class _SuperTabViewState extends State<SuperTabView>conversationId: chatId,padding: const EdgeInsets.fromLTRB(grid.AppDesktop.composerSide,- 0,+ grid.AppDesktop.controlGap,grid.AppDesktop.composerSide,grid.AppDesktop.controlGap,),diff --git a/desktop/test/super_tab_activity_threads_all_test.dart b/desktop/test/super_tab_activity_threads_all_test.dartnew file mode 100644index 000000000..f38985af1--- /dev/null+++ b/desktop/test/super_tab_activity_threads_all_test.dart@@ -0,0 +1,356 @@+import 'dart:io';++import 'package:clock/clock.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/activity.dart';+import 'package:harness/super_tabs/activity_view.dart';++import 'super_tab_activity_lists_test.dart' show load, swarm, unreadThread;+import 'support/capture.dart';+import 'support/super_tab_fixture.dart';++// Darren (11-04, task #2835): Activity's Threads lists every thread he took part in, not only the unread ones: unread on+// top as before, then the read ones, plain, newest reply first, 50 at a time.+final shots = Platform.environment['HARNESS_SUPER_TAB_CAPTURE'];+final _now = DateTime(2026, 11, 2, 20, 30);++Finder _key(String key) => find.byKey(ValueKey(key));++/// A thread the person follows and has read, its newest reply at [at].+Map<String, dynamic> readThread(+ String root, {+ required DateTime at,+ String text = 'Read root',+ String replier = 'Kiln',+}) => {+ 'conversationId': 'offline',+ 'rootId': root,+ 'root': {+ 'id': root,+ 'sequence': 1,+ 'author': {'kind': 'person', 'id': 'darren', 'name': 'Darren'},+ 'text': text,+ 'createdAt': '2026-10-30T01:00:00Z',+ 'attachments': 0,+ },+ 'replies': 4,+ 'lastReplyAt': at.toUtc().toIso8601String(),+ 'lastReplySequence': 9,+ 'lastReplier': {+ 'kind': 'agent',+ 'id': replier.toLowerCase(),+ 'name': replier,+ },+ 'follow': null,+};++Future<SuperTabActivity> _loaded(+ WidgetTester tester,+ ConversationServer server,+) async => (await tester.runAsync(() => load(server)))!;++Future<List<(String, String)>> _show(+ WidgetTester tester,+ SuperTabActivity activity, {+ Brightness brightness = Brightness.dark,+}) async {+ await tester.binding.setSurfaceSize(const Size(900, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ final opened = <(String, String)>[];+ await tester.pumpWidget(const SizedBox());+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: SuperTabActivityView(+ activity: activity,+ onOpenMention: (_) {},+ onOpenThread: (conversation, root) =>+ opened.add((conversation, root)),+ onOpenConversation: (_) {},+ now: () => _now,+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return opened;+}++Future<void> _threadsTab(WidgetTester tester) async {+ await tester.tap(_key('super-activity-tab-threads'));+ await tester.pumpAndSettle();+}++/// Lets the server's answer arrive, then draws it.+Future<void> _settle(WidgetTester tester) async {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 50)),+ );+ await tester.pumpAndSettle();+}++double _top(WidgetTester tester, Finder f) => tester.getTopLeft(f).dy;++void main() {+ setUpAll(() => loadCaptureFonts(shots));++ testWidgets(+ 'unread threads first as before, then the read ones, plain, newest reply first',+ (tester) async {+ final server = swarm();+ server.followedThreads = {+ 'unread': [unreadThread('new-1', text: 'Title: Dial fix — details')],+ 'read': [+ readThread(+ 'read-new',+ at: DateTime(2026, 11, 2, 16, 42),+ text: 'Title: Lamp boot loop — it reboots',+ ),+ readThread(+ 'read-old',+ at: DateTime(2026, 11, 1, 9, 10),+ text: 'Title: Firmware OTA timeout — after 30 s',+ ),+ ],+ 'more': false,+ };+ await withClock(Clock.fixed(_now), () async {+ await _show(tester, await _loaded(tester, server));+ await _threadsTab(tester);+ final unread = _key('super-activity-row-thread:offline/new-1');+ final newer = _key('super-activity-row-thread:offline/read-new');+ final older = _key('super-activity-row-thread:offline/read-old');+ final heading = _key('super-activity-threads-read');+ for (final f in [unread, heading, newer, older]) {+ expect(f, findsOneWidget);+ }+ expect(_top(tester, unread), lessThan(_top(tester, heading)));+ expect(_top(tester, heading), lessThan(_top(tester, newer)));+ expect(_top(tester, newer), lessThan(_top(tester, older)));+ // A read thread says when its last reply came, never a "new" count.+ expect(+ find.descendant(of: newer, matching: find.textContaining('new')),+ findsNothing,+ );+ expect(+ find.descendant(+ of: newer,+ matching: find.text('Kiln replied · # web-project'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(of: newer, matching: find.text('Lamp boot loop')),+ findsOneWidget,+ );+ // The tab's number stays the unread ones.+ expect(+ find.descendant(+ of: _key('super-activity-tab-threads'),+ matching: find.text('1'),+ ),+ findsOneWidget,+ );+ });+ },+ );++ testWidgets('a read thread opens beside its chat', (tester) async {+ final server = swarm();+ server.followedThreads = {+ 'unread': [],+ 'read': [readThread('read-1', at: DateTime(2026, 11, 2, 16, 42))],+ 'more': false,+ };+ await withClock(Clock.fixed(_now), () async {+ final opened = await _show(tester, await _loaded(tester, server));+ await _threadsTab(tester);+ await tester.tap(_key('super-activity-row-thread:offline/read-1'));+ await tester.pumpAndSettle();+ expect(opened, [('offline', 'read-1')]);+ });+ });++ testWidgets(+ 'it asks for 50 read threads, and 50 more at the end only while there are more',+ (tester) async {+ final server = swarm();+ final fifty = [+ for (var i = 0; i < 50; i++)+ readThread(+ 'read-$i',+ at: DateTime(2026, 11, 2, 16).subtract(Duration(minutes: i)),+ ),+ ];+ server.followedThreads = {'unread': [], 'read': fifty, 'more': true};+ await withClock(Clock.fixed(_now), () async {+ await _show(tester, await _loaded(tester, server));+ await _threadsTab(tester);+ expect(+ server.threadListReads.where((p) => p.contains('/threads')).last,+ endsWith('/threads?read=50'),+ );+ // The marker is not on screen until the list nears its end.+ expect(_key('super-activity-threads-more'), findsNothing);+ expect(+ server.threadListReads.where((p) => p.contains('read=100')),+ isEmpty,+ );+ // The server's next page: 60 in all, nothing after.+ server.followedThreads = {+ 'unread': [],+ 'read': [+ ...fifty,+ for (var i = 50; i < 60; i++)+ readThread(+ 'read-$i',+ at: DateTime(2026, 11, 2, 15).subtract(Duration(minutes: i)),+ ),+ ],+ 'more': false,+ };+ await tester.scrollUntilVisible(+ _key('super-activity-row-thread:offline/read-49'),+ 600,+ scrollable: find.descendant(+ of: _key('super-activity-list'),+ matching: find.byType(Scrollable),+ ),+ );+ await _settle(tester);+ expect(+ server.threadListReads.where((p) => p.contains('/threads')).last,+ endsWith('/threads?read=100'),+ );+ await tester.scrollUntilVisible(+ _key('super-activity-row-thread:offline/read-59'),+ 600,+ scrollable: find.descendant(+ of: _key('super-activity-list'),+ matching: find.byType(Scrollable),+ ),+ );+ // No more to read: no marker, no further read.+ final reads = server.threadListReads.length;+ expect(_key('super-activity-threads-more'), findsNothing);+ await _settle(tester);+ expect(server.threadListReads.length, reads);+ });+ },+ );++ // Review of #2993 (Alder2878): the threads are read again on every Swarm change. Only the open view asks for read+ // threads, the pages it shows; closed, it asks as before, and the next visit starts at 50 again.+ testWidgets(+ 'only the open view asks for read pages, and closing it starts over',+ (tester) async {+ final server = swarm();+ final fifty = [+ for (var i = 0; i < 50; i++)+ readThread(+ 'read-$i',+ at: DateTime(2026, 11, 2, 16).subtract(Duration(minutes: i)),+ ),+ ];+ server.followedThreads = {'unread': [], 'read': fifty, 'more': true};+ String last() =>+ server.threadListReads.where((p) => p.contains('/threads')).last;+ await withClock(Clock.fixed(_now), () async {+ final activity = await _loaded(tester, server);+ // Read for the sidebar, with Activity closed: no read pages asked.+ expect(last(), endsWith('/threads'));+ await _show(tester, activity);+ await _threadsTab(tester);+ expect(last(), endsWith('/threads?read=50'));+ await tester.runAsync(activity.attention.readMore);+ expect(last(), endsWith('/threads?read=100'));+ // Activity closes: the reads that follow ask as before.+ await tester.pumpWidget(const SizedBox());+ await tester.pumpAndSettle();+ await tester.runAsync(activity.attention.load);+ expect(last(), endsWith('/threads'));+ // The next visit starts at the first page again.+ await _show(tester, activity);+ await _settle(tester);+ expect(last(), endsWith('/threads?read=50'));+ });+ },+ );++ testWidgets('a server before paging still lists its read threads', (+ tester,+ ) async {+ final server = swarm()+ ..refuseThreadsRead = true+ ..followedThreads = {+ 'unread': [],+ 'read': [readThread('read-1', at: DateTime(2026, 11, 2, 16, 42))],+ 'more': true,+ };+ await withClock(Clock.fixed(_now), () async {+ await _show(tester, await _loaded(tester, server));+ await _threadsTab(tester);+ await _settle(tester);+ expect(_key('super-activity-row-thread:offline/read-1'), findsOneWidget);+ // It cannot page: no marker that would ask again and again.+ expect(_key('super-activity-threads-more'), findsNothing);+ });+ });++ testWidgets('no thread at all says so', (tester) async {+ final server = swarm();+ server.followedThreads = {'unread': [], 'read': [], 'more': false};+ await withClock(Clock.fixed(_now), () async {+ await _show(tester, await _loaded(tester, server));+ await _threadsTab(tester);+ expect(find.text('No threads yet'), findsOneWidget);+ });+ });++ testWidgets('screenshots for Darren', (tester) async {+ for (final (brightness, name) in [+ (Brightness.light, 'light'),+ (Brightness.dark, 'dark'),+ ]) {+ final server = swarm();+ server.followedThreads = {+ 'unread': [unreadThread('new-1', text: 'Title: Dial fix — details')],+ 'read': [+ readThread(+ 'read-new',+ at: DateTime(2026, 11, 2, 16, 42),+ text: 'Title: Lamp boot loop — it reboots when it wakes',+ ),+ readThread(+ 'read-mid',+ at: DateTime(2026, 11, 2, 11, 5),+ text: 'Title: Brightness curve — too dim at 10%',+ replier: 'Ken',+ ),+ readThread(+ 'read-old',+ at: DateTime(2026, 11, 1, 9, 10),+ text: 'Title: Firmware OTA timeout — after 30 s on the dial',+ ),+ ],+ 'more': false,+ };+ await withClock(Clock.fixed(_now), () async {+ await _show(+ tester,+ await _loaded(tester, server),+ brightness: brightness,+ );+ await _threadsTab(tester);+ await captureWindow(tester, shots, 'activity-threads-all-$name');+ });+ }+ }, skip: shots == null);+}diff --git a/desktop/test/super_tab_backlog_shots_test.dart b/desktop/test/super_tab_backlog_shots_test.dartindex 94fc00530..3a05eb685 100644--- a/desktop/test/super_tab_backlog_shots_test.dart+++ b/desktop/test/super_tab_backlog_shots_test.dart@@ -264,15 +264,25 @@ void main() {'many-shipped','mine','project',+ 'mine-nothing-open','mine-empty',- 'mine-shipped',]) {testWidgets('screenshots for review ($scene, ${brightness.name})', (tester,) async {final picture = GlobalKey();final server = swarm(perProject: 3);- if (scene.startsWith('mine-')) nothingOpenWithArchived(server);+ if (scene == 'mine-nothing-open') {+ // Scholes's 72 (#2885): nothing open, and Shipped still lists.+ nothingOpenWithArchived(server);+ manyShipped(server, 69);+ }+ if (scene == 'mine-empty') {+ // Nothing open and nothing shipped: the one empty message.+ for (final g in (server.state['conversations'] as List).cast<Map>()) {+ if (g['requesterId'] == 'owner') g['requesterId'] = 'huy';+ }+ }if (scene == 'many-shipped') manyShipped(server, 12);// GitHub's answer for the open pull requests: checks passed on the// one in review, and its approval; checks running on the others.@@ -305,12 +315,6 @@ void main() {if (scene.startsWith('mine')) {await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));await tester.pumpAndSettle();- if (scene == 'mine-shipped') {- await tester.tap(- find.byKey(const ValueKey('super-backlog-mine-shipped')),- );- await tester.pumpAndSettle();- }} else if (scene == 'project') {await tester.tap(find.byKey(const ValueKey('super-backlog-project')));await tester.pumpAndSettle();diff --git a/desktop/test/super_tab_backlog_test.dart b/desktop/test/super_tab_backlog_test.dartindex 59bd0aa51..9f6230e87 100644--- a/desktop/test/super_tab_backlog_test.dart+++ b/desktop/test/super_tab_backlog_test.dart@@ -720,6 +720,33 @@ void main() {expect(listed(tester), hasLength(6));});+ testWidgets('under Mine, each card counts its group\'s rows (task #2885)', (+ tester,+ ) async {+ await show(tester, swarm());+ await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));+ await tester.pumpAndSettle();+ int headed(SuperTabBacklogGroup g) {+ if (header(g).evaluate().isEmpty) return 0;+ return int.parse(+ tester+ .widgetList<Text>(+ find.descendant(of: header(g), matching: find.byType(Text)),+ )+ .map((t) => int.tryParse(t.data ?? ''))+ .nonNulls+ .single+ .toString(),+ );+ }++ final cards = summary(tester);+ expect(cards.working, headed(SuperTabBacklogGroup.working));+ expect(cards.review, headed(SuperTabBacklogGroup.inReview));+ expect(cards.shipped, headed(SuperTabBacklogGroup.shipped));+ expect(cards.working + cards.review, greaterThan(0));+ });+testWidgets('the summary counts what the filters show', (tester) async {await show(tester, swarm());expect(summary(tester), (working: 1, review: 1, shipped: 1));@@ -1242,54 +1269,77 @@ void main() {expect(c.snapshot!.conversation('recent'), isNotNull);});- testWidgets(- 'an empty Mine says so and links to what the reader shipped',- (tester) async {+ /// [count] tasks the reader asked for, shipped and archived an hour+ /// apart, the newest first: Scholes's 72 (task #2885).+ List<Map<String, dynamic>> shippedOfMine(int count) => [+ for (var i = 0; i < count; i++)+ archived('mine-$i', 100 + i, daysAgo: (i + 1) / 24),+ ];++ for (final mine in [true, false]) {+ testWidgets('with nothing open, Shipped still lists the newest 7 of '+ '72 with Show 65 more shipped (${mine ? 'Mine' : 'Everyone'}, '+ 'task #2885)', (tester) async {final server = nothingOpen();server.parts.clock = now;- add(server, [- archived('mine-a', 30),- archived('mine-b', 31),- archived('theirs', 32, requester: 'pilot'),- ]);+ add(server, shippedOfMine(72));+ if (!mine) {+ // Everyone has nothing open either: only the project chats stay.+ (server.state['conversations'] as List).removeWhere(+ (g) =>+ (g as Map)['number'] != null &&+ !(g['id'] as String).startsWith('mine-'),+ );+ }await show(tester, server, today: at);- await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));- await tester.pumpAndSettle();- expect(find.text('No open tasks of yours'), findsOneWidget);- expect(row('mine-a'), findsNothing);- // The cards still count what Mine shipped.- expect(summary(tester), (working: 0, review: 0, shipped: 2));- final link = find.byKey(const ValueKey('super-backlog-mine-shipped'));+ if (mine) {+ await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));+ await tester.pumpAndSettle();+ }+ expect(summary(tester), (working: 0, review: 0, shipped: 72));+ expect(find.text('No open tasks of yours'), findsNothing);+ expect(find.text('No tasks'), findsNothing);+ expect(header(SuperTabBacklogGroup.shipped), findsOneWidget);+ expect(listed(tester), [for (var i = 0; i < 7; i++) 'mine-$i']);+ final more = find.byKey(const ValueKey('super-backlog-shipped-more'));expect(find.descendant(- of: link,- matching: find.text(- 'Your shipped tasks from the last 7 days · 2',- ),+ of: more,+ matching: find.text('Show 65 more shipped'),),findsOneWidget,);- await tester.tap(link);+ await tester.tap(more);await tester.pumpAndSettle();- expect(find.text('No open tasks of yours'), findsNothing);- expect(row('mine-a'), findsOneWidget);- expect(row('mine-b'), findsOneWidget);- expect(row('theirs'), findsNothing);- expect(summary(tester), (working: 0, review: 0, shipped: 2));- },- );+ // The list builds what fits; the eighth is there, and no foot.+ expect(row('mine-7'), findsOneWidget);+ expect(more, findsNothing);+ });+ }- testWidgets('an empty Mine with nothing shipped has no link', (- tester,- ) async {+ testWidgets('the empty message shows only when nothing is open and '+ 'nothing shipped (task #2885)', (tester) async {+ final server = nothingOpen();+ server.parts.clock = now;+ add(server, [+ archived('mine-a', 30),+ archived('theirs', 32, requester: 'pilot'),+ ]);+ await show(tester, server, today: at);+ await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));+ await tester.pumpAndSettle();+ // One shipped task of the reader's: it lists, and nothing says empty.+ expect(find.text('No open tasks of yours'), findsNothing);+ expect(listed(tester), ['mine-a']);+ expect(summary(tester), (working: 0, review: 0, shipped: 1));+ await tester.pumpWidget(const SizedBox());+ // Nothing open and nothing shipped: the message, and no rows.await show(tester, nothingOpen(), today: at);await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));await tester.pumpAndSettle();expect(find.text('No open tasks of yours'), findsOneWidget);- expect(- find.byKey(const ValueKey('super-backlog-mine-shipped')),- findsNothing,- );+ expect(listed(tester), isEmpty);+ expect(summary(tester), (working: 0, review: 0, shipped: 0));});testWidgets('Mine goes by who asked, not who worked on it', (@@ -1308,10 +1358,7 @@ void main() {await show(tester, server, today: at);await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));await tester.pumpAndSettle();- expect(- find.text('Your shipped tasks from the last 7 days · 1'),- findsOneWidget,- );+ expect(listed(tester), ['asked']);});testWidgets('a failed read says so, and trying again reads it', (diff --git a/desktop/test/super_tab_chat_find_test.dart b/desktop/test/super_tab_chat_find_test.dartnew file mode 100644index 000000000..78d7257c2--- /dev/null+++ b/desktop/test/super_tab_chat_find_test.dart@@ -0,0 +1,245 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/chat_find.dart';+import 'package:harness/super_tabs/model.dart';+import 'package:unorm_dart/unorm_dart.dart' as unorm;++SuperTabMessage _message(int sequence, String text) =>+ SuperTabMessage.fromJson({+ 'id': 'm$sequence',+ 'conversationId': 'g1',+ 'sequence': sequence,+ 'text': text,+ 'author': {'kind': 'person', 'id': 'tony', 'name': 'Tony'},+ });++/// A chat whose older pages are read one at a time, as the view reads them.+class _Chat {+ _Chat(this.rows, {List<List<SuperTabMessage>>? older}) : older = older ?? [];++ final List<SuperTabMessage> rows;+ final List<List<SuperTabMessage>> older;+ int reads = 0;+ bool fails = false;+ Completer<void>? hold;++ late final find = SuperTabChatFind(+ rows: () => rows,+ hasOlder: () => older.isNotEmpty,+ readOlder: () async {+ reads++;+ await hold?.future;+ if (fails) return false;+ rows.insertAll(0, older.removeLast());+ return true;+ },+ );+}++void main() {+ test('case and accents fold, Vietnamese included', () {+ expect(superTabFindFold('Tiếng VIỆT đồng Đà'), 'tieng viet dong da');+ // The same words typed with combining marks fold the same.+ expect(superTabFindFold(unorm.nfd('Tiếng Việt')), 'tieng viet');+ });++ test('matches in the loaded rows, numbered from the newest', () {+ final chat = _Chat([+ for (var i = 1; i <= 5; i++)+ _message(i, i.isEven ? 'Tiếng Việt $i' : 'other $i'),+ ]);+ chat.find.search('tieng viet');+ expect(chat.find.matches, ['m2', 'm4']);+ expect(chat.find.current, 'm4');+ expect(chat.find.number, 1);+ expect(chat.find.total, 2);+ });++ test('stepping goes older and back newer', () async {+ final chat = _Chat([+ for (var i = 1; i <= 5; i++) _message(i, i.isEven ? 'x' : 'y'),+ ]);+ chat.find.search('x');+ await chat.find.older();+ expect((chat.find.current, chat.find.number), ('m2', 2));+ chat.find.newer();+ expect((chat.find.current, chat.find.number), ('m4', 1));+ // The newest match is as new as it goes.+ chat.find.newer();+ expect(chat.find.current, 'm4');+ });++ test('up reads older pages until one has a match', () async {+ final chat = _Chat(+ [_message(100, 'found here'), _message(101, 'nothing')],+ older: [+ [_message(1, 'found long ago')],+ [_message(2, 'quiet')],+ [_message(3, 'quiet')],+ ],+ );+ chat.find.search('FOUND');+ expect(chat.find.total, 1);+ await chat.find.older();+ expect(chat.reads, 3);+ expect(chat.find.current, 'm1');+ expect(chat.find.number, 2);+ expect(chat.find.note, isNull);+ expect(chat.find.reading, isNull);+ });++ test('a search reads at most 50 older pages', () async {+ final chat = _Chat(+ [_message(1000, 'found')],+ older: [+ for (var page = 0; page < 60; page++) [_message(page + 1, 'quiet')],+ ],+ );+ chat.find.search('found');+ await chat.find.older();+ expect(chat.reads, superTabFindPages);+ expect(superTabFindPages, 50);+ expect(chat.find.note, 'No more matches in the last 50 pages');+ expect(chat.find.current, 'm1000');+ // Up again reads nothing more for this search.+ await chat.find.older();+ expect(chat.reads, 50);+ });++ test('a new search may read 50 pages again', () async {+ final chat = _Chat(+ [_message(1000, 'found')],+ older: [+ for (var page = 0; page < 120; page++) [_message(page + 1, 'quiet')],+ ],+ );+ chat.find.search('found');+ await chat.find.older();+ chat.find.search('foun');+ expect(chat.find.note, isNull);+ await chat.find.older();+ expect(chat.reads, 100);+ });++ test('at the start of the chat it says so and reads nothing', () async {+ final chat = _Chat([_message(1, 'found'), _message(2, 'found')]);+ chat.find.search('found');+ await chat.find.older();+ expect(chat.find.current, 'm1');+ await chat.find.older();+ expect(chat.reads, 0);+ expect(chat.find.note, 'No more matches in this chat');+ });++ test('a failed read says so and stops', () async {+ final chat = _Chat(+ [_message(10, 'found')],+ older: [+ [_message(1, 'found')],+ ],+ )..fails = true;+ chat.find.search('found');+ await chat.find.older();+ expect(chat.reads, 1);+ expect(chat.find.note, 'Couldn’t read older messages');+ expect(chat.find.current, 'm10');+ });++ test('one read-back at a time', () async {+ final chat = _Chat(+ [_message(10, 'found')],+ older: [+ [_message(1, 'found')],+ ],+ )..hold = Completer();+ chat.find.search('found');+ final first = chat.find.older();+ final second = chat.find.older();+ // The page on its way is counted, as the phone counts it.+ expect(chat.find.reading, 1);+ chat.hold!.complete();+ await Future.wait([first, second]);+ expect(chat.reads, 1);+ expect(chat.find.current, 'm1');+ });++ test('a new search stops a read-back under way', () async {+ final chat = _Chat(+ [_message(10, 'a')],+ older: [+ for (var page = 0; page < 5; page++) [_message(page + 1, 'quiet')],+ ],+ )..hold = Completer();+ chat.find.search('a');+ final back = chat.find.older();+ chat.find.clear();+ chat.hold!.complete();+ await back;+ expect(chat.reads, 1);+ expect(chat.find.query, '');+ expect(chat.find.current, isNull);+ expect(chat.find.reading, isNull);+ });++ test('disposing it stops a read-back under way', () async {+ final chat = _Chat(+ [_message(10, 'a')],+ older: [+ for (var page = 0; page < 5; page++) [_message(page + 1, 'quiet')],+ ],+ )..hold = Completer();+ chat.find.search('a');+ final back = chat.find.older();+ chat.find.dispose();+ chat.hold!.complete();+ await back;+ expect(chat.reads, 1);+ });++ test('down stops a read-back under way', () async {+ final chat = _Chat(+ [_message(9, 'a'), _message(10, 'a')],+ older: [+ [_message(1, 'a')],+ ],+ );+ chat.find.search('a');+ await chat.find.older();+ expect(chat.find.current, 'm9');+ chat.hold = Completer();+ final back = chat.find.older();+ chat.find.newer();+ chat.hold!.complete();+ await back;+ expect(chat.reads, 1);+ expect(chat.find.current, 'm10');+ expect(chat.find.reading, isNull);+ });++ test('a blank query matches nothing and reads nothing', () async {+ final chat = _Chat(+ [_message(1, ' ')],+ older: [+ [_message(0, 'x')],+ ],+ );+ chat.find.search(' ');+ expect(chat.find.total, 0);+ await chat.find.older();+ expect(chat.reads, 0);+ });++ test('a new matching message keeps the current one', () async {+ final chat = _Chat([_message(1, 'x'), _message(2, 'x')]);+ chat.find.search('x');+ await chat.find.older();+ expect((chat.find.current, chat.find.number), ('m1', 2));+ chat.rows.add(_message(3, 'x again'));+ chat.find.refresh();+ expect(+ (chat.find.current, chat.find.number, chat.find.total),+ ('m1', 3, 3),+ );+ });+}diff --git a/desktop/test/super_tab_composer_mic_test.dart b/desktop/test/super_tab_composer_mic_test.dartindex e51d54152..a230bd72b 100644--- a/desktop/test/super_tab_composer_mic_test.dart+++ b/desktop/test/super_tab_composer_mic_test.dart@@ -1,6 +1,7 @@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/composer_actions.dart';import 'package:harness/super_tabs/controller.dart';import 'package:harness/super_tabs/view.dart';import 'package:harness/super_tabs/voice_row.dart';@@ -26,6 +27,22 @@ void main() {Finder key(String value) => find.byKey(ValueKey(value));+ /// The refused line's words sit a gap below the row, as any line under a+ /// composer's buttons does (Alder2878's review of 83e32f41a).+ void expectGapUnder(WidgetTester tester, Finder send) {+ final words = tester.getRect(+ find.textContaining("Harness can't use the microphone"),+ );+ expect(+ words.top - tester.getRect(send).bottom,+ greaterThanOrEqualTo(+ composerRowInsets(target: grid.AppControl.height).bottom ++ grid.AppDesktop.controlGap -+ 0.5,+ ),+ );+ }+Future<SuperTabController> show(WidgetTester tester, {String chat = 'lead',@@ -159,6 +176,7 @@ void main() {find.textContaining("Harness can't use the microphone"),findsOneWidget,);+ expectGapUnder(tester, find.byTooltip('Send message'));await tester.tap(key('super-voice-settings'));expect(opened, [superTabMicrophoneSettings]);await close(tester);@@ -166,6 +184,18 @@ void main() {});group('a thread', () {+ testWidgets('a refused microphone says so under the thread\'s row', (+ tester,+ ) async {+ await show(tester, thread: 'message-1');+ mic.allow = false;+ await tester.tap(key('super-thread-mic'));+ await tester.pumpAndSettle();+ expect(key('super-voice-refused'), findsOneWidget);+ expectGapUnder(tester, key('super-thread-send'));+ await close(tester);+ });+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'));diff --git a/desktop/test/super_tab_find_in_chat_shots_test.dart b/desktop/test/super_tab_find_in_chat_shots_test.dartnew file mode 100644index 000000000..21877f35d--- /dev/null+++ b/desktop/test/super_tab_find_in_chat_shots_test.dart@@ -0,0 +1,135 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.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 'box_render_preview_test.dart' show loadPreviewFonts;+import 'support/super_tab_fixture.dart';++/// Set to a folder to write the PR's screenshots there (task #2826).+final shots = Platform.environment['SUPER_TAB_FIND_SHOTS'];+final _picture = GlobalKey();++const _notes = [+ 'Gõ Tiếng Việt trong ô tìm kiếm vẫn ra đúng tin nhắn.',+ 'Pushed the branch; the checks are running.',+ 'Reading the older pages before the reconnect.',+ 'The reconnect keeps every queued edit in order.',+];++Future<void> _shot(WidgetTester tester, String name) async {+ await tester.runAsync(() async {+ final boundary =+ _picture.currentContext!.findRenderObject()! as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/$name.png').writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+}++Future<SuperTabController> _show(+ WidgetTester tester,+ ConversationServer server,+ Brightness brightness,+) async {+ await tester.binding.setSurfaceSize(const Size(1400, 820));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final c = server.controller();+ addTearDown(c.dispose);+ final before = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = before);+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => RepaintBoundary(key: _picture, child: child),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return c;+}++Future<void> _find(WidgetTester tester, String query, {int up = 0}) async {+ await tester.tap(find.byKey(const ValueKey('super-find-button')).first);+ await tester.pumpAndSettle();+ await tester.enterText(+ find.byKey(const ValueKey('super-find-field')).first,+ query,+ );+ await tester.pumpAndSettle();+ for (var i = 0; i < up; i++) {+ await tester.tap(find.byKey(const ValueKey('super-find-older')).first);+ await tester.pumpAndSettle();+ }+}++void main() {+ setUpAll(() async {+ if (shots != null) await loadPreviewFonts();+ });++ for (final brightness in Brightness.values) {+ final theme = brightness.name;++ testWidgets('the chat at 2 of 4 ($theme)', (tester) async {+ final server = ConversationServer();+ for (var i = 1; i <= 20; i++) {+ server.append(_notes[i % 4 == 1 && i > 2 ? 0 : i % 3 + 1]);+ }+ await _show(tester, server, brightness);+ await _find(tester, 'tieng viet', up: 1);+ await _shot(tester, 'find-chat-$theme');+ }, skip: shots == null);++ testWidgets('a thread at 1 of 2 ($theme)', (tester) async {+ final server = ConversationServer()..threads = true;+ server.append('Có lỗi khi đọc trang cũ không?');+ server.append('Lỗi nhỏ thôi, đã sửa.');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1';+ server.append('Pushed the fix.');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-2';+ final c = await _show(tester, server, brightness);+ c.openThread('message-1');+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-thread-find-button')));+ await tester.pumpAndSettle();+ await tester.enterText(+ find.byKey(const ValueKey('super-find-field')).last,+ 'loi',+ );+ await tester.pumpAndSettle();+ await _shot(tester, 'find-thread-$theme');+ }, skip: shots == null);++ testWidgets('the 50-page stop ($theme)', (tester) async {+ final server = ConversationServer()..messagePage = 1;+ for (var i = 1; i <= 80; i++) {+ server.append(i == 80 ? _notes[0] : _notes[i % 3 + 1]);+ }+ await _show(tester, server, brightness);+ await _find(tester, 'tiếng việt', up: 1);+ await _shot(tester, 'find-50-pages-$theme');+ }, skip: shots == null);+ }+}diff --git a/desktop/test/super_tab_find_in_chat_test.dart b/desktop/test/super_tab_find_in_chat_test.dartnew file mode 100644index 000000000..6dcfa1f3c--- /dev/null+++ b/desktop/test/super_tab_find_in_chat_test.dart@@ -0,0 +1,347 @@+import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shortcuts/keymap.dart';+import 'package:harness/shortcuts/keymap_commands.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/message_row.dart';+import 'package:harness/super_tabs/view.dart';++import 'keymap_host_test.dart' show key;+import 'super_tab_quick_switcher_test.dart' show close, setup;+import 'support/super_tab_fixture.dart';++/// Find in the open chat (task #2826, Tony): matches in what is loaded,+/// stepping, older pages read on demand up to 50, accents folded.+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;+ }++ Finder row(String id) => find.byKey(ValueKey('super-message-$id'));+ SuperTabMessageHighlight light(WidgetTester tester, String id) =>+ tester.widget<SuperTabMessageHighlight>(+ find+ .ancestor(+ of: row(id),+ matching: find.byType(SuperTabMessageHighlight),+ )+ .first,+ );+ String count(WidgetTester tester) =>+ tester.widget<Text>(find.byKey(const ValueKey('super-find-count'))).data!;+ final field = find.byKey(const ValueKey('super-find-field'));++ Future<void> search(WidgetTester tester, String query) async {+ await tester.tap(find.byKey(const ValueKey('super-find-button')));+ await tester.pumpAndSettle();+ await tester.enterText(field, query);+ await tester.pumpAndSettle();+ }++ Future<void> up(WidgetTester tester) async {+ await tester.tap(find.byKey(const ValueKey('super-find-older')));+ await tester.pumpAndSettle();+ }++ /// [count] notes; those numbered in [matching] speak Vietnamese.+ ConversationServer chat(int count, {Set<int> matching = const {}}) {+ final server = ConversationServer();+ for (var i = 1; i <= count; i++) {+ server.append(matching.contains(i) ? 'Gõ Tiếng Việt $i' : 'Note $i');+ }+ return server;+ }++ test('Cmd+F is the chat’s find in a Swarm chat and still the terminal’s '+ 'in a terminal', () {+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;+ addTearDown(() => debugDefaultTargetPlatformOverride = null);+ final f = KeyStroke.parse('cmd+f');+ expect(+ harnessDefaultKeymap.match(KeymapContext.swarmChat, [f]).command,+ 'swarm.find_in_chat',+ );+ expect(+ harnessDefaultKeymap.match(KeymapContext.terminal, [f]).command,+ 'terminal.find',+ );+ });++ testWidgets('Cmd+F opens find in the open chat', (tester) async {+ final (f, c) = await setup(tester);+ await key(tester, LogicalKeyboardKey.keyF, cmd: true);+ await tester.pumpAndSettle();+ expect(field, findsOneWidget);+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);+ await key(tester, LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(field, findsNothing);+ await close(tester, f, c);+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));++ testWidgets('matches in loaded messages are lit and counted, accents '+ 'folded', (tester) async {+ await show(tester, chat(30, matching: {5, 20, 28}));+ await search(tester, 'TIENG viet');+ expect(count(tester), '1 of 3');+ expect(light(tester, 'message-28').on, isTrue);+ expect(light(tester, 'message-20').match, isTrue);+ expect(light(tester, 'message-20').on, isFalse);+ expect(light(tester, 'message-29').match, isFalse);+ });++ testWidgets('up and down step through matches and bring each into view', (+ tester,+ ) async {+ await show(tester, chat(60, matching: {2, 59}));+ await search(tester, 'tiếng');+ expect(row('message-2').hitTestable(), findsNothing);+ await up(tester);+ expect(count(tester), '2 of 2');+ expect(row('message-2').hitTestable(), findsOneWidget);+ expect(light(tester, 'message-2').on, isTrue);+ // Enter in the field steps up too, Shift+Enter down.+ await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);+ await tester.pumpAndSettle();+ expect(count(tester), '1 of 2');+ expect(row('message-59').hitTestable(), findsOneWidget);+ });++ testWidgets('up reads older pages until one has a match', (tester) async {+ final server = chat(250, matching: {10, 240})..messagePage = 50;+ final reads = <String>[];+ final c = await show(tester, server);+ server.onRead = reads.add;+ expect(c.messages('lead').any((m) => m.id == 'message-10'), isFalse);+ await search(tester, 'tieng');+ expect(count(tester), '1 of 1');+ // Typing reads nothing.+ expect(reads, isEmpty);+ await up(tester);+ expect(count(tester), '2 of 2');+ expect(row('message-10').hitTestable(), findsOneWidget);+ expect(light(tester, 'message-10').on, isTrue);+ // Pages 151–200, 101–150, 51–100 and 1–50: four reads, no more.+ expect(reads, hasLength(4));+ expect(reads, everyElement(contains('before=')));+ });++ testWidgets('a search reads at most 50 older pages, then says so', (+ tester,+ ) async {+ final server = chat(80, matching: {80})..messagePage = 1;+ final reads = <String>[];+ await show(tester, server);+ server.onRead = reads.add;+ await search(tester, 'tieng');+ // A list this short reads back by itself as it shows; the search's own+ // reads are those its step makes.+ final before = reads.length;+ await up(tester);+ expect(count(tester), 'No more matches in the last 50 pages');+ expect(reads.length - before, 50);+ expect(reads.skip(before), everyElement(contains('before=')));+ await up(tester);+ expect(reads.length - before, 50);+ });++ testWidgets('Esc and close clear the field and every light', (tester) async {+ await show(tester, chat(10, matching: {3, 8}));+ await search(tester, 'viet');+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(field, findsNothing);+ expect(light(tester, 'message-8').on, isFalse);+ expect(light(tester, 'message-3').match, isFalse);+ await search(tester, 'viet');+ await tester.tap(find.byKey(const ValueKey('super-find-close')));+ await tester.pumpAndSettle();+ expect(field, findsNothing);+ expect(light(tester, 'message-8').match, isFalse);+ });++ testWidgets('a new matching message keeps the current one', (tester) async {+ final server = chat(10, matching: {3, 8});+ final c = await show(tester, server);+ await search(tester, 'viet');+ await up(tester);+ expect(count(tester), '2 of 2');+ server.append('Tiếng Việt again');+ await c.refresh();+ await tester.pumpAndSettle();+ expect(count(tester), '3 of 3');+ expect(light(tester, 'message-3').on, isTrue);+ // The read mark the new message sends waits its moment.+ await tester.pump(const Duration(seconds: 5));+ });++ testWidgets('another chat closes find', (tester) async {+ final server = chat(10, matching: {3});+ final c = await show(tester, server);+ await search(tester, 'viet');+ await c.select('offline');+ await tester.pumpAndSettle();+ await c.select('lead');+ await tester.pumpAndSettle();+ expect(field, findsNothing);+ });++ group('in a thread', () {+ /// A root and two replies saying "lỗi", one main-chat note saying it+ /// too, and a reply that does not.+ ConversationServer threaded() {+ final server = ConversationServer()..threads = true;+ server.append('Có lỗi ở đây?');+ server.append('Lỗi nhỏ thôi.');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1';+ server.append('Fixed.');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-2';+ server.append('Một lỗi khác, in the chat.');+ return server;+ }++ Finder inThread(Finder finder) => find.descendant(+ of: find.byKey(const ValueKey('super-thread-panel')),+ matching: finder,+ );++ testWidgets('finds the root and its replies only', (tester) async {+ final c = await show(tester, threaded());+ c.openThread('message-1');+ await tester.pumpAndSettle();+ await tester.tap(+ inThread(find.byKey(const ValueKey('super-thread-find-button'))),+ );+ await tester.pumpAndSettle();+ await tester.enterText(inThread(field), 'loi');+ await tester.pumpAndSettle();+ expect(+ tester+ .widget<Text>(+ inThread(find.byKey(const ValueKey('super-find-count'))),+ )+ .data,+ '1 of 2',+ );+ await tester.tap(+ inThread(find.byKey(const ValueKey('super-find-older'))),+ );+ await tester.pumpAndSettle();+ expect(+ tester+ .widget<Text>(+ inThread(find.byKey(const ValueKey('super-find-count'))),+ )+ .data,+ '2 of 2',+ );+ // Esc closes the find first, and the thread only after.+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(inThread(field), findsNothing);+ expect(find.byKey(const ValueKey('super-thread-panel')), findsOneWidget);+ });++ testWidgets('earlier replies are read before the root counts', (+ tester,+ ) async {+ final server = ConversationServer()+ ..threads = true+ ..messagePage = 1;+ server.append('Có lỗi ở đây?');+ for (var i = 1; i <= 9; i++) {+ server.append(i == 1 || i == 9 ? 'Lỗi $i' : 'Reply $i');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1';+ }+ final c = await show(tester, server);+ c.openThread('message-1');+ await tester.pumpAndSettle();+ expect(c.hasEarlierReplies('message-1'), isTrue);+ await tester.tap(+ inThread(find.byKey(const ValueKey('super-thread-find-button'))),+ );+ await tester.pumpAndSettle();+ await tester.enterText(inThread(field), 'loi');+ await tester.pumpAndSettle();+ String said() => tester+ .widget<Text>(+ inThread(find.byKey(const ValueKey('super-find-count'))),+ )+ .data!;+ // The root waits until the replies before the loaded ones are read.+ expect(said(), '1 of 1');+ await tester.tap(+ inThread(find.byKey(const ValueKey('super-find-older'))),+ );+ await tester.pumpAndSettle();+ // Reply 1, the earliest, not the root above the unread ones.+ expect(said(), '2 of 2');+ expect(+ tester+ .widget<SuperTabMessageHighlight>(+ find+ .ancestor(+ of: find.byKey(+ const ValueKey('super-thread-message-message-2'),+ ),+ matching: find.byType(SuperTabMessageHighlight),+ )+ .first,+ )+ .on,+ isTrue,+ );+ // The root is the thread's earliest page; once it is read, it counts.+ await tester.tap(+ inThread(find.byKey(const ValueKey('super-find-older'))),+ );+ await tester.pumpAndSettle();+ expect(said(), '3 of 3');+ });++ testWidgets('the chat’s find leaves thread-only replies out', (+ tester,+ ) async {+ await show(tester, threaded());+ await search(tester, 'loi');+ // The root and the chat's own note; the reply "Lỗi nhỏ thôi." is in+ // its thread only.+ expect(count(tester), '1 of 2');+ });+ });+}diff --git a/desktop/test/super_tab_native_messages_test.dart b/desktop/test/super_tab_native_messages_test.dartindex 717c077b2..f14e89835 100644--- a/desktop/test/super_tab_native_messages_test.dart+++ b/desktop/test/super_tab_native_messages_test.dart@@ -104,11 +104,9 @@ void main() {'id': 'lead-agent','name': 'Lead',};- server.messages.last['source'] = {- 'kind': 'native',- 'phase': 'prompt',- 'operator': {'id': 'leo', 'name': '[email protected]'},- };+ // A terminal's answer: what was typed into it is no chat row+ // (task #2849).+ server.messages.last['source'] = {'kind': 'native', 'phase': 'answer'};if (profile.scale == 1) {server.append('@Builder, check persistence. @Reviewer, check account switching.',@@ -201,7 +199,7 @@ void main() {);await tester.pumpAndSettle();final source = find.text(- 'Terminal input · session opened by [email protected]',+ 'Verify offline edits through a restart and reconnect.',);// The first of the chat's messages: with Slack's spacing (Huy,// 2026-11-03) it is above what the chat builds at this window size.@@ -216,9 +214,18 @@ void main() {.first,);expect(source, findsOneWidget);- await tester.ensureVisible(- find.ancestor(of: source, matching: find.byType(SuperTabMessageRow)),+ final sourceRow = find.ancestor(+ of: source,+ matching: find.byType(SuperTabMessageRow),+ );+ expect(+ find.descendant(+ of: sourceRow,+ matching: find.text('Terminal answer'),+ ),+ findsOneWidget,);+ await tester.ensureVisible(sourceRow);await tester.pumpAndSettle();expect(tester.takeException(), isNull);if (capture != null) {diff --git a/desktop/test/super_tab_terminal_prompt_rows_test.dart b/desktop/test/super_tab_terminal_prompt_rows_test.dartnew file mode 100644index 000000000..182fda5ad--- /dev/null+++ b/desktop/test/super_tab_terminal_prompt_rows_test.dart@@ -0,0 +1,80 @@+import 'package:flutter_test/flutter_test.dart';++import 'super_tab_mentions_test.dart' show showView;+import 'super_tab_quiet_chat_test.dart' show project, row;++// Ken, 11-04 (task #2849): the project chat showed a row "Terminal input ·+// session opened by ken15@…" carrying the whole hourly cleanup prompt typed+// into the PM's terminal. What was typed into an agent's terminal is no chat+// row; the terminal's answer still is.++const _prompt = 'Run the hourly cleanup: archive finished groups.';+const _answer = 'Cleanup done: 3 groups archived.';++Map<String, dynamic> _typed(int sequence) => row(+ 'typed',+ sequence,+ _prompt,+ kind: 'native',+ source: {+ 'phase': 'prompt',+ 'operator': {'name': '[email protected]'},+ },+);++Map<String, dynamic> _answered(int sequence) =>+ row('answered', sequence, _answer, kind: 'native');++void main() {+ testWidgets('a terminal\'s prompt is no chat row; its answer still is', (+ tester,+ ) async {+ final c = await showView(tester, project([_typed(1), _answered(2)]));+ await c.loadMessages('lead');+ await tester.pumpAndSettle();+ expect(find.text(_prompt), findsNothing);+ expect(find.textContaining('Terminal input'), findsNothing);+ expect(find.text(_answer), findsOneWidget);+ expect(find.text('Terminal answer'), findsOneWidget);+ expect(tester.takeException(), isNull);+ });++ testWidgets('a terminal\'s prompt counts as nothing unread; its answer '+ 'counts', (tester) async {+ final server = project([+ row('m1', 1, 'Hello'),+ _typed(2),+ _answered(3),+ ], read: 1);+ final c = server.controller();+ await c.refresh();+ addTearDown(c.dispose);+ await c.loadMessages('lead');+ final lead = c.snapshot!.conversation('lead')!;+ expect(c.unread(lead), isTrue);+ expect(c.unreadCount(lead), 1);+ });++ testWidgets('a chat whose only new row is a terminal\'s prompt shows as '+ 'read', (tester) async {+ final server = project([row('m1', 1, 'Hello'), _typed(2)], read: 1);+ final c = server.controller();+ await c.refresh();+ addTearDown(c.dispose);+ await c.loadMessages('lead');+ final lead = c.snapshot!.conversation('lead')!;+ expect(c.unread(lead), isFalse);+ expect(c.unreadCount(lead), 0);+ });++ test('reading to the last row drawn reads a terminal\'s prompt after it '+ 'too, so other devices show the chat read', () async {+ final server = project([row('m1', 1, 'Hello'), _typed(2)]);+ final c = server.controller();+ await c.refresh();+ addTearDown(c.dispose);+ await c.loadMessages('lead');+ c.markRead('lead', through: 1);+ expect(c.readMark('lead'), 2);+ });+}diff --git a/desktop/test/super_tab_view_test.dart b/desktop/test/super_tab_view_test.dartindex 3d8909764..049a6dbb2 100644--- a/desktop/test/super_tab_view_test.dart+++ b/desktop/test/super_tab_view_test.dart@@ -104,8 +104,7 @@ void main() {};server.messages.last['source'] = {'kind': 'native',- 'phase': 'prompt',- 'operator': {'name': '[email protected]'},+ 'phase': 'answer','truncated': true,};final controller = server.controller();@@ -125,10 +124,7 @@ void main() {);await tester.pumpAndSettle();expect(find.text('Builder'), findsOneWidget);- expect(- find.text('Terminal input · session opened by [email protected]'),- findsOneWidget,- );+ expect(find.text('Terminal answer'), findsOneWidget);expect(find.text('Excerpt · open the terminal for the full response'),findsOneWidget,diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex a718ca503..f13052cc6 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -551,6 +551,10 @@ class ConversationServer {/// and the inbox ([inbox]) is read instead.Map<String, dynamic>? followedThreads;+ /// Refuses the followed-threads read's `read` query, as a backend before+ /// task #2835 does.+ bool refuseThreadsRead = false;+/// The inbox read's answer (backend read/inbox.ts): `{threads, latest,/// more}`; null answers 404.Map<String, dynamic>? inbox;@@ -1796,6 +1800,14 @@ class ConversationServer {statusCode: threadListStatus,);}+ // A backend before task #2835: its strict query refuses `read`.+ if (refuseThreadsRead && uri.queryParameters.containsKey('read')) {+ throw const SuperTabFailure(+ 'VALIDATION_ERROR',+ 'Unrecognized key: "read"',+ statusCode: 400,+ );+ }final answer = uri.pathSegments.last == 'threads'? followedThreads: inbox;diff --git a/docs/plans/2026-11-04-activity-threads-all-plan.md b/docs/plans/2026-11-04-activity-threads-all-plan.mdnew file mode 100644index 000000000..d8ef2df1b--- /dev/null+++ b/docs/plans/2026-11-04-activity-threads-all-plan.md@@ -0,0 +1,78 @@+# Activity › Threads lists every thread you took part in — plan++> Way of working: this project's Engineer role (project instructions): plan first, each plan task test first, one pull+> request, one review step. No Execution Handoff.++**Goal:** Darren (11-04, task #2835, follow-up to #2929): Activity's Threads tab lists every thread the person follows+(started, replied in, tagged in, or followed), across their projects: unread ones on top as today, then read ones below,+plainly, newest reply first. Each row: project, thread title, last replier and time. Clicking opens the thread beside its+chat. Paged: the first 50 read threads, the next 50 on scroll. No change to counts or the red badge.++**Architecture:** the server's followed-threads read (`backend/src/superTabs/read/followedThreads.ts`) already answers+`unread` and up to 30 `read` threads; Desktop reads both (`attention.dart`) and shows only `unread`+(`activity.dart threadRows`). So: the read takes how many read threads to answer (`?read=N`, 1 to 250, default 30 as+today), and Desktop asks for 50 more each time the list reaches its end; the Threads tab draws the read ones below.++**Tech stack:** backend TypeScript (Fastify, Prisma on Mongo, vitest), Desktop Flutter.++**Spec:** task #2835's brief; #2929's spec `docs/specs/2026-11-04-activity-needs-you.md` (Threads).++## Global constraints++- Reuse #2929's Threads tab and read path; no new collection, index or count. The tab's number and the red badge stay+ the unread count.+- Read cost per page measured by existing indexes only, in the PR.+- Harness design language; read rows use the existing `_ActivityRow`, plain (not bold).+- An older backend refuses the new query (strict schema, 400): Desktop then reads as today, without paging.++## Review focus++- The read's cost grows with N only through the candidates it checks (2N mark rows of at most 500 already in memory,+ their roots by id, their thread summaries by root id): no scan.+- Order: unread first (as today), then read newest reply first; the same thread never in both.+- Paging never loops: Desktop asks for more only when the server said `more`, and at most 250.++## Design++- Growth: N/A because nothing is stored; the read lists what thread marks (capped at 500 per person per Swarm, 180-day+ sweep) and tags already hold.+- Concurrency: N/A because the read writes nothing; it runs as today, outside a transaction.+- Read cost: one more page reads 2×50 more candidates' roots by `_id` and summaries by root id (SuperTabThread `_id`);+ the mark rows are already loaded once by the inbox read. Measured per page in the PR. Only the open Activity view asks+ for pages: each of its refreshes (every Swarm change, at most every 3 s while open) reads the pages it shows, up to+ 250 threads (500 candidates). Closed, the reads on every Swarm change ask for none and cost what they did (30, 60+ candidates), and the next visit starts at 50 again (review of #2993).+- Scale: at 10x threads per person the cap (500 marks, 250 answered) bounds a read; the first metric to warn is the+ threads read's p95 in the route's timing.+- Compatibility: an old Desktop sends no `read` and gets 30 as today; a new Desktop on an old backend gets 400 and reads+ without it.+- Migration + rollback: none; rolling back the backend makes Desktop fall back as above.+- Audience: the server already lists only chats the person reads and threads they are in (`readable`, `inIt`).+- Identity: the signed-in person's own marks and tags only.+- Failure: a failed page keeps the rows shown and shows the tab's existing error line with Retry.+- Platforms: Desktop and web share this code; the phone's Activity is its own package and is not changed here.++## Tasks++### Task 1: the read answers N read threads (backend)++Files: `backend/src/superTabs/read/followedThreads.ts`, `backend/src/routes/superTabs.ts`,+`backend/integration/superTabFollowedThreads.test.ts`.+Interface: `GET /api/super-tabs/:tabId/threads?read=N` (integer 1..250); `readFollowedThreads(store, user, tabId, read = 30)`.++- [ ] Failing test: 60 read threads; `?read=50` answers the 50 with the newest replies and `more: true`; `?read=100`+ answers all 60 and `more: false`; no `read` answers 30 as today; `read=0` and `read=251` are refused (400).+- [ ] Code: candidates `2 × read` mark rows plus tags; answer `read` threads; route query schema.+- [ ] Measure: commands and documents read for `read=50` and `read=100` under the profiler; into the PR.++### Task 2: Desktop lists read threads below the unread ones, 50 at a time++Files: `desktop/lib/super_tabs/attention.dart`, `desktop/lib/super_tabs/activity.dart`,+`desktop/lib/super_tabs/activity_view.dart`, `desktop/test/super_tab_activity_threads_all_test.dart`.++- [ ] Failing tests: unread on top (bold, "N new"), then a "Read" heading and read rows (plain, time of last reply),+ newest reply first; reaching the end asks for 50 more only when the server said more; opening a read row opens+ its thread; tab count unchanged; an old backend (400 on `read`) still lists what it answers.+- [ ] Code: `SuperTabAttention.readWanted` (50, +50 up to 250) and `loadMoreRead()`; `GET /threads?read=`; fallback;+ the Threads tab's read section; empty text when there are none at all.+- [ ] Guard tests (`check-ui-style`, `laid_out_list_test`); light and dark screenshots to Darren.diff --git a/docs/plans/2026-11-04-find-in-chat-plan.md b/docs/plans/2026-11-04-find-in-chat-plan.mdnew file mode 100644index 000000000..daad22125--- /dev/null+++ b/docs/plans/2026-11-04-find-in-chat-plan.md@@ -0,0 +1,241 @@+# Find in the open chat Implementation Plan++> Implemented by the task's Engineer task by task, each failing test committed before its code (project instructions,+> Engineer). Desktop and phone share no files, so their tasks run in parallel. One independent review on the pull+> request.++**Goal:** In the open chat (main chat or a thread), on Desktop/web and the phone, a find field lights the loaded+messages that match, shows "n of N", and steps through them with the jump-and-light a message link uses. When the+loaded part has no older match, stepping up reads older pages the way scrolling back does, at most 50 per search, then+says "No more matches in the last 50 pages". Case and accents fold: "tieng viet" finds "Tiếng Việt", "dong" finds+"đồng" (task #2826, Tony, phase 1).++**Architecture:** Each app gets one small find model and one find bar in a file of its own, used by both its main chat+and its thread view:++- Desktop/web: `SuperTabChatFind` and `SuperTabFindBar` in `desktop/lib/super_tabs/chat_find.dart`.+- Phone: `SwarmChatFind` and `SwarmFindBar` in `mobile/lib/swarm/swarm_chat_find.dart`.++The model is a `ChangeNotifier`. It is given three callbacks: the rows the view shows (oldest first), whether older+rows remain, and a read of one older page. It folds each row's text, keeps the matching ids, and numbers them from the+newest (1). Older pages then add matches above without moving "n". The page that owns the list does three things:++- It reveals and lights the current match with the jump path it already has (`_revealTarget` + `_light` on Desktop,+ `_jumpTo`'s `_target`/`_reveal`/`_lit` on the phone).+- It gives every match a quiet fill.+- It keeps the current match lit while find is open.++Reading back reuses each view's own older-page read: `_loadEarlier` / `loadThread(earlier: true)` on Desktop,+`loadOlder` / `loadEarlier` on the phone. There is no new route and no index.++**Tech Stack:** Flutter 3.47.2 (Dart 3.13). flutter_test widget tests: Desktop on the Super Tab fixture's+`ConversationServer` (memory store, fake sign-in), the phone on `FakeSwarm`. `unorm_dart` (already a dependency of+both apps) for NFD.++**Spec:** task #2826's brief. The mockup Tony was sent is in the task chat.++## Design++N/A for stored or synced data: nothing is stored, synced or exposed. It only reads pages the chat already reads, from+the same routes and under the same server-side audience checks. Read cost: a search reads at most 50 older pages,+only when the person steps past the oldest loaded match, and never while they type. The cost is measured in the pull+request. Platforms: macOS, Linux, Windows and web (one Desktop screen); iOS and Android (one phone screen).++## Global Constraints++- PR body first line: "Requested by [email protected] through Harness."+- At most 50 older pages per search, counted from the moment the query last changed. Copy:+ - after 50 pages: "No more matches in the last 50 pages"+ - when the chat has no older page: "No more matches in this chat"+ - when a page read fails: "Couldn’t read older messages"+ - while reading: "Reading older messages · N of 50"+- Typing never reads a page. Only stepping up past the oldest loaded match does.+- Fold: NFD, strip U+0300–U+036F, `foldDiacritics` (đ→d and other letters NFD leaves whole), lowercase.+- Esc and the close button clear the query, the fills and the light, and stop a read-back in progress.+- No new server route and no index. Swarm code stays out of cli/src/core.+- Desktop tests use the fixture's memory store and fake sign-in. Phone tests run on the VM test runner (simulator+ only), never on a real phone.+- Harness design language: the bar uses the shared field, icon buttons and metadata type. Phone targets are 44+ points.++## Review Focus++1. A new message arriving while find is open: the current match stays the same message, and N grows if it matches.+ Pinned in Tasks 2 and 4 ("a new matching message keeps the current one").+2. Switching chats or opening another thread with find open: the find closes, and no read-back runs on for the old+ chat. Pinned in Tasks 2 and 4.+3. An empty or whitespace-only query matches nothing and reads nothing. Pinned in Tasks 1 and 3.+4. A thread's find matches the root and its replies only, never main-chat messages, and the main chat's find never+ matches thread-only replies. Pinned in Tasks 2 and 4.+5. Pressing up again while a read-back runs starts no second read-back. Pinned in Tasks 1 and 3 ("one read-back at a+ time").++---++### Task 1: Desktop find model and bar++**Files:**+- Create: `desktop/lib/super_tabs/chat_find.dart`+- Test: `desktop/test/super_tab_chat_find_test.dart`++**Interfaces:**+- Produces:+ - `String superTabFindFold(String text)`+ - `const superTabFindPages = 50`+ - `class SuperTabChatFind extends ChangeNotifier`, constructed as+ `SuperTabChatFind({required List<SuperTabMessage> Function() rows, required bool Function() hasOlder, required Future<bool> Function() readOlder})`.+ `readOlder` returns false when the read failed.+ - Members of `SuperTabChatFind`:+ - `String query`+ - `void search(String query)`+ - `List<String> matches` (ids, oldest first)+ - `Set<String> matching`+ - `String? current`+ - `int? number` (1 = newest)+ - `int get total`+ - `int? reading` (pages read so far in this read-back)+ - `String? note`+ - `Future<void> older()`+ - `void newer()`+ - `void refresh()` (rows changed)+ - `void clear()`+ - `SuperTabFindBar({required SuperTabChatFind find, required VoidCallback onClose, FocusNode? focus})`, keyed+ `super-find-field`, `super-find-count`, `super-find-older`, `super-find-newer`, `super-find-close`. In the field,+ Enter steps older and Shift+Enter newer.++- [ ] **Step 1: Write the failing tests**+ - `fold`: `superTabFindFold('Tiếng VIỆT đồng')` == `'tieng viet dong'`. The decomposed form folds the same.+ - `matches in loaded rows`: rows m1..m5, with m2 and m4 matching. After `search('x')`: `current == 'm4'`,+ `number == 1`, `total == 2`.+ - `stepping`: `older()` goes to m2 (2 of 2), and `newer()` back to m4 (1 of 2).+ - `reads older pages until a match`: no older match is loaded. A fake `readOlder` adds a page and only the third page+ matches. Expect `older()` to make 3 reads and leave the match current (3 of 3).+ - `50-page stop`: `readOlder` never matches and `hasOlder` stays true. Expect 50 reads, then+ `note == 'No more matches in the last 50 pages'` and `current` unchanged.+ - `chat start`: with `hasOlder` false, note == 'No more matches in this chat' and no read.+ - `failed read`: `readOlder` returns false, so note == 'Couldn’t read older messages' and the reads stop.+ - `one read-back at a time`: two `older()` calls while a read is held make one read.+ - `blank query`: `search(' ')` gives no matches and no read on `older()`.+ - `a new search starts the 50 again`: after a 50-page stop, `search` of another query can read 50 more.+- [ ] **Step 2: Run** `flutter test test/super_tab_chat_find_test.dart`. Expected: FAIL (no `chat_find.dart`).+- [ ] **Step 3: Implement `chat_find.dart`.** `refresh()` keeps `current` by id when it is still a match; otherwise it+ takes the newest. A generation counter stops a read-back when `search`/`clear` runs during it. The bar's count reads+ "n of N" when there are matches, the note or reading line when there is one, and "No matches" otherwise.+- [ ] **Step 4: Run the test again.** Expected: PASS.+- [ ] **Step 5: Commit** the test first (red), then the code (green).++### Task 2: Desktop main chat and thread panel use it++**Files:**+- Modify:+ - `desktop/lib/super_tabs/view.dart` (find state, bar under `_header`, row fills, reveal, Cmd+F)+ - `desktop/lib/super_tabs/thread_panel.dart` (bar under its header, row fills, reveal)+ - `desktop/lib/super_tabs/message_row.dart` (`SuperTabMessageHighlight` gets `match`)+ - `desktop/lib/shortcuts/keymap_commands.dart`: command `swarm.find_in_chat`, "Find in chat", context `swarmChat`,+ keys cmd+f (ctrl+f where Ctrl is the prefix)+- Test:+ - `desktop/test/super_tab_find_in_chat_test.dart`+ - `desktop/test/super_tab_unread_keys_test.dart` (the key lesson)++**Interfaces:**+- Consumes: Task 1.+- Produces: `SuperTabMessageHighlight({required bool on, bool match = false, required Widget child})`. The match fill is+ `DesktopChrome.selection` at half its alpha, and `on` wins.++- [ ] **Step 1: Write the failing widget tests** on `ConversationServer`, using `show()` as in+ `super_tab_reply_jump_test.dart`:+ - `Cmd+F opens the find field in the chat` (macOS variant). The swarmChat keymap maps cmd+f to+ `swarm.find_in_chat`, and the terminal context still maps it to `terminal.find`.+ - `matches in loaded messages are lit and counted`: 30 messages, 3 of them saying "Tiếng Việt". Typing "tieng viet"+ shows "1 of 3", the newest match row is highlighted, and the other two have the match fill.+ - `Up steps to the older match and brings it into view`.+ - `Up reads older pages until a match`: 250 messages, `messagePage = 50`, and the only match is message 10. Up reads+ pages until the match, then it shows "1 of 1" and is in view. `onRead` counts the pages read.+ - `the 50-page stop`: `messagePage = 1`, 80 messages, and no match. Up makes 50 reads, then shows "No more matches in+ the last 50 pages".+ - `Esc clears it`: the field is gone and no row is filled.+ - `a thread finds its own replies only`: a root with replies saying "lỗi" and a main-chat message saying "lỗi".+ Thread find shows "1 of 2" (root + replies containing it, no main-only message), and the main chat find leaves+ thread-only replies out.+ - `a new matching message keeps the current one`: `server.append` of a matching message while at "2 of 2" shows+ "3 of 3" on the same row.+ - `switching chats closes find`.+- [ ] **Step 2: Run** `flutter test test/super_tab_find_in_chat_test.dart test/super_tab_unread_keys_test.dart`.+ Expected: FAIL.+- [ ] **Step 3: Wire the main chat.**+ - `_find` is a `SuperTabChatFind` per open conversation, made when find opens.+ - Its `rows` are `superTabTranscriptEntries(_shownMessages(id))` with no interruptions.+ - Its `readOlder` is `_loadEarlier(id, keep: _find.current)`, which reports whether rows grew. `_readEarlierNearTop`+ skips while a find read-back runs.+ - A changed `current` sets `_target`, stops following the end and calls `_revealTarget(... arrived: ensureVisible+ .3 + _light)`.+ - The bar sits between the header's rule and the list. `swarm.find_in_chat` goes into `_unreadKeys`' actions: it+ opens the thread's find when the thread panel has focus and the chat's otherwise.+- [ ] **Step 4: Wire the thread panel.**+ - Its rows are root + replies.+ - Its `readOlder` is `_scroll.holdPlace(); await c.loadThread(earlier: true)`.+ - Its `hasOlder` is `c.hasEarlierReplies(root)`.+ - Rows get `GlobalKey`s for `ensureVisible`. Its own Esc closes find first, then the thread.+- [ ] **Step 5: Run the tests again.** Expected: PASS.+- [ ] **Step 6: Screenshots** in light and dark, offscreen (`SUPER_TAB_FIND_SHOTS=<dir>`): the main chat with "2 of+ 5", the thread with "1 of 2", and the 50-page note.+- [ ] **Step 7: Commit** the tests first (red), then the code (green).++### Task 3: Phone find model and bar++**Files:**+- Create: `mobile/lib/swarm/swarm_chat_find.dart`+- Test: `mobile/test/swarm/swarm_chat_find_test.dart`++**Interfaces:**+- Produces: `SwarmChatFind` with the same members and contract as Task 1's `SuperTabChatFind` (rows are+ `List<SuperTabMessage>`), `swarmFindPages = 50`, and the same copy.+ - Folding reuses `swarmSearchFold` (`swarm_new_message_sheet.dart`), which already does NFD, the strip,+ `foldDiacritics` and lowercase.+ - `SwarmFindBar({required SwarmChatFind find, required VoidCallback onClose})`, keyed `swarm-find-field`,+ `swarm-find-count`, `swarm-find-older`, `swarm-find-newer`, `swarm-find-close`, with every button at 44 points.+ - Keyboard search action: older.+- [ ] **Steps 1–5:** the same tests and cycle as Task 1, run with `flutter test test/swarm/swarm_chat_find_test.dart`.++### Task 4: Phone chat and thread pages use it++**Files:**+- Modify:+ - `mobile/lib/swarm/swarm_chat_menu.dart` ("Find in chat" sheet action, after Work details)+ - `mobile/lib/swarm/swarm_conversation_page.dart` (bar under `_header`, row fills, reveal)+ - `mobile/lib/swarm/swarm_thread_page.dart` (🔍 button in `_header`, bar, fills, reveal)+ - `mobile/lib/swarm/swarm_message_row.dart` (`match` fill; `lit` kept for the current match)+- Test: `mobile/test/swarm/swarm_find_in_chat_test.dart`++**Interfaces:**+- Consumes: Task 3.+- Produces: `SwarmMessageRow(..., match: bool)`. The fill is `accentOnSurface` at 0.08 for a match and 0.16 when lit.+ `match` and the current match go into the row memo key (`swarm_conversation_page.dart` ~2003).++- [ ] **Step 1: Write the failing widget tests** on `FakeSwarm`, using `pump` from `swarm_chat_test.dart`:+ - the chat menu has "Find in chat" and it opens the field+ - matches in loaded messages are lit and counted+ - Up steps to the older match and shows it+ - Up reads older pages until a match (`routes['$messages?before=..']` chain, `fake.paths` counted)+ - the 50-page stop (51 chained pages, none matching): 50 reads, then the note+ - diacritics fold+ - close clears it+ - the thread page's 🔍 finds root + replies only+ - a new matching message keeps the current one+- [ ] **Step 2: Run** `flutter test test/swarm/swarm_find_in_chat_test.dart`. Expected: FAIL.+- [ ] **Step 3: Wire the conversation page.**+ - Its rows are `c.stream`, its `readOlder` is `c.loadOlder()` (rows grew?), and its `hasOlder` is `c.hasOlder`.+ - A changed current sets `_target`, `_reveal()`, and `_lit = id` for as long as it is current. The near-top reader+ skips while a read-back runs.+- [ ] **Step 4: Wire the thread page.** Its rows are root + replies, its `readOlder` is `loadEarlier()`, its+ `hasOlder` is `hasEarlier`, and it reveals as `_findFocus` does.+- [ ] **Step 5: Run the tests again.** Expected: PASS.+- [ ] **Step 6: Screenshots** in light and dark on the test runner (the chat with "2 of 5", the menu, and the thread).+- [ ] **Step 7: Commit** the tests first (red), then the code (green).++### Task 5: Read cost and evidence++- [ ] Measure a 50-page search: the requests and messages read (from Tasks 2 and 4's counting tests), plus bytes and+ time per page against the live API for a long chat, read with the same `before`/`beforeId` cursor. Put the numbers+ in the PR body.+- [ ] Post red/green evidence as a PR comment, and the screenshots to Tony with a person line.diff --git a/docs/plans/2026-11-04-grown-feed-reads-plan.md b/docs/plans/2026-11-04-grown-feed-reads-plan.mdnew file mode 100644index 000000000..faf0afbad--- /dev/null+++ b/docs/plans/2026-11-04-grown-feed-reads-plan.md@@ -0,0 +1,84 @@+# Starts and conversations reads stay one round trip as a Swarm grows — 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:** Atlas ops per request stop growing with a Swarm's history (task #2839, Watch Production #2773: 928 → 1,226 ops/s+over four hours at flat traffic; SwarmStart getMore on `{tabId, changedAt}` 239 → 351 per 2 h, SwarmGroup getMore on+`{tabId, agentIds}` 28 → 42).++**Architecture:** measured on a grown bench Swarm (3,000 finished starts, 1,500 quiet Lead conversations,+`backend/integration/bench/grownFeedOps.ts`):++1. A host's poll after any change rebuilds the host signature (`read/hostInputs.ts hostInputs`, the `host:inputs` entry,+ no patch rule) by reading the key and change time of **every live start**, member and agent: 3,279 rows, a command and+ a getMore through `{tabId, changedAt}`, once per pod per change. Finished starts stay live for 7 days, so this grows+ with the Swarm's history. That is the SwarmStart getMore of the slow log.+2. Reads that return more than 101 rows take a getMore: Mongo's first batch is 101 documents. An agent's quiet+ conversations (`dormant:agent:{id}`, `light-dormant:agent:{id}`, loaded whole on a cold or aged cache entry) are+ hundreds for a Lead, so each load is a command plus getMores, more as the Lead's history grows. Prisma's `aggregateRaw`+ takes `options.batchSize`; with it the same read is one round trip (probe: 350 rows, one command, no getMore).++The fixes: every named-index read (`parts/indexed.ts readBy`, which all the hot part reads use) asks for one batch; the host+signature holds its member, agent and start stamps in a cache entry patched from each delta, so a change reads only what+changed. The signature stays byte-identical.++**Tech Stack:** TypeScript, Prisma on MongoDB (`aggregateRaw`), vitest; the bench on mongodb-memory-server.++**Spec:** task #2839's brief; [2026-11-02 poll cost](../superpowers/specs/2026-11-02-poll-cost-design.md) Part 1.3 (the host+signature's patched map, superseded then by `host:groups` for conversations only). Coordinates with #2976 (task #2783):+that PR fixes the delta and feed reads of `GET changes`; this one touches neither.++## Global Constraints++- Answers identical: the host signature equals today's for every write (equivalence test after seeded writes).+- No env switches. Red-first per task. Backend only. Temp files only in `mktemp -d` folders.+- Guard rows (GET changes p95, POST commands p95) not worse: one round trip is never slower than several.++## Review Focus++- The stamps rule: a removal drops the key, a revival or change sets it, a touch (version without `changedAt`) leaves it;+ the hash is built from the same values in the same order as today.+- `batchSize` on every named read: what the first reply may hold is bounded by Mongo's 16 MB reply limit either way.++## Design (AGENTS.md checklist)++- **Growth:** the new entry holds one `key → changedAt` per live member, agent and start of a Swarm (as the reads it+ replaces return), in the read cache's byte budget; it goes with the Swarm's entries.+- **Concurrency:** the cache's rules: one delta per Swarm and stamp, no locks.+- **Read cost:** a host poll after a change reads the delta, not every live start; a large read is one round trip.+- **Scale:** at 10x starts the host signature costs the same per change. First warning: `swarm cache` full loads of+ `host`, and SwarmStart/SwarmGroup getMore counts in the slow log.+- **Compatibility:** no API or stored shape change.+- **Migration + rollback:** nothing stored; roll back with the previous release.+- **Audience:** the signature is the host's own, as today.+- **Identity:** nothing keyed by or sent as the machine owner's login.+- **Failure:** an entry that cannot patch loads in full, as every cache entry does.+- **Platforms:** backend on Linux pods.++## Task 1: named reads are one round trip++**Files:** `backend/src/superTabs/parts/indexed.ts` (`readBy`), `backend/src/superTabs/parts/indexed.test.ts` or a new test,+`backend/integration/superTabGroupPlans.test.ts`.++**Interfaces:** `readBy` passes `options.batchSize: READ_BATCH` with or without a hint.++- [ ] Failing test: readBy sends a batch size (red today: options has only the hint).+- [ ] Implement; integration: an agent's quiet conversations past 101 rows come in one command, no getMore.++## Task 2: the host signature's stamps are patched, not read again++**Files:** `backend/src/superTabs/read/hostInputs.ts`, `backend/src/superTabs/cachePatch.ts` (`hostStampsRule`), tests in+`read/hostInputs.test.ts`, `integration/superTabHostGroups.test.ts`.++**Interfaces:** entry `host:stamps` (scope `main`, kinds member, agent, start): `{ member, agent, start }`, each+`key → { changedAt, version }`. `hostInputs` hashes it as today's rows.++- [ ] Failing test: after a held signature, a change reads no live start whose stamp did not move (red today: every live+ start is read).+- [ ] Implement; equivalence test against today's signature after seeded writes.++## Task 3: measure and hand over++- [ ] `grownFeedOps.ts` before (main) and after; numbers and red/green in the PR.+- [ ] `npm test`, typecheck; ready; review step.diff --git a/docs/plans/2026-11-04-message-reach-latency-plan.md b/docs/plans/2026-11-04-message-reach-latency-plan.mdnew file mode 100644index 000000000..5cdd8e6bf--- /dev/null+++ b/docs/plans/2026-11-04-message-reach-latency-plan.md@@ -0,0 +1,85 @@+# Message reach latency log — 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:** Task #2840 (Watch Production #2773). Ken's guard "how fast a message reaches its reader" has no measurement in+any production log, so the load work cannot show it got no worse. Log it per pod per minute, in the style of the logs Ken+already reads (`cpu by kind`, `route latency`, `messages by reader`).++**Architecture:** A new in-memory module, `superTabs/messageReachStats.ts`, like `messageReadStats.ts`: callers record one+duration per message reaching one reader, keyed by the reader's kind and the way it reached them. Every minute it logs+`message reach latency` with the pod, the window and, per key, the count, p50, p95 and max in ms (a bounded reservoir+sample per key, as `route latency` keeps). A message that reaches its reader late (a read over a minute old: an app brought+back or opened; a delivery over 10 minutes old, which includes the time its agent was busy) is counted as `late`, outside the+percentiles (review of #2995). A person's reads count per reading app: Desktop and the phone both open count a message+twice. Two places record:++1. **An agent:** its host's acknowledgement that a delivery was typed (`store.ts delivery`, `ack` not uncertain, the first+ time the row gets `deliveredAt`): now − the delivery's creation, which is written with its message. Recorded after the+ transaction commits, so a retried transaction records once. Reader `agent` or `buddy`, way `delivery`.+2. **A person:** a read of new messages (`store.ts messages` with an `after` cursor, which every app uses after a push or+ poll says the conversation moved): now − each returned message's creation, for messages the reader did not write.+ Reader `person`, way `read`. A latest page, a thread or a scroll back is a re-read, not the message reaching them.++**Tech Stack:** backend TypeScript (Fastify, Prisma on MongoDB), vitest.++**Spec:** task #2840's brief.++## Global Constraints++- No message text, ids or emails in the log: reader kinds, ways and numbers only.+- In memory per pod, nothing stored; no new database read or write.+- The guard rows (`GET changes` p95, `POST commands` p95) must not get worse: the hooks add only arithmetic on rows+ already in memory. Measured per call before and after on a seeded Swarm.+- Red-first tests; backend `npm test`; the Super Tab suite runs in PR CI.++## Design++- **Growth:** nothing stored; the window is cleared each minute. Memory: at most a few keys × 2,000 samples.+- **Concurrency:** single-threaded per pod; recorded after commit, so a retried transaction records once.+- **Read cost:** none added: the rows are those the call already read.+- **Scale:** at 10x messages, the per-minute samples stay capped (reservoir); count and max stay exact.+- **Compatibility:** server-only log; no client change.+- **Migration + rollback:** none; rolling back removes the log line.+- **Audience:** operators reading the pod logs; the line carries no personal data.+- **Identity:** N/A because no identity is logged or used beyond the reader's kind.+- **Failure:** recording cannot throw into the request: plain arithmetic on numbers; a stopped module records nothing.+- **Platforms:** backend only.++## Review Focus++1. Each message reaches each reading app or agent once in the count: no double count from retried transactions, re-reads or+ the reader's own messages.+2. No id, text or email can reach the line.+3. No added reads or awaits on the hot paths.++## Task 1: the stats module++**Files:** `backend/src/superTabs/messageReachStats.ts` (new), `backend/src/superTabs/messageReachStats.test.ts`,+`backend/src/server.ts` (start and stop beside `messages by reader`).+**Interfaces:** `recordMessageReach({ reader, via }, ms)`, `startMessageReachStats({ everyMs, pod, maxSamples, random, log })`,+`LATE_MS`.++- [x] Failing tests: the minute line's shape and percentiles, late rows, silent empty minutes, bounded samples, stop.+- [x] Code.++## Task 2: an agent's delivery receipt records++**Files:** `backend/src/superTabs/store.ts` (`delivery`), test `backend/integration/superTabs.test.ts`.++- [x] Failing test: an ack records once with the delivery's age; a second ack, an uncertain ack and a claim record nothing.+- [x] Code: `afterCommit` on the first `deliveredAt`.++## Task 3: a person's read of new messages records++**Files:** `backend/src/superTabs/store.ts` (`messages`), test `backend/integration/superTabs.test.ts`.++- [x] Failing test: an `after` read records each returned message others wrote; the person's own message, a latest page and+ an agent's read record nothing.+- [x] Code.++## Task 4: measure++- [x] Per call before/after on a seeded Swarm: an `after` read and a delivery ack, timed over many calls on main and on the+ branch. A sample log line in the PR.diff --git a/docs/plans/2026-11-04-phone-test-temp-cleanup-plan.md b/docs/plans/2026-11-04-phone-test-temp-cleanup-plan.mdnew file mode 100644index 000000000..25da1123e--- /dev/null+++ b/docs/plans/2026-11-04-phone-test-temp-cleanup-plan.md@@ -0,0 +1,80 @@+# Phone tests' temp folders go without racing what still writes into them 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:** A phone test's teardown never fails with "Directory not empty" because something the test started is still+writing into the temp folder it deletes. Seen in batch #2952: `swarm_session_test.dart` "the app icon's count is what+the drawer counts after a read" failed at `swarm_fixture.dart:392` (`memoryHomeCache`'s `deleteSync`) while the+session's inbox was still keeping its Home in the background (task #2759, River, 2026-11-04).++**Architecture:** `SwarmHomeCache.write` runs unawaited from `SwarmHomeKeeper._write` (a temp file `home.bin.next`, then+a rename). The fixture's teardown deleted the folder at once, so a save landing during the recursive delete leaves a+file behind and the delete fails. Two parts:++1. `memoryHomeCache`'s teardown first waits for the saves its cache has under way (`homeSaved`, the cache's own+ one-at-a-time queue), then deletes. Under a fake clock that queue never moves again, so the wait is bounded and+ nothing is written after it.+2. The delete itself (`deleteTempFolder`, mobile/test/temp_folder.dart) tries again for a moment while the folder is+ still there, for writers no fixture can wait for: hosts built without a `homeCache` keep their Home and kept chats+ in the per-file test home (`flutter_test_config.dart`), whose `tearDownAll` gets the same delete.++**Tech Stack:** Flutter 3.47.2, flutter_test; test code only.++**Spec:** task #2759's brief. No app code changes.++## Global Constraints++- Test code only (mobile/test). No change in mobile/lib.+- Red first: each risk has a test committed failing before its fix.+- Temp folders only from `createTempSync` under the system temp folder.+- No fixed sleeps in tests: the tests wait for the save or the writer to finish.++## Design++- growth: N/A because nothing is stored.+- concurrency: the point of the change; the wait follows the cache's own queue, the retry covers writers outside it.+- read cost: N/A.+- scale: N/A.+- compatibility: N/A because no wire or saved format changes.+- migration + rollback: N/A; revert the commits.+- audience: N/A.+- identity: N/A.+- failure: a folder that still will not go after the retries fails the teardown with the last error, as before.+- platforms: macOS (local) and Linux (CI), where the failure was seen.++## Review Focus++- The bounded wait in `memoryHomeCache`'s teardown: real time, and harmless when a fake clock froze the save.+- The retry gives up and rethrows, so a folder that cannot be deleted for another reason is still seen.+- The other temp-folder teardowns in mobile/test were audited: every write into them is awaited by the test, except+ the shared test home and the picture tests' folder (swarm_attachment_test.dart: "a narrow message makes the box+ narrower" ends with its fetch released but not waited for), which take the retry. The rest keep a plain+ `deleteSync`.++## Task 1: the Home's folder goes only after the saves under way++**Files:** mobile/test/swarm/swarm_fixture.dart, mobile/test/swarm/swarm_fixture_test.dart, mobile/test/temp_folder.dart++**Interfaces:** `Future<void> removeHome(SwarmHomeCache cache)`, `memoryHomeCache()`'s teardown calls it.++- [ ] Test: a save parked at its key when `removeHome` starts; once both are done, no folder is left.+- [ ] Run red (the folder is back: the save landed after the delete), commit; implement; run green, commit.++## Task 2: a folder still being written into goes once the writing stops++**Files:** mobile/test/temp_folder.dart, mobile/test/temp_folder_test.dart, mobile/test/flutter_test_config.dart,+mobile/test/swarm/swarm_attachment_test.dart++**Interfaces:** `Future<void> deleteTempFolder(Directory folder)`.++- [ ] Test: another isolate writing files into a folder while `deleteTempFolder` runs; the delete does not fail and the+ folder is gone.+- [ ] Run red ("Directory not empty"), commit; implement; run green, commit.+- [ ] `flutter_test_config.dart`'s `tearDownAll` deletes the test home with it, and swarm_attachment_test.dart's+ `tearDown` its folder.++## Evidence++- Forced reproduction of the CI failure with the old fixture, then the session test file 20/20 and under parallel+ load with the fix; the phone suite green in CI.diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dartindex 49e66811c..2fd88d842 100644--- a/mobile/lib/swarm/model.dart+++ b/mobile/lib/swarm/model.dart@@ -1462,6 +1462,10 @@ class SuperTabMessage {String get authorId => author['id'] as String? ?? '';bool get fromAgent => author['kind'] == 'agent';bool get fromTerminal => source['kind'] == 'native';++ /// What was typed into an agent's terminal, a scheduled prompt too: no chat+ /// row (Ken 11-04, task #2849; the desktop's). Its answer still is one.+ bool get terminalPrompt => fromTerminal && source['phase'] == 'prompt';SuperTabRoute? get route => SuperTabRoute.fromSource(source);bool get routeOverride => source['kind'] == 'route-override';diff --git a/mobile/lib/swarm/swarm_buddy_chat.dart b/mobile/lib/swarm/swarm_buddy_chat.dartindex 918be5932..4e5357927 100644--- a/mobile/lib/swarm/swarm_buddy_chat.dart+++ b/mobile/lib/swarm/swarm_buddy_chat.dart@@ -463,10 +463,14 @@ class SwarmBuddyMenuButton extends StatelessWidget {required this.chatId,this.swarmId,this.swarmSwitch,+ this.onFind,});final SwarmBuddyActions actions;+ /// Find in chat, where the page holding the chat offers it (task #2826).+ final VoidCallback? onFind;+/// The Buddy chat it is on: what Rename names the Buddy of, by its id/// rather than its project. Null while that chat is not known yet.final String? chatId;@@ -603,6 +607,12 @@ class SwarmBuddyMenuButton extends StatelessWidget {onTap: () => unawaited(_rename(context, chatId)),),],+ if (onFind case final find?)+ PhoneSheetAction(+ icon: LucideIcons.search300,+ label: 'Find in chat',+ onTap: find,+ ),if (_oldChats(reader).isNotEmpty)PhoneSheetAction(icon: LucideIcons.history,diff --git a/mobile/lib/swarm/swarm_chat_find.dart b/mobile/lib/swarm/swarm_chat_find.dartnew file mode 100644index 000000000..d6a03d13d--- /dev/null+++ b/mobile/lib/swarm/swarm_chat_find.dart@@ -0,0 +1,415 @@+import 'dart:async';++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/shared/theme/app_icon_size.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';++import 'model.dart';+import 'swarm_new_message_sheet.dart' show swarmSearchFold;+import 'swarm_style.dart';++/// How many older pages one search reads at the most, counted from the last+/// change to its query (task #2826): as many as a quote's original is looked+/// for in.+const swarmFindPages = 50;++const _limitNote = 'No more matches in the last $swarmFindPages pages';+const _startNote = 'No more matches in this chat';+const _failedNote = 'Couldn’t read older messages';++/// Find in the open chat — the main chat or a thread (task #2826, the+/// desktop's `SuperTabChatFind`): the messages [rows] shows (oldest first)+/// that say [query], case and accents aside ([swarmSearchFold]), numbered+/// from the newest (1), so an older page adds matches above without moving+/// [number].+///+/// Typing never reads a page. [older] past the oldest loaded match reads+/// older pages ([readOlder]) one at a time until one brings a match, the chat+/// starts, a read fails, or [swarmFindPages] were read since the query last+/// changed; [note] says which. A new [search], [newer] or [clear] stops a+/// read-back under way.+class SwarmChatFind extends ChangeNotifier {+ SwarmChatFind({+ required this.rows,+ required this.hasOlder,+ required this.readOlder,+ });++ /// The messages the chat shows, oldest first.+ final List<SuperTabMessage> Function() rows;++ /// Older messages wait to be read.+ final bool Function() hasOlder;++ /// Reads the page before the oldest shown; false when it failed, or+ /// brought nothing while more is said to be there.+ final Future<bool> Function() readOlder;++ String _query = '';+ String get query => _query;++ List<String> _matches = const [];+ Set<String> _matching = const {};++ /// The ids of the rows that match, oldest first.+ List<String> get matches => _matches;+ Set<String> get matching => _matching;++ /// The match shown and lit; null with none.+ String? get current => _current;+ String? _current;++ /// [current]'s place, the newest match being 1.+ int? get number {+ final at = _current == null ? -1 : _matches.indexOf(_current!);+ return at < 0 ? null : _matches.length - at;+ }++ int get total => _matches.length;++ /// While a read-back runs: how many of this search's [swarmFindPages] it+ /// has read, the one under way included. Null otherwise.+ int? get reading => _reading;+ int? _reading;++ /// Why Up found nothing older: the page limit, the chat's start, or a read+ /// that failed.+ String? get note => _note;+ String? _note;++ /// Older pages this search has read.+ int _pages = 0;++ /// Moves on with every search, close and step down: a read-back that+ /// started under another stops.+ int _generation = 0;+ bool _disposed = false;++ /// Each row's text folded, by id, with the text it was folded from: a row+ /// is folded again only once edited.+ var _folded = <String, (String, String)>{};++ /// What the person typed: the newest match is current. Reads nothing.+ void search(String query) {+ if (query == _query) return;+ _query = query;+ _restart();+ _match();+ _current = _matches.lastOrNull;+ _tell();+ }++ /// Closes the search: no query, no matches, no read-back.+ void clear() {+ _query = '';+ _restart();+ _matches = const [];+ _matching = const {};+ _current = null;+ _folded = {};+ _tell();+ }++ void _restart() {+ _generation++;+ _pages = 0;+ _reading = null;+ _note = null;+ }++ /// The rows changed (a message arrived, was edited or went): [current]+ /// stays the same message while it still matches, else the newest does.+ void refresh() {+ final before = (_matches, _current);+ _match();+ if (!_matching.contains(_current)) _current = _matches.lastOrNull;+ if (!listEquals(before.$1, _matches) || before.$2 != _current) _tell();+ }++ /// One match newer; it stops a read-back under way, which went the other+ /// way.+ void newer() {+ if (_reading != null) {+ _generation++;+ _reading = null;+ }+ _note = null;+ final at = _current == null ? -1 : _matches.indexOf(_current!);+ if (at >= 0 && at < _matches.length - 1) _current = _matches[at + 1];+ _tell();+ }++ /// One match older: read in from older pages when none older is loaded.+ /// Nothing while a read-back runs.+ Future<void> older() async {+ if (_reading != null) return;+ final at = _current == null ? -1 : _matches.indexOf(_current!);+ if (at > 0) {+ _current = _matches[at - 1];+ _note = null;+ return _tell();+ }+ if (_needle.isEmpty) return;+ final generation = _generation, from = _current;+ _note = null;+ while (true) {+ if (!hasOlder()) {+ _note = _startNote;+ break;+ }+ if (_pages >= swarmFindPages) {+ _note = _limitNote;+ break;+ }+ _reading = ++_pages;+ _tell();+ bool read;+ try {+ read = await readOlder();+ } catch (_) {+ read = false;+ }+ if (_disposed || generation != _generation) return;+ _match();+ if (!_matching.contains(_current)) _current = _matches.lastOrNull;+ if (!read) {+ _note = _failedNote;+ break;+ }+ // The match just older than where Up was pressed, or the newest one+ // when there was none.+ final was = from == null ? -1 : _matches.indexOf(from);+ if (was > 0 || (was < 0 && _matches.isNotEmpty)) {+ _current = was > 0 ? _matches[was - 1] : _matches.last;+ break;+ }+ }+ _reading = null;+ _tell();+ }++ String get _needle => swarmSearchFold(_query.trim());++ void _match() {+ final needle = _needle;+ if (needle.isEmpty) {+ _matches = const [];+ _matching = const {};+ return;+ }+ final kept = _folded, folded = <String, (String, String)>{};+ final ids = <String>[];+ for (final m in rows()) {+ if (m.deleted || folded.containsKey(m.id)) continue;+ final was = kept[m.id];+ final text = was != null && was.$1 == m.text+ ? was+ : (m.text, swarmSearchFold(m.text));+ folded[m.id] = text;+ if (text.$2.contains(needle)) ids.add(m.id);+ }+ _folded = folded;+ _matches = List.unmodifiable(ids);+ _matching = Set.unmodifiable(ids);+ }++ void _tell() {+ if (!_disposed) notifyListeners();+ }++ @override+ void dispose() {+ _disposed = true;+ _generation++;+ super.dispose();+ }+}++/// Find's bar, under the chat's or the thread's header: the field, "n of N",+/// ↑ older, ↓ newer and ✕, each a 44-point target; what Up found nothing+/// older for, or how far it reads back, on a line under them. The keyboard's+/// search key steps older, the keyboard staying up.+class SwarmFindBar extends StatefulWidget {+ const SwarmFindBar({+ super.key,+ required this.find,+ required this.onClose,+ this.hint = 'Find in chat',+ });++ final SwarmChatFind find;+ final VoidCallback onClose;++ /// What the empty field says: the thread's says "Find in thread".+ final String hint;++ @override+ State<SwarmFindBar> createState() => _SwarmFindBarState();+}++class _SwarmFindBarState extends State<SwarmFindBar> {+ late final _field = TextEditingController(text: widget.find.query);++ @override+ void initState() {+ super.initState();+ _field.addListener(_typed);+ widget.find.addListener(_cleared);+ }++ @override+ void didUpdateWidget(SwarmFindBar old) {+ super.didUpdateWidget(old);+ if (old.find == widget.find) return;+ old.find.removeListener(_cleared);+ widget.find.addListener(_cleared);+ _cleared();+ }++ @override+ void dispose() {+ widget.find.removeListener(_cleared);+ _field.dispose();+ super.dispose();+ }++ void _typed() => widget.find.search(_field.text);++ /// The search was closed or replaced under the field: it says so too.+ void _cleared() {+ if (widget.find.query != _field.text) _field.text = widget.find.query;+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return ListenableBuilder(+ listenable: widget.find,+ builder: (context, _) {+ final find = widget.find;+ final typed = find.query.trim().isNotEmpty;+ final number = find.number;+ final count = !typed+ ? null+ : number == null+ ? 'No matches'+ : '$number of ${find.total}';+ final status = switch (find.reading) {+ final pages? => 'Reading older messages · $pages of $swarmFindPages',+ null => find.note,+ };+ return Padding(+ key: const ValueKey('swarm-find-bar'),+ // The ✕'s drawn box ends at the screen's side inset.+ padding: const EdgeInsetsDirectional.fromSTEB(+ AppSpace.screenInset,+ AppSpace.xs,+ AppSpace.xs,+ AppSpace.xs,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ children: [+ Expanded(child: _input()),+ if (count != null)+ Padding(+ padding: const EdgeInsetsDirectional.only(+ start: AppSpace.s,+ ),+ child: Text(+ count,+ key: const ValueKey('swarm-find-count'),+ maxLines: 1,+ style: AppType.caption(+ color: AppPalette.textSecondary,+ fontFeatures: const [FontFeature.tabularFigures()],+ ),+ ),+ ),+ SwarmIconButton(+ key: const ValueKey('swarm-find-older'),+ icon: LucideIcons.chevronUp300,+ label: 'Older match',+ onPressed: typed && find.reading == null+ ? () => unawaited(find.older())+ : null,+ ),+ SwarmIconButton(+ key: const ValueKey('swarm-find-newer'),+ icon: LucideIcons.chevronDown300,+ label: 'Newer match',+ onPressed:+ number != null && number > 1 || find.reading != null+ ? find.newer+ : null,+ ),+ SwarmIconButton(+ key: const ValueKey('swarm-find-close'),+ icon: LucideIcons.x300,+ label: 'Close find',+ onPressed: widget.onClose,+ ),+ ],+ ),+ if (status != null)+ Padding(+ padding: const EdgeInsetsDirectional.only(+ start: AppSpace.m,+ top: AppSpace.xs,+ ),+ child: Text(+ status,+ key: const ValueKey('swarm-find-status'),+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ),+ ],+ ),+ );+ },+ );+ }++ /// The field, as Search's is: a pill with the search glyph, none of the+ /// app's field look.+ Widget _input() => Material(+ color: AppPalette.swarmSearchSurface,+ shape: const StadiumBorder(),+ clipBehavior: Clip.antiAlias,+ child: TextField(+ key: const ValueKey('swarm-find-field'),+ controller: _field,+ autofocus: true,+ autocorrect: false,+ textInputAction: TextInputAction.search,+ // Search steps older, and the keyboard stays up for the next.+ onEditingComplete: () {},+ onSubmitted: (_) => unawaited(widget.find.older()),+ style: AppType.label(color: AppPalette.textPrimary),+ cursorColor: AppPalette.swarmAccent,+ decoration: InputDecoration(+ isDense: true,+ filled: false,+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ hintText: widget.hint,+ hintStyle: AppType.label(color: AppPalette.textFaint),+ prefixIcon: Icon(+ LucideIcons.search300,+ size: AppIconSize.besideText,+ color: AppPalette.textSecondary,+ ),+ contentPadding: const EdgeInsets.symmetric(vertical: AppSpace.m),+ ),+ ),+ );+}diff --git a/mobile/lib/swarm/swarm_chat_menu.dart b/mobile/lib/swarm/swarm_chat_menu.dartindex c4af11666..bdccaddf6 100644--- a/mobile/lib/swarm/swarm_chat_menu.dart+++ b/mobile/lib/swarm/swarm_chat_menu.dart@@ -123,8 +123,8 @@ Future<void> showSwarmNotifySheet(}}-/// At the end of a chat's header: ⋮, whose sheet holds Add agent-/// ([swarmCanAddAgent]), Rename and Archive where the person may+/// At the end of a chat's header: ⋮, whose sheet holds Find in chat where+/// the chat's page offers it ([onFind]), Add agent ([swarmCanAddAgent]), Rename and Archive where the person may/// ([swarmChatManage]) and the chat's Notifications/// ([swarmNotifySection]), as the desktop's chat menu does for every chat a/// person reads, a viewer's too. Nothing while the chat is not@@ -135,11 +135,16 @@ class SwarmChatMenuButton extends StatefulWidget {super.key,required this.reader,required this.chatId,+ this.onFind,});final SwarmReader reader;final String chatId;+ /// Opens find in the chat (swarm_chat_find.dart), after Work details;+ /// null offers no Find in chat.+ final VoidCallback? onFind;+@overrideState<SwarmChatMenuButton> createState() => _SwarmChatMenuButtonState();}@@ -207,6 +212,12 @@ class _SwarmChatMenuButtonState extends State<SwarmChatMenuButton> {chatId: widget.chatId,),),+ if (widget.onFind case final find?)+ PhoneSheetAction(+ icon: LucideIcons.search300,+ label: 'Find in chat',+ onTap: find,+ ),...swarmAddAgentActions(context, widget.reader, widget.chatId),...swarmChatManageActions(context, widget.reader, widget.chatId),],diff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dartindex 81214e4bc..73db4eac8 100644--- a/mobile/lib/swarm/swarm_conversation.dart+++ b/mobile/lib/swarm/swarm_conversation.dart@@ -178,11 +178,15 @@ class SwarmConversation extends ChangeNotifierList<SuperTabMessage> messages = const [];/// The [messages] the chat lists: a reply only in its thread shows there- /// alone ([SuperTabMessage.inMainStream], the desktop's main stream).+ /// alone ([SuperTabMessage.inMainStream], the desktop's main stream), and+ /// what was typed into a terminal is no row+ /// ([SuperTabMessage.terminalPrompt]).List<SuperTabMessage> get stream {if (!identical(_streamOf, messages)) {_streamOf = messages;- _stream = List.unmodifiable(messages.where((m) => m.inMainStream));+ _stream = List.unmodifiable(+ messages.where((m) => m.inMainStream && !m.terminalPrompt),+ );}return _stream;}diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dartindex 88ab06726..9f83b11dd 100644--- a/mobile/lib/swarm/swarm_conversation_page.dart+++ b/mobile/lib/swarm/swarm_conversation_page.dart@@ -31,6 +31,7 @@ import 'swarm_buddy_chat.dart';import 'swarm_session_widgets.dart';import 'swarm_buddy_tab.dart'show SwarmBuddyDot, SwarmBuddyMark, swarmBuddyMark;+import 'swarm_chat_find.dart';import 'swarm_chat_menu.dart';import 'swarm_file_links.dart';import 'swarm_choices.dart';@@ -151,6 +152,7 @@ class SwarmConversationPage extends StatefulWidget {required this.swarmId,required this.conversationId,this.header = true,+ this.findRequests,this.buddy,this.messageId,this.threadId,@@ -181,6 +183,10 @@ class SwarmConversationPage extends StatefulWidget {/// (`swarm_project_page.dart`), under the project's own header.final bool header;+ /// Told when the page around the chat asks to find in it: the project's+ /// own menu, where the chat has no header of its own (task #2826).+ final Listenable? findRequests;+/// What the person does to their Buddy, where the page around the chat/// holds it, for its own header's menu; null makes the chat its own while/// it is their Buddy chat.@@ -239,6 +245,13 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>/// "Earlier messages" is offered only once that read failed.bool _loadingOlder = false, _olderFailed = false;+ /// Find in the chat (task #2826), while its bar is open under the header;+ /// and its current match as last brought into view, which stays+ /// [_target] and [_lit] for as long as it is current.+ SwarmChatFind? _find;+ String? _found;+ bool _findRefreshing = false;+/// No other screen covers this one.bool _visible = true;@@ -320,6 +333,16 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>WidgetsBinding.instance.addObserver(this);_text.addListener(_typed);_scroll.addListener(_scrolled);+ widget.findRequests?.addListener(_openFind);+ }++ @override+ void didUpdateWidget(SwarmConversationPage old) {+ super.didUpdateWidget(old);+ if (old.findRequests != widget.findRequests) {+ old.findRequests?.removeListener(_openFind);+ widget.findRequests?.addListener(_openFind);+ }}@override@@ -697,6 +720,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>_steps.clear();if (_buddy != widget.buddy) _buddy?.dispose();_buddy = null;+ // Find goes with the chat it searched, a read-back under way too.+ _dropFind();_rows.clear();_madeFrom = null;_lineAt = null;@@ -718,6 +743,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>@overridevoid dispose() {WidgetsBinding.instance.removeObserver(this);+ widget.findRequests?.removeListener(_openFind);_close();_voice?.dispose();_view.dispose();@@ -807,6 +833,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>_loadingOlder ||_olderFailed ||_finding ||+ _findReading ||!_scroll.hasClients) {return;}@@ -817,6 +844,91 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>}}+ /// Find reads older pages itself: the near-top read waits until it is+ /// done.+ bool get _findReading => _find?.reading != null;++ /// Opens find under the header, from the chat's ⋮.+ void _openFind() {+ final c = _conversation;+ if (c == null || _find != null || !mounted) return;+ final find = SwarmChatFind(+ rows: () => _findRows(c),+ hasOlder: () => c.hasOlder,+ readOlder: () => _findOlder(c),+ )..addListener(_findMoved);+ setState(() => _find = find);+ }++ /// ✕: the query, the fills and the light go, and a read-back stops.+ void _closeFind() {+ if (_find == null) return;+ _dropFind();+ if (mounted) setState(() {});+ }++ void _dropFind() {+ final find = _find;+ if (find == null) return;+ find+ ..removeListener(_findMoved)+ ..dispose();+ _find = null;+ if (_target == _found) _target = null;+ if (_lit == _found) _lit = null;+ _found = null;+ }++ /// What find searches: the messages the list draws, oldest first, as far+ /// as it draws them — those waiting below while the person reads back+ /// join once they show. Thread-only replies are the thread's own.+ List<SuperTabMessage> _findRows(SwarmConversation c) {+ final rows = _drawnOf(c).rows;+ final held = _held.value;+ final at = held == null ? -1 : rows.lastIndexWhere((m) => m.id == held);+ return at < 0 ? rows : rows.sublist(0, at + 1);+ }++ /// One older page for find, as scrolling back reads it: false when it+ /// failed, or brought nothing while more is said to be there.+ Future<bool> _findOlder(SwarmConversation c) async {+ final shown = c.messages.length;+ await c.loadOlder();+ if (!mounted || _conversation != c) return false;+ return c.messages.length > shown || (!c.hasOlder && c.error == null);+ }++ /// Find moved: a new current match is brought into view and lit, as a+ /// message link's original is, and stays lit while it is current.+ void _findMoved() {+ final find = _find, c = _conversation;+ if (find == null || c == null || !mounted) return;+ final current = find.current;+ if (current != _found) {+ _litTimer?.cancel();+ if (_target == _found) _target = null;+ if (_lit == _found) _lit = null;+ _found = current;+ if (current != null) {+ _target = current;+ _lit = current;+ _reveal(c, current, 0);+ }+ }+ setState(() {});+ }++ /// The rows the list draws changed: find counts them again once this+ /// frame is built.+ void _refreshFindSoon() {+ if (_find == null || _findRefreshing) return;+ _findRefreshing = true;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ _findRefreshing = false;+ if (mounted) _find?.refresh();+ });+ }+/// Reads the page before the oldest message shown. The list is drawn from/// its foot, so what arrives above leaves what the person reads in place.Future<void> _loadOlder(SwarmConversation c) async {@@ -912,6 +1024,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>required acting,required lit,required followed,+ required match,required onTap,}) => _threadRow(c,@@ -921,6 +1034,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>acting: acting,lit: lit,followed: followed,+ match: match,onTap: onTap,),pending: (t, post) => _threadPending(c, t, post),@@ -967,6 +1081,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>required bool acting,required bool lit,required bool followed,+ required bool match,required VoidCallback onTap,}) {final view = _view.value;@@ -989,6 +1104,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>grouped: grouped,lit: lit,followed: followed,+ match: match,quote: null,actions: acting,onTap: onTap,@@ -1379,13 +1495,19 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>final buddy? => SwarmBuddyMenuButton(actions: buddy,chatId: widget.conversationId,+ onFind: _openFind,swarmId: widget.swarmId,swarmSwitch: widget.swarmSwitch,),- null => SwarmChatMenuButton(reader: c.reader, chatId: c.id),+ null => SwarmChatMenuButton(+ reader: c.reader,+ chatId: c.id,+ onFind: _openFind,+ ),},),),+ if (_find case final find?) SwarmFindBar(find: find, onClose: _closeFind),if (_buddy case final buddy?) SwarmBuddyBar(actions: buddy),// The composer takes what it needs, up to all of the room under the// header: on a short phone with the keyboard up its field gives up lines@@ -2003,13 +2125,14 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>_placeOf = {for (final (i, entry) in _shown.indexed) _keyOf(entry): i};_rows.removeWhere((key, _) => !_placeOf.containsKey(key));_madeFrom = from;+ _refreshFindSoon();}final entries = _shown;final byId = _byId;// Newest at the foot: the list runs bottom up.final pending = c.outgoing.reversed.toList();// A page shorter than the screen never scrolls: look once it is drawn.- if (c.hasOlder && !_loadingOlder && !_olderFailed) {+ if (c.hasOlder && !_loadingOlder && !_olderFailed && !_findReading) {WidgetsBinding.instance.addPostFrameCallback((_) {if (mounted) _nearTop();});@@ -2050,6 +2173,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>final tagged = _taggedOf(c, m);final labels = _labelsOf(c, m);final lit = _lit == m.id, followed = _target == m.id;+ final match = _find?.matching.contains(m.id) ?? false;final acting = _acting == m.id;final reactions = c.reactionsOf(m);final receipt =@@ -2087,6 +2211,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>grouped,lit,followed,+ match,acting,receipt,reply,@@ -2125,6 +2250,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>grouped: grouped,lit: lit,followed: followed,+ match: match,quote: m.threadReply? SwarmRepliedInThread(key: ValueKey('swarm-replied-in-thread-${m.id}'),diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dartindex 60f05a645..1edd45f43 100644--- a/mobile/lib/swarm/swarm_message_row.dart+++ b/mobile/lib/swarm/swarm_message_row.dart@@ -258,7 +258,8 @@ const swarmDeletedText = 'This message was deleted.';/// author changed it), its files, its [reactions] and its [thread]'s line. A/// deleted one keeps only "This message was deleted." and its thread's line./// A tap opens its actions, a long-press [onLongPress]; lit for a moment when-/// a quote leads to it.+/// a quote leads to it, and while it is find's current match; a quieter fill+/// while it is one of find's other matches.class SwarmMessageRow extends StatelessWidget {const SwarmMessageRow({super.key,@@ -276,6 +277,7 @@ class SwarmMessageRow extends StatelessWidget {required this.grouped,required this.lit,this.followed = false,+ this.match = false,required this.quote,required this.actions,required this.onTap,@@ -328,6 +330,10 @@ class SwarmMessageRow extends StatelessWidget {/// The row a quote led to: lit, then fading. Only it animates — a fade on/// every row would give each its own ticker.final bool followed;++ /// One of find's matches (swarm_chat_find.dart): a quiet fill, under+ /// [lit]'s.+ final bool match;final Widget? quote;final VoidCallback onTap;@@ -479,6 +485,8 @@ class SwarmMessageRow extends StatelessWidget {deletedBody ??[if (lit) SizedBox(key: ValueKey('swarm-lit-${message.id}')),+ if (match && !lit)+ SizedBox(key: ValueKey('swarm-match-${message.id}')),?quote,?swarmTerminalNote(message),// A voice message's text is its words: under its bubble, on →A.@@ -562,6 +570,22 @@ class SwarmMessageRow extends StatelessWidget {): null;if (!followed) {+ // Find's matches; its current one keeps its light once a post moved+ // the list's target away.+ if (match) {+ return Container(+ key: key,+ padding: padding,+ decoration: BoxDecoration(+ color: lit+ ? AppPalette.accentOnSurface.withValues(alpha: 0.16)+ : _matchFill,+ borderRadius: BorderRadius.circular(AppControl.rowRadius),+ ),+ foregroundDecoration: bar,+ child: held,+ );+ }if (!taggedYou) return Padding(key: key, padding: padding, child: held);return KeyedSubtree(key: key,@@ -582,6 +606,8 @@ class SwarmMessageRow extends StatelessWidget {decoration: BoxDecoration(color: lit? AppPalette.accentOnSurface.withValues(alpha: 0.16)+ : match+ ? _matchFill: taggedYou? AppSurface.accentWash: Colors.transparent,@@ -593,6 +619,9 @@ class SwarmMessageRow extends StatelessWidget {}}+/// A find match's fill: half a lit row's.+Color get _matchFill => AppPalette.accentOnSurface.withValues(alpha: 0.08);+/// A message's first line: who, in what role, then [trailing] — its time,/// or how its post is going — and [tag], where the ask it is stands.class SwarmMessageHeader extends StatelessWidget {diff --git a/mobile/lib/swarm/swarm_project_page.dart b/mobile/lib/swarm/swarm_project_page.dartindex 25b15fd55..aa0e5bdd9 100644--- a/mobile/lib/swarm/swarm_project_page.dart+++ b/mobile/lib/swarm/swarm_project_page.dart@@ -338,6 +338,11 @@ class SwarmProjectPage extends StatefulWidget {class _SwarmProjectPageState extends State<SwarmProjectPage> {SwarmSession? _session;++ /// Find in the chat shown, asked from the project's header (task #2826):+ /// the chat's page under it answers.+ final _findRequests = ValueNotifier(0);+ void _findInChat() => _findRequests.value++;late SwarmProjectTab _tab = widget.tabs.contains(widget.tab)? widget.tab: widget.tabs.first;@@ -393,6 +398,7 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {@overridevoid dispose() {+ _findRequests.dispose();_closeSheet();_session?.inbox.removeListener(_inboxChanged);_session?.leave();@@ -562,10 +568,8 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {}void _openSharingSheet(SwarmReader reader) => _openSheet(- (_) => SwarmProjectSharingSheet(- reader: reader,- projectId: widget.projectId,- ),+ (_) =>+ SwarmProjectSharingSheet(reader: reader, projectId: widget.projectId),);/// Project settings…'s Project details ([SwarmProjectInfoSheet]): not the@@ -657,6 +661,7 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {SwarmBuddyMenuButton(actions: _buddy!,chatId: swarmBuddyChat(_buddy!.reader, widget.projectId)?.id,+ onFind: _findInChat,),// The project chat's Notifications (the desktop's chat menu): its// header is the project's, so they are here.@@ -664,6 +669,7 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {SwarmChatMenuButton(reader: reader,chatId: project.leadConversationId,+ onFind: _findInChat,),if (_homeC)_ProjectMenu(@@ -677,6 +683,7 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {? () => _openSharingSheet(reader): null,onSettings: () => unawaited(_openSettings(reader)),+ onFind: _tab == SwarmProjectTab.chat ? _findInChat : null,onNotifications:snapshot.conversation(project.leadConversationId) == null? null@@ -734,6 +741,7 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {swarmId: widget.swarmId,conversationId: project.leadConversationId,header: false,+ findRequests: _findRequests,mention: widget.mention,messageId: _messageId,threadId: _threadId,@@ -741,6 +749,7 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {homeC: _homeC,),SwarmProjectTab.buddy => SwarmProjectBuddy(+ findRequests: _findRequests,reader: reader,swarmId: widget.swarmId,projectId: project.id,@@ -911,6 +920,7 @@ SuperTabAgent? swarmProjectPm(SuperTabSnapshot? snapshot, String projectId) {/// menu has them. It goes with the header: losing the project/// closes it. Open terminal follows the Swarm and the phone's computers/// while open, and at the tap reads the PM of [projectId] again.+/// Find in chat follows Open terminal while the chat is shown (task #2826).class _ProjectMenu extends StatelessWidget {const _ProjectMenu({required this.reader,@@ -922,12 +932,13 @@ class _ProjectMenu extends StatelessWidget {required this.onSettings,this.onSharing,this.onNotifications,+ this.onFind,});final SwarmReader reader;final String projectId;final VoidCallback onStatus, onLeaderboard, onWork, onTeam, onSettings;- final VoidCallback? onSharing, onNotifications;+ final VoidCallback? onSharing, onNotifications, onFind;@overrideWidget build(BuildContext context) {@@ -978,11 +989,11 @@ class _ProjectMenu extends StatelessWidget {return MenuTheme(data: MenuThemeData(submenuIcon: MenuTheme.of(context).submenuIcon,- // Home C sits near the top of the phone. Eight rows at their 48-point+ // Home C sits near the top of the phone. Nine rows at their 48-point// layout height, panel padding, and a small edge fit without scrolling.style: AppMenu.style(maxHeight:- 8 * (minTouchTarget + AppSpace.xs) ++ 9 * (minTouchTarget + AppSpace.xs) +AppMenu.panelPadding.vertical +AppSpace.xs,),@@ -997,6 +1008,8 @@ class _ProjectMenu extends StatelessWidget {terminal.enabled ? terminal.onTap : null,value: terminal.value,),+ if (onFind case final onTap?)+ row('swarm-project-menu-find', 'Find in chat', onTap),row('swarm-project-menu-status', 'Status', onStatus),row('swarm-project-menu-leaderboard', 'Leaderboard', onLeaderboard),row('swarm-project-menu-work', 'Work', onWork),diff --git a/mobile/lib/swarm/swarm_project_tabs.dart b/mobile/lib/swarm/swarm_project_tabs.dartindex 38ba268d8..32829ff28 100644--- a/mobile/lib/swarm/swarm_project_tabs.dart+++ b/mobile/lib/swarm/swarm_project_tabs.dart@@ -193,12 +193,16 @@ class SwarmProjectBuddy extends StatefulWidget {required this.swarmId,required this.projectId,required this.actions,+ this.findRequests,});final SwarmReader reader;final String swarmId, projectId;final SwarmBuddyActions actions;+ /// Told when the project's header asks to find in the Buddy chat.+ final Listenable? findRequests;+@overrideState<SwarmProjectBuddy> createState() => _SwarmProjectBuddyState();}@@ -283,6 +287,7 @@ class _SwarmProjectBuddyState extends State<SwarmProjectBuddy> {conversationId: id,header: false,buddy: widget.actions,+ findRequests: widget.findRequests,);}final Widget body;diff --git a/mobile/lib/swarm/swarm_thread_page.dart b/mobile/lib/swarm/swarm_thread_page.dartindex e7cdbe0da..50047b9f4 100644--- a/mobile/lib/swarm/swarm_thread_page.dart+++ b/mobile/lib/swarm/swarm_thread_page.dart@@ -6,6 +6,7 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:harness_mobile/phone/tty.dart';import 'package:harness_mobile/phone/tty_controls.dart';import 'package:harness_mobile/phone/voice_language_store.dart';+import 'package:harness_mobile/shared/theme/app_icon_size.dart';import 'package:harness_mobile/shared/theme/app_ink.dart';import 'package:harness_mobile/shared/theme/app_space.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';@@ -14,6 +15,7 @@ import 'package:harness_mobile/shared/theme/app_type.dart';import 'model.dart';import 'swarm_attach.dart';+import 'swarm_chat_find.dart';import 'swarm_choices.dart';import 'swarm_conversation.dart';import 'swarm_conversation_page.dart';@@ -22,11 +24,12 @@ import 'swarm_outbox.dart';import 'swarm_paste.dart';import 'swarm_session.dart';import 'swarm_session_widgets.dart';+import 'swarm_style.dart' show SwarmIconButton;import 'swarm_thread.dart';import 'swarm_voice.dart';/// Draws one of a thread's messages as its chat draws them; a tap on it-/// opens or closes its actions ([acting]).+/// opens or closes its actions ([acting]); [match] while it is one of find's.typedef SwarmThreadRow = Widget Function(SwarmThread thread,SuperTabMessage message, {@@ -34,6 +37,7 @@ typedef SwarmThreadRow = Widget Function(required bool acting,required bool lit,required bool followed,+ required bool match,required VoidCallback onTap,});@@ -138,6 +142,79 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {/// Reply options under the card is open: folded each time the page opens.bool _optionsOpen = false;+ /// Find in the thread (task #2826), while its bar is open under the+ /// header; and its current match as last brought into view, which stays+ /// [_target] and [_lit] for as long as it is current.+ SwarmChatFind? _find;+ String? _found;++ /// The header's search: find opens under it.+ void _openFind() {+ if (_find != null) return;+ final find = SwarmChatFind(+ rows: _findRows,+ hasOlder: () => _thread.hasEarlier,+ readOlder: _findEarlier,+ )..addListener(_findMoved);+ setState(() => _find = find);+ }++ /// ✕: the query, the fills and the light go, and a read-back stops.+ void _closeFind() {+ final find = _find;+ if (find == null) return;+ find+ ..removeListener(_findMoved)+ ..dispose();+ setState(() {+ _find = null;+ if (_target == _found) _target = null;+ if (_lit == _found) _lit = null;+ _found = null;+ });+ }++ /// The thread's own messages, oldest first: its replies, and its root —+ /// once no earlier reply waits, as that is when it is the oldest of what+ /// is read; until then Up reads back to it through the earlier replies.+ List<SuperTabMessage> _findRows() => [+ if (!_thread.hasEarlier) ?_thread.rootMessage,+ ..._thread.replies,+ ];++ /// One page of earlier replies for find, as Show earlier replies reads it:+ /// false when it failed, or brought nothing while more is said to be+ /// there.+ Future<bool> _findEarlier() async {+ final t = _thread, read = t.messages.length;+ await t.loadEarlier();+ if (!mounted) return false;+ return t.messages.length > read || (!t.hasEarlier && t.error == null);+ }++ /// Find moved: a new current match is brought into view and lit, as the+ /// thread's focus is, and stays lit while it is current.+ void _findMoved() {+ final find = _find;+ if (find == null || !mounted) return;+ final current = find.current;+ if (current != _found) {+ _litTimer?.cancel();+ if (_target == _found) _target = null;+ if (_lit == _found) _lit = null;+ _found = current;+ if (current != null) {+ _target = current;+ _lit = current;+ _reveal(current, 0);+ }+ }+ setState(() {});+ }++ /// The thread's messages changed: find counts them again.+ void _threadMoved() => _find?.refresh();+/// Once the thread is read: finds the focus (reading earlier replies back/// to it, a bounded number of pages), scrolls to it and lights it for/// 2 seconds, as the chat does for a quoted message.@@ -236,6 +313,7 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {_thread.addListener(_seen);_thread.addListener(_guardVoice);_thread.addListener(_land);+ _thread.addListener(_threadMoved);// Before the thread shows, so showing it does not move the mark first._readThrough;unawaited(_thread.load());@@ -292,6 +370,10 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {_thread.removeListener(_seen);_thread.removeListener(_guardVoice);_thread.removeListener(_land);+ _thread.removeListener(_threadMoved);+ _find+ ?..removeListener(_findMoved)+ ..dispose();_litTimer?.cancel();_voice?.dispose();_thread.dispose();@@ -402,6 +484,12 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {crossAxisAlignment: CrossAxisAlignment.stretch,children: [_header(context, tty),+ if (_find case final find?)+ SwarmFindBar(+ find: find,+ onClose: _closeFind,+ hint: 'Find in thread',+ ),ListenableBuilder(listenable: _thread,builder: (context, _) => SwarmThreadSessionLine(thread: _thread),@@ -516,6 +604,14 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {],),),+ // A thread has no ⋮: its find is here (task #2826).+ SwarmIconButton(+ key: const ValueKey('swarm-thread-find'),+ icon: LucideIcons.search300,+ size: AppIconSize.standalone,+ label: 'Find in thread',+ onPressed: _openFind,+ ),],),);@@ -560,6 +656,7 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {acting: _acting == m.id,lit: _lit == m.id,followed: _target == m.id,+ match: _find?.matching.contains(m.id) ?? false,onTap: () => _toggleActions(m.id),);if (_acting == m.id) return KeyedSubtree(key: _actingKey, child: built);diff --git a/mobile/test/flutter_test_config.dart b/mobile/test/flutter_test_config.dartindex 2785e5443..ee5508829 100644--- a/mobile/test/flutter_test_config.dart+++ b/mobile/test/flutter_test_config.dart@@ -4,6 +4,8 @@ import 'dart:io';import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/core/harness_file_store.dart';+import 'temp_folder.dart';+/// Runs before every test file under `test/`.////// ⚠️ **Every default path points into a throwaway home.** The app's stores,@@ -16,9 +18,9 @@ Future<void> testExecutable(FutureOr<void> Function() testMain) async {HttpOverrides.global = _NoNetwork();final home = Directory.systemTemp.createTempSync('harness-test-home-');HarnessFileStore.homeForTest = home.path;- tearDownAll(() {- if (home.existsSync()) home.deleteSync(recursive: true);- });+ // Hosts built without a Home or kept chats of their own keep them here, in+ // the background, so the last test's can still be landing.+ tearDownAll(() => deleteTempFolder(home));await testMain();}diff --git a/mobile/test/swarm/swarm_attachment_test.dart b/mobile/test/swarm/swarm_attachment_test.dartindex 24fda860c..b00e5cabe 100644--- a/mobile/test/swarm/swarm_attachment_test.dart+++ b/mobile/test/swarm/swarm_attachment_test.dart@@ -10,6 +10,7 @@ import 'package:harness_mobile/swarm/swarm_attachment.dart';import 'package:harness_mobile/swarm/swarm_attachment_store.dart';import 'package:harness_mobile/swarm/swarm_file_download.dart';+import '../temp_folder.dart';import 'swarm_attachment_fakes.dart';/// A picture in a chat shows in place, as Slack shows one (Dee, 10-29): a@@ -38,9 +39,8 @@ void main() {storage = FakeFileStorage();store = storeIn(root, storage);});- tearDown(() {- if (root.existsSync()) root.deleteSync(recursive: true);- });+ // A test can end with a fetch still writing its picture in.+ tearDown(() => deleteTempFolder(root));Finder key(String value) => find.byKey(ValueKey(value));final chip = key('chip');diff --git a/mobile/test/swarm/swarm_buddy_chat_test.dart b/mobile/test/swarm/swarm_buddy_chat_test.dartindex aff52340d..2d3008900 100644--- a/mobile/test/swarm/swarm_buddy_chat_test.dart+++ b/mobile/test/swarm/swarm_buddy_chat_test.dart@@ -576,6 +576,17 @@ void main() {]);});+ testWidgets('⋮ has Find in chat, which opens the find field (#2826)', (+ tester,+ ) async {+ await pump(tester, backend(buddy: wren()));+ await tester.tap(key('swarm-buddy-menu'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Find in chat'));+ await tester.pumpAndSettle();+ expect(key('swarm-find-field'), findsOneWidget);+ });+testWidgets('⋮ holds the chat\'s Notifications too: Muted is kept, and ''access lost while the sheet is open closes it', (tester) async {final fake = backend(buddy: wren());diff --git a/mobile/test/swarm/swarm_buddy_unread_line_test.dart b/mobile/test/swarm/swarm_buddy_unread_line_test.dartindex b661b7551..d2bdd0ab2 100644--- a/mobile/test/swarm/swarm_buddy_unread_line_test.dart+++ b/mobile/test/swarm/swarm_buddy_unread_line_test.dart@@ -207,6 +207,32 @@ void main() {expect(tester.getTopLeft(find.text('Update 3.')).dy, greaterThan(y));});+ // Task #2849: a terminal's prompt is no chat row, so the line never+ // sits above it.+ testWidgets('passes over a terminal\'s prompt, which the chat does not '+ 'draw', (tester) async {+ await pump(+ tester,+ backend([+ said(1),+ said(2),+ {+ ...said(3, text: 'Run the hourly cleanup.'),+ 'source': {+ 'kind': 'native',+ 'phase': 'prompt',+ 'operator': {'name': '[email protected]'},+ },+ },+ said(4),+ ], mark: 2),+ );+ expect(find.text('Run the hourly cleanup.'), findsNothing);+ final y = tester.getTopLeft(line).dy;+ expect(tester.getTopLeft(find.text('Update 2.')).dy, lessThan(y));+ expect(tester.getTopLeft(find.text('Update 4.')).dy, greaterThan(y));+ });+testWidgets("passes over the person's own messages", (tester) async {await pump(tester,diff --git a/mobile/test/swarm/swarm_chat_find_test.dart b/mobile/test/swarm/swarm_chat_find_test.dartnew file mode 100644index 000000000..00728e36b--- /dev/null+++ b/mobile/test/swarm/swarm_chat_find_test.dart@@ -0,0 +1,369 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_chat_find.dart';+import 'package:harness_mobile/swarm/swarm_new_message_sheet.dart'+ show swarmSearchFold;+import 'package:unorm_dart/unorm_dart.dart' as unorm;++/// Find in the open chat's model (task #2826): it lights the loaded messages+/// that match, numbers them from the newest, and steps up past the oldest+/// loaded match by reading older pages, at most 50 a search.+void main() {+ SuperTabMessage message(String id, int sequence, String text) =>+ SuperTabMessage.fromJson({+ 'id': id,+ 'conversationId': 'g1',+ 'text': text,+ 'sequence': sequence,+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},+ 'createdAt': DateTime.utc(2026, 11, 4).toIso8601String(),+ });++ /// A chat of [rows] (oldest first) whose older pages come from [page], one+ /// call each; [reads] counts them. Older rows remain while [older] says so.+ ({SwarmChatFind find, List<SuperTabMessage> rows, int Function() reads}) chat(+ List<SuperTabMessage> rows, {+ bool Function()? older,+ FutureOr<bool> Function(int page, List<SuperTabMessage> rows)? page,+ }) {+ var reads = 0;+ final find = SwarmChatFind(+ rows: () => rows,+ hasOlder: older ?? () => true,+ readOlder: () async {+ reads++;+ return page == null ? false : await page(reads, rows);+ },+ );+ addTearDown(find.dispose);+ return (find: find, rows: rows, reads: () => reads);+ }++ /// m1..m5, with m2 and m4 saying x.+ List<SuperTabMessage> five() => [+ for (var i = 1; i <= 5; i++)+ message('m$i', i, i.isEven ? 'an x here' : 'nothing'),+ ];++ /// One older page of a message that never matches, put above the others.+ bool plain(int page, List<SuperTabMessage> rows) {+ rows.insert(0, message('old$page', -page, 'nothing older'));+ return true;+ }++ test('fold', () {+ expect(swarmSearchFold('Tiếng VIỆT đồng'), 'tieng viet dong');+ expect(swarmSearchFold(unorm.nfd('Tiếng VIỆT đồng')), 'tieng viet dong');+ final c = chat([+ message('m1', 1, 'Tiếng Việt'),+ message('m2', 2, 'tiền đồng'),+ ]);+ c.find.search('tieng viet');+ expect(c.find.matches, ['m1']);+ c.find.search('DONG');+ expect(c.find.matches, ['m2']);+ });++ test('matches in loaded rows', () {+ final c = chat(five());+ c.find.search('x');+ expect(c.find.matches, ['m2', 'm4']);+ expect(c.find.matching, {'m2', 'm4'});+ expect(c.find.current, 'm4');+ expect(c.find.number, 1);+ expect(c.find.total, 2);+ expect(c.find.note, isNull);+ // Typing never reads a page.+ expect(c.reads(), 0);+ });++ test('stepping', () async {+ final c = chat(five());+ c.find.search('x');+ await c.find.older();+ expect((c.find.current, c.find.number, c.find.total), ('m2', 2, 2));+ c.find.newer();+ expect((c.find.current, c.find.number), ('m4', 1));+ // Newer than the newest stays where it is.+ c.find.newer();+ expect((c.find.current, c.find.number), ('m4', 1));+ expect(c.reads(), 0);+ });++ test('reads older pages until a match', () async {+ final c = chat(+ five(),+ page: (page, rows) {+ rows.insert(+ 0,+ message('old$page', -page, page == 3 ? 'x at last' : 'nothing'),+ );+ return true;+ },+ );+ c.find.search('x');+ await c.find.older();+ expect(c.reads(), 0);+ await c.find.older();+ expect(c.reads(), 3);+ expect((c.find.current, c.find.number, c.find.total), ('old3', 3, 3));+ expect(c.find.reading, isNull);+ expect(c.find.note, isNull);+ });++ test('says how far the read-back is while it reads', () async {+ final held = <Completer<bool>>[];+ final c = chat(+ five(),+ page: (page, rows) {+ plain(page, rows);+ final read = Completer<bool>();+ held.add(read);+ return read.future;+ },+ );+ c.find.search('x');+ await c.find.older();+ final going = c.find.older();+ await Future<void>.delayed(Duration.zero);+ expect(c.find.reading, 1);+ held.last.complete(true);+ await Future<void>.delayed(Duration.zero);+ expect(c.find.reading, 2);+ c.find.clear();+ held.last.complete(true);+ await going;+ });++ test('50-page stop', () async {+ final c = chat(five(), page: plain);+ c.find.search('x');+ await c.find.older();+ await c.find.older();+ expect(c.reads(), swarmFindPages);+ expect(c.reads(), 50);+ expect(c.find.note, 'No more matches in the last 50 pages');+ expect((c.find.current, c.find.number, c.find.total), ('m2', 2, 2));+ expect(c.find.reading, isNull);+ // Up again reads nothing more for this search.+ await c.find.older();+ expect(c.reads(), 50);+ expect(c.find.note, 'No more matches in the last 50 pages');+ });++ test('chat start', () async {+ final c = chat(five(), older: () => false, page: plain);+ c.find.search('x');+ await c.find.older();+ await c.find.older();+ expect(c.reads(), 0);+ expect(c.find.note, 'No more matches in this chat');+ expect(c.find.current, 'm2');+ // Down again says nothing of the start.+ c.find.newer();+ expect(c.find.note, isNull);+ });++ test('reaching the start while reading says so', () async {+ var older = 3;+ final c = chat(+ five(),+ older: () => older > 0,+ page: (page, rows) {+ older--;+ return plain(page, rows);+ },+ );+ c.find.search('x');+ await c.find.older();+ await c.find.older();+ expect(c.reads(), 3);+ expect(c.find.note, 'No more matches in this chat');+ });++ test('failed read', () async {+ final c = chat(five(), page: (_, _) => false);+ c.find.search('x');+ await c.find.older();+ await c.find.older();+ expect(c.reads(), 1);+ expect(c.find.note, 'Couldn’t read older messages');+ expect(c.find.current, 'm2');+ expect(c.find.reading, isNull);+ });++ test('one read-back at a time', () async {+ final read = Completer<bool>();+ final c = chat(+ five(),+ page: (page, rows) {+ if (page > 1) return false;+ rows.insert(0, message('old1', -1, 'x'));+ return read.future;+ },+ );+ c.find.search('x');+ await c.find.older();+ final first = c.find.older();+ final second = c.find.older();+ await Future<void>.delayed(Duration.zero);+ expect(c.reads(), 1);+ read.complete(true);+ await Future.wait([first, second]);+ expect(c.reads(), 1);+ expect(c.find.current, 'old1');+ });++ test('blank query', () async {+ final c = chat(five(), page: plain);+ c.find.search(' ');+ expect(c.find.matches, isEmpty);+ expect(c.find.current, isNull);+ expect(c.find.number, isNull);+ await c.find.older();+ expect(c.reads(), 0);+ expect(c.find.note, isNull);+ });++ test('with no match loaded, Up reads back to the newest older one', () async {+ final c = chat(+ five(),+ page: (page, rows) {+ rows.insert(+ 0,+ message('old$page', -page, page == 2 ? 'zebra' : 'nothing'),+ );+ return true;+ },+ );+ c.find.search('zebra');+ expect(c.find.total, 0);+ expect(c.find.current, isNull);+ await c.find.older();+ expect(c.reads(), 2);+ expect((c.find.current, c.find.number, c.find.total), ('old2', 1, 1));+ });++ test('a new search starts the 50 again', () async {+ final c = chat(five(), page: plain);+ c.find.search('x');+ await c.find.older();+ await c.find.older();+ expect(c.reads(), 50);+ c.find.search('nothing older');+ expect(c.find.note, isNull);+ // Its oldest loaded match is the oldest row: Up reads 50 more.+ while (c.find.number != c.find.total) {+ await c.find.older();+ }+ expect(c.reads(), 50);+ c.find.search('x');+ await c.find.older();+ await c.find.older();+ expect(c.reads(), 100);+ expect(c.find.note, 'No more matches in the last 50 pages');+ });++ test('search or clear during a read-back stops it', () async {+ final read = Completer<bool>();+ final c = chat(+ five(),+ page: (page, rows) {+ plain(page, rows);+ return page == 1 ? read.future : true;+ },+ );+ c.find.search('x');+ await c.find.older();+ final going = c.find.older();+ await Future<void>.delayed(Duration.zero);+ c.find.clear();+ expect(c.find.query, '');+ expect(c.find.matches, isEmpty);+ expect(c.find.current, isNull);+ expect(c.find.reading, isNull);+ read.complete(true);+ await going;+ expect(c.reads(), 1);+ expect(c.find.note, isNull);+ expect(c.find.current, isNull);+ });++ test('a new matching message keeps the current one', () async {+ final c = chat(five());+ c.find.search('x');+ await c.find.older();+ expect((c.find.current, c.find.number, c.find.total), ('m2', 2, 2));+ c.rows.add(message('m6', 6, 'x again'));+ c.find.refresh();+ expect((c.find.current, c.find.number, c.find.total), ('m2', 3, 3));+ // The current one gone (deleted), the newest is current.+ c.rows.removeWhere((m) => m.id == 'm2');+ c.find.refresh();+ expect((c.find.current, c.find.number, c.find.total), ('m6', 1, 2));+ });++ test('an edited message is folded again', () {+ final c = chat([message('m1', 1, 'nothing')]);+ c.find.search('x');+ expect(c.find.total, 0);+ c.rows[0] = message('m1', 1, 'now an x');+ c.find.refresh();+ expect(c.find.current, 'm1');+ });++ testWidgets('the bar: count, steps and close, each a 44-point target', (+ tester,+ ) async {+ final c = chat(five(), older: () => false);+ var closed = 0;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SwarmFindBar(find: c.find, onClose: () => closed++),+ ),+ ),+ );+ Finder key(String value) => find.byKey(ValueKey(value));+ // It takes the keyboard as it opens.+ final field = find.descendant(+ of: key('swarm-find-field'),+ matching: find.byType(EditableText),+ );+ expect(tester.widget<EditableText>(field).focusNode.hasFocus, isTrue);+ await tester.enterText(key('swarm-find-field'), 'x');+ await tester.pump();+ expect(c.find.query, 'x');+ expect(tester.widget<Text>(key('swarm-find-count')).data, '1 of 2');+ for (final button in [+ 'swarm-find-older',+ 'swarm-find-newer',+ 'swarm-find-close',+ ]) {+ final size = tester.getSize(key(button));+ expect(size.width, greaterThanOrEqualTo(44), reason: button);+ expect(size.height, greaterThanOrEqualTo(44), reason: button);+ }+ await tester.tap(key('swarm-find-older'));+ await tester.pump();+ expect(find.text('2 of 2'), findsOneWidget);+ await tester.tap(key('swarm-find-newer'));+ await tester.pump();+ expect(find.text('1 of 2'), findsOneWidget);+ // The keyboard's search key steps older too.+ await tester.testTextInput.receiveAction(TextInputAction.search);+ await tester.pump();+ expect(find.text('2 of 2'), findsOneWidget);+ await tester.testTextInput.receiveAction(TextInputAction.search);+ await tester.pump();+ expect(find.text('No more matches in this chat'), findsOneWidget);+ await tester.enterText(key('swarm-find-field'), 'zebra');+ await tester.pump();+ expect(find.text('No matches'), findsOneWidget);+ await tester.tap(key('swarm-find-close'));+ expect(closed, 1);+ });+}diff --git a/mobile/test/swarm/swarm_chat_menu_test.dart b/mobile/test/swarm/swarm_chat_menu_test.dartindex 640f45d6c..8881f93ea 100644--- a/mobile/test/swarm/swarm_chat_menu_test.dart+++ b/mobile/test/swarm/swarm_chat_menu_test.dart@@ -276,6 +276,47 @@ void main() {expect(find.text('Muted'), findsNothing);});+ testWidgets("Swarm Home C: the project's ⋮ finds in its chat (#2826)", (+ tester,+ ) async {+ addTearDown(tester.view.reset);+ tester.view+ ..physicalSize = const Size(1170, 2532)+ ..devicePixelRatio = 3;+ await pump(+ tester,+ backend(),+ home: const SwarmProjectPage(+ swarmId: tab,+ projectId: project,+ tabs: SwarmProjectTab.homeC,+ ),+ );+ await tester.tap(key('swarm-project-menu'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-project-menu-find'));+ await tester.pumpAndSettle();+ expect(key('swarm-find-field'), findsOneWidget);+ });++ testWidgets("with tabs: the project chat's ⋮ finds in it (#2826)", (+ tester,+ ) async {+ await pump(+ tester,+ backend(),+ home: const SwarmProjectPage(+ swarmId: tab,+ projectId: project,+ tabs: SwarmProjectTab.homeB,+ ),+ );+ await open(tester);+ await tester.tap(find.text('Find in chat'));+ await tester.pumpAndSettle();+ expect(key('swarm-find-field'), findsOneWidget);+ });+testWidgets("with tabs: ⋮ for the project chat's Notifications while its "'Chat tab is shown, and not on another tab', (tester) async {final fake = backend();diff --git a/mobile/test/swarm/swarm_find_in_chat_shots_test.dart b/mobile/test/swarm/swarm_find_in_chat_shots_test.dartnew file mode 100644index 000000000..39c9b4205--- /dev/null+++ b/mobile/test/swarm/swarm_find_in_chat_shots_test.dart@@ -0,0 +1,251 @@+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/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/terminal/terminal_font_store.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Review screenshots of find in the open chat on the phone (task #2826):+/// the chat with find at "2 of 5", its ⋮ with Find in chat, and a thread+/// with find. On a 390-point phone in both phone themes, from made-up data+/// only, to the folder `SWARM_FIND_SHOTS` names.+final shots = Platform.environment['SWARM_FIND_SHOTS'];+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';++ 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',+ AppFont.sans,+ ...AppFont.sansFallback,+ }) {+ await (FontLoader(family)..addFont(Future.value(sf))).load();+ }+ // The chat's title is set in the terminal's face.+ final mono = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),+ );+ final terminal = terminalFontStore.value;+ for (final family in {+ '.AppleSystemUIFontMonospaced',+ 'monospace',+ AppFont.mono,+ ...AppFont.monoFallback,+ terminal.fontFamily,+ ...terminal.fontFamilyFallback,+ }) {+ 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();+ }+ });++ Map<String, dynamic> said(+ String id,+ int sequence,+ String text, {+ String author = 'agent-builder',+ String? thread,+ }) => {+ 'id': id,+ 'conversationId': 'g1',+ 'text': text,+ 'sequence': sequence,+ 'thread': ?thread,+ if (thread != null && thread != id) 'replyTo': thread,+ 'author': author == me+ ? {'kind': 'person', 'id': me, 'name': 'tony'}+ : {+ 'kind': 'agent',+ 'id': author,+ 'name': author == 'agent-lead' ? 'River' : 'Nova',+ },+ 'attachments': <Object>[],+ 'reactions': <Object>[],+ 'createdAt': DateTime(2026, 11, 4, 9, sequence * 3).toIso8601String(),+ };++ final chat = [+ said('m1', 1, 'Starting on the login fix.', author: 'agent-lead'),+ said('m2', 2, 'The deploy to staging failed on the migration step.'),+ said('m3', 3, 'Which migration?', author: me),+ said('m4', 4, 'The one that adds the session index.'),+ said('m5', 5, 'Retrying the deploy with the index built online.'),+ said('m6', 6, 'Tests pass locally.', author: 'agent-lead'),+ said('m7', 7, 'Deploy is green on staging now.'),+ said('m8', 8, 'Great, ship it behind the flag.', author: me),+ said('m9', 9, 'Production deploy starts at 10:30.', author: 'agent-lead'),+ said('m10', 10, 'Watching the dashboards.'),+ said('m11', 11, 'Deploy finished, error rate flat.'),+ ];++ final thread = [+ said('t1', 20, 'Lỗi đăng nhập trên iOS sau bản cập nhật', thread: 't1'),+ said('t2', 21, 'Tôi thấy lỗi ở bước xác thực.', thread: 't1'),+ said('t3', 22, 'Đã sửa, đang chờ review.', thread: 't1'),+ said('t4', 23, 'Còn lỗi nào nữa không?', thread: 't1', author: me),+ ];++ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Autonomous', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Fix login flake',+ number: 7,+ agentIds: ['agent-lead', 'agent-builder'],+ lastMessageSequence: 23,+ ),+ ],+ );+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ final line = {+ 'id': 't1',+ 'replies': 3,+ 'lastSequence': 23,+ 'lastAt': DateTime(2026, 11, 4, 10, 9).toIso8601String(),+ 'authors': [+ {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ ],+ 'people': [me],+ };+ fake.routes[messages] = (_) => {+ 'messages': [thread.first, ...chat.reversed],+ 'next': null,+ 'threads': [line],+ };+ fake.routes['$messages?thread=t1'] = (_) => {+ 'messages': thread.reversed.toList(),+ 'next': null,+ 'threads': [line],+ };+ return fake;+ }++ testWidgets('find in the chat, its ⋮ and a thread, in both phone themes', (+ tester,+ ) async {+ addTearDown(tester.view.reset);+ debugDisableShadows = false;+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);+ addTearDown(tester.view.resetPadding);+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {+ const size = Size(390, 844);+ tester.view+ ..physicalSize = size * 3+ ..devicePixelRatio = 3;+ final brightness = palette.brightness;+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = brightness;+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => me,+ account: account,+ request: backend().request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ )..foreground = false;+ final boundary = GlobalKey();+ Future<void> show({String? threadId}) async {+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: buildAppTheme(brightness: brightness),+ builder: (_, child) => SwarmScope(notifier: host, child: child!),+ home: SwarmConversationPage(+ key: ValueKey('shot-$threadId'),+ swarmId: tab,+ conversationId: 'g1',+ messageId: threadId,+ threadId: threadId,+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ Future<void> capture(String name) async {+ if (shots == null) return;+ await tester.runAsync(() async {+ final image =+ await (boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await File('$shots/find-in-chat-390-$name-${brightness.name}.png')+ .writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ await show();+ await tester.tap(key('swarm-chat-menu'));+ await tester.pumpAndSettle();+ expect(find.text('Find in chat'), findsOneWidget);+ await capture('menu');+ await tester.tap(find.text('Find in chat'));+ await tester.pumpAndSettle();+ await tester.enterText(key('swarm-find-field'), 'deploy');+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-find-older'));+ await tester.pumpAndSettle();+ expect(find.text('2 of 5'), findsOneWidget);+ await capture('chat');++ await show(threadId: 't1');+ await tester.tap(key('swarm-thread-find'));+ await tester.pumpAndSettle();+ await tester.enterText(key('swarm-find-field'), 'loi');+ await tester.pumpAndSettle();+ expect(find.text('1 of 3'), findsOneWidget);+ await capture('thread');++ await tester.pumpWidget(const SizedBox());+ host.dispose();+ }+ debugDisableShadows = true;+ }, skip: shots == null);+}diff --git a/mobile/test/swarm/swarm_find_in_chat_test.dart b/mobile/test/swarm/swarm_find_in_chat_test.dartnew file mode 100644index 000000000..fdf522e80--- /dev/null+++ b/mobile/test/swarm/swarm_find_in_chat_test.dart@@ -0,0 +1,589 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_thread_page.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Find in the open chat on the phone (task #2826): from the chat's ⋮ or the+/// thread's search button, a bar under the header lights the loaded+/// messages that match, says "n of N", and steps through them as a message+/// link does — reading older pages on Up past the oldest loaded match, at+/// most 50 a search.+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';++ Map<String, dynamic> message(+ String id,+ int sequence, {+ String text = 'hello',+ String? thread,+ String? replyTo,+ int minute = 0,+ }) => {+ 'id': id,+ 'conversationId': 'g1',+ 'text': text,+ 'sequence': sequence,+ 'replyTo': ?replyTo,+ 'thread': ?thread,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ 'attachments': <Object>[],+ 'reactions': <Object>[],+ 'createdAt': DateTime.utc(2026, 10, 27, 1, minute % 60).toIso8601String(),+ };++ /// A message two lines tall, so 30 of them are taller than the screen.+ Map<String, dynamic> tall(int i, {String? text}) =>+ message('m$i', i, text: text ?? 'Line $i\nof the log', minute: i);++ /// One Swarm whose chat g1 reads [page] as its latest messages, with the+ /// lines of [threads], and [next] as the cursor to the page before.+ FakeSwarm backend(+ List<Map<String, dynamic>> page, {+ Object? next,+ List<Map<String, dynamic>> threads = const [],+ }) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'working',+ lastMessageSequence: page.isEmpty+ ? 0+ : page+ .map((m) => m['sequence'] as int)+ .reduce((a, b) => a > b ? a : b),+ ),+ ],+ derived: {'decisionsWaiting': 0},+ ),+ 'members': [part(me, 1, person(me))],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: {'decisionsWaiting': 0});+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes[messages] = (_) => {+ 'messages': page.reversed.toList(),+ 'next': next,+ 'threads': threads,+ };+ fake.routes['/api/super-tabs/$tab/commands'] = (_) => {+ 'result': <String, dynamic>{},+ };+ return fake;+ }++ /// Chat g1 on a 390-point phone; [threadId] opens that thread over it.+ Future<SwarmHost> pump(+ WidgetTester tester,+ FakeSwarm fake, {+ String? threadId,+ }) async {+ await tester.binding.setSurfaceSize(const Size(390, 844));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ upload: refuseSwarmUpload,+ notices: SilentSystemNotices(),+ features: features,+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: SwarmConversationPage(+ swarmId: tab,+ conversationId: 'g1',+ messageId: threadId,+ threadId: threadId,+ ),+ ),+ );+ await tester.pumpAndSettle();+ return host;+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ /// [finder] is drawn inside the message list's view.+ bool inView(+ WidgetTester tester,+ Finder finder, {+ String list = 'swarm-messages',+ }) {+ final view = tester.getRect(key(list));+ final rect = tester.getRect(finder);+ return rect.top >= view.top - 1 && rect.bottom <= view.bottom + 1;+ }++ String? count(WidgetTester tester) =>+ switch (key('swarm-find-count').evaluate().firstOrNull?.widget) {+ final Text text => text.data,+ _ => null,+ };++ /// The older pages read.+ int olderReads(FakeSwarm fake) =>+ fake.paths.where((p) => p.contains('before=')).length;++ /// Opens find from the chat's ⋮ and types [query].+ Future<void> findInChat(WidgetTester tester, String query) async {+ await tester.tap(key('swarm-chat-menu'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Find in chat'));+ await tester.pumpAndSettle();+ await tester.enterText(key('swarm-find-field'), query);+ await tester.pumpAndSettle();+ }++ testWidgets('the chat menu has Find in chat, and it opens the field', (+ tester,+ ) async {+ await pump(tester, backend([message('m1', 1, text: 'The plan')]));+ expect(key('swarm-find-field'), findsNothing);++ await tester.tap(key('swarm-chat-menu'));+ await tester.pumpAndSettle();+ expect(find.text('Find in chat'), findsOneWidget);+ await tester.tap(find.text('Find in chat'));+ await tester.pumpAndSettle();++ expect(key('swarm-find-field'), findsOneWidget);+ final field = find.descendant(+ of: key('swarm-find-field'),+ matching: find.byType(EditableText),+ );+ expect(tester.widget<EditableText>(field).focusNode.hasFocus, isTrue);+ // Directly under the header.+ expect(+ tester.getTopLeft(key('swarm-find-bar')).dy,+ moreOrLessEquals(tester.getBottomLeft(key('swarm-chat-header')).dy),+ );+ });++ testWidgets('matches in loaded messages are lit and counted', (tester) async {+ final fake = backend([+ for (var i = 1; i <= 8; i++)+ message(+ 'm$i',+ i,+ text: i.isOdd && i > 1 ? 'Tiếng Việt, bản $i' : 'Line $i',+ minute: i,+ ),+ ]);+ await pump(tester, fake);+ await findInChat(tester, 'tieng viet');++ expect(count(tester), '1 of 3');+ expect(key('swarm-lit-m7'), findsOneWidget);+ expect(key('swarm-match-m7'), findsNothing, reason: 'lit wins');+ expect(key('swarm-match-m5'), findsOneWidget);+ expect(key('swarm-match-m3'), findsOneWidget);+ expect(key('swarm-match-m1'), findsNothing);+ expect(key('swarm-lit-m5'), findsNothing);+ // The current match stays lit while it is current.+ await tester.pump(const Duration(seconds: 3));+ await tester.pumpAndSettle();+ expect(key('swarm-lit-m7'), findsOneWidget);+ // Typing read nothing.+ expect(olderReads(fake), 0);+ });++ testWidgets('Up steps to the older match and brings it into view', (+ tester,+ ) async {+ final fake = backend([+ for (var i = 1; i < 40; i++)+ tall(i, text: i == 3 || i == 38 ? 'needle $i\nin the log' : null),+ ]);+ await pump(tester, fake);+ await findInChat(tester, 'needle');+ expect(count(tester), '1 of 2');+ expect(key('swarm-lit-m38'), findsOneWidget);++ await tester.tap(key('swarm-find-older'));+ await tester.pumpAndSettle();++ expect(count(tester), '2 of 2');+ expect(key('swarm-lit-m3'), findsOneWidget);+ expect(inView(tester, key('swarm-message-m3')), isTrue);+ expect(olderReads(fake), 0);++ await tester.tap(key('swarm-find-newer'));+ await tester.pumpAndSettle();+ expect(count(tester), '1 of 2');+ expect(inView(tester, key('swarm-message-m38')), isTrue);+ });++ testWidgets('Up reads older pages until a match', (tester) async {+ final fake = backend(+ [for (var i = 10; i < 40; i++) tall(i)],+ next: {'sequence': 10, 'id': 'm10'},+ );+ // Three older pages; only the last says it.+ for (final (before, to, next) in [(10, 7, 7), (7, 4, 4), (4, 1, null)]) {+ fake.routes['$messages?before=$before&beforeId=m$before'] = (_) => {+ 'messages': [+ for (var i = before - 1; i >= to; i--)+ message(+ 'm$i',+ i,+ text: i == 2 ? 'the needle' : 'Older $i',+ minute: i,+ ),+ ],+ 'next': next == null ? null : {'sequence': next, 'id': 'm$next'},+ };+ }+ await pump(tester, fake);+ await findInChat(tester, 'needle');+ expect(count(tester), 'No matches');+ expect(olderReads(fake), 0, reason: 'typing never reads a page');++ await tester.tap(key('swarm-find-older'));+ await tester.pumpAndSettle();++ expect(olderReads(fake), 3);+ expect(count(tester), '1 of 1');+ expect(key('swarm-lit-m2'), findsOneWidget);+ expect(inView(tester, key('swarm-message-m2')), isTrue);+ expect(key('swarm-find-status'), findsNothing);+ });++ testWidgets('the 50-page stop', (tester) async {+ final fake = backend(+ [for (var i = 100; i < 130; i++) tall(i)],+ next: {'sequence': 100, 'id': 'm100'},+ );+ // 51 older pages of one message each, none of them a match.+ for (var before = 100; before > 49; before--) {+ final at = before - 1;+ fake.routes['$messages?before=$before&beforeId=m$before'] = (_) => {+ 'messages': [message('m$at', at, text: 'Older $at')],+ 'next': {'sequence': at, 'id': 'm$at'},+ };+ }+ await pump(tester, fake);+ await findInChat(tester, 'zebra');++ await tester.tap(key('swarm-find-older'));+ await tester.pumpAndSettle();++ expect(olderReads(fake), 50);+ expect(find.text('No more matches in the last 50 pages'), findsOneWidget);+ expect(count(tester), 'No matches');++ // Up again reads nothing more for this search.+ await tester.tap(key('swarm-find-older'));+ await tester.pumpAndSettle();+ expect(olderReads(fake), 50);+ });++ testWidgets('it says how far it reads back, and closing stops it', (+ tester,+ ) async {+ final fake = backend(+ [for (var i = 10; i < 40; i++) tall(i)],+ next: {'sequence': 10, 'id': 'm10'},+ );+ final held = Completer<Object?>();+ fake.routes['$messages?before=10&beforeId=m10'] = (_) => held.future;+ await pump(tester, fake);+ await findInChat(tester, 'zebra');+ await tester.tap(key('swarm-find-older'));+ await tester.pump();+ expect(find.text('Reading older messages · 1 of 50'), findsOneWidget);++ await tester.tap(key('swarm-find-close'));+ await tester.pumpAndSettle();+ held.complete({+ 'messages': [message('m9', 9, text: 'Older 9')],+ 'next': {'sequence': 9, 'id': 'm9'},+ });+ await tester.pumpAndSettle();+ expect(olderReads(fake), 1);+ expect(key('swarm-find-field'), findsNothing);+ });++ testWidgets('leaving the chat stops a read-back', (tester) async {+ final fake = backend(+ [for (var i = 10; i < 40; i++) tall(i)],+ next: {'sequence': 10, 'id': 'm10'},+ );+ final held = Completer<Object?>();+ fake.routes['$messages?before=10&beforeId=m10'] = (_) => held.future;+ fake.routes['$messages?before=9&beforeId=m9'] = (_) => {+ 'messages': [message('m8', 8, text: 'Older 8')],+ 'next': {'sequence': 8, 'id': 'm8'},+ };+ await pump(tester, fake);+ await findInChat(tester, 'zebra');+ await tester.tap(key('swarm-find-older'));+ await tester.pump();++ await tester.pumpWidget(const SizedBox());+ held.complete({+ 'messages': [message('m9', 9, text: 'Older 9')],+ 'next': {'sequence': 9, 'id': 'm9'},+ });+ await tester.pumpAndSettle();+ expect(olderReads(fake), 1);+ });++ testWidgets('the chat start and a failed read say so', (tester) async {+ final fake = backend(+ [for (var i = 10; i < 40; i++) tall(i)],+ next: {'sequence': 10, 'id': 'm10'},+ );+ fake.routes['$messages?before=10&beforeId=m10'] = (_) =>+ throw const SuperTabFailure('UNAVAILABLE', 'Down', statusCode: 503);+ await pump(tester, fake);+ await findInChat(tester, 'zebra');+ await tester.tap(key('swarm-find-older'));+ await tester.pumpAndSettle();+ expect(find.text('Couldn’t read older messages'), findsOneWidget);++ fake.routes['$messages?before=10&beforeId=m10'] = (_) => {+ 'messages': [message('m9', 9, text: 'Older 9')],+ 'next': null,+ };+ await tester.tap(key('swarm-find-older'));+ await tester.pumpAndSettle();+ expect(find.text('No more matches in this chat'), findsOneWidget);+ });++ testWidgets('accents and case fold', (tester) async {+ await pump(+ tester,+ backend([+ message('m1', 1, text: 'Tiếng Việt'),+ message('m2', 2, text: 'Giá 100 nghìn đồng', minute: 1),+ message('m3', 3, text: 'Nothing here', minute: 2),+ ]),+ );+ await findInChat(tester, 'dong');+ expect(count(tester), '1 of 1');+ expect(key('swarm-lit-m2'), findsOneWidget);++ await tester.enterText(key('swarm-find-field'), 'TIENG viet');+ await tester.pumpAndSettle();+ expect(count(tester), '1 of 1');+ expect(key('swarm-lit-m1'), findsOneWidget);+ expect(key('swarm-lit-m2'), findsNothing);+ });++ testWidgets('close clears the query, the fills and the light', (+ tester,+ ) async {+ await pump(+ tester,+ backend([+ message('m1', 1, text: 'an x'),+ message('m2', 2, text: 'another x', minute: 1),+ ]),+ );+ await findInChat(tester, 'x');+ expect(key('swarm-lit-m2'), findsOneWidget);+ expect(key('swarm-match-m1'), findsOneWidget);++ await tester.tap(key('swarm-find-close'));+ await tester.pumpAndSettle();++ expect(key('swarm-find-field'), findsNothing);+ expect(key('swarm-lit-m2'), findsNothing);+ expect(key('swarm-match-m1'), findsNothing);++ // Opened again, it starts empty.+ await tester.tap(key('swarm-chat-menu'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Find in chat'));+ await tester.pumpAndSettle();+ expect(+ tester.widget<TextField>(key('swarm-find-field')).controller!.text,+ '',+ );+ expect(key('swarm-find-count'), findsNothing);+ });++ testWidgets('the main chat leaves out replies only in a thread', (+ tester,+ ) async {+ await pump(+ tester,+ backend(+ [+ message('m1', 1, text: 'lỗi in the root', thread: 'm1'),+ message(+ 'm2',+ 2,+ text: 'lỗi only in the thread',+ thread: 'm1',+ replyTo: 'm1',+ minute: 1,+ ),+ message('m3', 3, text: 'lỗi in the chat', minute: 2),+ ],+ threads: [threadLine('m1', replies: 1, last: 2)],+ ),+ );+ await findInChat(tester, 'loi');+ expect(count(tester), '1 of 2');+ expect(key('swarm-lit-m3'), findsOneWidget);+ expect(key('swarm-match-m1'), findsOneWidget);+ expect(key('swarm-match-m2'), findsNothing);+ });++ testWidgets("a thread's search button finds its root and replies only", (+ tester,+ ) async {+ final fake = backend(+ [+ message('m1', 1, text: 'lỗi in the root', thread: 'm1'),+ message('m3', 3, text: 'lỗi in the chat', minute: 2),+ ],+ threads: [threadLine('m1', replies: 2, last: 4)],+ );+ fake.routes['$messages?thread=m1'] = (_) => {+ 'messages': [+ message(+ 'm4',+ 4,+ text: 'no match here',+ thread: 'm1',+ replyTo: 'm1',+ minute: 3,+ ),+ message(+ 'm2',+ 2,+ text: 'a lỗi reply',+ thread: 'm1',+ replyTo: 'm1',+ minute: 1,+ ),+ message('m1', 1, text: 'lỗi in the root', thread: 'm1'),+ ],+ 'next': null,+ 'threads': [threadLine('m1', replies: 2, last: 4)],+ };+ await pump(tester, fake, threadId: 'm1');+ expect(find.byType(SwarmThreadPage), findsOneWidget);+ final button = key('swarm-thread-find');+ expect(button, findsOneWidget);+ expect(tester.getSize(button).height, greaterThanOrEqualTo(44));+ expect(find.bySemanticsLabel('Find in thread'), findsOneWidget);++ await tester.tap(button);+ await tester.pumpAndSettle();+ await tester.enterText(key('swarm-find-field'), 'loi');+ await tester.pumpAndSettle();++ expect(count(tester), '1 of 2');+ expect(key('swarm-lit-m2'), findsOneWidget);+ expect(key('swarm-match-m1'), findsOneWidget);++ await tester.tap(key('swarm-find-older'));+ await tester.pumpAndSettle();+ expect(count(tester), '2 of 2');+ expect(key('swarm-lit-m1'), findsOneWidget);+ expect(+ inView(tester, key('swarm-message-m1'), list: 'swarm-thread-messages'),+ isTrue,+ );+ // The main chat's own message is not among them.+ await tester.tap(key('swarm-find-older'));+ await tester.pumpAndSettle();+ expect(find.text('No more matches in this chat'), findsOneWidget);+ });++ testWidgets('a new matching message keeps the current one', (tester) async {+ final fake = backend([+ for (var i = 1; i <= 6; i++)+ message('m$i', i, text: i.isEven ? 'an x $i' : 'Line $i', minute: i),+ ]);+ final host = await pump(tester, fake);+ await findInChat(tester, 'x');+ expect(count(tester), '1 of 3');+ await tester.tap(key('swarm-find-older'));+ await tester.pumpAndSettle();+ expect(count(tester), '2 of 3');+ expect(key('swarm-lit-m4'), findsOneWidget);++ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ lastChangedAt: 200,+ derived: {'decisionsWaiting': 0},+ groups: [+ part(+ 'g1',+ 9,+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'working',+ lastMessageSequence: 7,+ ),+ ),+ ],+ );+ fake.routes['$messages?after=6'] = (_) => {+ 'messages': [message('m7', 7, text: 'one more x', minute: 7)],+ 'next': null,+ };+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();++ expect(find.text('one more x'), findsOneWidget);+ expect(count(tester), '3 of 4');+ expect(key('swarm-lit-m4'), findsOneWidget);+ expect(key('swarm-match-m7'), findsOneWidget);+ });+}++/// Thread [root]'s line as a page names it.+Map<String, dynamic> threadLine(+ String root, {+ required int replies,+ required int last,+}) => {+ 'id': root,+ 'replies': replies,+ 'lastSequence': last,+ 'lastAt': DateTime.utc(2026, 10, 27, 2).toIso8601String(),+ 'authors': [+ {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ ],+ 'people': <String>[],+};diff --git a/mobile/test/swarm/swarm_fixture.dart b/mobile/test/swarm/swarm_fixture.dartindex c1670a2f7..24c1ae68b 100644--- a/mobile/test/swarm/swarm_fixture.dart+++ b/mobile/test/swarm/swarm_fixture.dart@@ -11,6 +11,8 @@ import 'package:harness_mobile/swarm/swarm_outbox.dart' show superTabMessageId;import 'package:harness_mobile/swarm/swarm_request.dart';import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';+import '../temp_folder.dart';+/// Swarm answers as the backend sends them (docs/design/2026-10-26-swarm-state-parts.md, section 4), built by hand so a/// test reads like the wire. Nothing here reaches a machine or the backend.@@ -386,14 +388,26 @@ class MemorySwarmHomeKey implements SwarmHomeKey {Future<void> homeSaved(SwarmHomeCache cache, {String account = me}) =>cache.read(account);-/// A kept Home in a folder of its own, gone after the test.+/// A kept Home in a folder of its own, gone after the test ([removeHome]).SwarmHomeCache memoryHomeCache() {final dir = Directory.systemTemp.createTempSync('swarm-home');- addTearDown(() => dir.deleteSync(recursive: true));- return SwarmHomeCache(+ final cache = SwarmHomeCache(key: MemorySwarmHomeKey(),file: File('${dir.path}/home.bin'),);+ addTearDown(() => removeHome(cache));+ return cache;+}++/// Deletes [cache]'s folder once the saves it has under way are done: one+/// landing mid-delete failed the test ('Directory not empty', task #2759), or+/// put the folder back after it. A save started under a widget test's fake+/// clock never moves again once the test is over, so the wait gives up after+/// a moment, as it does after every such test.+Future<void> removeHome(SwarmHomeCache cache) async {+ await homeSaved(cache)+ .timeout(const Duration(milliseconds: 300), onTimeout: () {});+ await deleteTempFolder(cache.file.parent);}/// Swarm Home C's project screen is up for the project named [name]: itsdiff --git a/mobile/test/swarm/swarm_fixture_test.dart b/mobile/test/swarm/swarm_fixture_test.dartnew file mode 100644index 000000000..4bc59bffb--- /dev/null+++ b/mobile/test/swarm/swarm_fixture_test.dart@@ -0,0 +1,44 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_home_cache.dart';++import 'swarm_fixture.dart';++/// The Keychain item, held until [open] completes: a save parked mid-way.+class _HeldKey extends MemorySwarmHomeKey {+ final open = Completer<void>();++ @override+ Future<String?> read() async {+ await open.future;+ return super.read();+ }+}++void main() {+ // An inbox keeps its Home in the background, so a test can end with a save+ // still under way: deleting its folder then raced it ('Directory not empty'+ // in CI, task #2759), or the save put the folder back after it.+ test('a Home goes only after the saves its cache has under way', () async {+ final folder = Directory.systemTemp.createTempSync('swarm-home');+ addTearDown(() {+ if (folder.existsSync()) folder.deleteSync(recursive: true);+ });+ final key = _HeldKey();+ final cache = SwarmHomeCache(+ key: key,+ file: File('${folder.path}/home.bin'),+ );+ final saving = cache.write(me, const []);+ await settle();++ final removing = removeHome(cache);+ key.open.complete();+ await removing;+ await saving;++ expect(folder.existsSync(), isFalse, reason: 'the save landed after it');+ });+}diff --git a/mobile/test/swarm/swarm_special_rows_test.dart b/mobile/test/swarm/swarm_special_rows_test.dartindex 069e0a3ee..57585db9a 100644--- a/mobile/test/swarm/swarm_special_rows_test.dart+++ b/mobile/test/swarm/swarm_special_rows_test.dart@@ -336,6 +336,28 @@ void main() {);});+ // Ken, 11-04 (task #2849): what was typed into an agent's terminal (a+ // scheduled prompt too) is no chat row; the terminal's answer still is.+ testWidgets('a terminal\'s prompt is no chat row; its answer still is', (+ tester,+ ) async {+ await show(+ tester,+ backend([+ row('typed', 2, 'Run the hourly cleanup.', {+ 'kind': 'native',+ 'phase': 'prompt',+ 'operator': {'name': '[email protected]'},+ }),+ row('answered', 3, 'Cleanup done.', {'kind': 'native'}),+ ]),+ );+ expect(find.text('Run the hourly cleanup.'), findsNothing);+ expect(find.textContaining('Terminal input'), findsNothing);+ expect(inRow('answered', find.text('Cleanup done.')), findsOneWidget);+ expect(inRow('answered', find.text('Terminal answer')), findsOneWidget);+ });+group('an ordinary message says', () {testWidgets('Terminal answer above a terminal\'s answer', (tester) async {await show(diff --git a/mobile/test/temp_folder.dart b/mobile/test/temp_folder.dartnew file mode 100644index 000000000..7b4fbc9ad--- /dev/null+++ b/mobile/test/temp_folder.dart@@ -0,0 +1,19 @@+import 'dart:io';++/// Deletes a test's temp [folder] and everything in it. What the test started+/// can still be writing there (a Home kept, a picture fetched): a file landing+/// mid-delete fails it with 'Directory not empty' (task #2759), so it tries+/// again, for a second or more, until that writing stops, and fails as before+/// if it never does.+Future<void> deleteTempFolder(Directory folder) async {+ for (var attempt = 1; ; attempt++) {+ try {+ folder.deleteSync(recursive: true);+ return;+ } on FileSystemException {+ if (!folder.existsSync()) return;+ if (attempt == 50) rethrow;+ await Future<void>.delayed(const Duration(milliseconds: 20));+ }+ }+}diff --git a/mobile/test/temp_folder_test.dart b/mobile/test/temp_folder_test.dartnew file mode 100644index 000000000..814704bb2--- /dev/null+++ b/mobile/test/temp_folder_test.dart@@ -0,0 +1,44 @@+import 'dart:io';+import 'dart:isolate';++import 'package:flutter_test/flutter_test.dart';++import 'temp_folder.dart';++void main() {+ // What a test started can still be writing into its folder when it ends: a+ // recursive delete then meets a file it did not list, and failed the test+ // with 'Directory not empty' (task #2759).+ test(+ 'a folder still being written into goes once the writing stops',+ () async {+ final folder = Directory.systemTemp.createTempSync('temp-folder');+ final path = folder.path;+ // Enough already there that the delete is still going when files land.+ for (var i = 0; i < 1000; i++) {+ File('$path/kept-$i').writeAsStringSync('x');+ }+ final writing = Isolate.run(() {+ for (var i = 0; i < 100; i++) {+ try {+ File('$path/$i').writeAsStringSync('x');+ } on FileSystemException {+ return; // The folder went.+ }+ }+ });+ addTearDown(() async {+ await writing;+ if (folder.existsSync()) folder.deleteSync(recursive: true);+ });+ while (!File('$path/0').existsSync()) {+ await Future<void>.delayed(Duration.zero);+ }++ await deleteTempFolder(folder);+ await writing;++ expect(folder.existsSync(), isFalse);+ },+ );+}