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 b2240: #3035 #3041 (#3047)
0xken15cdbd5f1983c7
diff --git a/backend/integration/superTabInbox.test.ts b/backend/integration/superTabInbox.test.tsindex 492f67260..6c25ddc19 100644--- a/backend/integration/superTabInbox.test.ts+++ b/backend/integration/superTabInbox.test.ts@@ -19,8 +19,9 @@ import { guardedWrite } from '../src/superTabs/parts/write.js'import { SwarmReads } from '../src/superTabs/read/service.js'import { HostReads } from '../src/superTabs/read/host.js'import { buddyChatId } from '../src/superTabs/buddies.js'-import { INBOX_READS, INBOX_WINDOW_MS, LATEST_CHATS, MAX_THREADS, newestInThreads, perRange, PREVIEW_CHARS, resetInboxReads, SCAN_FIELDS, THREAD_CHATS } from '../src/superTabs/read/inbox.js'+import { INBOX_READS, INBOX_WINDOW_MS, LATEST_CHATS, MAX_THREADS, newestInThreads, perRange, PREVIEW_CHARS, resetInboxReads, SCAN_FIELDS, THREAD_CHATS, UNREAD_SCAN } from '../src/superTabs/read/inbox.js'import { SEED_SCAN } from '../src/superTabs/read/threadMarkSeeds.js'+import { resetRangeCache } from '../src/superTabs/read/rangeCache.js'import { stableId, type Author, type Conversation, type SuperTabState } from '../src/superTabs/model.js'import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'import { NOW, outsider as outsiderActor, owner as ownerActor, peer as peerActor, swarm } from '../src/superTabs/read/fixture.test-support.js'@@ -194,7 +195,7 @@ async function busyScene() {return { ...s, webRoot, webLatest }}-beforeEach(() => resetInboxReads())+beforeEach(() => { resetInboxReads(); resetRangeCache() })describe('a person\'s inbox: unread threads and each chat\'s latest message', () => {it('gives a collaborator exactly the chats the messages read gives them: their own Buddy chat, never the private project or the closed chat', async () => {@@ -822,6 +823,105 @@ describe('what the inbox costs the database', () => {}, 120_000)})+// Ken's slow log of 11-04: a getMore of `{tabId, conversationId, sequence $gt}` returning ~419 rows was 32% of the evening's slow+// message ops. It was the unread scan's second batch: its union over the unread chats asked for Mongo's default first batch.+describe('the inbox\'s scan of unread chats', () => {+ it(`reads ${THREAD_CHATS} unread chats of ${UNREAD_SCAN + 1} rows each in one operation, never a getMore`, async () => {+ const s = await scene(f => { for (let i = 0; i < THREAD_CHATS; i++) f.group(`Busy ${i}`) })+ const chats = (await store.readLoad(peer, s.tabId)).state.conversations.filter(c => c.title.startsWith('Busy ')).map(c => c.id)+ for (const chat of chats) {+ const [root] = await insert(s.tabId, chat, [{ text: `Root in ${chat}`, author: personAuthor(owner), mentions: [peer.sub] }])+ await markRead(s.tabId, chat, await sequenceOf(root!), peer)+ await insert(s.tabId, chat, Array.from({ length: UNREAD_SCAN + 5 }, (_, i) => ({ text: `Reply ${i}`, author: agentAuthor(s.worker), thread: root })))+ }+ const entries = await profiled(db, async () => expect((await inbox(s.tabId, peer)).status).toBe(200))+ const messages = entries.filter(e => e.ns.endsWith('.SuperTabMessage'))+ expect(messages.filter(e => e.op === 'getmore'), JSON.stringify(messages.map(e => [e.op, e.nreturned]))).toEqual([])+ const scan = messages.filter(e => e.op !== 'getmore' && JSON.stringify(filterOf(e)).includes('"$gt"'))+ expect(scan.reduce((n, e) => n + (e.nreturned ?? 0), 0)).toBe(THREAD_CHATS * (UNREAD_SCAN + 1))+ }, 120_000)+})++// Ken's slow log of 11-04: the `$or` over threads' ranges (66% of the peak's slow message ops) and the chats' unread scans were read+// again on every inbox read, which apps make whenever the Swarm moves, though most of the ranges had not changed. A range is kept+// (read/rangeCache.ts) under its chat's newest sequence and reactionSeq, which every new row, edit and delete moves.+describe('re-reading the inbox', () => {+ /** Peer in two chats. Web: peer's root, read in the thread at the first of two worker replies, then the chat read past a main+ * message, so the thread's mark is behind the chat's. Other: owner's root tagging peer, read at the root, then two worker+ * replies. */+ async function rereadScene() {+ const s = await scene(f => { f.group('Other') })+ const other = (await store.readLoad(peer, s.tabId)).state.conversations.find(c => c.title === 'Other')!.id+ const [webRoot] = await insert(s.tabId, s.web, [{ text: 'Web root', author: personAuthor(peer) }])+ await markRead(s.tabId, s.web, await sequenceOf(webRoot!), peer)+ const [first] = await insert(s.tabId, s.web, [{ text: 'Web 1', author: agentAuthor(s.worker), thread: webRoot }])+ await insert(s.tabId, s.web, [{ text: 'Web 2', author: agentAuthor(s.worker), thread: webRoot }])+ const response = await app.inject({ method: 'POST', url: `/api/super-tabs/${s.tabId}/conversations/${s.web}/threads/${webRoot}/read`,+ headers: { authorization: `Bearer ${peer.sub}` }, payload: { sequence: await sequenceOf(first!) } })+ expect(response.statusCode).toBe(200)+ const [main] = await insert(s.tabId, s.web, [{ text: 'Web main', author: personAuthor(owner) }])+ await markRead(s.tabId, s.web, await sequenceOf(main!), peer)+ const [otherRoot] = await insert(s.tabId, other, [{ text: 'Other root', author: personAuthor(owner), mentions: [peer.sub] }])+ await markRead(s.tabId, other, await sequenceOf(otherRoot!), peer)+ await insert(s.tabId, other, [1, 2].map(i => ({ text: `Other ${i}`, author: agentAuthor(s.worker), thread: otherRoot })))+ return { ...s, other, webRoot: webRoot!, otherRoot: otherRoot! }+ }+ /** The message reads that read a range of rows (by sequence), and what they cost. */+ const ranges = (entries: ProfileEntry[]) => entries.filter(e => e.ns.endsWith('.SuperTabMessage') && JSON.stringify(filterOf(e) ?? {}).includes('"sequence"'))+ const cost = (entries: ProfileEntry[]) => {+ const messages = entries.filter(e => e.ns.endsWith('.SuperTabMessage'))+ return { reads: messages.length, ranges: ranges(entries).length, docsExamined: messages.reduce((n, e) => n + (e.docsExamined ?? 0), 0),+ returned: messages.reduce((n, e) => n + (e.nreturned ?? 0), 0), bytes: messages.reduce((n, e) => n + (e.responseLength ?? 0), 0) }+ }+ const read = async (tabId: string) => {+ let body: any+ const entries = await profiled(db, async () => { const reply = await inbox(tabId, peer); expect(reply.status).toBe(200); body = reply.body.data })+ return { body, entries }+ }++ it('reads no range again when nothing in it changed, and answers the same', async () => {+ const s = await rereadScene()+ const cold = await read(s.tabId)+ expect(threadsOf(cold.body).sort((a, b) => a.root < b.root ? -1 : 1)).toEqual([+ { chat: s.other, root: 'Other root', unread: 2, last: s.worker }, { chat: s.web, root: 'Web root', unread: 1, last: s.worker }])+ const warm = await read(s.tabId)+ console.info(`inbox message reads, cold: ${JSON.stringify(cost(cold.entries))}; re-read unchanged: ${JSON.stringify(cost(warm.entries))}`)+ expect(ranges(cold.entries).length).toBeGreaterThan(0)+ expect(ranges(warm.entries), JSON.stringify(ranges(warm.entries).map(filterOf))).toEqual([])+ expect(warm.body).toEqual(cold.body)+ })++ it('reads again only the chat a new reply is in, and counts it', async () => {+ const s = await rereadScene()+ await read(s.tabId)+ await insert(s.tabId, s.other, [{ text: 'Other 3', author: agentAuthor(s.worker), thread: s.otherRoot }])+ const after = await read(s.tabId)+ const named = ranges(after.entries).map(e => JSON.stringify(filterOf(e)))+ expect(named.length).toBeGreaterThan(0)+ for (const filter of named) {+ expect(filter).toContain(s.other)+ expect(filter).not.toContain(s.web)+ }+ expect(threadsOf(after.body).find(t => t.chat === s.other)!.unread).toBe(3)+ expect(threadsOf(after.body).find(t => t.chat === s.web)!.unread).toBe(1)+ })++ it('no longer counts a reply deleted after it was read', async () => {+ const s = await rereadScene()+ const reply = await send(s.tabId, s.web, 'Owner reply', { replyTo: s.webRoot })+ expect(threadsOf((await read(s.tabId)).body).find(t => t.chat === s.web)).toMatchObject({ unread: 2, last: owner.sub })+ await store.execute(owner, s.tabId, { operationId: randomUUID(), command: { type: 'message.delete', conversationId: s.web, messageId: reply.id } })+ expect(await db.superTabMessage.findUnique({ where: { id: reply.id } })).toBeNull()+ expect(threadsOf((await read(s.tabId)).body).find(t => t.chat === s.web)).toMatchObject({ unread: 1, last: s.worker })+ })++ it('never answers one Swarm\'s rows for another\'s same chat numbers', async () => {+ const a = await rereadScene(), b = await rereadScene()+ expect(threadsOf((await read(a.tabId)).body).map(t => t.chat).sort()).toEqual([a.other, a.web].sort())+ expect(threadsOf((await read(b.tabId)).body).map(t => t.chat).sort()).toEqual([b.other, b.web].sort())+ })+})+// Task #2148: Ken's profile showed these reads spending their time racing two plans per range, in a union no hint can reach.describe('reading many thread ranges at once', () => {/** What one pipeline per thread answers, as these reads were written before: the answers the single read must keep. */diff --git a/backend/integration/superTabNamedReads.test.ts b/backend/integration/superTabNamedReads.test.tsindex 874ce9d50..68743289c 100644--- a/backend/integration/superTabNamedReads.test.ts+++ b/backend/integration/superTabNamedReads.test.ts@@ -8,7 +8,7 @@ import { listGroupIndexes, NAMED_INDEX, retryStaleIndex } from '../src/superTabsimport { logger } from '../src/utils/logger.js'import { SwarmReads } from '../src/superTabs/read/service.js'import { SwarmWorkspaces } from '../src/superTabs/workspaceStore.js'-import { agentOpenDeliveries } from '../src/superTabs/pageReads.js'+import { agentOpenDeliveries, storedMessages } from '../src/superTabs/pageReads.js'import { loadChanged } from '../src/superTabs/parts/index.js'import { planDatabase, plan, profiled, reads } from './plans.test-support.js'@@ -363,6 +363,51 @@ describe('the rows a page points at', () => {})})+// Ken's slow log of 11-04: 8% of the slow SuperTabMessage ops were an `$expr $and[$eq]` read on `_id`, ~101 rows for 1 s: the+// check of a machine report's or a Lead poll's notices already stored (store.ts writeMessages), sent by Prisma's `id: { in }`.+describe('the stored notices a time check keeps', () => {+ it('are read by a plain id match through the id index, examining only the rows it returns', async () => {+ const tabId = `tab-${randomUUID()}`+ const author = { kind: 'agent', id: 'lead', name: 'Lead', membershipGeneration: tabId }+ const ids = Array.from({ length: 101 }, (_, i) => `${tabId}-notice-${i}`)+ await db.superTabMessage.createMany({ data: [+ ...ids.map((id, i) => ({ id, tabId, conversationId: `chat-${i % 3}`, sequence: i + 1, text: id, author, recipientIds: [], mentions: [],+ source: { kind: 'work-lost', worker: `w-${i}` } })),+ // Rows of the same Swarm the read must not examine.+ ...Array.from({ length: 50 }, (_, i) => ({ id: `${tabId}-other-${i}`, tabId, conversationId: 'chat-0', sequence: 200 + i, text: 'other', author,+ recipientIds: [], mentions: [] })),+ ] })+ let found: Awaited<ReturnType<typeof storedMessages>> = []+ const entries = await profiled(db, async () => { found = await storedMessages(db, [...ids, `${tabId}-missing`]) })+ expect(found.map(m => m.id).sort()).toEqual([...ids].sort())+ expect(found.find(m => m.id === ids[4])).toEqual({ id: ids[4], tabId, conversationId: 'chat-1', source: { kind: 'work-lost', worker: 'w-4' } })+ const rows = entries.filter(e => e.ns.endsWith('.SuperTabMessage'))+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)+ expect(JSON.stringify(rows[0]!.command), 'no $expr').not.toContain('$expr')+ expect(rows[0]!.planSummary).toBe('IXSCAN { _id: 1 }')+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBe(101)+ expect(rows[0]!.nreturned).toBe(101)+ console.info(`stored notices by id: ${JSON.stringify(plan(rows))}`)+ })++ it('answers each source as Prisma reads it, so a notice already stored is kept, not written twice', async () => {+ const tabId = `tab-${randomUUID()}`+ const author = { kind: 'agent', id: 'lead', name: 'Lead', membershipGeneration: tabId }+ // What a lost task's notice holds: ids, a time in ms past 2^31, a fraction, a list and a nested object.+ const source = { kind: 'work-lost', worker: 'w-1', assignmentId: 'a-1', at: 1793804932778, share: 0.25, ids: ['x', 'y'], why: { code: 'stalled', n: 3 } }+ await db.superTabMessage.create({ data: { id: `${tabId}-n`, tabId, conversationId: 'c', sequence: 1, text: 'n', author, recipientIds: [], mentions: [], source } })+ const prisma = await db.superTabMessage.findUniqueOrThrow({ where: { id: `${tabId}-n` }, select: { source: true } })+ const [found] = await storedMessages(db, [`${tabId}-n`])+ expect(found!.source).toStrictEqual(prisma.source)+ expect(found!.source).toStrictEqual(source)+ })++ it('reads nothing for no ids', async () => {+ const entries = await profiled(db, async () => { expect(await storedMessages(db, [])).toEqual([]) })+ expect(entries.filter(e => e.ns.endsWith('.SuperTabMessage'))).toEqual([])+ })+})+describe('who a named read answers', () => {it('a Swarm list leaves out a Swarm the person was removed from, and one of another environment', async () => {const me = await signedIn('removed')diff --git a/backend/src/superTabs/hotFilters.allowed.json b/backend/src/superTabs/hotFilters.allowed.jsonindex 9188c1e93..52242d03b 100644--- a/backend/src/superTabs/hotFilters.allowed.json+++ b/backend/src/superTabs/hotFilters.allowed.json@@ -20,7 +20,6 @@"src/superTabs/store.ts superTabDelivery.findFirst": 1,"src/superTabs/store.ts superTabDelivery.findMany": 1,"src/superTabs/store.ts superTabDelivery.updateMany": 11,- "src/superTabs/store.ts superTabMessage.findMany": 1,"src/superTabs/store.ts superTabOperation.findMany": 1,"src/superTabs/store.ts superTabRun.deleteMany": 1,"src/superTabs/store.ts superTabTerminalRequest.count": 1,diff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.tsindex 5e9682358..134e2188b 100644--- a/backend/src/superTabs/pageReads.ts+++ b/backend/src/superTabs/pageReads.ts@@ -176,6 +176,17 @@ export async function messagesById(tx: Transaction, tabId: string, conversationI})}+/**+ * The stored rows with these ids, whichever Swarm or conversation holds them: what a machine report's or a Lead poll's time+ * check compares its notices with before it writes them (store.ts writeMessages keepStored). A plain `_id` match through the id+ * index; Prisma's `id: { in }` sent it as `$expr` (8% of the slow message reads in Ken's log of 11-04, ~1 s for 101 rows).+ */+export async function storedMessages(tx: Transaction, ids: string[]): Promise<Array<{ id: string; tabId: string; conversationId: string; source: unknown }>> {+ if (!ids.length) return []+ const rows = await readBy(tx, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: ids } } }, { $project: { tabId: 1, conversationId: 1, source: 1 } }])+ return rows.map(row => ({ id: row._id as string, tabId: row.tabId as string, conversationId: row.conversationId as string, source: row.source ?? null }))+}+/** The Lead's notices that leave a copy in a task's chat when the Lead hears them in its own chat (terminal.ts toLead). */const LEAD_COPY_KINDS = new Set<unknown>(['work-lost', 'work-resumed'])diff --git a/backend/src/superTabs/read/inbox.ts b/backend/src/superTabs/read/inbox.tsindex 2d032444b..a09b23f48 100644--- a/backend/src/superTabs/read/inbox.ts+++ b/backend/src/superTabs/read/inbox.ts@@ -31,10 +31,11 @@ import { threadSummaries } from '../threads.js'import { sessionReadsRow } from '../buddySessions.js'import { readMarks, readThreadMarkRows, type ThreadMarkRow } from '../readMarks.js'import { voiceLabel } from '../voiceMessages.js'-import { readBy } from '../parts/indexed.js'+import { READ_BATCH, readBy } from '../parts/indexed.js'import { logger } from '../../utils/logger.js'import { ms } from '../parts/light.js'import type { SuperTabStore } from '../store.js'+import { chatTop, chatVersion, rangeCache, rangeKey } from './rangeCache.js'/** Rows past the read mark read per chat: the newest ones, so the latest replies are always counted. */export const UNREAD_SCAN = 100@@ -150,15 +151,45 @@ export async function perRange(db: PrismaClient, pipelines: Prisma.InputJsonValuconst rows: Row[] = []for (let i = 0; i < pipelines.length; i += CHATS_PER_READ) {const [first, ...rest] = pipelines.slice(i, i + CHATS_PER_READ)+ // Every row in the first reply (READ_BATCH, as readBy asks): Mongo's default first batch of 101 left the rest of 30 chats'+ // scans to a getMore, 32% of the slow message ops in Ken's log of 11-04 (~419 rows each).const raw = await db.superTabMessage.aggregateRaw({ pipeline: [...first!,- ...rest.map(pipeline => ({ $unionWith: { coll: 'SuperTabMessage', pipeline } }))] }) as unknown as Array<Record<string, unknown>>+ ...rest.map(pipeline => ({ $unionWith: { coll: 'SuperTabMessage', pipeline } }))], options: { batchSize: READ_BATCH } }) as unknown as Array<Record<string, unknown>>rows.push(...raw.map(row))}return rows}-/** One thread's rows in a sequence range. */-export interface ThreadRange { conversationId: string; thread: string; sequence: Record<string, number> }+/** One thread's rows in a sequence range. With `version` (its chat's chatVersion) and bounds no new row can enter (at most+ * the chat's chatTop), its rows are kept and a re-read of it reads nothing (rangeCache.ts). */+export interface ThreadRange { conversationId: string; thread: string; sequence: Record<string, number>; version?: number }++/** The ranges this process kept (rangeCache.ts): chats' scans and previews, and threads' ranges. */+const kept = rangeCache<Row>()++/** Each chat's `limit` newest rows in its range, newest first, chat by chat, as perRange of each chat's newestIn answers: a range+ * kept since its chat last changed is not read again, and only the others are, in one perRange. `fields` names the projection+ * in the key. Each range must be bounded by its chat's chatTop. */+async function chatRanges(db: PrismaClient, tabId: string, of: ReadonlyArray<{ group: Conversation; sequence: Record<string, number> }>,+ limit: number, fields: 'scan' | 'preview'): Promise<Row[]> {+ const keyed = of.map(c => ({ ...c, key: rangeKey(tabId, c.group.id, null, c.sequence, limit, chatVersion(c.group), fields) }))+ const held = new Map<string, Row[]>()+ const misses = keyed.filter(c => {+ const rows = kept.get(c.key)+ if (rows) held.set(c.key, rows)+ return !rows+ })+ if (misses.length) {+ const read = groupBy(await perRange(db, misses.map(c => newestIn(tabId, c.group.id, c.sequence, limit, fields === 'scan' ? SCAN_FIELDS : FIELDS))),+ m => m.conversationId)+ for (const c of misses) {+ const rows = read.get(c.group.id) ?? []+ kept.set(c.key, rows)+ held.set(c.key, rows)+ }+ }+ return keyed.flatMap(c => held.get(c.key)!)+}/*** Each range's newest `limit` rows, newest first, range by range, as `perRange` of each thread's own pipeline answers, or only those@@ -168,7 +199,26 @@ export interface ThreadRange { conversationId: string; thread: string; sequence:* so past a cap of a quarter of what the ranges' limits allow, a batch of long threads takes the union instead, which bounds each one.*/export async function newestInThreads(db: PrismaClient, tabId: string, ranges: ThreadRange[], limit: number, namedBy?: string): Promise<Row[]> {- const rows: Row[] = []+ // A range kept since its chat last changed is not read again (rangeCache.ts); only the others go to the database.+ const keyOf = (r: ThreadRange) => r.version === undefined ? undefined : rangeKey(tabId, r.conversationId, r.thread, r.sequence, limit, r.version, 'scan', namedBy)+ const held = new Map<ThreadRange, Row[]>()+ const misses = ranges.filter(r => {+ const key = keyOf(r), rows = key === undefined ? undefined : kept.get(key)+ if (rows) held.set(r, rows)+ return !rows+ })+ const read = misses.length ? await readThreadRanges(db, tabId, misses, limit, namedBy) : new Map<string, Row[]>()+ for (const r of misses) {+ const rows = read.get(threadKey(r.conversationId, r.thread)) ?? [], key = keyOf(r)+ if (key !== undefined) kept.set(key, rows)+ held.set(r, rows)+ }+ return ranges.flatMap(r => held.get(r)!)+}++/** newestInThreads' reads, each thread's rows by threadKey. */+async function readThreadRanges(db: PrismaClient, tabId: string, ranges: ThreadRange[], limit: number, namedBy?: string): Promise<Map<string, Row[]>> {+ const rows = new Map<string, Row[]>()const named = namedBy === undefined ? [] : [{ $match: { $or: [{ 'author.kind': 'person', 'author.id': namedBy }, { mentions: namedBy }] } }]for (let i = 0; i < ranges.length; i += CHATS_PER_READ) {const batch = ranges.slice(i, i + CHATS_PER_READ)@@ -185,12 +235,12 @@ export async function newestInThreads(db: PrismaClient, tabId: string, ranges: TArray<{ _id: { conversationId: string; thread: string }; seen: number; newest: Array<Record<string, unknown>> }>if (found.reduce((seen, thread) => seen + Number(thread.seen), 0) > cap) {logger.info('[inbox] a batch of thread ranges passed its cap and read by union', { ranges: batch.length, limit })- rows.push(...await perRange(db, batch.map(r => [{ $match: { tabId, conversationId: r.conversationId, thread: r.thread, sequence: r.sequence } },- { $sort: { sequence: -1 } }, { $limit: limit }, ...named, { $project: { ...SCAN_FIELDS, conversationId: 1 } }] as Prisma.InputJsonValue[])))+ const each = await perRange(db, batch.map(r => [{ $match: { tabId, conversationId: r.conversationId, thread: r.thread, sequence: r.sequence } },+ { $sort: { sequence: -1 } }, { $limit: limit }, ...named, { $project: { ...SCAN_FIELDS, conversationId: 1 } }] as Prisma.InputJsonValue[]))+ for (const [key, found] of groupBy(each, m => threadKey(m.conversationId, m.thread!))) rows.set(key, found)continue}- const byThread = new Map(found.map(thread => [threadKey(thread._id.conversationId, thread._id.thread), thread.newest]))- for (const r of batch) rows.push(...(byThread.get(threadKey(r.conversationId, r.thread)) ?? []).map(row))+ for (const thread of found) rows.set(threadKey(thread._id.conversationId, thread._id.thread), thread.newest.map(row))}return rows}@@ -217,8 +267,12 @@ export async function namedInThreads(db: PrismaClient, tabId: string, state: Supfor (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 } })),- MEMBER_SCAN, personId)+ const groups = new Map(state.conversations.map(g => [g.id, g]))+ const rows = await newestInThreads(db, tabId, scanned.map(t => {+ const group = groups.get(t.conversationId)+ return { conversationId: t.conversationId, thread: t.thread, ...group+ ? { sequence: { $lte: Math.min(t.sequence, chatTop(group)) }, version: chatVersion(group) } : { sequence: { $lte: t.sequence } } }+ }), MEMBER_SCAN, personId)for (const m of await readable(db, tabId, rows, state)) named.add(threadKey(m.conversationId, m.thread!))}return named@@ -232,14 +286,14 @@ const newestIn = (tabId: string, conversationId: string, sequence: Record<string* before it only for a chat where that row is not one (an older chat's newest row may be a thread reply or a hidden copy).* `more` when such a chat has none in that range. */export async function latestIn(db: PrismaClient, tabId: string, state: SuperTabState, chats: Conversation[]): Promise<{ latest: Map<string, Row>; more: boolean }> {- const tops = chats.flatMap(g => { const top = g.lastMainSequence ?? g.lastMessageSequence; return top ? [{ id: g.id, top }] : [] })+ const tops = chats.flatMap(g => { const top = g.lastMainSequence ?? g.lastMessageSequence; return top ? [{ id: g.id, top, group: g }] : [] })const pick = async (rows: Row[]) => {const shown = (await readable(db, tabId, rows, state)).filter(isMain)const newest = new Map<string, Row>()for (const m of shown) if (!newest.has(m.conversationId)) newest.set(m.conversationId, m)return newest}- const read = (of: typeof tops, limit: number) => perRange(db, of.map(c => newestIn(tabId, c.id, { $lte: c.top }, limit, FIELDS)))+ const read = (of: typeof tops, limit: number) => chatRanges(db, tabId, of.map(c => ({ group: c.group, sequence: { $lte: Math.min(c.top, chatTop(c.group)) } })), limit, 'preview')const latest = await pick(await read(tops, 1))const missing = tops.filter(c => !latest.has(c.id))if (!missing.length) return { latest, more: false }@@ -277,8 +331,14 @@ async function threadsIn(db: PrismaClient, tabId: string, state: SuperTabState,const own = (a: Pick<Author, 'kind' | 'id'>) => a.kind === 'person' && a.id === personIdconst inIt = (m: Row) => own(m.author) || m.mentions.includes(personId)const lagging = behind.slice(0, BEHIND_THREADS)- const [scanned, past] = await Promise.all([perRange(db, chats.map(g => newestIn(tabId, g.id, { $gt: marks.get(g.id)! }, UNREAD_SCAN + 1, SCAN_FIELDS))),- newestInThreads(db, tabId, lagging.map(r => ({ conversationId: r.conversationId, thread: r.threadId, sequence: { $gt: r.sequence } })), UNREAD_SCAN + 1)])+ // Each range bounded by its chat's newest row and kept (rangeCache.ts): a re-read reads only the chats that moved.+ const chatOf = new Map(readableChats.map(g => [g.id, g]))+ const [scanned, past] = await Promise.all([chatRanges(db, tabId, chats.map(g => ({ group: g, sequence: { $gt: marks.get(g.id)!, $lte: chatTop(g) } })),+ UNREAD_SCAN + 1, 'scan'),+ newestInThreads(db, tabId, lagging.map(r => {+ const group = chatOf.get(r.conversationId)!+ return { conversationId: r.conversationId, thread: r.threadId, sequence: { $gt: r.sequence, $lte: chatTop(group) }, version: chatVersion(group) }+ }), UNREAD_SCAN + 1)])const byChat = groupBy(scanned, m => m.conversationId)const pastByThread = groupBy(past, m => threadKey(m.conversationId, m.thread!))// A chat or thread whose newest UNREAD_SCAN rows do not reach its mark: older unread replies are not counted.diff --git a/backend/src/superTabs/read/rangeCache.test.ts b/backend/src/superTabs/read/rangeCache.test.tsnew file mode 100644index 000000000..35a2ae1e0--- /dev/null+++ b/backend/src/superTabs/read/rangeCache.test.ts@@ -0,0 +1,91 @@+import { describe, expect, it } from 'vitest'+import { chatTop, rangeKey, RangeCache } from './rangeCache.js'++describe('the range cache', () => {+ const limits = { entries: 3, rows: 10, ttlMs: 1_000 }++ it('answers what was set under a key as a copy, and nothing for another key', () => {+ const cache = new RangeCache<{ id: string }>(limits, () => 0)+ const rows = [{ id: 'a' }, { id: 'b' }]+ cache.set('k', rows)+ const got = cache.get('k')!+ expect(got).toEqual(rows)+ got.pop()+ expect(cache.get('k')).toEqual(rows)+ expect(cache.get('other')).toBeUndefined()+ })++ it('keeps an empty range, so a range with no rows is not read again', () => {+ const cache = new RangeCache<{ id: string }>(limits, () => 0)+ cache.set('empty', [])+ expect(cache.get('empty')).toEqual([])+ })++ it('drops the least recently used entry past its entry limit', () => {+ const cache = new RangeCache<{ id: string }>(limits, () => 0)+ for (const key of ['a', 'b', 'c']) cache.set(key, [{ id: key }])+ cache.get('a')+ cache.set('d', [{ id: 'd' }])+ expect(cache.get('b')).toBeUndefined()+ expect(['a', 'c', 'd'].map(key => cache.get(key)?.[0]?.id)).toEqual(['a', 'c', 'd'])+ })++ it('drops the oldest entries past its row limit, and never holds a range larger than it', () => {+ const cache = new RangeCache<{ id: string }>(limits, () => 0)+ const of = (n: number) => Array.from({ length: n }, (_, i) => ({ id: String(i) }))+ cache.set('six', of(6))+ cache.set('four', of(4))+ expect(cache.get('six')).toHaveLength(6)+ cache.set('two', of(2))+ // 12 rows held: the least recently used (four) goes.+ expect(cache.get('four')).toBeUndefined()+ expect(cache.size()).toEqual({ entries: 2, rows: 8 })+ cache.set('huge', of(11))+ expect(cache.get('huge')).toBeUndefined()+ expect(cache.size()).toEqual({ entries: 2, rows: 8 })+ })++ it('forgets an entry past its time to live', () => {+ let now = 0+ const cache = new RangeCache<{ id: string }>(limits, () => now)+ cache.set('k', [{ id: 'a' }])+ now = 1_000+ expect(cache.get('k')).toHaveLength(1)+ now = 1_001+ expect(cache.get('k')).toBeUndefined()+ expect(cache.size()).toEqual({ entries: 0, rows: 0 })+ })++ it('replacing a key counts its rows once', () => {+ const cache = new RangeCache<{ id: string }>(limits, () => 0)+ cache.set('k', [{ id: 'a' }, { id: 'b' }])+ cache.set('k', [{ id: 'c' }])+ expect(cache.size()).toEqual({ entries: 1, rows: 1 })+ })+})++describe('a range\'s key', () => {+ const base = { tabId: 't', conversationId: 'c', thread: 'r', sequence: { $gt: 5, $lte: 9 }, limit: 101, version: 2 }+ const key = (over: Partial<typeof base> & { namedBy?: string; fields?: string } = {}) => {+ const k = { ...base, ...over }+ return rangeKey(k.tabId, k.conversationId, k.thread, k.sequence, k.limit, k.version, k.fields ?? 'scan', k.namedBy)+ }++ it('differs whenever anything that decides the range\'s rows differs', () => {+ const keys = [key(), key({ tabId: 'u' }), key({ conversationId: 'd' }), key({ thread: 's' }), key({ sequence: { $gt: 5, $lte: 10 } }),+ key({ sequence: { $gt: 6, $lte: 9 } }), key({ limit: 100 }), key({ version: 3 }), key({ namedBy: 'p' }), key({ fields: 'preview' })]+ expect(new Set(keys).size).toBe(keys.length)+ })++ it('cannot be forged by an id holding the separator', () => {+ expect(key({ tabId: 'a\u0000b', conversationId: 'c' })).not.toBe(key({ tabId: 'a', conversationId: 'b\u0000c' }))+ })+})++describe('a chat\'s newest sequence', () => {+ it('is the newest of its numbered rows, a hidden one too', () => {+ expect(chatTop({ messageSeq: 12, lastMessageSequence: 10 })).toBe(12)+ expect(chatTop({ lastMessageSequence: 10 })).toBe(10)+ expect(chatTop({ messageSeq: 3, lastMessageSequence: 10 })).toBe(10)+ })+})diff --git a/backend/src/superTabs/read/rangeCache.ts b/backend/src/superTabs/read/rangeCache.tsnew file mode 100644index 000000000..f7e7a5fc7--- /dev/null+++ b/backend/src/superTabs/read/rangeCache.ts@@ -0,0 +1,92 @@+/**+ * The message ranges the inbox and the Threads view read (inbox.ts), kept per process so a re-read of a range nothing changed in+ * reads nothing. Apps read the inbox whenever the Swarm moves, about once a second in a busy one, and most of the ranges a read+ * names have not changed since the last: in Ken's slow log of 11-04 those re-reads (the `$or` over threads and each chat's+ * unread scan) were most of the slow message ops.+ *+ * Exact, never a guess: a range is keyed by its Swarm, chat, thread, sequence bounds, row limit and fields, and by its chat's+ * reactionSeq. A range is bounded above by the chat's newest numbered row (chatTop), so a new row is outside every range kept+ * before it; an edit and a delete bump reactionSeq (messageEdits.ts), so no range kept before them is read again. Rows are the+ * stored rows, the same for every reader: each read still applies its reader's checks to them (inbox.ts readable).+ *+ * Design. Growth: at most RANGE_ENTRIES ranges and RANGE_ROWS rows, least recently used out first, each gone after+ * RANGE_TTL_MS. Concurrency: one process's Map, no lock; two reads of one range may both read it and the later one stays.+ * Scale: rows held are SCAN_FIELDS or a preview (~0.3-1 KB), so 200k rows stay under ~200 MB at worst; a pod's memory warns first.+ * Compatibility: old and new pods read the same rows; nothing is stored. Rollback: none needed. Failure: a miss reads Mongo.+ */++export interface RangeLimits { entries: number; rows: number; ttlMs: number }++export class RangeCache<T> {+ private readonly held = new Map<string, { rows: T[]; at: number }>()+ private rows = 0++ constructor(private readonly limits: RangeLimits, private readonly now: () => number = Date.now) {}++ /** The rows kept under `key`, as a new list, or undefined when none are (or they are past their time). */+ get(key: string): T[] | undefined {+ const entry = this.held.get(key)+ if (!entry) return undefined+ this.held.delete(key)+ if (this.now() - entry.at > this.limits.ttlMs) {+ this.rows -= entry.rows.length+ return undefined+ }+ this.held.set(key, entry)+ return [...entry.rows]+ }++ /** Keeps `rows` under `key`; a range larger than the whole budget is not kept. */+ set(key: string, rows: readonly T[]): void {+ const old = this.held.get(key)+ if (old) {+ this.held.delete(key)+ this.rows -= old.rows.length+ }+ if (rows.length > this.limits.rows) return+ this.held.set(key, { rows: [...rows], at: this.now() })+ this.rows += rows.length+ for (const [oldest, entry] of this.held) {+ if (this.held.size <= this.limits.entries && this.rows <= this.limits.rows) break+ this.held.delete(oldest)+ this.rows -= entry.rows.length+ }+ }++ size(): { entries: number; rows: number } {+ return { entries: this.held.size, rows: this.rows }+ }++ clear(): void {+ this.held.clear()+ this.rows = 0+ }+}++/** The key of one range: every part that decides its rows, each JSON-quoted so no id can stand for two parts. */+export function rangeKey(tabId: string, conversationId: string, thread: string | null, sequence: Record<string, number>, limit: number,+ version: number, fields: string, namedBy?: string): string {+ return JSON.stringify([tabId, conversationId, thread, sequence, limit, version, fields, namedBy ?? null])+}++/** A chat's newest numbered row: a hidden one (recipients only) moves messageSeq but not lastMessageSequence. A range bounded by+ * it holds every row a read of it could find, and none written after. */+export const chatTop = (group: { messageSeq?: number; lastMessageSequence?: number }): number =>+ Math.max(group.messageSeq ?? 0, group.lastMessageSequence ?? 0)++/** What an edit or a delete in the chat moves (messageEdits.ts), with reactions. */+export const chatVersion = (group: { reactionSeq?: number }): number => group.reactionSeq ?? 0++export const RANGE_ENTRIES = 4_000+export const RANGE_ROWS = 200_000+export const RANGE_TTL_MS = 10 * 60_000++/** Test seam: forget every kept range (inbox.ts holds them). */+export const resetRangeCache = (): void => { for (const clear of clears) clear() }+const clears: Array<() => void> = []+/** A cache whose ranges resetRangeCache forgets. */+export function rangeCache<T>(): RangeCache<T> {+ const cache = new RangeCache<T>({ entries: RANGE_ENTRIES, rows: RANGE_ROWS, ttlMs: RANGE_TTL_MS })+ clears.push(() => cache.clear())+ return cache+}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex c0a3b2217..821be0d09 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -22,7 +22,7 @@ import { applyCommand, authorizeCommandAccess, IGNORED_NOTE, LOOP_NOTICE_AT, mayimport { redactCredentials } from './credentials.js'import type { AvatarUpload } from './profile.js'import { reactionCounts, type ReactionTarget } from './reactions.js'-import { agentGatheredCount, agentGatheredDeliveries, agentOpenDeliveries, CANCELLABLE_DELIVERY, compactedDelivery, deliveredCopies, messagesById, messagesPast, OPEN_DELIVERY, type MessageEdge, pageDeliveries, pageReactions, pageThreads, refreshReplies, refreshThreads, type PageDelivery, type ThreadFacet } from './pageReads.js'+import { agentGatheredCount, agentGatheredDeliveries, agentOpenDeliveries, CANCELLABLE_DELIVERY, compactedDelivery, deliveredCopies, messagesById, messagesPast, OPEN_DELIVERY, type MessageEdge, pageDeliveries, pageReactions, pageThreads, refreshReplies, refreshThreads, storedMessages, type PageDelivery, type ThreadFacet } from './pageReads.js'import { deliveriesByMessage } from './read/pageDeliveries.js'import { restoreDelivery } from './deliveryCompaction.js'import { threadSummaries } from './threads.js'@@ -2819,8 +2819,7 @@ export class SuperTabStore {* (2026-10-28); any other message under the id still fails, so another task's notice is never delivered as this one. */private async writeMessages(tx: Transaction, tabId: string, state: SuperTabState, messages: MessageDraft[], sequences: ReadonlyMap<string, number>,keepStored = false): Promise<Map<string, ThreadFacet>> {- const stored = keepStored && messages.length ? await tx.superTabMessage.findMany({ where: { id: { in: messages.map(m => m.id) } },- select: { id: true, tabId: true, conversationId: true, source: true } }) : []+ const stored = keepStored ? await storedMessages(tx, messages.map(m => m.id)) : []const kept = new Set(stored.filter(row => messages.some(m => m.id === row.id && row.tabId === tabId && row.conversationId === m.conversationId&& isDeepStrictEqual(row.source ?? undefined, m.source))).map(row => row.id))if (kept.size) logger.warn('Kept Swarm notices already stored', { tabId, ids: [...kept] })diff --git a/desktop/lib/devices/devices_screen.dart b/desktop/lib/devices/devices_screen.dartindex 89ad99129..e52617ed0 100644--- a/desktop/lib/devices/devices_screen.dart+++ b/desktop/lib/devices/devices_screen.dart@@ -12,6 +12,7 @@ import '../shared/widgets/skeleton.dart';import '../shared/widgets/app_icon_button.dart';import '../core/test_run.dart';import '../state/app_state.dart';+import '../super_tabs/visible_tick.dart';import '../widgets/desktop_chrome.dart';import 'device_artwork.dart';import 'device_settings.dart';@@ -26,13 +27,19 @@ final harnessDeviceShopUrl = Uri.parse();class DevicesTab extends StatefulWidget {- const DevicesTab({super.key, required this.notifier});+ const DevicesTab({super.key, required this.notifier, this.refreshEvery});final AppNotifier notifier;++ /// How often the machines' devices are read again while the tab is seen. Null: every 10+ /// seconds, and never under test (where a test passes its own).+ @visibleForTesting+ final Duration? refreshEvery;@overrideState<DevicesTab> createState() => _DevicesTabState();}-class _DevicesTabState extends State<DevicesTab> {+class _DevicesTabState extends State<DevicesTab>+ with WidgetsBindingObserver, VisibleTick<DevicesTab> {late final controller = DevicesController(hosts: widget.notifier.deviceHosts,accountId: widget.notifier.currentUser?.id ?? 'guest',@@ -45,22 +52,26 @@ class _DevicesTabState extends State<DevicesTab> {late final wifi = WifiRobotsController(onLocalNetworkBlocked: widget.notifier.localNetworkBlocked,);- Timer? _refresh;+ late final _every =+ widget.refreshEvery ?? (kUnderTest ? null : const Duration(seconds: 10));@overridevoid initState() {super.initState();unawaited(widget.notifier.refreshDevices());- if (!kUnderTest) {- _refresh = Timer.periodic(- const Duration(seconds: 10),- (_) => unawaited(widget.notifier.refreshDevices()),- );- }+ // Again on the interval while the tab can be seen, and once as it is seen again.+ if (_every case final every?) visibleTick(every);+ }++ @override+ void onTick() => unawaited(widget.notifier.refreshDevices());++ @override+ void onScreenChanged(bool onScreen) {+ if (onScreen && _every != null) onTick();}@overridevoid dispose() {- _refresh?.cancel();controller.dispose();wifi.dispose();super.dispose();@@ -121,7 +132,8 @@ class DevicesScreen extends StatefulWidget {State<DevicesScreen> createState() => _DevicesScreenState();}-class _DevicesScreenState extends State<DevicesScreen> {+class _DevicesScreenState extends State<DevicesScreen>+ with WidgetsBindingObserver, VisibleTick<DevicesScreen> {String? _selectedKey;String? _shopError;final _cards = ScrollController();@@ -163,6 +175,16 @@ class _DevicesScreenState extends State<DevicesScreen> {widget.wifi?.start();}+ // The robots are read again only while the screen can be seen.+ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ widget.wifi?.seen = onScreen;+ }++ @override+ void onScreenChanged(bool onScreen) => widget.wifi?.seen = onScreen;+@overridevoid didUpdateWidget(DevicesScreen oldWidget) {super.didUpdateWidget(oldWidget);diff --git a/desktop/lib/devices/wifi_robots.dart b/desktop/lib/devices/wifi_robots.dartindex 447e8e93c..44d178d33 100644--- a/desktop/lib/devices/wifi_robots.dart+++ b/desktop/lib/devices/wifi_robots.dart@@ -25,14 +25,21 @@ import '../widgets/desktop_chrome.dart';/// dialog read the same state, so a pairing shows up in the list the moment the CLI confirms it./// The CLI keeps the trust and the connection; nothing here holds a code longer than one request.class WifiRobotsController extends ChangeNotifier {- WifiRobotsController({AutonomousDeviceCli? cli, this.onLocalNetworkBlocked})- : _injected = cli,- // Tests may inject a fake; without one under test nothing may reach a real CLI.- _inert = kUnderTest && cli == null;+ WifiRobotsController({+ AutonomousDeviceCli? cli,+ this.onLocalNetworkBlocked,+ Duration? refreshEvery,+ }) : _injected = cli,+ // Tests may inject a fake; without one under test nothing may reach a real CLI.+ _inert = kUnderTest && cli == null,+ // Under test no background clock runs unless the test asks for one (with its fake).+ _every =+ refreshEvery ?? (kUnderTest ? null : const Duration(seconds: 60));final AutonomousDeviceCli? _injected;late final AutonomousDeviceCli _cli = _injected ?? AutonomousDeviceCli();final bool _inert;+ final Duration? _every;/// Discovery found the local network refused: the app restarts a daemon it did not launch so it/// gets the app's permission (AppNotifier.localNetworkBlocked).@@ -40,6 +47,22 @@ class WifiRobotsController extends ChangeNotifier {Timer? _timer;bool _started = false, _refreshing = false, _disposed = false;+ bool _seen = true;++ /// Whether the robots can be seen, set by the screen that lists them (its `VisibleTick`).+ /// While they cannot, the CLI is not asked; when they can again, once at once, then every+ /// minute.+ bool get seen => _seen;+ set seen(bool seen) {+ if (seen == _seen) return;+ _seen = seen;+ _timer?.cancel();+ _timer = null;+ if (seen && _started && _every != null && !unsupported && !busy) {+ unawaited(refresh());+ }+ }+int _generation = 0;bool loading = true;@@ -81,10 +104,9 @@ class WifiRobotsController extends ChangeNotifier {void _scheduleRefresh() {_timer?.cancel();- // Tests may inject a fake for the initial fetch and user actions, but must- // never start a background clock or invoke a real CLI.- if (_disposed || kUnderTest || unsupported || busy) return;- _timer = Timer(const Duration(seconds: 60), () => unawaited(refresh()));+ final every = _every;+ if (_disposed || every == null || !_seen || unsupported || busy) return;+ _timer = Timer(every, () => unawaited(refresh()));}String _message(Object error) => error is AutonomousDeviceCliExceptiondiff --git a/desktop/lib/measurement/product_runtime_health.dart b/desktop/lib/measurement/product_runtime_health.dartindex 57c3f462d..87e586085 100644--- a/desktop/lib/measurement/product_runtime_health.dart+++ b/desktop/lib/measurement/product_runtime_health.dart@@ -203,8 +203,10 @@ class ProductRuntimeHealth {measurement.milestone(ProductHealthMeasure.funnelWorkspaceReady);}+ /// Only while the window is in sight: a hidden one made a report every minute for this sample+ /// alone (task #2953), and what it would say is the memory of an app nobody is using.void sampleResources() {- if (!_active || !measurement.sharing) return;+ if (!_active || !measurement.sharing || _hidden(_lifecycle())) return;try {final rss = ProcessInfo.currentRss;measurement.health(diff --git a/desktop/lib/orchestrator/orchestrator_workspace.dart b/desktop/lib/orchestrator/orchestrator_workspace.dartindex 670743b4f..30586bf87 100644--- a/desktop/lib/orchestrator/orchestrator_workspace.dart+++ b/desktop/lib/orchestrator/orchestrator_workspace.dart@@ -9,6 +9,7 @@ import '../shared/widgets/app_dialog.dart';import '../shared/widgets/app_icon_button.dart';import '../state/app_state.dart';import '../state/terminal_pane.dart';+import '../super_tabs/visible_tick.dart';import '../widgets/web_pane_panel.dart';import 'orchestrator_controller.dart';import 'orchestrator_launcher.dart';@@ -29,7 +30,8 @@ class OrchestratorWorkspace extends StatefulWidget {State<OrchestratorWorkspace> createState() => _OrchestratorWorkspaceState();}-class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace> {+class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace>+ with WidgetsBindingObserver, VisibleTick<OrchestratorWorkspace> {late final OrchestratorController model =widget.controller ??widget.notifier.orchestratorProject(widget.machineId, widget.projectId);@@ -39,12 +41,30 @@ class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace> {int _nextPane = -1;String? _expanded;+ /// Whether this view is one of [model]'s readers: only while it can be seen. A hidden app or a+ /// tab not showing reads nothing; seen again, [OrchestratorController.watch] reads at once.+ bool _watching = false;+@overridevoid initState() {super.initState();model.addListener(_changed);widget.notifier.addListener(_attentionChanged);- model.watch();+ }++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _follow(onScreen);+ }++ @override+ void onScreenChanged(bool onScreen) => _follow(onScreen);++ void _follow(bool seen) {+ if (seen == _watching) return;+ _watching = seen;+ seen ? model.watch() : model.unwatch();}void _attentionChanged() {@@ -70,7 +90,7 @@ class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace> {void dispose() {model.removeListener(_changed);widget.notifier.removeListener(_attentionChanged);- model.unwatch();+ if (_watching) model.unwatch();_composer.dispose();_composerFocus.dispose();_messagesScroll.dispose();diff --git a/desktop/lib/settings/experimental_features.dart b/desktop/lib/settings/experimental_features.dartindex dc4f01a07..43a8af4b1 100644--- a/desktop/lib/settings/experimental_features.dart+++ b/desktop/lib/settings/experimental_features.dart@@ -108,7 +108,21 @@ class ExperimentalFeaturesStore extends ChangeNotifier {ExperimentalFeaturesStore({this.pollInterval = safetyNet,this.retryInterval = const Duration(seconds: 30),- });+ ValueListenable<bool>? seen,+ }) : _seen = seen {+ seen?.addListener(_seenChanged);+ }++ /// Whether the window is in sight (`AppNotifier.inSight`); null is always. Out of sight the+ /// safety net reads nothing (task #2953): a read that comes due waits for the return.+ final ValueListenable<bool>? _seen;+ bool _owed = false;++ void _seenChanged() {+ if (_seen?.value != true || !_owed) return;+ _owed = false;+ unawaited(refresh());+ }/// The read with no push: a missed one. Every write is pushed/// (`desk_changed`, backend routes/experimentalSettings.ts), so the 30 s poll@@ -171,7 +185,12 @@ class ExperimentalFeaturesStore extends ChangeNotifier {void _look(Duration every) {final quiet =loaded && error == null && every * ++_quietLooks < pollInterval;- if (!quiet) unawaited(refresh());+ if (quiet) return;+ if (_seen?.value == false) {+ _owed = true;+ return;+ }+ unawaited(refresh());}void _notify() {@@ -296,6 +315,7 @@ class ExperimentalFeaturesStore extends ChangeNotifier {void dispose() {_disposed = true;_poll?.cancel();+ _seen?.removeListener(_seenChanged);super.dispose();}}diff --git a/desktop/lib/settings/sections/tab_invites_section.dart b/desktop/lib/settings/sections/tab_invites_section.dartindex b1b58e1d8..4e0b6a606 100644--- a/desktop/lib/settings/sections/tab_invites_section.dart+++ b/desktop/lib/settings/sections/tab_invites_section.dart@@ -13,6 +13,7 @@ import '../../shared/widgets/section_scaffold.dart';import '../../shared/widgets/setting_row.dart';import '../../state/app_state.dart';import '../../super_tabs/model.dart';+import '../../super_tabs/visible_tick.dart';/// Settings ▸ Tab invites: the invitations to shared tabs waiting for an/// answer, and the tabs whose owner's computer has a new key.@@ -25,12 +26,12 @@ class TabInvitesSection extends StatefulWidget {State<TabInvitesSection> createState() => _TabInvitesSectionState();}-class _TabInvitesSectionState extends State<TabInvitesSection> {+class _TabInvitesSectionState extends State<TabInvitesSection>+ with WidgetsBindingObserver, VisibleTick<TabInvitesSection> {List<Map<String, dynamic>> _superInvites = [], _superTabs = [];String? _superError, _accepting;final _accepts = SwarmInviteAccepts();bool _loadingSuper = true;- Timer? _refreshTimer;int _read = 0;@overridevoid initState() {@@ -38,16 +39,16 @@ class _TabInvitesSectionState extends State<TabInvitesSection> {// Read when the panel opens, so an invitation that arrived a moment ago is here.unawaited(widget.notifier.sharedTabs.refresh());unawaited(_refreshSuper());- _refreshTimer = Timer.periodic(- const Duration(seconds: 15),- (_) => unawaited(_refreshSuper()),- );+ // Again every 15 seconds while the panel can be seen, and once as it is seen again.+ visibleTick(const Duration(seconds: 15));}@override- void dispose() {- _refreshTimer?.cancel();- super.dispose();+ void onTick() => unawaited(_refreshSuper());++ @override+ void onScreenChanged(bool onScreen) {+ if (onScreen) unawaited(_refreshSuper());}Future<void> _refreshSuper() async {diff --git a/desktop/lib/sharing/harness_comments.dart b/desktop/lib/sharing/harness_comments.dartindex ce7f4cba5..656cdb9c4 100644--- a/desktop/lib/sharing/harness_comments.dart+++ b/desktop/lib/sharing/harness_comments.dart@@ -4,6 +4,7 @@ import 'dart:math';import 'package:flutter/material.dart';import '../shared/theme/app_theme.dart' as grid;+import '../super_tabs/visible_tick.dart';import '../widgets/desktop_chrome.dart';import '../ws/ws_conn.dart';import '../widgets/laid_out_list.dart';@@ -32,20 +33,29 @@ class HarnessComments extends StatefulWidget {State<HarnessComments> createState() => _HarnessCommentsState();}-class _HarnessCommentsState extends State<HarnessComments> {+class _HarnessCommentsState extends State<HarnessComments>+ with WidgetsBindingObserver, VisibleTick<HarnessComments> {final _text = TextEditingController();List<Map<String, dynamic>> _comments = [];bool _loading = true, _refreshing = false, _busy = false, _canComment = false;int _revision = 0;String? _error, _postId, _postText;- Timer? _timer;@overridevoid initState() {super.initState();widget.updates?.addListener(_refresh);_refresh();- _timer = Timer.periodic(const Duration(seconds: 5), (_) => _refresh());+ // Read every 5 seconds while the comments can be seen; once at once when they are again.+ visibleTick(const Duration(seconds: 5));+ }++ @override+ void onTick() => _refresh();++ @override+ void onScreenChanged(bool onScreen) {+ if (onScreen) _refresh();}@override@@ -59,7 +69,6 @@ class _HarnessCommentsState extends State<HarnessComments> {@overridevoid dispose() {- _timer?.cancel();widget.updates?.removeListener(_refresh);_text.dispose();super.dispose();diff --git a/desktop/lib/sharing/share_harness_dialog.dart b/desktop/lib/sharing/share_harness_dialog.dartindex 518bb5174..cc1bef175 100644--- a/desktop/lib/sharing/share_harness_dialog.dart+++ b/desktop/lib/sharing/share_harness_dialog.dart@@ -7,6 +7,7 @@ import 'package:flutter/services.dart';import 'package:flutter/material.dart';import '../shared/theme/app_theme.dart' as grid;+import '../super_tabs/visible_tick.dart';import '../shortcuts/app_keymap.dart';import '../shortcuts/keymap.dart';import '../shortcuts/keymap_commands.dart';@@ -73,7 +74,8 @@ enum _ShareRow { access, people, options, expiry, comments, stop, copy, retry }const maxTabInvites = 8;-class _ShareHarnessDialogState extends State<ShareHarnessDialog> {+class _ShareHarnessDialogState extends State<ShareHarnessDialog>+ with WidgetsBindingObserver, VisibleTick<ShareHarnessDialog> {final _focus = FocusNode(debugLabel: 'share-form');final _emailFocus = FocusNode(debugLabel: 'share-emails');final _commentsFocus = FocusNode(debugLabel: 'share-comments');@@ -93,7 +95,6 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {int _days = 30;Map<String, dynamic>? _link;bool _collaboration = false, _manualCopy = false;- Timer? _presence;int _revision = 0;bool _refreshing = false;@override@@ -105,16 +106,22 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {unawaited(_load());// A shared tab's people come from the roster the app already holds; it// reads again after each action, so nothing polls while the form is open.- if (!widget.tabMode) {- _presence = Timer.periodic(const Duration(seconds: 5), (_) {- if (!_busy) unawaited(_load(quiet: true));- });- }+ // A harness's list is read every 5 seconds while the dialog can be seen.+ if (!widget.tabMode) visibleTick(const Duration(seconds: 5));+ }++ @override+ void onTick() {+ if (!_busy) unawaited(_load(quiet: true));+ }++ @override+ void onScreenChanged(bool onScreen) {+ if (onScreen && !widget.tabMode) onTick();}@overridevoid dispose() {- _presence?.cancel();_emails.dispose();_focus.dispose();_emailFocus.dispose();diff --git a/desktop/lib/sharing/shared_agent_page.dart b/desktop/lib/sharing/shared_agent_page.dartindex a98c5bbbc..541dfcffd 100644--- a/desktop/lib/sharing/shared_agent_page.dart+++ b/desktop/lib/sharing/shared_agent_page.dart@@ -12,6 +12,7 @@ import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/empty_state.dart';import '../state/app_state.dart';import '../state/terminal_pane.dart';+import '../super_tabs/visible_tick.dart';import '../widgets/desktop_chrome.dart';import '../widgets/web_download_button.dart';import 'shared_agent_location.dart';@@ -44,7 +45,8 @@ class SharedAgentPage extends StatefulWidget {State<SharedAgentPage> createState() => _SharedAgentPageState();}-class _SharedAgentPageState extends State<SharedAgentPage> {+class _SharedAgentPageState extends State<SharedAgentPage>+ with WidgetsBindingObserver, VisibleTick<SharedAgentPage> {late final _dio =widget.dio ??Dio(@@ -59,6 +61,9 @@ class _SharedAgentPageState extends State<SharedAgentPage> {bool _loading = true;int _revision = 0;Timer? _offlineRetry;++ /// The owner was offline while the page could not be seen: read once when it can.+ bool _offlineOwed = false;late bool _signedIn = widget.app.status == AppStatus.authenticated;late final _usage = widget.usage ?? hubUsage;bool _viewCounted = false;@@ -132,6 +137,18 @@ class _SharedAgentPageState extends State<SharedAgentPage> {webOnlyWindowName: '_self',);+ /// An offline owner is asked about every 10 seconds only while the page can be seen; a hidden+ /// tab asks nothing, and asks once as it is shown again.+ @override+ void onScreenChanged(bool onScreen) {+ if (!onScreen) {+ if (_offlineRetry?.isActive ?? false) _offlineOwed = true;+ _offlineRetry?.cancel();+ } else if (_offlineOwed) {+ unawaited(_load(quietly: true));+ }+ }+@overridevoid didUpdateWidget(SharedAgentPage oldWidget) {super.didUpdateWidget(oldWidget);@@ -163,6 +180,7 @@ class _SharedAgentPageState extends State<SharedAgentPage> {/// says its state again.Future<void> _load({bool quietly = false}) async {_offlineRetry?.cancel();+ _offlineOwed = false;final revision = ++_revision;if (!quietly) {setState(() {@@ -214,10 +232,14 @@ class _SharedAgentPageState extends State<SharedAgentPage> {if (data['online'] != true) {_countOpen(SharedOpen.offline);_show(SharedLinkProblem.offline);- _offlineRetry = Timer(- const Duration(seconds: 10),- () => unawaited(_load(quietly: true)),- );+ if (onScreen) {+ _offlineRetry = Timer(+ const Duration(seconds: 10),+ () => unawaited(_load(quietly: true)),+ );+ } else {+ _offlineOwed = true;+ }return;}_countOpen(SharedOpen.live);diff --git a/desktop/lib/sharing/shared_harness_panel.dart b/desktop/lib/sharing/shared_harness_panel.dartindex eb5b26fff..e1bf78250 100644--- a/desktop/lib/sharing/shared_harness_panel.dart+++ b/desktop/lib/sharing/shared_harness_panel.dart@@ -11,6 +11,7 @@ import '../measurement/hub_usage.dart';import '../shared/theme/app_theme.dart' as grid;import '../state/app_state.dart';import '../state/terminal_pane.dart';+import '../super_tabs/visible_tick.dart';import '../terminal/terminal_binary.dart';import '../terminal/terminal_session.dart';import '../widgets/terminal_panel.dart';@@ -52,7 +53,8 @@ class SharedHarnessPanel extends StatefulWidget {State<SharedHarnessPanel> createState() => _SharedHarnessPanelState();}-class _SharedHarnessPanelState extends State<SharedHarnessPanel> {+class _SharedHarnessPanelState extends State<SharedHarnessPanel>+ with WidgetsBindingObserver, VisibleTick<SharedHarnessPanel> {late WsConn _connection;late TerminalSession _terminal;late SharedTerminalWatch _watch;@@ -124,7 +126,7 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {onChanged: () {if (mounted && generation == _generation) setState(() {});},- );+ )..seen = onScreen;_lastViewerState = '';_connection = WsConn(wsBaseUrl: widget.notifier.config.wsBaseUrl,@@ -262,6 +264,16 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {unawaited(_connection.close());}+ // A stopped terminal is asked for again only while the pane can be seen.+ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _watch.seen = onScreen;+ }++ @override+ void onScreenChanged(bool onScreen) => _watch.seen = onScreen;+@overridevoid didUpdateWidget(SharedHarnessPanel oldWidget) {super.didUpdateWidget(oldWidget);diff --git a/desktop/lib/sharing/shared_terminal_watch.dart b/desktop/lib/sharing/shared_terminal_watch.dartindex 5fa06285d..44cd87dfc 100644--- a/desktop/lib/sharing/shared_terminal_watch.dart+++ b/desktop/lib/sharing/shared_terminal_watch.dart@@ -41,6 +41,29 @@ class SharedTerminalWatch {bool get stopped => _stopped;+ bool _seen = true;++ /// Whether the pane can be seen, set by the pane from its `VisibleTick`. While it cannot,+ /// nothing asks again; when it can again, a stopped terminal is asked for once at once, then+ /// every [retryEvery].+ bool get seen => _seen;+ set seen(bool seen) {+ if (seen == _seen) return;+ _seen = seen;+ _retry?.cancel();+ _retry = null;+ if (!seen || !_stopped) return;+ if (canRetry()) unawaited(session.reopen());+ _arm();+ }++ void _arm() {+ if (!_seen) return;+ _retry ??= Timer.periodic(retryEvery, (_) {+ if (canRetry()) unawaited(session.reopen());+ });+ }+void _update() {if (session.status == TerminalSessionStatus.controlling) {_set(false);@@ -51,9 +74,7 @@ class SharedTerminalWatch {void _set(bool stopped) {if (stopped) {- _retry ??= Timer.periodic(retryEvery, (_) {- if (canRetry()) unawaited(session.reopen());- });+ _arm();} else {_retry?.cancel();_retry = null;diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 65ee42719..b137b6564 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1074,12 +1074,14 @@ class AppNotifier extends ChangeNotifier {/// Fed by the workspace's [AppLifecycleListener]. A null state is unknown, read as foreground.void appLifecycleChanged(AppLifecycleState? state) {if (_disposed) return;- final wasForeground = foreground.value;+ final wasForeground = foreground.value, wasInSight = inSight.value;foreground.value = state == null || state == AppLifecycleState.resumed;inSight.value =state == null ||state == AppLifecycleState.resumed ||state == AppLifecycleState.inactive;+ if (wasInSight && !inSight.value) _pauseBackgroundRereads();+ if (!wasInSight && inSight.value) _resumeBackgroundRereads();// Every transition, not only the three the listener has callbacks for: hidden -> inactive fires// onShow, and a window shown again without focus must not keep telling the daemon it shows nothing._announceVisibleAgents();@@ -1599,10 +1601,11 @@ class AppNotifier extends ChangeNotifier {);}- final experimentalFeatures = ExperimentalFeaturesStore(+ late final experimentalFeatures = ExperimentalFeaturesStore(pollInterval: kUnderTest? Duration.zero: ExperimentalFeaturesStore.safetyNet,+ seen: inSight,);final ExperimentalSettingsTransport? experimentalSettingsTransport;ApiClient? _experimentApi;@@ -10503,6 +10506,7 @@ class AppNotifier extends ChangeNotifier {void _stopMachineRecovery() {_machineRecoveryTimer?.cancel();_machineRecoveryTimer = null;+ _recoveryParked = null;_machineRecoveryAttempts = 0;}@@ -10519,6 +10523,12 @@ class AppNotifier extends ChangeNotifier {}_machineRecoveryTimer = Timer(Duration(seconds: delay), () {_machineRecoveryTimer = null;+ // Out of sight a failing list is not asked again and again: it is asked once on return.+ if (!inSight.value) {+ _recoveryParked = revision;+ _machineRecoveryAttempts = 0;+ return;+ }if (_authWorkCurrent(revision) && status == AppStatus.authenticated) {unawaited(_retryMachines(automatic: true).whenComplete(() {@@ -10848,7 +10858,13 @@ class AppNotifier extends ChangeNotifier {_startAgentSyncTimer(machine.machine.machineId);}}- // The list is pushed (`machines_changed`); this only catches a missed push.+ _armMachineListSafetyNet();+ }++ /// The machine list's safety net, every [machineListSafetyNetInterval] while the window is in+ /// sight ([inSight]). The list is pushed (`machines_changed`); this only catches a missed push.+ void _armMachineListSafetyNet() {+ if (_disposed || isGuest || !inSight.value) return;_sharingDiscoveryTimer ??= Timer.periodic(machineListSafetyNetInterval, (timer,) {@@ -10860,26 +10876,87 @@ class AppNotifier extends ChangeNotifier {}return;}- // The desk is pushed too, and a missed desk push is caught here as well:- // one small GET, and an unchanged revision applies nothing.- if (!_disposed &&- status == AppStatus.authenticated &&- _desk.enabled &&- _desk.pending.isEmpty) {- unawaited(_deskFetch());- }- // Agent Messages' first answer, when the read beside the desk failed- // (a backend away at sign-in) and no backend-online flip followed.- if (!_disposed &&- status == AppStatus.authenticated &&- _desk.enabled &&- !agentMessages.loaded) {- unawaited(agentMessages.refresh());- }- unawaited(_rereadMachinesInBackground(pushed: false));+ _machineListSafetyNetTick();});}+ void _machineListSafetyNetTick() {+ // The desk is pushed too, and a missed desk push is caught here as well:+ // one small GET, and an unchanged revision applies nothing.+ if (!_disposed &&+ status == AppStatus.authenticated &&+ _desk.enabled &&+ _desk.pending.isEmpty) {+ unawaited(_deskFetch());+ }+ // Agent Messages' first answer, when the read beside the desk failed+ // (a backend away at sign-in) and no backend-online flip followed.+ if (!_disposed &&+ status == AppStatus.authenticated &&+ _desk.enabled &&+ !agentMessages.loaded) {+ unawaited(agentMessages.refresh());+ }+ unawaited(_rereadMachinesInBackground(pushed: false));+ }++ /// When the window last went out of sight ([inSight] false); null while it is in sight.+ DateTime? _unseenSince;++ /// The window went out of sight: minimised, behind other windows, closed to the menu bar, or a+ /// browser tab in the background. Its background re-reads stop (Phase 3 of the WebSocket+ /// roadmap, task #2953): nobody sees what they would bring, and every open window kept asking+ /// every machine for its agents each minute and the backend for the machine list every five.+ /// Pushes still land; [_resumeBackgroundRereads] catches up on what came due meanwhile.+ void _pauseBackgroundRereads() {+ _unseenSince = clock.now();+ for (final timer in [+ ..._agentSyncTimers.values,+ ..._heldSyncTimers.values,+ ]) {+ timer.cancel();+ }+ _agentSyncTimers.clear();+ _heldSyncTimers.clear();+ _sharingDiscoveryTimer?.cancel();+ _sharingDiscoveryTimer = null;+ }++ /// Back in sight: each re-read that came due while away reads once, now, and every timer runs+ /// again from here. A glance away shorter than an interval reads nothing.+ void _resumeBackgroundRereads() {+ final since = _unseenSince;+ _unseenSince = null;+ if (_disposed || isGuest || status != AppStatus.authenticated) return;+ final away = since == null ? Duration.zero : clock.now().difference(since);+ for (final machine in machineStates.values.toList()) {+ if (machine.connectionStatus != ConnectionStatus.connected) continue;+ _startAgentSyncTimer(machine.machine.machineId);+ if (away >= agentSyncInterval) {+ unawaited(_syncAgentsIfChanged(machine));+ } else {+ _watchHeldLaunches(machine);+ }+ }+ _armMachineListSafetyNet();+ if (away >= machineListSafetyNetInterval) _machineListSafetyNetTick();+ final parked = _recoveryParked;+ _recoveryParked = null;+ if (parked != null) _scheduleMachineRecovery(parked);+ for (final machineId in _offlinePollsParked.toList()) {+ _offlinePollsParked.remove(machineId);+ final machine = machineStates[machineId];+ if (machine != null) _startOfflineRetry(machine);+ }+ }++ /// The machine list's recovery, waiting for the window to be in sight again: the auth revision+ /// it was for ([_scheduleMachineRecovery]).+ int? _recoveryParked;++ /// Remote machines whose offline poll waits for the window to be in sight again.+ final Set<String> _offlinePollsParked = {};+/// The inventory has answered, and answered for now: loaded, not loading,/// not stale, no error. What the account HAS, independent of what is open.bool get machineInventorySettled =>@@ -11053,6 +11130,14 @@ class AppNotifier extends ChangeNotifier {)];late final Timer timer;timer = Timer(delay, () async {+ // Out of sight, the machine is asked about again only once the window is back.+ if (!inSight.value) {+ if (identical(_offlineRetryTimers[machineId], timer)) {+ _offlineRetryTimers.remove(machineId);+ _offlinePollsParked.add(machineId);+ }+ return;+ }await _pollOfflineMachine(machineId);if (_disposed || !identical(_offlineRetryTimers[machineId], timer)) {return;@@ -11064,6 +11149,7 @@ class AppNotifier extends ChangeNotifier {void _stopOfflineRetry(String machineId) {_offlineRetryTimers.remove(machineId)?.cancel();+ _offlinePollsParked.remove(machineId);}/// Dials [machineId] now instead of at the link retry's next tick. Native@@ -11220,6 +11306,7 @@ class AppNotifier extends ChangeNotifier {timer.cancel();}_offlineRetryTimers.clear();+ _offlinePollsParked.clear();for (final timer in _slowReloadTimers.values) {timer.cancel();}@@ -11233,6 +11320,8 @@ class AppNotifier extends ChangeNotifier {// A guest asks nothing on a timer: an unattended computer on the sign-in// page must go idle. Sign-in starts it ([_startBackgroundRereads]).if (isGuest) return;+ // Out of sight it arms nothing; coming back does ([_resumeBackgroundRereads]).+ if (!inSight.value) return;if (_agentSyncTimers.containsKey(machineId)) return;_agentSyncTimers[machineId] = Timer.periodic(agentSyncInterval, (_) {final machine = machineStates[machineId];@@ -11281,6 +11370,9 @@ class AppNotifier extends ChangeNotifier {_heldSyncRounds.remove(machineId);return;}+ // Out of sight the daemon's own push still says when it starts; the re-read waits for the+ // window to come back ([_resumeBackgroundRereads]).+ if (!inSight.value) return;if (_heldSyncTimers.containsKey(machineId)) return;final round = _heldSyncRounds[machineId] ?? 0;_heldSyncTimers[machineId] = Timer(@@ -12986,8 +13078,10 @@ class AppNotifier extends ChangeNotifier {/// Subscription readings for the whole window: the Models panel, New Harness and every pane's model/// picker read this ONE controller. Each used to own its own, read at a different moment, and the/// picker said "Not signed in" beside a menu showing the same account with 8% left.- ModelsMenuController get modelsMenu =>- _modelsMenu ??= ModelsMenuController(remote: readRemoteUsage);+ ModelsMenuController get modelsMenu => _modelsMenu ??= ModelsMenuController(+ remote: readRemoteUsage,+ seen: inSight,+ );/// This machine's local models. [setup] makes it Grid's first use there too: `grid` installed,/// signed in with this Harness account (its token, no second browser) and the account's griddiff --git a/desktop/lib/state/session_activity.dart b/desktop/lib/state/session_activity.dartindex 9d2a3d0f3..7de259e85 100644--- a/desktop/lib/state/session_activity.dart+++ b/desktop/lib/state/session_activity.dart@@ -31,8 +31,28 @@ class SessionActivityController extends ChangeNotifier {bool _disposed = false;bool _reading = false;bool _scheduled = false;+ bool _seen = true;int _revision = 0;+ /// Whether the rows can be seen, set by the widget that shows them (its `VisibleTick`). While+ /// they cannot, nothing is read; when they can again, one read at once, then every 5 seconds.+ set seen(bool seen) {+ if (seen == _seen || _disposed) return;+ _seen = seen;+ _timer?.cancel();+ _timer = null;+ if (seen) _poll();+ }++ /// Reads the external rows now and every 5 seconds, while they can be seen.+ void _poll() {+ _timer?.cancel();+ _timer = null;+ if (!_seen || !_rows.values.any((row) => row.external != null)) return;+ _timer = Timer.periodic(const Duration(seconds: 5), (_) => refresh());+ _schedule();+ }+SessionActivity read(SwarmDestination row) {final machine = app.stateOf(row.machineId ?? '');final online =@@ -74,11 +94,7 @@ class SessionActivityController extends ChangeNotifier {_external.removeWhere((id, _) => !next.containsKey(id));// A conversation that came back to the index shows again._notHeld.clear();- _timer?.cancel();- if (next.values.any((row) => row.external != null)) {- _timer = Timer.periodic(const Duration(seconds: 5), (_) => refresh());- _schedule();- }+ _poll();}void _schedule() {@@ -86,7 +102,7 @@ class SessionActivityController extends ChangeNotifier {_scheduled = true;scheduleMicrotask(() {_scheduled = false;- if (!_disposed) unawaited(refresh());+ if (!_disposed && _seen) unawaited(refresh());});}diff --git a/desktop/lib/store/store_screen.dart b/desktop/lib/store/store_screen.dartindex 986b3dffa..82a3d0bbf 100644--- a/desktop/lib/store/store_screen.dart+++ b/desktop/lib/store/store_screen.dart@@ -23,6 +23,7 @@ import '../shortcuts/app_keymap.dart';import '../shortcuts/keymap.dart';import '../state/app_state.dart';import '../state/essential_harness_controller.dart';+import '../super_tabs/visible_tick.dart';import '../widgets/dsh_install_panel.dart' show describeInstallFailure;import '../widgets/engine_identity.dart';import '../widgets/new_agent_dialog.dart';@@ -138,7 +139,8 @@ class _StorePlace {final _storePlaces = Expando<_StorePlace>('store place');-class _StoreTabState extends State<StoreTab> {+class _StoreTabState extends State<StoreTab>+ with WidgetsBindingObserver, VisibleTick<StoreTab> {late final StoreController _store = StoreController(widget.api ?? ApiStoreApi(widget.notifier.api),);@@ -156,7 +158,7 @@ class _StoreTabState extends State<StoreTab> {);final _searchFocus = FocusNode(debugLabel: 'Store search');final _browseFocus = FocusNode(debugLabel: 'Store navigation');- Timer? _catalogRefresh;+ bool _catalogPolls = false;void _remember() {_place@@ -191,18 +193,28 @@ class _StoreTabState extends State<StoreTab> {if (local != null) _ask(local, userAction: opened);widget.notifier.addListener(_onAppChanged);// A Store left open picks up new publications; engines do not need reprobes.- // The daemon caches catalog HTTP requests for five minutes.- _catalogRefresh = Timer.periodic(const Duration(minutes: 1), (_) {- final local = widget.notifier.localMachineState;- if (local?.connectionStatus == ConnectionStatus.connected) {- unawaited(- widget.notifier.probeDsh(local!.machine.machineId, force: true),- );- }- });+ // The daemon caches catalog HTTP requests for five minutes. Only while the Store can be+ // seen, and once as it is seen again.+ _catalogPolls = true;+ visibleTick(const Duration(minutes: 1));});}+ @override+ void onTick() {+ final local = widget.notifier.localMachineState;+ if (local?.connectionStatus == ConnectionStatus.connected) {+ unawaited(+ widget.notifier.probeDsh(local!.machine.machineId, force: true),+ );+ }+ }++ @override+ void onScreenChanged(bool onScreen) {+ if (onScreen && _catalogPolls) onTick();+ }+/// Machines asked since they last connected.////// A store tab restored when the app launches is built before any machine@@ -254,7 +266,6 @@ class _StoreTabState extends State<StoreTab> {@overridevoid dispose() {- _catalogRefresh?.cancel();widget.notifier.removeListener(_onAppChanged);_search.dispose();_searchFocus.dispose();diff --git a/desktop/lib/super_tabs/backlog_view.dart b/desktop/lib/super_tabs/backlog_view.dartindex 177184ee1..610d641a7 100644--- a/desktop/lib/super_tabs/backlog_view.dart+++ b/desktop/lib/super_tabs/backlog_view.dart@@ -17,6 +17,7 @@ import 'machine_status.dart';import 'model.dart';import 'pull_request_facts.dart';import 'task_status.dart';+import 'visible_tick.dart';/// How many shipped tasks show before "Show N more shipped" (Scholes's/// mockup, task #2774).@@ -85,7 +86,8 @@ class SuperTabBacklogView extends StatefulWidget {State<SuperTabBacklogView> createState() => _SuperTabBacklogViewState();}-class _SuperTabBacklogViewState extends State<SuperTabBacklogView> {+class _SuperTabBacklogViewState extends State<SuperTabBacklogView>+ with WidgetsBindingObserver, VisibleTick<SuperTabBacklogView> {String? _project;bool _mine = false;String _query = '';@@ -109,10 +111,35 @@ class _SuperTabBacklogViewState extends State<SuperTabBacklogView> {@overridevoid dispose() {- widget.facts?.unwatch(_watched);+ if (_watching) widget.facts?.unwatch(_watched);super.dispose();}+ /// Whether the rows' pull requests are watched: only while on screen, as live cards do, so a+ /// hidden window asks GitHub nothing for them (task #2953).+ bool _watching = false;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _hold(onScreen);+ }++ @override+ void onScreenChanged(bool onScreen) => _hold(onScreen);++ void _hold(bool onScreen) {+ if (onScreen == _watching) return;+ _watching = onScreen;+ final facts = widget.facts;+ if (facts == null) return;+ if (onScreen) {+ facts.watch(_watched);+ } else {+ facts.unwatch(_watched);+ }+ }+void _readClosed() => unawaited(widget.controller.readClosedShipped(widget.now().subtract(superTabBacklogShippedWindow),@@ -131,9 +158,11 @@ class _SuperTabBacklogViewState extends State<SuperTabBacklogView> {if (facts == null) return;final next = {for (final task in open) ?_pullRequest(task)};if (const SetEquality<String>().equals(next, _watched)) return;- facts- ..watch(next.difference(_watched))- ..unwatch(_watched.difference(next));+ if (_watching) {+ facts+ ..watch(next.difference(_watched))+ ..unwatch(_watched.difference(next));+ }_watched = next;}diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dartindex 9c5e86c59..fa043dc8a 100644--- a/desktop/lib/super_tabs/client.dart+++ b/desktop/lib/super_tabs/client.dart@@ -159,12 +159,40 @@ class SuperTabClient {}/// False while the page or window is hidden: every Swarm tab is away.+ ///+ /// Hidden while the server pushes, nothing is read on a clock: a told change is still read at+ /// once (tags and notices), the safety nets wait (task #2953). Shown again, each open Swarm+ /// reads once ([SuperTabController.away]) and so does the list, if its safety net came due or+ /// the server's word came meanwhile.set pageVisible(bool visible) {if (_pageVisible == visible) return;_pageVisible = visible;_applyAway();+ if (!visible) return;+ final last = _lastDiscovery;+ if (_toldWhileHidden ||+ (_pushing &&+ last != null &&+ clock.now().difference(last) >= kSwarmDiscoverySafetyNet)) {+ _toldWhileHidden = false;+ _discoverWhenAllowed();+ }}+ /// The server's word that it pushes came while the page was hidden: what it asks for is read+ /// on return.+ bool _toldWhileHidden = false;++ /// When the server's word that it pushes was last heard.+ DateTime? _lastPushWord;++ /// How far from [kSwarmPushRepeat] a repeat may land: a hidden window's socket is read late+ /// (App Nap), and a reconnect inside this window waits, at worst, for the return.+ static const _pushBeatSlack = Duration(seconds: 30);++ /// Hidden while the server pushes: the reads on a clock rest.+ bool get _restsHidden => !_pageVisible && _pushing;+bool _isAway(String id) => !_pageVisible || id != _shown;late final _views = SuperTabSavedViews(viewStorage);@@ -270,7 +298,9 @@ class SuperTabClient {_tagCounts.remove(entry.key);_tagDigests.remove(entry.key);}- entry.value.away = away;+ entry.value+ ..pageHidden = !_pageVisible+ ..away = away;}}@@ -327,6 +357,24 @@ class SuperTabClient {if (_account == null) return;final tabId = payload['tabId'], parts = payload['parts'];if (tabId == null && parts == null) {+ // Hidden, the word repeated every 4 minutes renews the lease and reads nothing until the+ // page shows; once the lease had lapsed the away poll was reading all along. A word off that+ // beat is a socket that reconnected, the same payload (review of #3035): a push may have been+ // lost meanwhile, so Desktop reads once, as shown, for the menu bar and notices. The web+ // reads nothing while away anyway ([SuperTabReading.pausesAway]).+ final now = clock.now(), last = _lastPushWord;+ _lastPushWord = now;+ final onBeat =+ last != null &&+ (now.difference(last) - kSwarmPushRepeat).abs() <= _pushBeatSlack;+ if (_restsHidden && (onBeat || _reading.pausesAway)) {+ _pushUntil = clock.now().add(kSwarmPushLease);+ for (final controller in _loaded.values) {+ controller.pushUntil = _pushUntil;+ }+ _toldWhileHidden = true;+ return;+ }_pushUntil = clock.now().add(kSwarmPushLease);// Said on every connect (review of #2121): a daemon that reconnected// was not told what changed meanwhile, so each open Swarm and the list@@ -584,7 +632,7 @@ class SuperTabClient {discoveryInterval > Duration.zero) {unawaited(refreshTabs());_discoveryTimer = Timer.periodic(discoveryInterval, (_) {- if (_discoveryDue) unawaited(refreshTabs());+ if (_discoveryDue && !_restsHidden) unawaited(refreshTabs());});}}@@ -892,6 +940,7 @@ class SuperTabClient {reading: _reading,stillListed: onTabs == null ? null : () => _stillListed(id),)+ ..pageHidden = !_pageVisible..away = _isAway(id)..pushUntil = _pushUntil;if (_keptFiles.remove(id) case final kept?) controller.adoptFiles(kept);diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 975d548b8..82bda3765 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -190,6 +190,10 @@ class SuperTabOutgoing {/// before.const kSwarmPushLease = Duration(minutes: 5);+/// How often a pushing server repeats that word on one socket (backend lib/swarmClientPushes.ts+/// `PUSHES_REPEAT_MS`). A word off this beat is a socket that (re)connected.+const kSwarmPushRepeat = Duration(minutes: 4);+/// While the server pushes, a Swarm nothing was said of is still read this/// often: the safety net for a push lost on the way.const kSwarmPushSafetyNet = Duration(seconds: 60);@@ -762,6 +766,14 @@ class SuperTabController extends ChangeNotifier {/// back reads at once.bool get away => _away;bool _away = false;++ /// The page or window is hidden ([SuperTabClient.pageVisible]), set before [away]. While the+ /// server pushes, a hidden Swarm reads only what it is told (task #2953): its safety net waits+ /// for the return, which reads at once.+ bool pageHidden = false;++ bool get _restsHidden =>+ pageHidden && _pushing && !(_toldMain || _toldMachine);set away(bool value) {if (_away == value) return;_away = value;@@ -2368,7 +2380,7 @@ class SuperTabController extends ChangeNotifier {if (_disposed || updateRequired || pollInterval <= Duration.zero) return;if (!_policy.adapts) {_poll = Timer.periodic(_every, (_) {- if (_pollDue) unawaited(refresh());+ if (_pollDue && !_restsHidden) unawaited(refresh());_checkReceipt();});return;diff --git a/desktop/lib/usage/models_menu_controller.dart b/desktop/lib/usage/models_menu_controller.dartindex f7ed9b120..5959f0a3a 100644--- a/desktop/lib/usage/models_menu_controller.dart+++ b/desktop/lib/usage/models_menu_controller.dart@@ -23,10 +23,24 @@ class ModelsMenuController extends ChangeNotifier {Future<List<MachineUsage>> Function()? remote,DateTime Function()? now,this.interval = const Duration(minutes: 5),+ ValueListenable<bool>? seen,}) : _usage = usage ?? UsageController(remote: remote, autoStart: false),_ownsUsage = usage == null,- _now = now ?? DateTime.now {+ _now = now ?? DateTime.now,+ _seen = seen {_usage.addListener(_changed);+ seen?.addListener(_seenChanged);+ }++ /// Whether the window is in sight (`AppNotifier.inSight`); null is always. Out of sight [start]'s+ /// background read asks nothing (task #2953); one that came due meanwhile reads on return.+ final ValueListenable<bool>? _seen;+ bool _owed = false;++ void _seenChanged() {+ if (_seen?.value != true || !_owed) return;+ _owed = false;+ unawaited(refresh());}final UsageController _usage;@@ -79,7 +93,13 @@ class ModelsMenuController extends ChangeNotifier {void start() {if (_disposed || _timer != null) return;unawaited(refresh());- _timer = Timer.periodic(interval, (_) => unawaited(refresh()));+ _timer = Timer.periodic(interval, (_) {+ if (_seen?.value == false) {+ _owed = true;+ return;+ }+ unawaited(refresh());+ });}Future<void> refresh() {@@ -133,6 +153,7 @@ class ModelsMenuController extends ChangeNotifier {void dispose() {_disposed = true;_timer?.cancel();+ _seen?.removeListener(_seenChanged);_usage.removeListener(_changed);if (_ownsUsage) _usage.dispose();super.dispose();diff --git a/desktop/lib/web/update/web_update_host.dart b/desktop/lib/web/update/web_update_host.dartindex b49900daa..1d402397e 100644--- a/desktop/lib/web/update/web_update_host.dart+++ b/desktop/lib/web/update/web_update_host.dart@@ -86,6 +86,12 @@ class _WebUpdateHostState extends State<WebUpdateHost> {running: running,readLatest: widget.readLatest,every: widget.every,+ shown: () => switch (WidgetsBinding.instance.lifecycleState) {+ AppLifecycleState.hidden ||+ AppLifecycleState.paused ||+ AppLifecycleState.detached => false,+ _ => true,+ },)..start();// A page an old cache kept may be out of date already: ask once now.unawaited(watcher.check());diff --git a/desktop/lib/web/update/web_update_watcher.dart b/desktop/lib/web/update/web_update_watcher.dartindex 6dcb775c9..f6946eeaa 100644--- a/desktop/lib/web/update/web_update_watcher.dart+++ b/desktop/lib/web/update/web_update_watcher.dart@@ -16,7 +16,14 @@ class WebUpdateWatcher extends ChangeNotifier {required this.running,required this.readLatest,this.every = const Duration(minutes: 5),- });+ bool Function()? shown,+ }) : _shown = shown ?? _always;++ static bool _always() => true;++ /// Whether the page is shown. A hidden tab asks the host nothing on the clock (task #2953);+ /// coming back to it checks at once (`pageShown`, [WebUpdateHost]).+ final bool Function() _shown;/// The version this page started on.final String? running;@@ -50,7 +57,9 @@ class WebUpdateWatcher extends ChangeNotifier {/// Asks the host every [every] from now on, until disposed.void start() {- _timer ??= Timer.periodic(every, (_) => unawaited(check()));+ _timer ??= Timer.periodic(every, (_) {+ if (_shown()) unawaited(check());+ });}@overridediff --git a/desktop/lib/widgets/swarm_resource_preview.dart b/desktop/lib/widgets/swarm_resource_preview.dartindex f638b4569..aa60286ef 100644--- a/desktop/lib/widgets/swarm_resource_preview.dart+++ b/desktop/lib/widgets/swarm_resource_preview.dart@@ -23,6 +23,7 @@ import '../state/harness_sessions.dart';import '../state/harness_placement.dart';import '../state/swarm_navigation.dart';import '../state/swarm_search.dart';+import '../super_tabs/visible_tick.dart';import '../terminal/terminal_text.dart';import 'finger_target.dart';import '../terminal/terminal_theme.dart';@@ -127,7 +128,8 @@ class SwarmResourcePreview extends StatefulWidget {State<SwarmResourcePreview> createState() => _SwarmResourcePreviewState();}-class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {+class _SwarmResourcePreviewState extends State<SwarmResourcePreview>+ with WidgetsBindingObserver, VisibleTick<SwarmResourcePreview> {AppNotifier get app => widget.search.app;SwarmDestination? get row => widget.search.selected;ModelSearchEntry? get model => widget.search.models?.entries[row?.modelId];@@ -136,7 +138,6 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {late SwarmPreviewScrollController _scroll;final _actionFocus = FocusNode(debugLabel: 'Resource controls');final _buttonFocus = <String, FocusNode>{};- Timer? _resourceTimer;String? _focusedResource;bool _readingResources = false;MachinePickerFormKind? _machineForm;@@ -345,11 +346,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {}Future<void> _readResources() async {- if (_readingResources ||- !widget.search.isMachineMode ||- !app.inForeground) {- return;- }+ if (_readingResources || !widget.search.isMachineMode) return;_readingResources = true;try {await widget.search.refreshMachineResources();@@ -365,15 +362,21 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {widget.controls.dispatch = _dispatch;widget.controls.commands = _commands;widget.search.addListener(_searchChanged);- final interval =- widget.resourcePollInterval ??- (kUnderTest ? null : const Duration(seconds: 10));- if (interval != null) {- _resourceTimer = Timer.periodic(- interval,- (_) => unawaited(_readResources()),- );- }+ // Machine metrics every 10 seconds while the preview can be seen, and once as it is seen+ // again: a hidden window asks no machine.+ if (_resourceEvery case final every?) visibleTick(every);+ }++ late final _resourceEvery =+ widget.resourcePollInterval ??+ (kUnderTest ? null : const Duration(seconds: 10));++ @override+ void onTick() => unawaited(_readResources());++ @override+ void onScreenChanged(bool onScreen) {+ if (onScreen && _resourceEvery != null) onTick();}SwarmPreviewScrollController _scrollController() =>@@ -412,7 +415,6 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {if (widget.controls.dispatch == _dispatch) widget.controls.dispatch = null;if (widget.controls.commands == _commands) widget.controls.commands = null;widget.search.removeListener(_searchChanged);- _resourceTimer?.cancel();_actionFocus.dispose();for (final node in _buttonFocus.values) {node.dispose();diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dartindex 7af793a7c..f24f1910b 100644--- a/desktop/lib/widgets/swarm_switcher.dart+++ b/desktop/lib/widgets/swarm_switcher.dart@@ -28,6 +28,7 @@ import '../state/app_state.dart';import '../state/swarm_navigation.dart';import '../state/session_content_search.dart';import '../state/session_activity.dart';+import '../super_tabs/visible_tick.dart';import '../state/swarm_search.dart';import '../models/api_connections_controller.dart' show contextWindowLabel;import '../models/model_search_catalog.dart';@@ -603,7 +604,8 @@ class SwarmSearchResults extends StatefulWidget {State<SwarmSearchResults> createState() => _SwarmSearchResultsState();}-class _SwarmSearchResultsState extends State<SwarmSearchResults> {+class _SwarmSearchResultsState extends State<SwarmSearchResults>+ with WidgetsBindingObserver, VisibleTick<SwarmSearchResults> {// Keep a small set of recently built rows, not the whole search catalog.// A new highlight only changes two rows; their neighbors keep their widgets.// Query highlights listen within the text, leaving these controls intact.@@ -782,6 +784,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {if (oldWidget.search != search) {_activity.dispose();_activity = SessionActivityController(search.app)+ ..seen = onScreen..addListener(_activityChanged);_watchActivity();oldWidget.search.removeListener(_changed);@@ -848,6 +851,16 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {}}+ // The rows' activity is read only while the results can be seen.+ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _activity.seen = onScreen;+ }++ @override+ void onScreenChanged(bool onScreen) => _activity.seen = onScreen;+void _activityChanged() {if (mounted) setState(() {});}diff --git a/desktop/lib/widgets/workspace_welcome.dart b/desktop/lib/widgets/workspace_welcome.dartindex 583a2585c..8c77dc572 100644--- a/desktop/lib/widgets/workspace_welcome.dart+++ b/desktop/lib/widgets/workspace_welcome.dart@@ -11,6 +11,7 @@ import '../state/swarm_navigation.dart';import '../state/welcome_sessions.dart';import '../state/workspace_chrome.dart';import '../state/session_activity.dart';+import '../super_tabs/visible_tick.dart';import 'engine_identity.dart';import 'finger_target.dart';import 'new_tab_actions.dart';@@ -72,7 +73,8 @@ class WorkspaceWelcome extends StatefulWidget {State<WorkspaceWelcome> createState() => _WorkspaceWelcomeState();}-class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {+class _WorkspaceWelcomeState extends State<WorkspaceWelcome>+ with WidgetsBindingObserver, VisibleTick<WorkspaceWelcome> {// Resolve the icon at compile time. Lazy initialization of Lucide's large// generated library overflows the browser debug runtime's stack here.static const _phoneIcon = AppIcons.smartphone;@@ -125,6 +127,16 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {});}+ // The rows' activity is read only while the page can be seen.+ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _activity?.seen = onScreen;+ }++ @override+ void onScreenChanged(bool onScreen) => _activity?.seen = onScreen;+void _appChanged() => _sessions?.appChanged();void _changed() {diff --git a/desktop/test/desktop_search_edges_test.dart b/desktop/test/desktop_search_edges_test.dartindex 8a259b832..5dd30412b 100644--- a/desktop/test/desktop_search_edges_test.dart+++ b/desktop/test/desktop_search_edges_test.dart@@ -716,15 +716,25 @@ void main() {reply.complete(null);await tester.pump();app.resourceReply = null;- app.foreground.value = false;+ // A hidden window asks no machine; shown again, it reads once at once (#2953).+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);+ addTearDown(+ () => tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ ),+ );await tester.pump(const Duration(seconds: 2));expect(app.resourceReads, before + 2);- app.foreground.value = true;+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ await tester.pump();+ expect(app.resourceReads, before + 4);fixture.search.setQuery(':');await tester.pump(const Duration(seconds: 2));expect(app.resourceReads,- before + 2,+ before + 4,reason: 'Model browsing should not poll machine telemetry',);fixture.search.setQuery('@');diff --git a/desktop/test/hidden_widget_pollers_test.dart b/desktop/test/hidden_widget_pollers_test.dartnew file mode 100644index 000000000..1bf4ce4fa--- /dev/null+++ b/desktop/test/hidden_widget_pollers_test.dart@@ -0,0 +1,613 @@+// #2953: a widget that reads on a timer reads nothing while the app is hidden (a minimised,+// occluded or closed window; a hidden web tab), reads once at once when it is shown again, and+// then goes on with its interval. Each poller ticks through VisibleTick, or through the widget+// that owns its controller. Every fake here counts requests; nothing reaches a machine or the+// network.+import 'dart:convert';++import 'package:dio/dio.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/autonomous_device/autonomous_device_cli.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/machine_resources.dart';+import 'package:harness/core/models.dart';+import 'package:harness/devices/devices_controller.dart';+import 'package:harness/devices/devices_screen.dart';+import 'package:harness/devices/wifi_robots.dart';+import 'package:harness/orchestrator/orchestrator_controller.dart';+import 'package:harness/orchestrator/orchestrator_workspace.dart';+import 'package:harness/settings/sections/tab_invites_section.dart';+import 'package:harness/sharing/harness_comments.dart';+import 'package:harness/sharing/share_harness_dialog.dart';+import 'package:harness/sharing/shared_agent_location.dart';+import 'package:harness/sharing/shared_agent_page.dart';+import 'package:harness/sharing/shared_terminal_watch.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/dial_status.dart';+import 'package:harness/state/swarm_search.dart';+import 'package:harness/store/store_controller.dart';+import 'package:harness/store/store_models.dart';+import 'package:harness/store/store_screen.dart';+import 'package:harness/super_tabs/client.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/widgets/desktop_chrome.dart';+import 'package:harness/widgets/swarm_resource_preview.dart';+import 'package:harness/widgets/swarm_switcher.dart';+import 'package:harness/widgets/workspace_welcome.dart';++import 'session_search_rendering_test.dart' show TailConnection;+import 'support/model_manager.dart';+import 'swarm_state_test.dart' show MemoryStore, createApp;++AppNotifier _plainApp() => AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+);++/// Well before any interval: what "at once" means here.+Future<void> _soon(WidgetTester tester) async {+ for (var i = 0; i < 5; i++) {+ await tester.pump(const Duration(milliseconds: 20));+ }+}++void _lifecycle(WidgetTester tester, AppLifecycleState state) =>+ tester.binding.handleAppLifecycleStateChanged(state);++/// Shown, hidden for three intervals, shown again. [reads] counts requests; [per] is how many+/// one read sends (one per row or machine).+Future<void> _expectQuietWhileHidden(+ WidgetTester tester, {+ required Duration every,+ required int Function() reads,+ int per = 1,+}) async {+ addTearDown(() => _lifecycle(tester, AppLifecycleState.resumed));+ var before = reads();+ await tester.pump(every);+ await _soon(tester);+ expect(reads(), before + per, reason: 'reads on its interval while shown');++ // Unfocused, still in sight: it keeps reading.+ _lifecycle(tester, AppLifecycleState.inactive);+ await tester.pump();+ before = reads();+ await tester.pump(every);+ await _soon(tester);+ expect(reads(), before + per, reason: 'an unfocused window still reads');++ _lifecycle(tester, AppLifecycleState.hidden);+ await tester.pump();+ before = reads();+ await tester.pump(every * 3);+ await _soon(tester);+ expect(reads(), before, reason: 'no request while the app is hidden');++ _lifecycle(tester, AppLifecycleState.inactive);+ _lifecycle(tester, AppLifecycleState.resumed);+ await _soon(tester);+ expect(reads(), before + per, reason: 'one read at once when it is shown');+ await tester.pump(every);+ await _soon(tester);+ expect(reads(), before + 2 * per, reason: 'then on its interval again');+}++Widget _host(Widget child) => MaterialApp(home: Scaffold(body: child));++class _DevicesApp extends AppNotifier {+ _DevicesApp()+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ );+ int reads = 0;+ @override+ Future<void> refreshDevices() async => reads++;+}++class _StoreApp extends AppNotifier {+ _StoreApp()+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ ) {+ const local = Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: 'This Mac',+ );+ machines = [local];+ machineStates['m'] = MachineState(local)+ ..localOnly = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded;+ }+ int probes = 0;+ @override+ Future<void> probeDsh(+ String machineId, {+ bool force = false,+ bool userAction = false,+ }) async => probes++;+ @override+ Future<void> probeEngines(String machineId, {bool force = false}) async {}+}++class _StoreApi implements StoreApi {+ @override+ Future<List<StoreRating>> ratings() async => [];+ @override+ Future<StoreReviews> reviews(String id) async =>+ StoreReviews(rating: StoreRating.none(id), reviews: const [], mine: null);+ @override+ Future<void> deleteReview(String id) async {}+ @override+ Future<StoreReview> putReview(+ String id, {+ required int rating,+ String? title,+ String? body,+ }) => throw UnimplementedError();+}++/// Its Swarm client answers from [paths] and counts every request.+class _InvitesApp extends AppNotifier {+ _InvitesApp()+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ );+ final paths = <String>[];+ late final SuperTabClient _client = SuperTabClient(+ transport: (method, path, {body}) async {+ paths.add(path);+ return path.endsWith('/invitations') ? <Object>[] : {'tabs': <Object>[]};+ },+ storage: MemoryStore(),+ discoveryInterval: Duration.zero,+ )..bind('account');+ @override+ SuperTabClient get superTabs => _client;+}++class _ResourcesApp extends ModelManagerTestApp {+ _ResourcesApp() : super(ModelManagerConnection());+ int reads = 0;+ @override+ Future<MachineResources?> readMachineResources(String machineId) async {+ reads++;+ return const MachineResources(cpuPercent: 33);+ }+}++class _Cli extends AutonomousDeviceCli {+ int statusCalls = 0;+ @override+ Future<Map<String, dynamic>> status() async {+ statusCalls++;+ return {'transport': 'direct', 'connected': true, 'paired': 0};+ }++ @override+ Future<Map<String, dynamic>> list() async => {'devices': const []};+ @override+ Future<Map<String, dynamic>> discover() async => {'devices': const []};+}++void main() {+ testWidgets(+ 'harness comments: hidden app — no request for 3 intervals; resumed — one read at once',+ (tester) async {+ var reads = 0;+ await tester.pumpWidget(+ _host(+ HarnessComments(+ manage: (action, _) async {+ if (action == 'comments') reads++;+ return {'comments': const [], 'canComment': true};+ },+ ),+ ),+ );+ await _soon(tester);+ expect(reads, 1);+ await _expectQuietWhileHidden(+ tester,+ every: const Duration(seconds: 5),+ reads: () => reads,+ );+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'share harness dialog: hidden app — no request for 3 intervals; resumed — one read at once',+ (tester) async {+ var reads = 0;+ await tester.pumpWidget(+ _host(+ ShareHarnessDialog(+ name: 'Climate dashboard',+ manage: (action, _) async {+ if (action == 'list') reads++;+ return {'shares': const [], 'link': null};+ },+ ),+ ),+ );+ await _soon(tester);+ expect(reads, 1);+ await _expectQuietWhileHidden(+ tester,+ every: const Duration(seconds: 5),+ reads: () => reads,+ );+ await tester.pumpWidget(const SizedBox());+ },+ );++ // The shared pane (SharedHarnessPanel) sets `seen` from its VisibleTick: a hidden app or a+ // tab not showing is unseen.+ testWidgets(+ 'shared terminal watch: hidden app (unseen) — no reopen for 3 intervals; seen — one reopen at once',+ (tester) async {+ final sent = <String>[];+ final session = TerminalSession(+ machineId: 'shared',+ agentId: 'agent',+ agentName: 'Demo',+ engineId: 'codex',+ readOnly: true,+ send: (type, payload) async {+ sent.add(type);+ return true;+ },+ sendBinary: (_) async => false,+ );+ final watch = SharedTerminalWatch(+ session,+ canRetry: () => true,+ onChanged: () {},+ );+ int opens() => sent.where((type) => type == 'terminal_open').length;+ await session.open();+ await session.handleFrame('terminal_error', {+ 'requestId': null,+ 'code': 'TERMINAL_RUNTIME_UNAVAILABLE',+ });+ expect(watch.stopped, isTrue);+ await tester.pump(const Duration(seconds: 10));+ expect(opens(), 2, reason: 'asks again while seen');++ watch.seen = false;+ await tester.pump(const Duration(seconds: 30));+ expect(opens(), 2, reason: 'no reopen while unseen');+ watch.seen = true;+ await tester.pump();+ expect(opens(), 3, reason: 'one reopen at once when seen');+ await tester.pump(const Duration(seconds: 10));+ expect(opens(), 4, reason: 'then on its interval again');+ watch.dispose();+ session.dispose();+ },+ );++ testWidgets(+ 'shared link page (owner offline): hidden app — no request for 3 intervals; resumed — one read at once',+ (tester) async {+ final app = _plainApp();+ addTearDown(app.dispose);+ var reads = 0;+ final dio = Dio()+ ..interceptors.add(+ InterceptorsWrapper(+ onRequest: (request, handler) {+ reads++;+ handler.resolve(+ Response(+ requestOptions: request,+ statusCode: 200,+ data: {+ 'data': {+ 'ownerPublicKey': base64Encode(List.filled(32, 1)),+ 'online': false,+ },+ },+ ),+ );+ },+ ),+ );+ addTearDown(dio.close);+ await tester.pumpWidget(+ MaterialApp(+ home: SharedAgentPage(+ app: app,+ dio: dio,+ location: SharedAgentLocation(+ '11111111-1111-4111-8111-111111111111',+ base64Encode(List.filled(32, 1)),+ 'stag',+ ),+ openHarness: () async {},+ ),+ ),+ );+ await _soon(tester);+ expect(reads, 1);+ await _expectQuietWhileHidden(+ tester,+ every: const Duration(seconds: 10),+ reads: () => reads,+ );+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'tab invites: hidden app — no request for 3 intervals; resumed — one read at once',+ (tester) async {+ final app = _InvitesApp();+ addTearDown(app.dispose);+ int reads() =>+ app.paths.where((p) => p == '/api/super-tabs/invitations').length;+ await tester.pumpWidget(_host(TabInvitesSection(notifier: app)));+ await _soon(tester);+ expect(reads(), 1);+ await _expectQuietWhileHidden(+ tester,+ every: const Duration(seconds: 15),+ reads: reads,+ );+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'orchestrator workspace: hidden app — no request for 3 intervals; resumed — one read at once',+ (tester) async {+ final app = createApp();+ addTearDown(app.dispose);+ var reads = 0;+ final controller = OrchestratorController(+ id: 'p',+ request: (payload) async {+ if (payload['action'] == 'status') reads++;+ return {+ 'project': {'id': 'p', 'revision': reads, 'state': 'active'},+ };+ },+ );+ addTearDown(controller.dispose);+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1280, 850);+ addTearDown(tester.view.reset);+ await tester.pumpWidget(+ _host(+ OrchestratorWorkspace(+ notifier: app,+ machineId: 'm',+ projectId: 'p',+ controller: controller,+ ),+ ),+ );+ await _soon(tester);+ expect(reads, 1);+ await _expectQuietWhileHidden(+ tester,+ every: const Duration(seconds: 3),+ reads: () => reads,+ );+ await tester.pumpWidget(const SizedBox());+ },+ );++ for (final picker in [false, true]) {+ testWidgets(+ 'session activity (${picker ? 'Cmd-P results' : 'Welcome'}): hidden app — no request for 3 intervals; resumed — one read at once',+ (tester) async {+ final now = tester.binding.clock.now();+ var reads = 0;+ final hit = <String, dynamic>{+ 'agentId': '',+ 'sessionId': 'claude-session',+ 'engine': 'claude',+ 'field': 'name',+ 'snippet': '',+ 'lastAt': now.millisecondsSinceEpoch,+ 'external': {+ 'title': 'Pane connection losses',+ 'cwd': '/work/api',+ 'origin': 'terminal',+ 'open': true,+ 'openIn': 'terminal',+ },+ };+ final connection = TailConnection(+ {+ '': [hit],+ 'Pane': [hit],+ },+ tail: (_) {+ reads++;+ return {+ 'lastAt': now.millisecondsSinceEpoch,+ 'external': {'open': true, 'working': true},+ 'rows': <Object>[],+ 'total': 0,+ 'hasMore': false,+ };+ },+ );+ final app = createApp(+ connected: true,+ connectionForTest: (_) => connection,+ );+ addTearDown(app.dispose);+ final search = SwarmSearchController(+ app,+ const [],+ adding: true,+ activityFirst: true,+ );+ addTearDown(search.dispose);+ if (picker) search.setQuery('Pane');+ await tester.pumpWidget(+ MaterialApp(+ home: DesktopChrome(+ child: Scaffold(+ body: picker+ ? SwarmSearchResults(+ search: search,+ onChoose: (_) {},+ onRefocus: () {},+ showPreview: false,+ now: tester.binding.clock.now,+ )+ : WorkspaceWelcome(+ app: app,+ onCommand: (_) {},+ onOpen: (_) {},+ now: tester.binding.clock.now,+ composerBuilder: (recents) =>+ recents ?? const SizedBox(),+ ),+ ),+ ),+ ),+ );+ await tester.pump(const Duration(milliseconds: 200));+ await _soon(tester);+ expect(reads, greaterThan(0), reason: 'the row is read');+ await _expectQuietWhileHidden(+ tester,+ every: const Duration(seconds: 5),+ reads: () => reads,+ );+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 1));+ },+ );+ }++ testWidgets(+ 'devices tab: hidden app — no request for 3 intervals; resumed — one read at once',+ (tester) async {+ final app = _DevicesApp();+ addTearDown(app.dispose);+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1280, 900);+ addTearDown(tester.view.reset);+ await tester.pumpWidget(+ _host(+ DevicesTab(notifier: app, refreshEvery: const Duration(seconds: 10)),+ ),+ );+ await _soon(tester);+ expect(app.reads, 1);+ await _expectQuietWhileHidden(+ tester,+ every: const Duration(seconds: 10),+ reads: () => app.reads,+ );+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'store catalog: hidden app — no request for 3 intervals; resumed — one read at once',+ (tester) async {+ final app = _StoreApp();+ addTearDown(app.dispose);+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1280, 900);+ addTearDown(tester.view.reset);+ await tester.pumpWidget(_host(StoreTab(notifier: app, api: _StoreApi())));+ await _soon(tester);+ expect(app.probes, 1, reason: 'the Store asks once as it opens');+ await _expectQuietWhileHidden(+ tester,+ every: const Duration(minutes: 1),+ reads: () => app.probes,+ );+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'resource preview machine metrics: hidden app — no request for 3 intervals; resumed — one read at once',+ (tester) async {+ final app = _ResourcesApp();+ addTearDown(app.dispose);+ final search = SwarmSearchController(app, const [], adding: true)+ ..setQuery('@This Mac');+ addTearDown(search.dispose);+ await tester.pumpWidget(+ _host(+ SizedBox(+ width: 600,+ height: 600,+ child: SwarmResourcePreview(+ search: search,+ controls: SearchPreviewControls(),+ onChoose: (_) {},+ onRefocus: () {},+ onModalChanged: (_) {},+ onCommands: () {},+ resourcePollInterval: const Duration(seconds: 10),+ ),+ ),+ ),+ );+ await _soon(tester);+ await _expectQuietWhileHidden(+ tester,+ every: const Duration(seconds: 10),+ reads: () => app.reads,+ per: app.machineStates.length,+ );+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'wifi robots: hidden app — no request for 3 intervals; resumed — one read at once',+ (tester) async {+ final cli = _Cli();+ final wifi = WifiRobotsController(+ cli: cli,+ refreshEvery: const Duration(seconds: 60),+ );+ final dial = DialState();+ addTearDown(dial.dispose);+ final controller = DevicesController(+ dial: dial,+ accountId: 'a',+ sendSettings: (_, _) async => true,+ );+ addTearDown(controller.dispose);+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1280, 900);+ addTearDown(tester.view.reset);+ await tester.pumpWidget(+ _host(DevicesScreen(controller: controller, wifi: wifi)),+ );+ await _soon(tester);+ expect(cli.statusCalls, 1);+ await _expectQuietWhileHidden(+ tester,+ every: const Duration(seconds: 60),+ reads: () => cli.statusCalls,+ );+ await tester.pumpWidget(const SizedBox());+ wifi.dispose();+ },+ );+}diff --git a/desktop/test/hidden_window_controllers_test.dart b/desktop/test/hidden_window_controllers_test.dartnew file mode 100644index 000000000..082d023aa--- /dev/null+++ b/desktop/test/hidden_window_controllers_test.dart@@ -0,0 +1,120 @@+/// The app-wide readers outside the app model ask nothing on a clock while the window is hidden+/// (task #2953, roadmap Phase 3 item 2), and catch up once on return when a read came due.+///+/// Each takes the window's sight as a listenable (`AppNotifier.inSight` in the app); null, as in+/// every older caller, is always in sight.+library;++import 'package:clock/clock.dart';+import 'package:fake_async/fake_async.dart';+import 'package:flutter/foundation.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/settings/experimental_features.dart';+import 'package:harness/usage/models_menu_controller.dart';+import 'package:harness/usage/usage_accounts.dart';+import 'package:harness/usage/usage_controller.dart';+import 'package:harness/web/update/web_update_watcher.dart';++import 'experimental_features_test.dart' show AccountSettings;++void main() {+ group('experimental settings', () {+ test('out of sight: no read for two safety nets; back: one, then every '+ 'five minutes', () {+ fakeAsync((async) {+ final seen = ValueNotifier(true);+ final server = AccountSettings('owner');+ final store = ExperimentalFeaturesStore(seen: seen)+ ..bind('owner', transport: server);+ async.elapse(const Duration(seconds: 1));+ expect(server.reads, 1);+ seen.value = false;+ async.elapse(ExperimentalFeaturesStore.safetyNet * 2);+ expect(server.reads, 1, reason: 'nothing read while hidden');+ seen.value = true;+ async.flushMicrotasks();+ expect(server.reads, 2, reason: 'one read on return');+ async.elapse(ExperimentalFeaturesStore.safetyNet);+ expect(server.reads, 3, reason: 'then the safety net again');+ store.dispose();+ });+ });++ test(+ 'a glance away shorter than the safety net reads nothing on return',+ () {+ fakeAsync((async) {+ final seen = ValueNotifier(true);+ final server = AccountSettings('owner');+ final store = ExperimentalFeaturesStore(seen: seen)+ ..bind('owner', transport: server);+ async.elapse(const Duration(seconds: 1));+ seen.value = false;+ async.elapse(const Duration(seconds: 40));+ seen.value = true;+ async.flushMicrotasks();+ expect(server.reads, 1);+ store.dispose();+ });+ },+ );+ });++ group('subscription usage (the models menu)', () {+ test('out of sight: no usage read; back: one at once, then every five '+ 'minutes', () {+ fakeAsync((async) {+ final seen = ValueNotifier(true);+ var reads = 0;+ final menu = ModelsMenuController(+ usage: UsageController(+ sources: const [],+ remote: () async {+ reads++;+ return const <MachineUsage>[];+ },+ autoStart: false,+ ),+ now: clock.now,+ seen: seen,+ )..start();+ async.flushMicrotasks();+ expect(reads, 1);+ seen.value = false;+ async.elapse(const Duration(minutes: 20));+ expect(reads, 1, reason: 'nothing read while hidden');+ seen.value = true;+ async.flushMicrotasks();+ expect(reads, 2, reason: 'one read on return');+ async.elapse(const Duration(minutes: 5));+ expect(reads, 3, reason: 'then every five minutes');+ menu.dispose();+ });+ });+ });++ group('the web page\'s release check', () {+ test('a hidden tab asks the host nothing on its clock', () {+ fakeAsync((async) {+ var shown = true, reads = 0;+ final watcher = WebUpdateWatcher(+ running: '1.3.51',+ readLatest: () async {+ reads++;+ return '1.3.51';+ },+ shown: () => shown,+ )..start();+ async.elapse(const Duration(minutes: 5));+ expect(reads, 1);+ shown = false;+ async.elapse(const Duration(minutes: 30));+ expect(reads, 1, reason: 'nothing read while hidden');+ shown = true;+ async.elapse(const Duration(minutes: 5));+ expect(reads, 2);+ watcher.dispose();+ });+ });+ });+}diff --git a/desktop/test/hidden_window_requests_test.dart b/desktop/test/hidden_window_requests_test.dartnew file mode 100644index 000000000..2829b123b--- /dev/null+++ b/desktop/test/hidden_window_requests_test.dart@@ -0,0 +1,328 @@+/// What one idle, hidden Desktop window asks of the backend per minute (task #2953): the PR's+/// before/after measurement.+///+/// The window: signed in, this computer connected (its agent list relayed like any machine's), two+/// Swarms open with the server pushing, as a person leaves it at the end of a day. Then the window+/// is hidden — minimised, or closed to the menu bar — and ten simulated minutes pass. Every read+/// the app model and the Swarm client make is counted by kind; the test prints requests per minute+/// and asserts none was made on a clock. Run on main's code it prints the before.+///+/// Fixtures as in hidden_window_rereads_test.dart: the real app model and Swarm client, a fake CLI+/// that never signs this Mac out, a memory store.+library;++import 'dart:async';++import 'package:fake_async/fake_async.dart';+import 'package:flutter/widgets.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/api/api_client.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/auth/cli_login.dart';+import 'package:harness/auth/sign_in_provider.dart';+import 'package:harness/bootstrap/environment_provisioner.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/client.dart';+import 'package:harness/super_tabs/reading.dart';+import 'package:harness/ws/local_cli_discovery.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_state_test.dart' show MemoryStore;+import 'support/super_tab_fixture.dart';++/// Two Swarms behind the backend, every read counted.+class _Swarms {+ final servers = {'tab': ConversationServer(), 'other': ConversationServer()};+ final paths = <String>[];++ _Swarms() {+ servers['other']!.state['id'] = 'other';+ }++ Future<Object?> call(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) async {+ paths.add(path);+ if (Uri.parse(path).path == '/api/super-tabs/list') {+ return {+ 'tabs': [+ {'id': 'tab', 'name': 'Pilot'},+ {'id': 'other', 'name': 'Other'},+ ],+ 'next': null,+ };+ }+ final id = Uri.parse(path).pathSegments[2];+ return servers[id]!.request(method, path, body: body);+ }+}++const _computerId = 'aabbccddeeff0011';++const _thisComputer = Machine(+ machineId: 'local-machine',+ name: 'Studio',+ computerId: _computerId,+ authMode: MachineAuthMode.remote,+ status: 'online',+);++/// What the app asks, counted: the machine list (through the CLI to the+/// backend) and every request on this computer's socket.+class _Asked {+ int machineReads = 0;+ int agentReads = 0;+ int deskReads = 0;++ /// Every request on this computer's socket, by type.+ final socket = <String, int>{};++ /// The backend is down: the machine list answers 503, which recovery retries.+ bool down = false;++ /// What an `agents_list` answers: the agents on this computer.+ List<Map<String, dynamic>> agents = const [];+}++class _Api extends ApiClient {+ _Api(this.asked)+ : super(+ config: AppConfig.dev,+ session: AuthSession(storage: MemoryStore()),+ );+ final _Asked asked;++ @override+ Future<Map<String, dynamic>?> me() async => null;++ @override+ Future<Map<String, dynamic>?> desk() async {+ asked.deskReads++;+ return null;+ }++ @override+ Future<Map<String, dynamic>?> daemonDevices() async => null;++ @override+ Future<List<Machine>> machines() async {+ asked.machineReads++;+ if (asked.down) throw ApiException('Service unavailable', status: 503);+ return const [_thisComputer];+ }+}++class _Login extends CliLogin {+ _Login({this.loggedIn = false});+ bool loggedIn;+ Completer<void>? pending;++ @override+ Future<CliAuthStatus> checkStatus() async =>+ CliAuthStatus(loggedIn: loggedIn);++ // Never the real CLI: this Mac stays signed in whatever a test does.+ @override+ Future<void> logout() async => loggedIn = false;++ @override+ Future<void> login({+ required void Function(String) onAuthorizeUrl,+ SignInProvider? provider,+ }) async {+ final wait = pending = Completer<void>();+ await wait.future;+ loggedIn = true;+ }+}++class _Setup extends EnvironmentProvisioner {+ _Setup() : super(isMacOS: true);++ @override+ Future<EnvironmentReadiness> ensureReady({+ required void Function(EnvironmentReadiness value) onProgress,+ EnvironmentReadiness? resumeFrom,+ bool install = true,+ EnvironmentSetupMode? mode,+ }) async {+ final ready = EnvironmentReadiness(+ steps: {+ for (final step in EnvironmentStep.values)+ step: EnvironmentStepStatus.ready,+ },+ phase: EnvironmentSetupPhase.ready,+ mode: EnvironmentSetupMode.automatic,+ );+ onProgress(ready);+ return ready;+ }+}++class _Discovery extends LocalCliDiscovery {+ _Discovery() : super(config: AppConfig.dev);+ @override+ Future<String?> computerId() async => _computerId;+ @override+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>+ LocalCliEndpoint(+ computerId: _computerId,+ wsUri: Uri.parse('ws://127.0.0.1:18473/ws'),+ protocolVersion: localWsProtocolVersion,+ terminalProtocolVersion: 1,+ machineId: 'local-machine',+ backendOnline: true,+ );+}++class _Connection extends WsConn {+ _Connection(this.asked)+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'local-machine',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ final _Asked asked;++ @override+ Future<void> waitUntilReady({required Duration timeout}) async {}++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type == 'agents_list') asked.agentReads++;+ asked.socket[type] = (asked.socket[type] ?? 0) + 1;+ return {'agents': asked.agents};+ }+}++class _Desktop extends AppNotifier {+ _Desktop(this.cli, this.asked)+ : super(+ config: AppConfig.dev,+ configStore: null,+ authSession: AuthSession(storage: MemoryStore()),+ cliLogin: cli,+ environmentProvisioner: _Setup(),+ localCliDiscovery: _Discovery(),+ connectionForTest: (_) => _Connection(asked),+ ) {+ api = _Api(asked);+ }++ final _Login cli;+ final _Asked asked;++ @override+ Future<void> ensureCliDaemonReady() async {}+}++/// Boots [app] and connects this computer, as a launch does.+void _launch(FakeAsync async, _Desktop app) {+ unawaited(app.bootstrap());+ async.flushMicrotasks();+ async.elapse(const Duration(seconds: 1));+ // The socket's own connect: what starts a signed-in window's agent sync.+ app.onMachineConnectedForTest('local-machine');+ async.elapse(const Duration(seconds: 1));+}++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ test('an idle hidden window makes no periodic backend request', () {+ fakeAsync((async) {+ final asked = _Asked();+ final app = _Desktop(_Login(loggedIn: true), asked);+ app.appLifecycleChanged(AppLifecycleState.resumed);+ _launch(async, app);+ expect(app.isGuest, isFalse);++ // The Swarm client as the workspace runs it (Desktop's reading, pushes heard).+ final swarms = _Swarms();+ final client = SuperTabClient(+ transport: swarms.call,+ storage: MemoryStore(),+ onTabs: (_, _) {},+ discoveryInterval: const Duration(seconds: 15),+ )..reading = SuperTabReading.desktop;+ client+ ..bind('owner')+ ..show('tab');+ client.open('tab');+ client.open('other');+ async.elapse(const Duration(seconds: 1));+ // The server's word that it pushes: on connect, then every 4 minutes (backend+ // lib/swarmClientPushes.ts PUSHES_REPEAT_MS).+ client.swarmChanged(const {});+ final repeat = Timer.periodic(+ const Duration(minutes: 4),+ (_) => client.swarmChanged(const {}),+ );+ async.elapse(const Duration(minutes: 1));++ // Hidden, as the workspace tells both (SuperTabWorkspace, SwarmScreen).+ app.appLifecycleChanged(AppLifecycleState.inactive);+ app.appLifecycleChanged(AppLifecycleState.hidden);+ client.pageVisible = false;+ async.elapse(const Duration(seconds: 2));++ final machines0 = asked.machineReads, desk0 = asked.deskReads;+ final socket0 = Map.of(asked.socket);+ swarms.paths.clear();+ const minutes = 10;+ for (var minute = 1; minute <= minutes; minute++) {+ async.elapse(const Duration(minutes: 1));+ }+ async.flushMicrotasks();++ final perKind = <String, int>{+ 'GET /api/machines (+ /api/harness-shares)':+ asked.machineReads - machines0,+ 'GET desk': asked.deskReads - desk0,+ for (final type in asked.socket.keys)+ 'machine $type (relayed)': asked.socket[type]! - (socket0[type] ?? 0),+ };+ for (final path in swarms.paths) {+ final uri = Uri.parse(path);+ final kind = uri.pathSegments.length > 3+ ? 'Swarm ${uri.pathSegments[3]}'+ : 'Swarm ${uri.pathSegments.last}';+ perKind[kind] = (perKind[kind] ?? 0) + 1;+ }+ perKind.removeWhere((_, count) => count == 0);+ final total = perKind.values.fold(0, (sum, n) => sum + n);+ // ignore: avoid_print+ print(+ 'hidden window, $minutes min: ${total / minutes} requests/min\n'+ '${[for (final e in perKind.entries) ' ${e.key}: ${e.value / minutes}/min'].join('\n')}',+ );+ expect(perKind, isEmpty, reason: 'no request on a clock while hidden');++ // Back in sight: each reads once.+ app.appLifecycleChanged(AppLifecycleState.inactive);+ app.appLifecycleChanged(AppLifecycleState.resumed);+ client.pageVisible = true;+ async.elapse(const Duration(seconds: 2));+ expect(asked.socket['agents_list'], greaterThan(socket0['agents_list']!));+ expect(asked.machineReads, machines0 + 1);+ expect(swarms.paths, isNotEmpty);++ repeat.cancel();+ client.dispose();+ app.dispose();+ async.flushMicrotasks();+ });+ });+}diff --git a/desktop/test/hidden_window_rereads_test.dart b/desktop/test/hidden_window_rereads_test.dartnew file mode 100644index 000000000..a38c5da0e--- /dev/null+++ b/desktop/test/hidden_window_rereads_test.dart@@ -0,0 +1,402 @@+/// A hidden window asks nothing on a timer (task #2953, roadmap Phase 3 item 2).+///+/// A signed-in window keeps two background re-reads: each connected machine's+/// agent list every minute, and the machine list (with the desk) every five.+/// While the window is hidden — minimised, behind other windows, closed to the+/// menu bar, a browser tab in the background — they used to keep going. These+/// pin that they stop while it is hidden, and that coming back reads once at+/// once (only what came due while away), then goes on as before.+///+/// Fixtures as in signed_out_polling_test.dart: the real app model, a fake+/// CLI that never signs this Mac out, a memory store.+library;++import 'dart:async';++import 'package:fake_async/fake_async.dart';+import 'package:flutter/widgets.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/api/api_client.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/auth/cli_login.dart';+import 'package:harness/auth/sign_in_provider.dart';+import 'package:harness/bootstrap/environment_provisioner.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/ws/local_cli_discovery.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_state_test.dart' show MemoryStore;++const _computerId = 'aabbccddeeff0011';++const _thisComputer = Machine(+ machineId: 'local-machine',+ name: 'Studio',+ computerId: _computerId,+ authMode: MachineAuthMode.remote,+ status: 'online',+);++/// What the app asks, counted: the machine list (through the CLI to the+/// backend) and every request on this computer's socket.+class _Asked {+ int machineReads = 0;+ int agentReads = 0;+ int deskReads = 0;++ /// The backend is down: the machine list answers 503, which recovery retries.+ bool down = false;++ /// What an `agents_list` answers: the agents on this computer.+ List<Map<String, dynamic>> agents = const [];+}++class _Api extends ApiClient {+ _Api(this.asked)+ : super(+ config: AppConfig.dev,+ session: AuthSession(storage: MemoryStore()),+ );+ final _Asked asked;++ @override+ Future<Map<String, dynamic>?> me() async => null;++ @override+ Future<Map<String, dynamic>?> desk() async {+ asked.deskReads++;+ return null;+ }++ @override+ Future<Map<String, dynamic>?> daemonDevices() async => null;++ @override+ Future<List<Machine>> machines() async {+ asked.machineReads++;+ if (asked.down) throw ApiException('Service unavailable', status: 503);+ return const [_thisComputer];+ }+}++class _Login extends CliLogin {+ _Login({this.loggedIn = false});+ bool loggedIn;+ Completer<void>? pending;++ @override+ Future<CliAuthStatus> checkStatus() async =>+ CliAuthStatus(loggedIn: loggedIn);++ // Never the real CLI: this Mac stays signed in whatever a test does.+ @override+ Future<void> logout() async => loggedIn = false;++ @override+ Future<void> login({+ required void Function(String) onAuthorizeUrl,+ SignInProvider? provider,+ }) async {+ final wait = pending = Completer<void>();+ await wait.future;+ loggedIn = true;+ }+}++class _Setup extends EnvironmentProvisioner {+ _Setup() : super(isMacOS: true);++ @override+ Future<EnvironmentReadiness> ensureReady({+ required void Function(EnvironmentReadiness value) onProgress,+ EnvironmentReadiness? resumeFrom,+ bool install = true,+ EnvironmentSetupMode? mode,+ }) async {+ final ready = EnvironmentReadiness(+ steps: {+ for (final step in EnvironmentStep.values)+ step: EnvironmentStepStatus.ready,+ },+ phase: EnvironmentSetupPhase.ready,+ mode: EnvironmentSetupMode.automatic,+ );+ onProgress(ready);+ return ready;+ }+}++class _Discovery extends LocalCliDiscovery {+ _Discovery() : super(config: AppConfig.dev);+ @override+ Future<String?> computerId() async => _computerId;+ @override+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>+ LocalCliEndpoint(+ computerId: _computerId,+ wsUri: Uri.parse('ws://127.0.0.1:18473/ws'),+ protocolVersion: localWsProtocolVersion,+ terminalProtocolVersion: 1,+ machineId: 'local-machine',+ backendOnline: true,+ );+}++class _Connection extends WsConn {+ _Connection(this.asked)+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'local-machine',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ final _Asked asked;++ @override+ Future<void> waitUntilReady({required Duration timeout}) async {}++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type == 'agents_list') asked.agentReads++;+ return {'agents': asked.agents};+ }+}++class _Desktop extends AppNotifier {+ _Desktop(this.cli, this.asked)+ : super(+ config: AppConfig.dev,+ configStore: null,+ authSession: AuthSession(storage: MemoryStore()),+ cliLogin: cli,+ environmentProvisioner: _Setup(),+ localCliDiscovery: _Discovery(),+ connectionForTest: (_) => _Connection(asked),+ ) {+ api = _Api(asked);+ }++ final _Login cli;+ final _Asked asked;++ @override+ Future<void> ensureCliDaemonReady() async {}+}++/// Boots [app] and connects this computer, as a launch does.+void _launch(FakeAsync async, _Desktop app) {+ unawaited(app.bootstrap());+ async.flushMicrotasks();+ async.elapse(const Duration(seconds: 1));+ // The socket's own connect: what starts a signed-in window's agent sync.+ app.onMachineConnectedForTest('local-machine');+ async.elapse(const Duration(seconds: 1));+}++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ const minute = AppNotifier.agentSyncInterval;+ const safetyNet = AppNotifier.machineListSafetyNetInterval;++ /// A signed-in Desktop with this computer connected and its first reads done.+ _Desktop signedIn(FakeAsync async, _Asked asked) {+ final app = _Desktop(_Login(loggedIn: true), asked);+ app.appLifecycleChanged(AppLifecycleState.resumed);+ _launch(async, app);+ expect(app.isGuest, isFalse);+ return app;+ }++ void hide(_Desktop app) {+ app.appLifecycleChanged(AppLifecycleState.inactive);+ app.appLifecycleChanged(AppLifecycleState.hidden);+ }++ void show(_Desktop app) {+ app.appLifecycleChanged(AppLifecycleState.inactive);+ app.appLifecycleChanged(AppLifecycleState.resumed);+ }++ void done(FakeAsync async, _Desktop app) {+ app.dispose();+ async.flushMicrotasks();+ }++ test('hidden: no agent list for five minutes; shown: one at once, then '+ 'every minute', () {+ fakeAsync((async) {+ final asked = _Asked();+ final app = signedIn(async, asked);+ // Shown, the minute's sync runs.+ var before = asked.agentReads;+ async.elapse(minute);+ async.flushMicrotasks();+ expect(asked.agentReads, before + 1, reason: 'shown: every minute');++ hide(app);+ before = asked.agentReads;+ async.elapse(minute * 5);+ async.flushMicrotasks();+ expect(asked.agentReads, before, reason: 'no agent sync while hidden');++ show(app);+ async.flushMicrotasks();+ expect(asked.agentReads, before + 1, reason: 'one read on return');+ async.elapse(minute);+ async.flushMicrotasks();+ expect(asked.agentReads, before + 2, reason: 'then every minute again');+ done(async, app);+ });+ });++ test('an unfocused window still in sight keeps its agent sync', () {+ fakeAsync((async) {+ final asked = _Asked();+ final app = signedIn(async, asked);+ app.appLifecycleChanged(AppLifecycleState.inactive);+ final before = asked.agentReads;+ async.elapse(minute * 3);+ async.flushMicrotasks();+ expect(asked.agentReads, before + 3);+ done(async, app);+ });+ });++ // The desk rides on the same tick; this fixture's desk answers nothing, so only its absence+ // while hidden is counted.+ test('hidden: the safety net reads no machine list or desk; shown: one '+ 'list', () {+ fakeAsync((async) {+ final asked = _Asked();+ final app = signedIn(async, asked);+ hide(app);+ final machines = asked.machineReads, desk = asked.deskReads;+ async.elapse(safetyNet * 3);+ async.flushMicrotasks();+ expect(asked.machineReads, machines, reason: 'no list while hidden');+ expect(asked.deskReads, desk, reason: 'no desk while hidden');++ show(app);+ async.elapse(const Duration(seconds: 1));+ expect(asked.machineReads, machines + 1, reason: 'one list on return');+ async.elapse(safetyNet);+ async.flushMicrotasks();+ expect(+ asked.machineReads,+ machines + 2,+ reason: 'then every five minutes again',+ );+ done(async, app);+ });+ });++ test('hidden for less than an interval: nothing read on return, and still '+ 'one timer', () {+ fakeAsync((async) {+ final asked = _Asked();+ final app = signedIn(async, asked);+ final agents = asked.agentReads, machines = asked.machineReads;+ // Hide, show, hide, show within a few seconds: a glance at another app.+ for (var i = 0; i < 3; i++) {+ hide(app);+ async.elapse(const Duration(seconds: 2));+ show(app);+ async.elapse(const Duration(seconds: 2));+ }+ expect(asked.agentReads, agents, reason: 'nothing came due');+ expect(asked.machineReads, machines, reason: 'nothing came due');+ async.elapse(minute);+ async.flushMicrotasks();+ expect(asked.agentReads, agents + 1, reason: 'one timer, not four');+ done(async, app);+ });+ });++ test('a machine connecting while hidden reads its list once, and starts '+ 'its minute only when shown', () {+ fakeAsync((async) {+ final asked = _Asked();+ final app = signedIn(async, asked);+ hide(app);+ // The socket drops and comes back while nobody looks.+ app.onMachineConnectedForTest('local-machine');+ async.elapse(const Duration(seconds: 1));+ final before = asked.agentReads;+ async.elapse(minute * 4);+ async.flushMicrotasks();+ expect(asked.agentReads, before, reason: 'no minute sync while hidden');+ show(app);+ async.flushMicrotasks();+ expect(asked.agentReads, before + 1);+ done(async, app);+ });+ });++ test('a held agent is not re-read while hidden', () {+ fakeAsync((async) {+ final asked = _Asked()+ ..agents = const [+ {+ 'id': 'a1',+ 'name': 'held one',+ 'engine': 'claude',+ 'terminal': {'available': true},+ 'launch': {'state': 'held', 'service': 'search'},+ },+ ];+ final app = signedIn(async, asked);+ app.heldLaunchSyncInterval = const Duration(seconds: 3);+ unawaited(+ app.handleEventForTest('local-machine', {+ 'type': 'agent_synced',+ 'payload': {'agent': asked.agents.single},+ }),+ );+ async.flushMicrotasks();+ hide(app);+ final before = asked.agentReads;+ async.elapse(minute * 2);+ async.flushMicrotasks();+ expect(asked.agentReads, before, reason: 'held: no re-read while hidden');+ show(app);+ async.elapse(const Duration(seconds: 1));+ expect(asked.agentReads, greaterThan(before));+ done(async, app);+ });+ });++ test('hidden with the backend down: recovery asks nothing until shown, '+ 'then once at once', () {+ fakeAsync((async) {+ final asked = _Asked();+ final app = signedIn(async, asked);+ asked.down = true;+ unawaited(+ app.refreshMachines().then<void>((_) {}, onError: (Object _) {}),+ );+ async.elapse(const Duration(seconds: 1));+ hide(app);+ // Recovery's one read already on its clock may still land; after it, nothing.+ async.elapse(const Duration(seconds: 3));+ final before = asked.machineReads;+ async.elapse(const Duration(minutes: 4));+ async.flushMicrotasks();+ expect(asked.machineReads, before, reason: 'no recovery while hidden');+ show(app);+ async.elapse(const Duration(seconds: 3));+ expect(asked.machineReads, greaterThan(before), reason: 'read on return');+ asked.down = false;+ async.elapse(const Duration(seconds: 30));+ done(async, app);+ });+ });+}diff --git a/desktop/test/hidden_window_swarm_test.dart b/desktop/test/hidden_window_swarm_test.dartnew file mode 100644index 000000000..d879ca4f2--- /dev/null+++ b/desktop/test/hidden_window_swarm_test.dart@@ -0,0 +1,199 @@+/// A hidden Desktop window reads its Swarms only when the server says something changed+/// (task #2953, roadmap Phase 3 item 2).+///+/// Desktop keeps reading the Swarms it does not show, because their badges and+/// notices come from those reads. With the server pushing, a change is told and+/// read at once; the reads on a clock (the 60 s safety net of each open Swarm,+/// discovery's 2-minute one) were the hidden window's idle traffic. These pin+/// that they stop while the window is hidden and catch up once on return, and+/// that without pushes the 15 s away poll still runs, so no tag is missed.+library;++import 'dart:async';++import 'package:fake_async/fake_async.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/client.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/reading.dart';++import 'swarm_state_test.dart' show MemoryStore;+import 'support/super_tab_fixture.dart';++/// Two Swarms behind one backend.+class _Backend {+ final servers = {'tab': ConversationServer(), 'other': ConversationServer()};+ final paths = <String>[];++ _Backend() {+ servers['other']!.state['id'] = 'other';+ }++ Future<Object?> call(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) async {+ paths.add(path);+ if (Uri.parse(path).path == '/api/super-tabs/list') {+ return {+ 'tabs': [+ {'id': 'tab', 'name': 'Pilot'},+ {'id': 'other', 'name': 'Other'},+ ],+ 'next': null,+ };+ }+ final id = Uri.parse(path).pathSegments[2];+ return servers[id]!.request(method, path, body: body);+ }++ int states(String id) => paths+ .where(+ (p) =>+ p == '/api/super-tabs/$id/parts' ||+ p.startsWith('/api/super-tabs/$id/changes?'),+ )+ .length;+ int get discoveries =>+ paths.where((p) => Uri.parse(p).path == '/api/super-tabs/list').length;+ int get reads => paths.length;+}++var _changedAt = DateTime.utc(2100).millisecondsSinceEpoch;++void main() {+ /// Desktop's client with Swarm 'tab' open and on screen.+ SuperTabClient desktop(FakeAsync async, _Backend backend) {+ final client = SuperTabClient(+ transport: backend.call,+ storage: MemoryStore(),+ onTabs: (_, _) {},+ discoveryInterval: const Duration(seconds: 15),+ )..reading = SuperTabReading.desktop;+ client+ ..bind('owner')+ ..show('tab');+ client.open('tab');+ async.elapse(const Duration(seconds: 1));+ return client;+ }++ test('hidden while the server pushes: no read on a clock for 10 minutes; '+ 'shown: the Swarm and the list once each', () {+ fakeAsync((async) {+ final backend = _Backend();+ final client = desktop(async, backend);+ // The server's word that it pushes: on connect, then every 4 minutes+ // (backend lib/swarmClientPushes.ts PUSHES_REPEAT_MS), as a live socket hears it.+ client.swarmChanged(const {});+ final repeat = Timer.periodic(+ const Duration(minutes: 4),+ (_) => client.swarmChanged(const {}),+ );+ async.elapse(const Duration(seconds: 20));+ client.pageVisible = false;+ async.elapse(const Duration(seconds: 1));+ backend.paths.clear();+ async.elapse(const Duration(minutes: 10));+ expect(backend.paths, isEmpty, reason: 'nothing read on a clock');+ repeat.cancel();+ async.elapse(const Duration(seconds: 2));+ expect(backend.paths, isEmpty, reason: 'nothing read on a clock');++ client.pageVisible = true;+ async.elapse(const Duration(seconds: 2));+ expect(backend.states('tab'), 1, reason: 'the Swarm on screen, once');+ expect(backend.discoveries, 1, reason: 'the list, once');+ client.dispose();+ });+ });++ test(+ 'hidden while the server pushes: a told change is still read at once',+ () {+ fakeAsync((async) {+ final backend = _Backend();+ final client = desktop(async, backend);+ client.swarmChanged(const {});+ async.elapse(const Duration(seconds: 20));+ client.pageVisible = false;+ async.elapse(const Duration(seconds: 1));+ backend.paths.clear();+ backend.servers['tab']!.append('A tag for you');+ client.swarmChanged({+ 'tabId': 'tab',+ 'lastChangedAt': ++_changedAt,+ 'parts': const ['main'],+ });+ async.elapse(const Duration(seconds: 2));+ expect(backend.states('tab'), 1);+ client.dispose();+ });+ },+ );++ // Review of #3035: the word comes on every connect too, with the same payload. A word off the+ // 4-minute beat is a socket that reconnected, and a push may have been lost meanwhile: a hidden+ // window reads its open Swarms and the list once, so a tag's notice still comes.+ test('hidden while the server pushes: a word off the 4-minute beat (a '+ 'reconnect) reads the open Swarm and the list once', () {+ fakeAsync((async) {+ final backend = _Backend();+ final client = desktop(async, backend);+ client.swarmChanged(const {});+ async.elapse(const Duration(seconds: 20));+ client.pageVisible = false;+ async.elapse(const Duration(seconds: 70));+ backend.paths.clear();+ // A tag lands while the socket is away, then the socket is back.+ backend.servers['tab']!.append('A tag for you');+ client.swarmChanged(const {});+ async.elapse(const Duration(seconds: 20));+ expect(backend.states('tab'), 1, reason: 'the open Swarm, once');+ expect(backend.discoveries, 1, reason: 'the list, once');+ backend.paths.clear();+ // Its own beat 4 minutes on is a repeat: nothing.+ async.elapse(const Duration(minutes: 4) - const Duration(seconds: 20));+ client.swarmChanged(const {});+ async.elapse(const Duration(seconds: 20));+ expect(backend.paths, isEmpty, reason: 'a repeat reads nothing');+ client.dispose();+ });+ });++ test('hidden with no push heard: the 15 s away poll still reads, so tags '+ 'and notices still arrive', () {+ fakeAsync((async) {+ final backend = _Backend();+ final client = desktop(async, backend);+ client.pageVisible = false;+ async.elapse(const Duration(seconds: 1));+ backend.paths.clear();+ async.elapse(const Duration(minutes: 1));+ expect(backend.states('tab'), inInclusiveRange(3, 4));+ client.dispose();+ });+ });++ test('a glance away shorter than the safety net reads nothing on return', () {+ fakeAsync((async) {+ final backend = _Backend();+ final client = desktop(async, backend);+ client.swarmChanged(const {});+ async.elapse(const Duration(seconds: 20));+ backend.paths.clear();+ client.pageVisible = false;+ async.elapse(const Duration(seconds: 5));+ client.pageVisible = true;+ async.elapse(const Duration(seconds: 1));+ expect(backend.discoveries, 0);+ client.dispose();+ });+ });++ test('the safety net constants this pins', () {+ expect(kSwarmPushSafetyNet, const Duration(seconds: 60));+ expect(kSwarmDiscoverySafetyNet, const Duration(minutes: 2));+ });+}diff --git a/desktop/test/product_health_test.dart b/desktop/test/product_health_test.dartindex 03e7fe2c4..47e6c7143 100644--- a/desktop/test/product_health_test.dart+++ b/desktop/test/product_health_test.dart@@ -151,7 +151,10 @@ void main() {usage.begin(ProductFlow.agentImport)(ProductOutcome.ok);usage.begin(ProductFlow.agentImport)(ProductOutcome.cancelled);await usage.flush();- expect(totals().keys.where((name) => name.contains('agent_import')), isEmpty);+ expect(+ totals().keys.where((name) => name.contains('agent_import')),+ isEmpty,+ );usage.proxyVocabulary = 7;await usage.flush();expect(totals()['ui_desktop_agent_import_started'], 2);@@ -412,6 +415,39 @@ void main() {},);+ // Task #2953: the minute's memory sample is what made a hidden window send a report every+ // minute. Out of sight it samples nothing, so nothing is sent; in sight it samples as before.+ testWidgets('memory is sampled only while the window is in sight', (+ tester,+ ) async {+ var lifecycle = AppLifecycleState.hidden;+ final runtime = ProductRuntimeHealth(+ usage,+ readState: () async => {},+ writeState: (_) async {},+ readVersion: () async => '1.2.73',+ lifecycle: () => lifecycle,+ );+ runtime.account('PRIVATE_ACCOUNT');+ await usage.flush();+ await tester.pump();+ int rss() => totals().entries+ .where((e) => e.key.contains('_rss_'))+ .fold(0, (sum, e) => sum + e.value);+ final before = rss();+ for (var i = 0; i < 5; i++) {+ runtime.sampleResources();+ }+ await usage.flush();+ expect(rss(), before, reason: 'hidden: no sample');+ lifecycle = AppLifecycleState.inactive;+ runtime.sampleResources();+ await usage.flush();+ expect(rss(), before + 1, reason: 'in sight, unfocused: sampled');+ runtime.dispose();+ await tester.pump();+ });+testWidgets('frames sample every 60th visible frame, never the first or a hidden one',(tester) async {diff --git a/desktop/test/super_tab_backlog_test.dart b/desktop/test/super_tab_backlog_test.dartindex 9f6230e87..a9a02316f 100644--- a/desktop/test/super_tab_backlog_test.dart+++ b/desktop/test/super_tab_backlog_test.dart@@ -915,6 +915,31 @@ void main() {);});+ // Task #2953: a hidden window asks GitHub nothing for the backlog's rows, as live cards do+ // (VisibleTick); back on screen it watches them again.+ testWidgets('a hidden window lets the rows\' pull requests go, and watches '+ 'them again on return', (tester) async {+ var reads = 0;+ final facts = SuperTabPullRequestFacts((_) async {+ reads++;+ return const {'account': 'ada', 'rows': []};+ });+ addTearDown(facts.dispose);+ await show(tester, swarm(), facts: facts);+ expect(facts.watching, isNotEmpty);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);+ await tester.pump();+ expect(facts.watching, isEmpty, reason: 'nothing watched while hidden');+ final before = reads;+ await tester.pump(SuperTabPullRequestFacts.every * 3);+ expect(reads, before, reason: 'no read while hidden');+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ await tester.pump();+ expect(facts.watching, isNotEmpty);+ });+testWidgets('clicking a row opens its chat', (tester) async {await show(tester, swarm());await tester.tap(row('review'));diff --git a/docs/plans/2026-11-04-hidden-windows-stop-polling-plan.md b/docs/plans/2026-11-04-hidden-windows-stop-polling-plan.mdnew file mode 100644index 000000000..c8ac75faf--- /dev/null+++ b/docs/plans/2026-11-04-hidden-windows-stop-polling-plan.md@@ -0,0 +1,156 @@+# Hidden windows stop polling — Implementation Plan++> Way of working: the project's Engineer workflow (docs/plans plan first, then each plan task test first —+> failing test committed before its code — with independent plan tasks run in parallel by subagents and+> merged into one pull request). Steps use checkbox (`- [ ]`) syntax.++**Goal:** A Desktop window or web tab that is hidden or closed, and the phone app in the background, make no+periodic backend requests; on return each poller reads once, then goes live again.++**Architecture:** One visibility signal per app, already in the code, used everywhere:+- Desktop and web app model: `AppNotifier.inSight` (`desktop/lib/state/app_state.dart`, true while the window+ is `resumed` or `inactive`; Flutter web turns `document.visibilityState == 'hidden'` into `hidden`, macOS an+ occluded, minimised or closed window). Long-lived pollers listen to it: off → cancel the timer; on → one+ read, then the timer again.+- Desktop and web widgets: the existing `VisibleTick` mixin (`desktop/lib/super_tabs/visible_tick.dart`:+ TickerMode on and the app shown). A widget poller ticks through it and reads once from+ `onScreenChanged(true)`.+- Swarm reads (`SuperTabClient.pageVisible` / `SuperTabController.away`): while the page is hidden and the+ server pushes, only a push reads; the safety nets wait for the return. Without push the away poll stays,+ so tags and notices still arrive (failure: nothing breaks silently).+- Phone: `AppNotifier.handleAppPaused` / `handleAppResumed` (`mobile/lib/state/app_state.dart`) stop and+ restart the app-model pollers; page pollers use `WidgetsBindingObserver` the way `swarm_machines.dart`+ already does.++Pollers already gated (Harness Monitor, the Swarm machines panel, its usage, machines panel, pull request+badges, model manager, agent messages watches, the web deaf watch, the web Swarm reading, phone desk/deaf+poll/Swarm reads) keep their gate and get a regression test where none pins "no request while hidden".++**Tech Stack:** Flutter 3.47 / Dart 3.13, flutter_test (`testWidgets` fake clock), the existing fakes+(`WsConn` subclasses, `ApiClient` subclasses, `MemoryStore`).++**Spec:** docs/plans/2026-10-28-websocket-optimization-roadmap.md, Phase 3 item 2, and task #2953's brief.++## Global Constraints++- Optimizations ship on, no switches (Ken).+- Phase 3 items 1 (shared E2EE session) and 3 (observer fan-out) are out of scope.+- Never run a test that signs the Mac out of the real CLI; Desktop tests use a memory store and a fake sign-in.+- Swarm code stays out of cli/src/core. No backend change.+- "Hidden" means not seen: Desktop `hidden`/`paused`/`detached` (minimised, occluded, closed to the menu+ bar); web tab hidden; phone `paused`/`hidden`. An unfocused window still in sight (`inactive`) keeps reading.+- Not periodic reads, left alone and listed in the PR: terminal stream heartbeats (`terminal_alive`, a 30 s+ lease the daemon holds the stream on), native pane leases (`renewNative`), WebRTC upgrade probes, socket+ reconnect backoff, the Desktop updater's check (Google Cloud Storage, not the backend), flows a person is+ in the middle of with their own deadline (pairing, Wi-Fi change, held New Harness, pet status).++## Review Focus++1. A window hidden while a read is in flight: the late answer still applies; no second timer is armed.+2. Hide → show → hide quickly: exactly one read on return, never two timers.+3. Sign-out while hidden, then show: nothing reads for the old account (existing sign-out cancels stay).+4. Desktop hidden with Swarm push down: the away poll still runs, so tag notices still arrive.+5. A machine that connects while the window is hidden starts no agent-sync timer until the window shows.++---++### Task 1: Desktop/web app model — agent sync, held sync, machine-list safety net, recovery loops++**Files:**+- Modify: `desktop/lib/state/app_state.dart` (`appLifecycleChanged`, `_startBackgroundRereads`,+ `_startAgentSyncTimer`, `_watchHeldLaunches`, `_scheduleRemoteOfflinePoll`, `_scheduleMachineRecovery`)+- Test: `desktop/test/hidden_window_rereads_test.dart`++**Interfaces:**+- Consumes: `AppNotifier.inSight` (ValueNotifier<bool>), `appLifecycleChanged(AppLifecycleState?)`.+- Produces: `@visibleForTesting Duration agentSyncEvery` (instance, defaults to `agentSyncInterval`), so a+ test can count ticks without a minute of fake time.++- [ ] **Step 1: Failing tests** — with one connected machine (fake `WsConn` counting `agents_list`) and a+ counting `ApiClient`:+ - `hidden: no agents_list for 5 agent-sync intervals; shown: exactly one at once, then on the interval`+ - `hidden: the 5-minute safety net reads no desk, agent messages or machine list; shown: one of each`+ - `a held agent is not re-read while hidden`+ - `a machine connecting while hidden starts reading only when shown`+ - `hide, show, hide within one interval: one read, one timer`+- [ ] **Step 2:** Run `flutter test test/hidden_window_rereads_test.dart` — FAIL (reads while hidden).+- [ ] **Step 3:** Commit the failing test.+- [ ] **Step 4: Implement** — `inSight` false cancels agent-sync, held-sync and the safety-net timers and+ makes the recovery/offline loops skip their read and stop rescheduling; `inSight` true re-arms them and+ reads each once (`_syncAgentsIfChanged` per connected machine, the safety-net tick's reads once).+ `_startAgentSyncTimer` arms nothing while not in sight.+- [ ] **Step 5:** Run the test file and `held_launch_sync_test.dart`, `web_machine_list_watch_test.dart` — PASS.+- [ ] **Step 6:** Commit.++### Task 2: Desktop/web app-level controllers++**Files:**+- Modify: `desktop/lib/super_tabs/client.dart` (discovery), `desktop/lib/super_tabs/controller.dart` (desktop+ non-adaptive poll and receipt reads), `desktop/lib/settings/experimental_features.dart`,+ `desktop/lib/usage/models_menu_controller.dart` + where the app-level one starts+ (`desktop/lib/screens/swarm_screen.dart`), `desktop/lib/super_tabs/pull_request_facts.dart`,+ `desktop/lib/web/update/web_update_watcher.dart`, `desktop/lib/measurement/product_runtime_health.dart`+- Test: `desktop/test/hidden_window_controllers_test.dart`++**Interfaces:**+- Consumes: `SuperTabClient.pageVisible` (already set by `SuperTabWorkspace`), `AppNotifier.inSight`.+- Produces: `ValueListenable<bool>? seen` constructor parameter on `ExperimentalFeatures`,+ `ModelsMenuController` and `WebUpdateWatcher` (null = always seen, every existing caller and test).++- [ ] **Step 1: Failing tests:**+ - `Swarm: page hidden while pushing — no state read for 3 safety nets; shown — one read`+ - `Swarm: page hidden without push — the 15 s away poll still reads` (pins Review Focus 4)+ - `Swarm discovery: page hidden while pushing — no list read for 2 safety nets; shown — one`+ - `experimental settings: unseen — no read for 2 poll intervals; seen — one`+ - `models menu usage: unseen — no usage read; seen — one, then on the interval`+ - `backlog pull request facts: away — no status read; back — one`+ - `web update watcher: hidden — no manifest read; shown — one`+ - `runtime health: hidden — no sample, so no report scheduled`+- [ ] **Step 2:** Run the file — FAIL. **Step 3:** commit it.+- [ ] **Step 4: Implement** each as the test states, through the one listenable each already has or gets.+- [ ] **Step 5:** Run the file and each touched controller's existing test file — PASS. **Step 6:** Commit.++### Task 3: Desktop/web widget pollers (parallel subagent)++**Files:** `desktop/lib/sharing/harness_comments.dart`, `sharing/share_harness_dialog.dart`,+`sharing/shared_terminal_watch.dart`, `sharing/shared_agent_page.dart`,+`settings/sections/tab_invites_section.dart`, `orchestrator/orchestrator_controller.dart` (via its+workspace widget), `state/session_activity.dart` (via its widgets), `devices/devices_screen.dart`,+`store/store_screen.dart`, `widgets/swarm_resource_preview.dart`, `devices/wifi_robots.dart`+- Test: `desktop/test/hidden_widget_pollers_test.dart`++**Interfaces:**+- Consumes: `VisibleTick` (`visibleTick(Duration)`, `onTick()`, `onScreenChanged(bool)`), or for a non-widget+ controller a `bool Function() seen` / listenable handed in by the widget that owns it.++- [ ] **Step 1:** One failing test per poller: `<poller>: hidden app — no request for 3 intervals; resumed — one read at once`.+- [ ] **Step 2:** Run — FAIL. **Step 3:** Commit.+- [ ] **Step 4:** Gate each through `VisibleTick` (or the owning widget's lifecycle for controllers).+- [ ] **Step 5:** Run the file and each poller's existing tests — PASS. **Step 6:** Commit.++### Task 4: Phone background (parallel subagent)++**Files:** `mobile/lib/state/app_state.dart` (agent sync, offline retry, key watch in+`handleAppPaused`/`handleAppResumed`), `mobile/lib/usage/usage_controller.dart` + `phone/usage_page.dart`,+`mobile/lib/phone/welcome/your_computer.dart` (`ComputerWatch`), `mobile/lib/swarm/swarm_leaderboard_reader.dart`+(read once on return)+- Test: `mobile/test/background_polling_test.dart`++- [ ] **Step 1:** Failing tests: `<poller>: paused — no request for 3 intervals; resumed — one read`.+- [ ] **Step 2:** Run — FAIL. **Step 3:** Commit.+- [ ] **Step 4:** Implement through `handleAppPaused`/`handleAppResumed` and page lifecycle observers.+- [ ] **Step 5:** Run the file and the touched files' existing tests — PASS. **Step 6:** Commit.++### Task 5: Measurement — one idle hidden window, requests per minute++**Files:**+- Test: `desktop/test/hidden_window_requests_test.dart`++- [ ] **Step 1:** A widget test that mounts the real `SwarmScreen`, signed in (memory store, fake sign-in),+ two connected machines (fake `WsConn` counting every request by type), a counting `ApiClient`, and the+ app-level controllers started; sets the window hidden, runs 10 simulated minutes and prints requests per+ minute by kind. Asserts zero periodic requests while hidden, and at least one read of each kind within a+ second of `resumed`.+- [ ] **Step 2:** Run it on main's code (before) and record the printed numbers in the PR; run on the branch+ (after) — PASS with 0/min.+- [ ] **Step 3:** Commit.diff --git a/docs/plans/2026-11-04-message-read-cuts-plan.md b/docs/plans/2026-11-04-message-read-cuts-plan.mdnew file mode 100644index 000000000..7a2988825--- /dev/null+++ b/docs/plans/2026-11-04-message-read-cuts-plan.md@@ -0,0 +1,102 @@+# Faster slow message reads (task #2966) Implementation Plan++> Worked by the project's Engineer role: plan first, then each task test first (failing test committed before its code),+> one review on the pull request. No execution handoff.++**Goal:** Cut the SuperTabMessage reads in Ken's 11-04 slow log: the `$expr` read on `_id`, the `$or`-over-threads range+reads, and the getMore that returns ~419 rows, without changing what any reader is answered.++**Architecture:** (1) The stored-notice check in `store.ts writeMessages` reads by a plain `{_id: {$in}}` through the id+index (`pageReads.ts storedMessages`) instead of Prisma's `id: { in }`, which Prisma sends as `$expr`. (2) The inbox's range+reads (`read/inbox.ts`: each unread chat's rows past its mark, and each thread's rows past or before a mark through+`newestInThreads`) are bounded above by the chat's newest sequence and kept in a per-process cache (`read/rangeCache.ts`)+keyed by the exact range and the chat's `reactionSeq`, which every edit and delete bumps; a re-read of an unchanged range+reads nothing. (3) `perRange` asks for all rows in its first reply (`READ_BATCH`, as `readBy`), so a 30-chat scan is one+operation, never an aggregate plus a getMore.++**Tech Stack:** TypeScript, Prisma `aggregateRaw` on MongoDB 7, vitest, mongodb-memory-server integration tests under the+profiler (`integration/plans.test-support.ts`).++**Spec:** task #2966's brief (Ken's slow-query data, 11-04).++## Global Constraints++- Optimizations ship on, with no on/off switches (Ken).+- Swarm code stays out of `cli/src/core`.+- Read-only production for checks only, shapes and totals, never documents.+- Every new or changed query has an integration test that reads its plan: IXSCAN on its index, docs examined close to+ returned (`backend/AGENTS.md` rule 3).+- Permissions are applied after the cache: it holds the stored rows of a range, the same for every reader, and each read+ still runs `readable()` on them.+- PR body first line: "Requested by [email protected] through Harness."++## Review Focus++1. A message deleted or edited in a cached range: the next inbox read must not show it (reactionSeq is in the key;+ test: delete a reply, re-read, it is gone).+2. A new reply in one chat: only that chat's ranges are read again, and the reply is counted (test).+3. Two Swarms or two chats with the same mark and sequence numbers never share an entry (tabId and conversationId in the+ key; test: second Swarm reads its own rows).+4. Memory: the cache is bounded by entries and rows, oldest first out (unit test).+5. A hidden row (recipients only) numbered past `lastMessageSequence`: the upper bound is the chat's `messageSeq`, so a+ range read holds exactly the rows it held before.++---++### Task 1: The stored-notice check reads by the id index++**Files:**+- Modify: `backend/src/superTabs/pageReads.ts` (add `storedMessages`)+- Modify: `backend/src/superTabs/store.ts` (`writeMessages`)+- Modify: `backend/src/superTabs/hotFilters.allowed.json` (drop `store.ts superTabMessage.findMany`)+- Test: `backend/integration/superTabNamedReads.test.ts`++**Interfaces:**+- Produces: `storedMessages(tx: Transaction, ids: string[]): Promise<Array<{ id: string; tabId: string; conversationId: string; source: unknown }>>`++- [ ] **Step 1: Failing tests.** `hotFilters.test.ts` fails once the allowed entry is removed (the Prisma `in` is still+ there). Integration: `storedMessages` of 101 stored rows profiles as one aggregate, IXSCAN `{ _id: 1 }`, no `$expr` in+ its filter, docsExamined = returned = 101; and a Lead poll's time check that keeps a stored notice sends no `$expr` read+ on SuperTabMessage.+- [ ] **Step 2: Run them, see them fail.** `npx vitest run src/superTabs/hotFilters.test.ts`;+ `npx vitest run --config vitest.super-tabs.config.ts integration/superTabNamedReads.test.ts -t "stored notices"`.+- [ ] **Step 3: Implement** `storedMessages` with `readBy(tx, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: ids } } }, { $project: { tabId: 1, conversationId: 1, source: 1 } }])`; `writeMessages` uses it.+- [ ] **Step 4: Run the tests, see them pass. Commit.**++### Task 2: perRange reads in one operation++**Files:**+- Modify: `backend/src/superTabs/read/inbox.ts` (`perRange`)+- Test: `backend/integration/superTabInbox.test.ts`++- [ ] **Step 1: Failing test** "scans 30 unread chats in one operation, never a getMore": a person with THREAD_CHATS unread+ chats of 101 rows past the mark; profiling the inbox read shows no `getmore` on SuperTabMessage and the chat scan's+ aggregate returns every row (nreturned 30 × 101).+- [ ] **Step 2: See it fail** (a getmore with the 2,929 rows past the first 101).+- [ ] **Step 3: Implement:** `perRange` passes `options: { batchSize: READ_BATCH }` (parts/indexed.ts).+- [ ] **Step 4: Pass. Commit.**++### Task 3: Range cache for the inbox's re-reads++**Files:**+- Create: `backend/src/superTabs/read/rangeCache.ts`, `backend/src/superTabs/read/rangeCache.test.ts`+- Modify: `backend/src/superTabs/read/inbox.ts` (`threadsIn` chat scan, `newestInThreads`, `namedInThreads`)+- Test: `backend/integration/superTabInbox.test.ts`++**Interfaces:**+- Produces: `class RangeCache<T> { constructor(limits: { entries: number; rows: number; ttlMs: number }, now?: () => number); get(key: string): T[] | undefined; set(key: string, rows: T[]): void; clear(): void }`,+ `rangeKey(tabId: string, conversationId: string, thread: string | null, sequence: Record<string, number>, limit: number, version: number, namedBy?: string): string`,+ `chatTop(group: Conversation): number` (max of `messageSeq` and `lastMessageSequence`), `resetRangeCache(): void` (test seam).+- `ThreadRange` gains `version: number` (the chat's `reactionSeq ?? 0`); each caller bounds `$gt` ranges with `$lte: chatTop`.++- [ ] **Step 1: Failing unit tests** (`rangeCache.test.ts`): get after set answers a copy; the oldest entry goes past+ `entries` or past `rows`; an entry past `ttlMs` is gone.+- [ ] **Step 2: Failing integration tests** (`superTabInbox.test.ts`, "re-reading the inbox"): in bigScene, a second inbox+ read with nothing changed sends no SuperTabMessage range read (no `sequence` filter); after one reply in one chat, the+ range reads name only that chat and the reply is counted; after deleting a counted reply (reactionSeq bumps), the next+ read no longer counts it; numbers printed: docs examined, returned and bytes for cold and warm reads.+- [ ] **Step 3: See them fail. Commit the tests.**+- [ ] **Step 4: Implement** `rangeCache.ts` (Map in insertion order, entries 4,000, rows 200,000, TTL 10 minutes) and use+ it in `perRange` callers of `threadsIn` and in `newestInThreads` (misses only go to the batch read; each range's rows+ stored under its key, empty ranges too).+- [ ] **Step 5: Run inbox, followed threads and named reads integration files and the touched unit tests. Commit.**diff --git a/mobile/lib/phone/usage_page.dart b/mobile/lib/phone/usage_page.dartindex 0330c5130..ba33caf5f 100644--- a/mobile/lib/phone/usage_page.dart+++ b/mobile/lib/phone/usage_page.dart@@ -38,7 +38,7 @@ class UsagePage extends StatefulWidget {State<UsagePage> createState() => _UsagePageState();}-class _UsagePageState extends State<UsagePage> {+class _UsagePageState extends State<UsagePage> with WidgetsBindingObserver {/// Owned by the page rather than by the app, which is the opposite of the/// desktop's choice and right for the opposite reason. There the rail/// unmounts whenever the sidebar folds, so a poller living in it would@@ -55,10 +55,27 @@ class _UsagePageState extends State<UsagePage> {void initState() {super.initState();_usage.addListener(_rememberSummary);+ WidgetsBinding.instance.addObserver(this);+ }++ /// In a pocket (`hidden`, `paused`) the page asks nothing; back in front, one cycle at once and+ /// the minute's poll again ([UsageController.pause]). `inactive` — the app switcher, a system+ /// sheet — is still in front of somebody, and changes nothing.+ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ switch (state) {+ case AppLifecycleState.hidden || AppLifecycleState.paused:+ _usage.pause();+ case AppLifecycleState.resumed:+ _usage.resume();+ case AppLifecycleState.inactive || AppLifecycleState.detached:+ break;+ }}@overridevoid dispose() {+ WidgetsBinding.instance.removeObserver(this);_usage.removeListener(_rememberSummary);_usage.dispose();super.dispose();@@ -232,7 +249,9 @@ class _EmptyUsage extends StatelessWidget {/// The providers named once each, in [UsageProvider] order — two machines/// signed out of the same account are one sentence, not two.static String _providers(List<ProviderUsage> readings) {- final seen = <UsageProvider>{for (final reading in readings) reading.provider};+ final seen = <UsageProvider>{+ for (final reading in readings) reading.provider,+ };final labels = [for (final provider in UsageProvider.values)if (seen.contains(provider)) provider.label,@@ -286,7 +305,9 @@ class _AccountCardState extends State<_AccountCard> {color: Colors.transparent,child: InkWell(borderRadius: BorderRadius.circular(AppCard.radius),- onTap: expandable ? () => setState(() => _expanded = !_expanded) : null,+ onTap: expandable+ ? () => setState(() => _expanded = !_expanded)+ : null,child: Padding(padding: const EdgeInsets.fromLTRB(13, 12, 13, 13),child: Column(@@ -451,7 +472,10 @@ class _WindowRow extends StatelessWidget {// Amber at 20% left, red at 5%. The figure is exact either way,// so the colour is not carrying the number — it is carrying the// moment the number starts to matter.- color: usagePressureInk(window.pressure, AppPalette.textPrimary),+ color: usagePressureInk(+ window.pressure,+ AppPalette.textPrimary,+ ),fontSize: 13.5,fontWeight: FontWeight.w600,fontFeatures: AppFont.tabularFigures,diff --git a/mobile/lib/phone/welcome/your_computer.dart b/mobile/lib/phone/welcome/your_computer.dartindex 1309a7940..634fc0b68 100644--- a/mobile/lib/phone/welcome/your_computer.dart+++ b/mobile/lib/phone/welcome/your_computer.dart@@ -245,6 +245,11 @@ class NotYouSignOut extends StatelessWidget {////// A request that fails (offline for a moment) is simply asked again on the next tick — caught/// here, where it would otherwise reach the zone as an unhandled error every five seconds.+///+/// Only in front of somebody: in a pocket (`hidden`, `paused`) nothing is asked, and back in front+/// the list is read once at once ([AppNotifier.rereadMachines], which joins the read the app makes+/// on its own return), then every few seconds again. `inactive` — the share sheet sending the+/// address — changes nothing.class ComputerWatch extends StatefulWidget {const ComputerWatch({super.key, required this.notifier, required this.child});@@ -257,20 +262,45 @@ class ComputerWatch extends StatefulWidget {State<ComputerWatch> createState() => _ComputerWatchState();}-class _ComputerWatchState extends State<ComputerWatch> {+class _ComputerWatchState extends State<ComputerWatch>+ with WidgetsBindingObserver {Timer? _watch;+ bool _away = false;@overridevoid initState() {super.initState();- _watch = Timer.periodic(ComputerWatch.every, (_) {+ WidgetsBinding.instance.addObserver(this);+ _arm();+ }++ void _arm() {+ _watch ??= Timer.periodic(ComputerWatch.every, (_) {if (!mounted) return;unawaited(widget.notifier.refreshMachines().catchError((Object _) {}));});}+ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ switch (state) {+ case AppLifecycleState.hidden || AppLifecycleState.paused:+ _away = true;+ _watch?.cancel();+ _watch = null;+ case AppLifecycleState.resumed:+ if (!_away) return;+ _away = false;+ widget.notifier.rereadMachines();+ _arm();+ case AppLifecycleState.inactive || AppLifecycleState.detached:+ break;+ }+ }+@overridevoid dispose() {+ WidgetsBinding.instance.removeObserver(this);_watch?.cancel();super.dispose();}diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 810de07fc..08e6682be 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -2683,10 +2683,17 @@ class AppNotifier extends ChangeNotifier {if (_disposed || !machine.needsLink) return;// Kept across refusals: the wait is from the first, not reset by every redial.machine.keyAwaitedSince ??= DateTime.now();- _keyWatch ??= Timer.periodic(keyWatchEvery, (_) => _watchAwaitedKeys());+ _armKeyWatch();notifyListeners();}+ /// Starts [_keyWatch] unless it runs already — or the app is in a pocket, where nobody is looking+ /// ([handleAppPaused]): [handleAppResumed] starts it then ([_resumeBackgroundPolls]).+ void _armKeyWatch() {+ if (_pausedAt != null) return;+ _keyWatch ??= Timer.periodic(keyWatchEvery, (_) => _watchAwaitedKeys());+ }+void _watchAwaitedKeys() {var waiting = false;for (final state in machineStates.values) {@@ -3058,6 +3065,8 @@ class AppNotifier extends ChangeNotifier {return;}if (_offlineRetryTimers.containsKey(machineId)) return;+ // In a pocket, nothing polls: [handleAppResumed] starts it again ([_resumeBackgroundPolls]).+ if (_pausedAt != null) return;_offlineRetryTimers[machineId] = Timer.periodic(offlineRetryInterval,(_) => unawaited(_pollOfflineMachine(machineId)),@@ -3078,6 +3087,9 @@ class AppNotifier extends ChangeNotifier {void _startAgentSyncTimer(String machineId) {if (_agentSyncTimers.containsKey(machineId)) return;+ // A machine that connects while the app is in a pocket has its first list read all the same+ // ([_onConnectionStatus]); its safety net waits for the app to come back ([_resumeBackgroundPolls]).+ if (_pausedAt != null) return;_agentSyncTimers[machineId] = Timer.periodic(agentSyncInterval,(_) => _agentSyncTick(machineId, DateTime.now()),@@ -11426,6 +11438,41 @@ class AppNotifier extends ChangeNotifier {// The zoo too, for the same reason: a `zoo_changed` sent while the phone// was in a pocket reached nobody.if (status == AppStatus.authenticated) unawaited(zoo.refresh());+ // Only back from a pocket: a moment on the app switcher (`inactive`) stopped nothing.+ if (pausedAt != null && status == AppStatus.authenticated) {+ _resumeBackgroundPolls();+ }+ }++ /// Back from a pocket: the periodic reads [handleAppPaused] stopped start again, each with one+ /// read now — and never a second beside a read this return already makes.+ ///+ /// - **Agent lists**, per connected machine: the safety net's tick, at once. It reads now a list+ /// older than its interval and waits for a fresher one to come due ([_agentSyncTick]) — a list+ /// costs the machine a second or two of the queue its keystrokes wait in. A socket lost while+ /// away is not connected yet, and reads its whole list when it is ([_onConnectionStatus]).+ /// - **An offline machine something waits on**: its poll, unless the machine list is being read+ /// again already ([_rereadMachinesWhileDeaf], above), which answers the same question.+ /// - **The key watch**: only started again — the device log was just read ([handleAppResumed]'s+ /// `ensureRegistered`).+ void _resumeBackgroundPolls() {+ final now = DateTime.now();+ for (final machine in machineStates.values.toList()) {+ final machineId = machine.machine.machineId;+ if (machine.connectionStatus == ConnectionStatus.connected) {+ _startAgentSyncTimer(machineId);+ _agentSyncTick(machineId, now);+ }+ if (machine.nodeOnline == false &&+ machine.pendingOfflineAgentId != null &&+ !_offlineRetryTimers.containsKey(machineId)) {+ _startOfflineRetry(machine);+ if (_machineReread == null) unawaited(_pollOfflineMachine(machineId));+ }+ }+ if (machineStates.values.any((m) => m.keyAwaitedSince != null)) {+ _armKeyWatch();+ }}/// The app went into a pocket: stop the reads that only make sense in front@@ -11444,6 +11491,10 @@ class AppNotifier extends ChangeNotifier {_pausedAt ??= DateTime.now();_desk.pause();_stopDeafPoll();+ // And every other read on a timer: Android keeps an app in a pocket running, and it would go on+ // asking — the agent lists, an offline machine, the device log while a key is awaited. A read+ // already under way still lands. [handleAppResumed] starts them again ([_resumeBackgroundPolls]).+ _pauseBackgroundPolls();// A socket waiting on a machine that is off stops dialling it while nobody is looking;// [handleAppResumed]'s reconnectAll asks again the moment the phone is back// ([WsConn.pauseParkedRecheck]).@@ -11459,6 +11510,25 @@ class AppNotifier extends ChangeNotifier {/// When the app last went into the background ([handleAppPaused]); null while it is in front.DateTime? _pausedAt;+ /// [handleAppPaused]'s half of [_resumeBackgroundPolls]: the timers go, what they counted stays+ /// (timeouts, a poll in flight) — a pocket is not the machine going.+ void _pauseBackgroundPolls() {+ for (final timer in _agentSyncTimers.values) {+ timer.cancel();+ }+ _agentSyncTimers.clear();+ for (final hold in _agentSyncHolds.values) {+ hold.cancel();+ }+ _agentSyncHolds.clear();+ for (final timer in _offlineRetryTimers.values) {+ timer.cancel();+ }+ _offlineRetryTimers.clear();+ _keyWatch?.cancel();+ _keyWatch = null;+ }+/// How long the app has to have been away before [handleAppResumed] stops trusting an open/// socket that heard nothing from its machine in that time.///@@ -11638,12 +11708,18 @@ class AppNotifier extends ChangeNotifier {/// Read the machine list again because something other than the person asked; reads under way are/// shared, and a failure is left to the next one.+ ///+ /// [rereadMachines] is the same read, for a screen that watches the list.void _rereadMachines() {_machineReread ??= refreshMachines().catchError((Object _) {}).whenComplete(() => _machineReread = null);}+ /// The machine list read again, joining a read already under way — for a screen waiting on a+ /// computer to join, back in front, beside [handleAppResumed]'s own read (`ComputerWatch`).+ void rereadMachines() => _rereadMachines();+/// What the local CLI closing this machine's socket with [code] does to the/// model — the `WsPool.onLocalFailure` path, without a socket.@visibleForTestingdiff --git a/mobile/lib/swarm/swarm_leaderboard.dart b/mobile/lib/swarm/swarm_leaderboard.dartindex 6ac0478c5..e0a666c0e 100644--- a/mobile/lib/swarm/swarm_leaderboard.dart+++ b/mobile/lib/swarm/swarm_leaderboard.dart@@ -204,7 +204,8 @@ class SwarmLeaderboardPage extends StatefulWidget {State<SwarmLeaderboardPage> createState() => _SwarmLeaderboardPageState();}-class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {+class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage>+ with WidgetsBindingObserver {SwarmSession? _session;/// The Swarm's reader, for the members' names; null until it is listed.@@ -224,6 +225,31 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {/// The week picker, while it is up: it goes with the board.ModalRoute<void>? _picker;+ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ }++ /// The app is in a pocket: a board started meanwhile waits for it too.+ bool _away = false;++ /// In a pocket (`hidden`, `paused`) the board is not read; back in front it is read once at once,+ /// then on its interval ([SwarmLeaderboardReader.resume]). `inactive` changes nothing.+ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ switch (state) {+ case AppLifecycleState.hidden || AppLifecycleState.paused:+ _away = true;+ _board?.pause();+ case AppLifecycleState.resumed:+ _away = false;+ _board?.resume();+ case AppLifecycleState.inactive || AppLifecycleState.detached:+ break;+ }+ }+@overridevoid didUpdateWidget(SwarmLeaderboardPage old) {super.didUpdateWidget(old);@@ -285,6 +311,7 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {inFront: () => session.inbox.shown,)..addListener(_changed);_board!.start();+ if (_away) _board!.pause();}void _changed() {@@ -349,6 +376,7 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {_session?.leave();_swarm?.removeListener(_swarmChanged);_board?.dispose();+ WidgetsBinding.instance.removeObserver(this);super.dispose();}diff --git a/mobile/lib/swarm/swarm_leaderboard_reader.dart b/mobile/lib/swarm/swarm_leaderboard_reader.dartindex 62f10b6e9..884e34183 100644--- a/mobile/lib/swarm/swarm_leaderboard_reader.dart+++ b/mobile/lib/swarm/swarm_leaderboard_reader.dart@@ -389,9 +389,33 @@ class SwarmLeaderboardReader extends ChangeNotifier {/// Reads now, and every [every] after while the app is in front.void start() {+ _arm();+ unawaited(refresh());+ }++ void _arm() {+ if (_disposed) return;_timer ??= Timer.periodic(every, (_) {if (inFront()) unawaited(refresh());});+ }++ bool _paused = false;++ /// The app went into a pocket: no tick until [resume].+ void pause() {+ if (_disposed || _timer == null) return;+ _paused = true;+ _timer?.cancel();+ _timer = null;+ }++ /// Back in front after [pause]: the board missed while away is read at once, and every [every]+ /// from now. Without a [pause] first — a moment on the app switcher — nothing.+ void resume() {+ if (_disposed || !_paused) return;+ _paused = false;+ _arm();unawaited(refresh());}diff --git a/mobile/lib/usage/usage_controller.dart b/mobile/lib/usage/usage_controller.dartindex 9b65054ff..88a9df9f3 100644--- a/mobile/lib/usage/usage_controller.dart+++ b/mobile/lib/usage/usage_controller.dart@@ -137,6 +137,31 @@ class UsageController extends ChangeNotifier {_timer = Timer.periodic(interval, (_) => unawaited(refresh()));}+ /// The app went into a pocket: nothing is asked until [resume]. A cycle under way still lands.+ ///+ /// Android keeps a backgrounded app running, and the poll with it — a relay round trip to every+ /// machine each minute for a page nobody can see.+ void pause() {+ if (_disposed || _paused) return;+ _paused = true;+ _pollingWhenPaused = _timer != null;+ _timer?.cancel();+ _timer = null;+ }++ /// Back in front after [pause]: one cycle now, then the poll again if it was running. Without a+ /// [pause] first — a moment on the app switcher — nothing.+ void resume() {+ if (_disposed || !_paused) return;+ _paused = false;+ unawaited(refresh());+ if (_pollingWhenPaused) {+ _timer = Timer.periodic(interval, (_) => unawaited(refresh()));+ }+ }++ bool _paused = false, _pollingWhenPaused = false;+/// This device's accounts and every remote machine's, asked at once — and/// landing apart. A remote machine is a relay round trip away and may never/// answer at all (see `AppNotifier.readRemoteUsage`), so it must not hold updiff --git a/mobile/test/app_state_phone_paths_test.dart b/mobile/test/app_state_phone_paths_test.dartindex 41479fb30..cfbf5e7c0 100644--- a/mobile/test/app_state_phone_paths_test.dart+++ b/mobile/test/app_state_phone_paths_test.dart@@ -724,7 +724,12 @@ void main() {capabilities();rig.app.bootstrap();async.flushMicrotasks();- rig.app.handleAppPaused();+ // Only the offline poll reads the list here: the read while no machine is connected is+ // put off. (Not by pausing the app: in a pocket the offline poll stops too.)+ rig.app+ ..deafMachineListInterval = const Duration(days: 1)+ ..asleepMachineListInterval = const Duration(days: 1)+ ..asleepMachinesListInterval = const Duration(days: 1);rig.app.stateOf('m')!.pendingOfflineAgentId = 'a';rig.api.onMachines = () async => [remoteMachine('m', status: 'offline'),@@ -785,7 +790,6 @@ void main() {rig.api.onMachines = () async => [remoteMachine('m')];rig.app.bootstrap();async.flushMicrotasks();- rig.app.handleAppPaused();rig.app.connectionStatusForTest('m', ConnectionStatus.connected);async.flushMicrotasks();final lists = rig.conn('m').payloadsOf('agents_list').length;diff --git a/mobile/test/background_polling_test.dart b/mobile/test/background_polling_test.dartnew file mode 100644index 000000000..c21dd562c--- /dev/null+++ b/mobile/test/background_polling_test.dart@@ -0,0 +1,452 @@+import 'dart:async';++import 'package:fake_async/fake_async.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/phone/usage_page.dart';+import 'package:harness_mobile/phone/welcome/your_computer.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/swarm/swarm_leaderboard.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/usage/usage_accounts.dart';+import 'package:harness_mobile/viewer/device_log.dart';+import 'package:harness_mobile/viewer/device_log_sync.dart';++import 'swarm/swarm_fixture.dart' hide settle;+import 'viewer_app_fixture.dart';+import 'voice_fakes.dart' show MemoryKeyValueStore;++/// The phone in a pocket (`paused`, `hidden`) asks nothing on a timer — of the backend or of a+/// machine. Android keeps a backgrounded app running, so the OS suspending it is not to be counted+/// on. Back in front (`resumed`) each poller reads once at once and then keeps its interval; a+/// moment on the app switcher (`inactive`) is not a time away (#2953).+void main() {+ group('the app model', () {+ test(+ 'agent sync: paused — no request for 3 intervals; resumed — one read',+ () {+ fakeAsync((async) {+ final rig = _phone();+ rig.app.bootstrap();+ async.flushMicrotasks();+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);+ async.flushMicrotasks();+ final conn = rig.conn('m');+ int lists() => conn.payloadsOf('agents_list').length;+ final before = lists();++ rig.app.handleAppPaused();+ _ageList(rig.app, 'm');+ async.elapse(AppNotifier.agentSyncInterval * 3);+ expect(lists(), before, reason: 'nothing asked from a pocket');++ rig.app.handleAppResumed();+ async.flushMicrotasks();+ expect(lists(), before + 1, reason: 'one read at once, and only one');++ _ageList(rig.app, 'm');+ async.elapse(AppNotifier.agentSyncInterval);+ expect(lists(), before + 2, reason: 'then on its interval again');++ rig.app.dispose();+ });+ },+ );++ test('agent sync: connected while paused — no request for 3 intervals; '+ 'resumed — one read', () {+ fakeAsync((async) {+ final rig = _phone();+ rig.app.bootstrap();+ async.flushMicrotasks();+ rig.app.handleAppPaused();+ // The socket comes up with the phone in a pocket: its first list is read, as it was.+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);+ async.flushMicrotasks();+ final conn = rig.conn('m');+ int lists() => conn.payloadsOf('agents_list').length;+ final before = lists();++ _ageList(rig.app, 'm');+ async.elapse(AppNotifier.agentSyncInterval * 3);+ expect(lists(), before, reason: 'no timer armed from a pocket');++ rig.app.handleAppResumed();+ async.flushMicrotasks();+ expect(lists(), before + 1);++ _ageList(rig.app, 'm');+ async.elapse(AppNotifier.agentSyncInterval);+ expect(lists(), before + 2);++ rig.app.dispose();+ });+ });++ test('agent sync: a moment on the app switcher changes nothing', () {+ fakeAsync((async) {+ final rig = _phone();+ rig.app.bootstrap();+ async.flushMicrotasks();+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);+ async.flushMicrotasks();+ final conn = rig.conn('m');+ int lists() => conn.payloadsOf('agents_list').length;+ final before = lists();++ // `inactive`, then `resumed`, with no `paused` between: the list was just read.+ rig.app.handleAppInactive();+ rig.app.handleAppResumed();+ async.flushMicrotasks();+ expect(lists(), before);++ _ageList(rig.app, 'm');+ async.elapse(AppNotifier.agentSyncInterval);+ expect(lists(), before + 1, reason: 'the timer kept running');++ rig.app.dispose();+ });+ });++ test(+ 'offline retry: paused — no request for 3 intervals; resumed — one read',+ () {+ fakeAsync((async) {+ final rig = _phone();+ rig.app.bootstrap();+ async.flushMicrotasks();+ rig.app.stateOf('m')!.pendingOfflineAgentId = 'a';+ rig.api.onMachines = () async => [+ remoteMachine('m', status: 'offline'),+ ];+ rig.app.handleEventForTest('m', {+ 'type': 'node_status',+ 'payload': {'online': false},+ });+ async.flushMicrotasks();+ final before = rig.api.machineFetches;+ async.elapse(AppNotifier.offlineRetryInterval);+ expect(+ rig.api.machineFetches,+ before + 1,+ reason: 'in front: polled',+ );++ rig.app.handleAppPaused();+ async.elapse(AppNotifier.offlineRetryInterval * 3);+ expect(+ rig.api.machineFetches,+ before + 1,+ reason: 'in a pocket: not',+ );++ // The resume's own read of the list (no machine is connected) is the one read: the+ // offline poll does not ask the same question beside it.+ rig.app.handleAppResumed();+ async.flushMicrotasks();+ expect(rig.api.machineFetches, before + 2);++ async.elapse(AppNotifier.offlineRetryInterval);+ expect(rig.api.machineFetches, before + 3, reason: 'polled again');++ rig.app.dispose();+ });+ },+ );++ test(+ 'key watch: paused — no request for 3 intervals; resumed — one read',+ () {+ fakeAsync((async) {+ final rig = _phone();+ rig.app+ ..trustSettleRound = Duration.zero+ ..onRedialForTest = (id) => scheduleMicrotask(+ () => rig.app.localFailureForTest(id, 4404, 'NO_PEER_LINK'),+ );+ rig.app.bootstrap();+ async.flushMicrotasks();+ final api = rig.app.api as _Api;+ // What a return reads of the log anyway, with no key awaited: `ensureRegistered`, since a+ // `device_keys_changed` sent while away reached nobody.+ var reads = api.keyReads;+ rig.app.handleAppPaused();+ rig.app.handleAppResumed();+ async.flushMicrotasks();+ final resumeReads = api.keyReads - reads;+ expect(resumeReads, greaterThan(0));+ // A computer that signed in a moment ago, its key not in the log yet.+ rig.app.localFailureForTest('m', 4404, 'NO_PEER_LINK');+ async.elapse(const Duration(seconds: 1));+ expect(rig.app.stateOf('m')!.awaitingKey, isTrue);+ final before = api.keyReads;+ async.elapse(rig.app.keyWatchEvery);+ expect(api.keyReads, before + 1, reason: 'in front: the log re-read');++ rig.app.handleAppPaused();+ async.elapse(rig.app.keyWatchEvery * 3);+ expect(api.keyReads, before + 1, reason: 'in a pocket: not');++ // The return's own read of the log is the watch's read, not one beside it.+ reads = api.keyReads;+ rig.app.handleAppResumed();+ async.flushMicrotasks();+ expect(api.keyReads, reads + resumeReads);++ async.elapse(rig.app.keyWatchEvery);+ expect(+ api.keyReads,+ reads + resumeReads + 1,+ reason: 'watched again',+ );++ rig.app.dispose();+ });+ },+ );+ });++ group('the pages', () {+ testWidgets(+ 'usage: paused — no request for 3 intervals; resumed — one read',+ (tester) async {+ final app = _UsageApp();+ addTearDown(app.dispose);+ await tester.pumpWidget(+ MaterialApp(+ theme: buildAppTheme(brightness: Brightness.dark),+ home: UsagePage(notifier: app),+ ),+ );+ await tester.pump();+ final before = app.reads;++ _toBackground(tester);+ await tester.pump(const Duration(seconds: 60) * 3);+ expect(app.reads, before, reason: 'nothing asked from a pocket');++ _toFront(tester);+ await tester.pump();+ expect(app.reads, before + 1, reason: 'one read at once');++ // The app switcher, and back: not a time away.+ tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.inactive,+ );+ tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ );+ await tester.pump();+ expect(app.reads, before + 1);++ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'computer watch: paused — no request for 3 intervals; resumed — one read',+ (tester) async {+ final rig = _phone(machines: false);+ await tester.runAsync(() async {+ await rig.app.bootstrap();+ await settle();+ });+ _forwardLifecycle(tester, rig.app);+ await tester.pumpWidget(+ MaterialApp(+ home: ComputerWatch(notifier: rig.app, child: const SizedBox()),+ ),+ );+ await tester.pump(ComputerWatch.every);+ final before = rig.api.machineFetches;+ expect(before, greaterThan(0), reason: 'in front: watched');++ _toBackground(tester);+ await tester.pump(ComputerWatch.every * 3);+ expect(rig.api.machineFetches, before, reason: 'nothing from a pocket');++ // The app model reads the list on its own return (no machine connected): the watch's+ // read is that one, not a second beside it.+ _toFront(tester);+ await tester.pump();+ expect(rig.api.machineFetches, before + 1);++ await tester.pump(ComputerWatch.every);+ expect(rig.api.machineFetches, before + 2, reason: 'watched again');++ await tester.pumpWidget(const SizedBox());+ rig.app.dispose();+ },+ );++ testWidgets(+ 'leaderboard: paused — no request for 3 intervals; resumed — one read',+ (tester) async {+ const board = '/api/super-tabs/$tab/leaderboard?projectId=$project';+ 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(),+ 'members': [part(me, 1, person(me))],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2');+ fake.routes[board] = (_) => leaderboardData();+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ )..foreground = false;+ addTearDown(host.dispose);+ await host.session!.inbox.refresh();+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) =>+ SwarmScope(notifier: host, child: child!),+ home: const SwarmLeaderboardPage(swarmId: tab, projectId: project),+ ),+ );+ await tester.pump();+ int boards() => fake.paths.where((p) => p.startsWith(board)).length;+ final before = boards();+ expect(before, 1, reason: 'read on opening');++ // The shell tells Swarm the app went behind (`PhoneShell`); the page hears the lifecycle.+ _toBackground(tester);+ host.foreground = false;+ await tester.pump(const Duration(minutes: 5) * 3);+ expect(boards(), before, reason: 'nothing asked from a pocket');++ host.foreground = true;+ _toFront(tester);+ await tester.pump();+ expect(boards(), before + 1, reason: 'one read at once');++ await tester.pump(const Duration(minutes: 5));+ expect(boards(), before + 2, reason: 'then on its interval again');++ host.foreground = false;+ await tester.pumpWidget(const SizedBox());+ },+ );+ });+}++/// The account's REST API, counting the device key log's reads and never reaching a backend.+class _Api extends FakeApi {+ int keyReads = 0;++ @override+ Future<DeviceLogFetched?> deviceKeys(int since, {String? self}) async {+ keyReads++;+ return null;+ }++ @override+ Future<DeviceLogAppendAnswer?> appendDeviceKey(DevLogEntry entry) async =>+ null;+}++/// A signed-in phone (memory store, fake sign-in, scripted sockets) on an account with one+/// machine, `m`, running agent `a` — or none when [machines] is false. The machine list re-read+/// that runs while no machine is connected is put a day off, so it counts only where a test means+/// it to: on the way back from a pocket.+({AppNotifier app, _Api api, ScriptedConn Function(String) conn}) _phone({+ bool machines = true,+}) {+ final rig = viewerApp();+ final api = _Api();+ rig.app.api = api;+ api.onMachines = () async => [if (machines) remoteMachine('m')];+ rig.conn('m').answers['agents_list'] = (_) => {+ 'agents': [agentJson('a')],+ };+ rig.conn('m').answers['terminal_capabilities'] = (_) => capabilities();+ rig.app+ ..deafMachineListInterval = const Duration(days: 1)+ ..asleepMachineListInterval = const Duration(days: 1)+ ..asleepMachinesListInterval = const Duration(days: 1);+ return (app: rig.app, api: api, conn: rig.conn);+}++/// A tick waits until the list is an interval old on the real clock (`DateTime.now()`), which the+/// fake clock does not move: the list is aged by hand instead.+void _ageList(AppNotifier app, String machineId) =>+ app.stateOf(machineId)!.agentsListedAt = DateTime.now().subtract(+ AppNotifier.agentSyncInterval * 4,+ );++/// What `PhoneShell` does with the lifecycle, ahead of every page (its observer is the first): the+/// app model told the app went into a pocket, and came back.+void _forwardLifecycle(WidgetTester tester, AppNotifier app) {+ final shell = _ShellLifecycle(app);+ tester.binding.addObserver(shell);+ addTearDown(() => tester.binding.removeObserver(shell));+}++class _ShellLifecycle with WidgetsBindingObserver {+ _ShellLifecycle(this.app);++ final AppNotifier app;++ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ if (state == AppLifecycleState.paused) app.handleAppPaused();+ if (state == AppLifecycleState.resumed) app.handleAppResumed();+ }+}++/// Into a pocket, the way the OS says it: `inactive`, `hidden`, `paused`.+void _toBackground(WidgetTester tester) {+ for (final state in const [+ AppLifecycleState.inactive,+ AppLifecycleState.hidden,+ AppLifecycleState.paused,+ ]) {+ tester.binding.handleAppLifecycleStateChanged(state);+ }+}++/// Back in front: `hidden`, `inactive`, `resumed`.+void _toFront(WidgetTester tester) {+ for (final state in const [+ AppLifecycleState.hidden,+ AppLifecycleState.inactive,+ AppLifecycleState.resumed,+ ]) {+ tester.binding.handleAppLifecycleStateChanged(state);+ }+}++/// A phone whose linked machines are asked what their accounts spent, counted.+class _UsageApp extends AppNotifier {+ _UsageApp()+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ );++ int reads = 0;++ @override+ Future<List<MachineUsage>> readRemoteUsage({String? machineId}) async {+ reads++;+ return const [];+ }+}diff --git a/mobile/test/usage/usage_controller_test.dart b/mobile/test/usage/usage_controller_test.dartindex a05752c5d..17d0e274e 100644--- a/mobile/test/usage/usage_controller_test.dart+++ b/mobile/test/usage/usage_controller_test.dart@@ -327,4 +327,43 @@ void main() {expect(asked, 2);});});++ test('paused it asks nothing; resumed, once now and once a minute again', () {+ fakeAsync((async) {+ var asked = 0;+ final usage = UsageController(+ remote: () async {+ asked++;+ return const <MachineUsage>[];+ },+ autoStart: false,+ );+ // Resumed without a pause first (the app switcher): nothing.+ usage.resume();+ async.flushMicrotasks();+ expect(asked, 0);++ usage.start();+ async.flushMicrotasks();+ expect(asked, 1);+ usage+ ..pause()+ ..pause();+ async.elapse(const Duration(minutes: 3));+ expect(asked, 1);++ usage.resume();+ async.flushMicrotasks();+ expect(asked, 2);+ usage.resume();+ async.flushMicrotasks();+ expect(asked, 2, reason: 'one return, one read');+ async.elapse(const Duration(seconds: 60));+ expect(asked, 3, reason: 'one timer, not two');++ usage.dispose();+ async.elapse(const Duration(minutes: 5));+ expect(asked, 3);+ });+ });}