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 b1327: #2934 #2933 #2936 #2937 #2924 (#2939)
0xken154cee8c501180
diff --git a/backend/integration/superTabReadMarks.test.ts b/backend/integration/superTabReadMarks.test.tsindex 050901264..f85a70e8a 100644--- a/backend/integration/superTabReadMarks.test.ts+++ b/backend/integration/superTabReadMarks.test.ts@@ -21,7 +21,7 @@ import { stableId } from '../src/superTabs/model.js'import { HostReads } from '../src/superTabs/read/host.js'import type { Conversation, SuperTabState } from '../src/superTabs/model.js'import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'-import { READ_MARK_EXPIRY_MS, sweepThreadMarks, THREAD_MARK_CAP, writeThreadMark } from '../src/superTabs/readMarks.js'+import { READ_MARK_EXPIRY_MS, sweepReadMarks, sweepThreadMarks, THREAD_MARK_CAP, writeThreadMark } from '../src/superTabs/readMarks.js'import { listNamedIndexes, NAMED_INDEX } from '../src/superTabs/parts/indexed.js'import { NOW, outsider as outsiderActor, owner as ownerActor, peer as peerActor, swarm } from '../src/superTabs/read/fixture.test-support.js'@@ -596,3 +596,31 @@ describe('thread marks (one per person and thread)', () => {expect(rows.every(row => row.planSummary?.startsWith('IXSCAN') && !row.fromMultiPlanner), JSON.stringify(rows.map(r => r.planSummary))).toBe(true)})})++describe('read marks past 180 days, where the database refuses their expiry (Ken\'s prod scan 11-04)', () => {+ const DAY = 86_400_000+ // Long before every other test's marks, so the cutoff below passes only the marks seeded here.+ const base = NOW - 400 * DAY+ const now = new Date(base + READ_MARK_EXPIRY_MS)+ /** One mark of a conversation per [name, last moved] in a new Swarm; answers the Swarm. */+ const seed = async (marks: Array<[string, number]>) => {+ const tabId = `tab-${randomUUID()}`+ await db.superTabReadMark.createMany({ data: marks.map(([conversationId, at]) =>+ ({ id: stableId(tabId, conversationId, owner.sub), tabId, personId: owner.sub, conversationId, sequence: 1, updatedAt: new Date(at) })) })+ return tabId+ }+ const left = async (tabId: string) =>+ (await db.superTabReadMark.findMany({ where: { tabId }, select: { conversationId: true } })).map(mark => mark.conversationId).sort()++ it('removes only the marks untouched for more than 180 days', async () => {+ const tabId = await seed([['older', base - DAY], ['just-older', base - 1], ['exactly', base], ['younger', base + DAY]])+ expect(await sweepReadMarks(db, now)).toBe(2)+ expect(await left(tabId)).toEqual(['exactly', 'younger'])+ })++ it('removes one bounded chunk a pass, oldest first', async () => {+ const tabId = await seed(['m0', 'm1', 'm2', 'm3', 'm4', 'm5', 'm6'].map((name, i) => [name, base - (7 - i) * DAY]))+ expect(await sweepReadMarks(db, now, 3)).toBe(3)+ expect(await left(tabId)).toEqual(['m3', 'm4', 'm5', 'm6'])+ })+})diff --git a/backend/integration/workerIndexPlans.test.ts b/backend/integration/workerIndexPlans.test.tsindex f5de8a5c0..07fca64c8 100644--- a/backend/integration/workerIndexPlans.test.ts+++ b/backend/integration/workerIndexPlans.test.ts@@ -238,6 +238,30 @@ describe('the usage-receipt sweep\'s done check (lib/productUsageReceiptSweep.ts})})+describe('the read-mark sweep where the expiry is refused (superTabs/readMarks.ts sweepReadMarks)', () => {+ // backend/AGENTS.md rule 3: every 30 s, one chunk of the oldest marks by the read_mark_expiry index, then exactly those by _id+ // (#2923: a delete on both _id and the range was planned on the range's index and examined every match).+ it('reads one chunk of the oldest marks by read_mark_expiry and deletes them by _id, examining only those', async () => {+ const { READ_MARK_EXPIRY_MS, sweepReadMarks } = await import('../src/superTabs/readMarks.js')+ const now = new Date(NOW)+ const mark = (n: number, ageMs: number) => ({ id: `plan-mark-${n}`, tabId: 'tab-plan', personId: 'p', conversationId: `c${n}`, sequence: 1,+ updatedAt: new Date(NOW - ageMs) })+ // 40 live marks and 10 past 180 days: a read the index does not bound examines them all.+ await db.superTabReadMark.createMany({ data: [...Array.from({ length: 40 }, (_, i) => mark(i, DAY)),+ ...Array.from({ length: 10 }, (_, i) => mark(100 + i, READ_MARK_EXPIRY_MS + (i + 1) * DAY))] })+ let removed = 0+ const entries = await profiled(db, async () => { removed = await sweepReadMarks(db, now, 4) })+ expect(removed).toBe(4)+ const [found] = reads(entries, 'SuperTabReadMark', ['updatedAt'], ['_id'])+ expect(found?.planSummary, JSON.stringify(plan(entries))).toMatch(/IXSCAN \{ updatedAt: 1/)+ expect(found!.keysExamined, JSON.stringify(plan([found!]))).toBeLessThanOrEqual(5)+ expect(found!.docsExamined, JSON.stringify(plan([found!]))).toBeLessThanOrEqual(4)+ const [removal] = reads(entries, 'SuperTabReadMark', ['_id', 'updatedAt'])+ expect(removal?.planSummary, JSON.stringify(plan(entries))).toMatch(/IXSCAN \{ _id: 1/)+ expect(removal!.docsExamined, JSON.stringify(plan([removal!]))).toBeLessThanOrEqual(4)+ })+})+// Dee, #1891; ENGINEERING.md 4 and the MongoDB query skill: the minute's pull request watch reads open tasks through the finished// mark's index, equality on its first two fields and the activity range last, newest first and capped.describe('the pull request watch', () => {diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 544795ab0..b97cd0b3a 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1237,7 +1237,8 @@ model SuperTabReadMark {loweredAt DateTime?@@index([tabId, personId, updatedAt])- /// A mark untouched this long goes (superTabs/readMarks.ts ensureReadMarkExpiry). Declared so db push keeps the index.+ /// A mark untouched for 180 days goes: by this index's expiry (superTabs/readMarks.ts ensureReadMarkExpiry), or where the+ /// database refuses it, by the worker's sweep (startReadMarkSweep). Declared so db push keeps the index.@@index([updatedAt], map: "read_mark_expiry")}diff --git a/backend/src/lib/chunkSweep.test.ts b/backend/src/lib/chunkSweep.test.tsnew file mode 100644index 000000000..aef1f14aa--- /dev/null+++ b/backend/src/lib/chunkSweep.test.ts@@ -0,0 +1,91 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { removeChunk, startChunkSweep } from './chunkSweep.js'++const RANGE = { updatedAt: { $lt: { $date: '2026-05-08T00:00:00.000Z' } } }+const CHUNK = { collection: 'SuperTabReadMark', filter: RANGE, sort: { updatedAt: 1 as const }, hint: 'read_mark_expiry', chunk: 3 }++/** A database whose find answers [found] ids, and whose delete removes as many as it is given; it records every command. */+function database(found: string[], deleteAnswer?: (ids: string[]) => unknown) {+ const commands: Record<string, unknown>[] = []+ const db = { $runCommandRaw: vi.fn(async (command: Record<string, unknown>) => {+ commands.push(command)+ if ('find' in command) return { cursor: { firstBatch: found.map(_id => ({ _id })) } }+ const ids = ((command.deletes as Array<{ q: { _id: { $in: string[] } } }>)[0]).q._id.$in+ return deleteAnswer ? deleteAnswer(ids) : { n: ids.length }+ }) }+ return { db: db as never, commands }+}++describe('removeChunk', () => {+ it('reads one bounded chunk of ids by the index it names, the whole chunk in one batch', async () => {+ const { db, commands } = database(['a', 'b', 'c'])+ await removeChunk(db, CHUNK)+ expect(commands[0]).toEqual({ find: 'SuperTabReadMark', filter: RANGE, projection: { _id: 1 }, sort: { updatedAt: 1 }, hint: 'read_mark_expiry',+ limit: 3, batchSize: 3, singleBatch: true })+ })++ it('removes exactly those ids by _id, their range checked again so one moved since the read stays', async () => {+ const { db, commands } = database(['a', 'b', 'c'], () => ({ n: 2 }))+ await expect(removeChunk(db, CHUNK)).resolves.toBe(2)+ expect(commands[1]).toEqual({ delete: 'SuperTabReadMark', deletes: [{ q: { _id: { $in: ['a', 'b', 'c'] }, ...RANGE }, limit: 0, hint: { _id: 1 } }] })+ })++ it('sends no delete when nothing is past the range', async () => {+ const { db, commands } = database([])+ await expect(removeChunk(db, CHUNK)).resolves.toBe(0)+ expect(commands).toHaveLength(1)+ })++ it('fails when the database refuses a removal', async () => {+ const { db } = database(['a'], () => ({ n: 0, writeErrors: [{ code: 2 }] }))+ await expect(removeChunk(db, CHUNK)).rejects.toThrow('The database refused some removals from SuperTabReadMark')+ })+})++describe('startChunkSweep', () => {+ afterEach(() => { vi.useRealTimers() })+ const lines = () => {+ const logged: string[] = []+ return { logged, log: { info: (message: string) => logged.push(`info ${message}`), warn: (message: string) => logged.push(`warn ${message}`) } }+ }++ it('runs a pass at once and every everyMs, and skips one due while the last still runs', async () => {+ vi.useFakeTimers()+ let release = () => {}+ const pass = vi.fn(() => new Promise<{ removed: number; done: boolean }>(resolve => { release = () => resolve({ removed: 0, done: false }) }))+ const stop = startChunkSweep({ label: '[test]', everyMs: 1000, pass, log: lines().log })+ expect(pass).toHaveBeenCalledTimes(1)+ await vi.advanceTimersByTimeAsync(3000)+ expect(pass).toHaveBeenCalledTimes(1)+ release()+ await vi.advanceTimersByTimeAsync(1000)+ expect(pass).toHaveBeenCalledTimes(2)+ stop()+ })++ it('logs each pass that removed some, and stops once a pass says it is done', async () => {+ vi.useFakeTimers()+ const answers = [{ removed: 3, done: false }, { removed: 0, done: false }, { removed: 2, done: true }]+ const pass = vi.fn(async () => answers.shift() ?? { removed: 0, done: true })+ const { logged, log } = lines()+ startChunkSweep({ label: '[test]', everyMs: 1000, pass, doneMessage: 'done: nothing left', log })+ await vi.advanceTimersByTimeAsync(10_000)+ expect(pass).toHaveBeenCalledTimes(3)+ expect(logged).toEqual(['info [test] pass', 'info [test] pass', 'info [test] done: nothing left'])+ })++ it('logs a failed pass and carries on with the next; an error the caller handles is not logged as a failure', async () => {+ vi.useFakeTimers()+ const errors = [new Error('connection closed'), new Error('handled')]+ const pass = vi.fn(async () => {+ const error = errors.shift()+ if (error) throw error+ return { removed: 1, done: false }+ })+ const { logged, log } = lines()+ const stop = startChunkSweep({ label: '[test]', everyMs: 1000, pass, log, handle: error => (error as Error).message === 'handled' })+ await vi.advanceTimersByTimeAsync(2000)+ stop()+ expect(logged).toEqual(['warn [test] pass failed; retrying next pass', 'info [test] pass'])+ })+})diff --git a/backend/src/lib/chunkSweep.ts b/backend/src/lib/chunkSweep.tsnew file mode 100644index 000000000..52784215a--- /dev/null+++ b/backend/src/lib/chunkSweep.ts@@ -0,0 +1,67 @@+import type { PrismaClient } from '@prisma/client'+import type { logger } from '../utils/logger.js'++/** One chunk of documents to remove: those matching [filter], first in [sort] order by the index [hint] names. */+export interface Chunk {+ collection: string+ filter: Record<string, unknown>+ sort: Record<string, 1 | -1>+ hint: string+ chunk: number+}++/** One chunk: up to [Chunk.chunk] ids in [Chunk.sort] order by [Chunk.hint] (a find's first batch holds only 101 unless asked+ * for more), then exactly those, by _id, their [Chunk.filter] checked again: one that moved out of it since the find stays.+ * On both _id and a range Mongo planned the range's index and examined every match (#2923: ~4M receipts, ~17 s a delete). */+export async function removeChunk(db: Pick<PrismaClient, '$runCommandRaw'>, { collection, filter, sort, hint, chunk }: Chunk): Promise<number> {+ const found = await db.$runCommandRaw({ find: collection, filter, projection: { _id: 1 }, sort, hint, limit: chunk, batchSize: chunk,+ singleBatch: true } as never) as { cursor: { firstBatch: Array<{ _id: string }> } }+ const ids = found.cursor.firstBatch.map(document => document._id)+ if (!ids.length) return 0+ const answer = await db.$runCommandRaw({ delete: collection, deletes: [{ q: { _id: { $in: ids }, ...filter }, limit: 0, hint: { _id: 1 } }] } as never) as+ { n?: number; writeErrors?: unknown[] }+ if (answer.writeErrors?.length) throw new Error(`The database refused some removals from ${collection}`)+ return answer.n ?? 0+}++export interface ChunkSweep {+ /** Starts every line it logs, such as `[usage-receipts]`. */+ label: string+ everyMs: number+ /** One pass; `done` once nothing is left that this sweep would ever remove. */+ pass: () => Promise<{ removed: number; done: boolean }>+ /** Logged after the label once a pass is done. */+ doneMessage?: string+ log: Pick<typeof logger, 'info' | 'warn'>+ /** True when the caller dealt with a pass's error itself, which is then not logged as a failed pass. */+ handle?: (error: unknown) => boolean+}++/** Runs [ChunkSweep.pass] now and every [ChunkSweep.everyMs] in the singleton worker until a pass is done; a pass still running+ * when the next is due skips it, and a failed pass is logged and the next one carries on. Answers its stop. */+export function startChunkSweep({ label, everyMs, pass, doneMessage = 'done', log, handle }: ChunkSweep): () => void {+ let running = false, total = 0+ const run = async () => {+ if (running) return+ running = true+ try {+ const { removed, done } = await pass()+ total += removed+ if (removed) log.info(`${label} pass`, { removed, removedSinceStart: total })+ if (done) {+ stop()+ log.info(`${label} ${doneMessage}`, { removedSinceStart: total })+ }+ } catch (error) {+ if (handle?.(error)) return+ log.warn(`${label} pass failed; retrying next pass`, { error: error instanceof Error ? error.message : String(error) })+ } finally {+ running = false+ }+ }+ const timer = setInterval(() => void run(), everyMs)+ timer.unref()+ const stop = () => clearInterval(timer)+ void run()+ return stop+}diff --git a/backend/src/lib/db/indexes.test.ts b/backend/src/lib/db/indexes.test.tsindex 5aa7ff778..0ffcf910c 100644--- a/backend/src/lib/db/indexes.test.ts+++ b/backend/src/lib/db/indexes.test.ts@@ -19,7 +19,7 @@ function db(collMod: () => unknown) {describe('ensureIndex', () => {it('sets a missing expiry with collMod and builds nothing', async () => {const { db: fake, calls } = db(() => ({ ok: 1 }))- await ensureIndex(fake, 'SuperTabReadMark', SPEC)+ await expect(ensureIndex(fake, 'SuperTabReadMark', SPEC)).resolves.toBe('ready')expect(calls.map(call => Object.keys(call)[0])).toEqual(['listIndexes', 'collMod'])})@@ -28,7 +28,8 @@ describe('ensureIndex', () => {const { db: fake, calls } = db(() => {throw new Error('Raw query failed. Code: `13`. Message: `not authorized on harness to execute command { collMod: "SuperTabReadMark" }`')})- await expect(ensureIndex(fake, 'SuperTabReadMark', SPEC)).resolves.toBeUndefined()+ // The caller hears it, so it can remove what the expiry would have (superTabs/readMarks.ts startReadMarkSweep).+ await expect(ensureIndex(fake, 'SuperTabReadMark', SPEC)).resolves.toBe('expiry-refused')expect(calls.map(call => Object.keys(call)[0])).toEqual(['listIndexes', 'collMod'])expect(warn).toHaveBeenCalledWith(expect.stringContaining('collMod'), expect.objectContaining({ collection: 'SuperTabReadMark', index: 'read_mark_expiry' }))warn.mockRestore()diff --git a/backend/src/lib/db/indexes.ts b/backend/src/lib/db/indexes.tsindex e77af3c1e..333146c40 100644--- a/backend/src/lib/db/indexes.ts+++ b/backend/src/lib/db/indexes.ts@@ -17,6 +17,9 @@ async function listIndexes(db: Pick<PrismaClient, '$runCommandRaw'>, collection:}}+/** What [ensureIndex] left: the index as asked, or the index without the expiry the database user may not set. */+export type IndexOutcome = 'ready' | 'expiry-refused'+const sameKey = (a: Record<string, number>, b: Record<string, number>) => JSON.stringify(Object.entries(a)) === JSON.stringify(Object.entries(b))/**@@ -24,11 +27,12 @@ const sameKey = (a: Record<string, number>, b: Record<string, number>) => JSON.s* the collection exclusively for a moment, and a Swarm read's transaction waits at most 5 ms for its lock (the 10-28 release);* listing the indexes takes no lock that reads or writes wait for. An index Prisma declares without expiry (db push builds it* so on a new database) gets its expiry with collMod, without a rebuild. Any other difference fails in createIndexes, as before.+ * It answers 'expiry-refused' when the database user may not run that collMod, so the caller can remove what the expiry would.*/-export async function ensureIndex(db: Pick<PrismaClient, '$runCommandRaw'>, collection: string, index: IndexSpec): Promise<void> {+export async function ensureIndex(db: Pick<PrismaClient, '$runCommandRaw'>, collection: string, index: IndexSpec): Promise<IndexOutcome> {const found = (await listIndexes(db, collection)).find(existing => existing.name === index.name)if (found && sameKey(found.key, index.key) && !!found.unique === !!index.unique) {- if (found.expireAfterSeconds === index.expireAfterSeconds) return+ if (found.expireAfterSeconds === index.expireAfterSeconds) return 'ready'if (index.expireAfterSeconds !== undefined) {try {await db.$runCommandRaw({ collMod: collection, index: { name: index.name, expireAfterSeconds: index.expireAfterSeconds } })@@ -37,9 +41,11 @@ export async function ensureIndex(db: Pick<PrismaClient, '$runCommandRaw'>, coll// exists and serves reads; only its expiry waits for someone with the right to set it, so warn and carry on.if (!notAuthorized(error)) throw errorlogger.warn('index expiry not set: the database user may not run collMod', { collection, index: index.name, expireAfterSeconds: index.expireAfterSeconds })+ return 'expiry-refused'}- return+ return 'ready'}}await db.$runCommandRaw({ createIndexes: collection, indexes: [index] })+ return 'ready'}diff --git a/backend/src/lib/db/schemaRelease.ts b/backend/src/lib/db/schemaRelease.tsindex d244e95ed..fee37342f 100644--- a/backend/src/lib/db/schemaRelease.ts+++ b/backend/src/lib/db/schemaRelease.ts@@ -9,9 +9,12 @@ import { ensurePartExpiry } from '../../superTabs/sweeps.js'import { ensureOperationExpiry } from '../../superTabs/operations.js'import { ensureSchema, type SchemaTarget } from './migrate.js'+/** What a release's index work left for the worker to do: remove old read marks itself where their expiry was refused. */+export interface SchemaRelease { readMarkExpirySet: boolean }+/** The index work of a release, run by the singleton worker at startup once the legacy unique indexes are gone: the* Prisma schema, then the indexes Prisma cannot describe (expiry, and the keys that must hold before the push). */-export async function releaseSchema(db: PrismaClient = prisma, target: SchemaTarget = {}): Promise<void> {+export async function releaseSchema(db: PrismaClient = prisma, target: SchemaTarget = {}): Promise<SchemaRelease> {// Before the push: an expiry index new to a collection that already exists. Built here, by createIndexes, it has its expiry// at once and the push keeps it; built by the push, it would need collMod for its expiry, which production's app user may// not run (10-29). The indexes below were made before they were declared, so the push has always found them.@@ -21,6 +24,7 @@ export async function releaseSchema(db: PrismaClient = prisma, target: SchemaTarawait ensureHarnessSessionExpiry(db)await ensureTerminalExpiry(db)await ensureMentionExpiry(db)- await ensureReadMarkExpiry(db)+ const readMarkExpirySet = await ensureReadMarkExpiry(db)await ensurePartExpiry(db)+ return { readMarkExpirySet }}diff --git a/backend/src/lib/productUsageReceiptSweep.ts b/backend/src/lib/productUsageReceiptSweep.tsindex b00a3744b..22c13b3c1 100644--- a/backend/src/lib/productUsageReceiptSweep.ts+++ b/backend/src/lib/productUsageReceiptSweep.ts@@ -3,6 +3,7 @@ import type { PrismaClient } from '@prisma/client'import { PRODUCT_USAGE_RECEIPT_EXPIRY_DAYS } from '../types/productUsageReceipt.js'import { logger } from '../utils/logger.js'import { notAuthorized } from './db/indexes.js'+import { removeChunk, startChunkSweep } from './chunkSweep.js'/*** Removes, a little at a time, the usage receipts written while a receipt lived 36 days (until 2026-10-29: about 4M of@@ -86,21 +87,10 @@ export async function lastOldReceipt(db: PrismaClient, now: Date): Promise<Datereturn newest ? dateOf(newest.expiresAt) : null}-/** One chunk: up to [chunk] old receipts in expiresAt order (a first batch holds only 101 unless asked for more), then exactly- * those, their range checked again. */-async function removeChunk(db: PrismaClient, now: Date, chunk: number): Promise<number> {- const range = { expiresAt: { $gt: oldFloor(now),- $lte: date(now.getTime() + (OLD_EXPIRY_DAYS - PRODUCT_USAGE_RECEIPT_EXPIRY_DAYS) * DAY) } }- const found = await db.$runCommandRaw({ find: COLLECTION, filter: range, projection: { _id: 1 }, sort: { expiresAt: 1 },- hint: 'product_usage_expiry', limit: chunk, batchSize: chunk, singleBatch: true } as never) as { cursor: { firstBatch: Array<{ _id: string }> } }- const ids = found.cursor.firstBatch.map(receipt => receipt._id)- if (!ids.length) return 0- // By _id: on both _id and the range Mongo planned the expiry index and examined every old receipt (~4M, ~17 s a delete, 11-04).- const answer = await db.$runCommandRaw({ delete: COLLECTION, deletes: [{ q: { _id: { $in: ids }, ...range }, limit: 0, hint: { _id: 1 } }] } as never) as- { n?: number; writeErrors?: unknown[] }- if (answer.writeErrors?.length) throw new Error('The database refused some receipt removals')- return answer.n ?? 0-}+/** One chunk of old receipts in expiresAt order (lib/chunkSweep.ts). */+const removeOldChunk = (db: PrismaClient, now: Date, chunk: number) => removeChunk(db, { collection: COLLECTION, sort: { expiresAt: 1 },+ hint: 'product_usage_expiry', chunk, filter: { expiresAt: { $gt: oldFloor(now),+ $lte: date(now.getTime() + (OLD_EXPIRY_DAYS - PRODUCT_USAGE_RECEIPT_EXPIRY_DAYS) * DAY) } } })/** One pass: the rule unless [SweepOptions.withoutRule], then at most [chunks] × [chunk] receipts. Safe to repeat, and from* two processes at once. */@@ -109,7 +99,7 @@ export async function sweepOldReceipts(db: PrismaClient, now = new Date(), optiolet removed = 0for (let i = 0; i < options.chunks; i++) {if (i) await delay(options.pauseMs)- const n = await removeChunk(db, now, options.chunk)+ const n = await removeOldChunk(db, now, options.chunk)removed += nif (n < options.chunk) break}@@ -121,33 +111,14 @@ export async function sweepOldReceipts(db: PrismaClient, now = new Date(), optioexport function startReceiptSweep(db: PrismaClient, settings: Partial<SweepOptions & { everyMs: number;now: () => Date; log: Pick<typeof logger, 'info' | 'warn'> }> = {}): () => void {const { everyMs, now, log, ...options } = { ...RECEIPT_SWEEP, now: () => new Date(), log: logger, ...settings }- let running = false, total = 0, withoutRule = options.withoutRule ?? false- const run = async () => {- if (running) return- running = true- try {- const pass = await sweepOldReceipts(db, now(), { ...options, withoutRule })- total += pass.removed- if (pass.removed) log.info('[usage-receipts] pass', { removed: pass.removed, removedSinceStart: total })- if (pass.done) {- stop()- log.info('[usage-receipts] done: no old receipts left', { removedSinceStart: total })- }- } catch (error) {- if (error instanceof ReceiptRuleRefused) {- withoutRule = true- log.warn('[usage-receipts] the database user may not install the receipt rule (collMod): removing the old receipts without it '- + '(Ken, 2026-11-04). A server from before 2026-10-29, were one rolled back, could count a retried report twice.')- return- }- log.warn('[usage-receipts] pass failed; retrying next pass', { error: error instanceof Error ? error.message : String(error) })- } finally {- running = false- }- }- const timer = setInterval(() => void run(), everyMs)- timer.unref()- const stop = () => clearInterval(timer)- void run()- return stop+ let withoutRule = options.withoutRule ?? false+ return startChunkSweep({ label: '[usage-receipts]', everyMs, log, doneMessage: 'done: no old receipts left',+ pass: () => sweepOldReceipts(db, now(), { ...options, withoutRule }),+ handle: error => {+ if (!(error instanceof ReceiptRuleRefused)) return false+ withoutRule = true+ log.warn('[usage-receipts] the database user may not install the receipt rule (collMod): removing the old receipts without it '+ + '(Ken, 2026-11-04). A server from before 2026-10-29, were one rolled back, could count a retried report twice.')+ return true+ } })}diff --git a/backend/src/superTabs/readMarks.test.ts b/backend/src/superTabs/readMarks.test.tsnew file mode 100644index 000000000..554f6be20--- /dev/null+++ b/backend/src/superTabs/readMarks.test.ts@@ -0,0 +1,84 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { ensureReadMarkExpiry, READ_MARK_EXPIRY_MS, READ_MARK_SWEEP, startReadMarkSweep } from './readMarks.js'+import { logger } from '../utils/logger.js'++const REFUSED = 'Raw query failed. Code: `13`. Message: `not authorized on harness to execute command { collMod: "SuperTabReadMark" }`'++/** A database whose read_mark_expiry index has [expireAfterSeconds] (none: as db push builds it), and whose collMod answers+ * `collMod`; it records every command. */+function database(options: { expireAfterSeconds?: number; collMod?: () => unknown; found?: string[] } = {}) {+ const commands: Record<string, unknown>[] = []+ const db = { $runCommandRaw: vi.fn(async (command: Record<string, unknown>) => {+ commands.push(command)+ if ('listIndexes' in command) return { cursor: { firstBatch: [{ key: { updatedAt: 1 }, name: 'read_mark_expiry', expireAfterSeconds: options.expireAfterSeconds }] } }+ if ('collMod' in command) return (options.collMod ?? (() => ({ ok: 1 })))()+ if ('find' in command) return { cursor: { firstBatch: (options.found ?? []).map(_id => ({ _id })) } }+ if ('delete' in command) return { n: (options.found ?? []).length }+ return { cursor: { firstBatch: [] } }+ }) }+ return { db: db as never, commands }+}++describe('ensureReadMarkExpiry', () => {+ it('answers that the expiry is set when the index has it already', async () => {+ await expect(ensureReadMarkExpiry(database({ expireAfterSeconds: 15_552_000 }).db)).resolves.toBe(true)+ })++ it('answers that the expiry is set when collMod sets it', async () => {+ await expect(ensureReadMarkExpiry(database().db)).resolves.toBe(true)+ })++ it('answers that it is not when the database user may not run collMod (production, Ken\'s prod scan 11-04)', async () => {+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => logger)+ try {+ await expect(ensureReadMarkExpiry(database({ collMod: () => { throw new Error(REFUSED) } }).db)).resolves.toBe(false)+ } finally { warn.mockRestore() }+ })+})++describe('startReadMarkSweep', () => {+ afterEach(() => { vi.useRealTimers() })+ const now = new Date('2026-11-04T06:00:00Z')+ const cutoff = { updatedAt: { $lt: { $date: new Date(now.getTime() - READ_MARK_EXPIRY_MS).toISOString() } } }+ const quiet = () => ({ info: vi.fn(), warn: vi.fn() })++ it('runs nothing where the expiry is set: no command, no timer', async () => {+ vi.useFakeTimers()+ const { db, commands } = database({ found: ['old'] })+ const stop = startReadMarkSweep(db, true, { now: () => now, log: quiet() })+ await vi.advanceTimersByTimeAsync(10 * READ_MARK_SWEEP.everyMs)+ expect(commands).toEqual([])+ expect(vi.getTimerCount()).toBe(0)+ stop()+ })++ it('where the expiry was refused, removes one chunk of marks past 180 days at once, by the expiry index', async () => {+ vi.useFakeTimers()+ const { db, commands } = database({ found: ['a', 'b'] })+ const log = quiet()+ const stop = startReadMarkSweep(db, false, { now: () => now, log })+ await vi.advanceTimersByTimeAsync(0)+ stop()+ expect(commands).toEqual([+ { find: 'SuperTabReadMark', filter: cutoff, projection: { _id: 1 }, sort: { updatedAt: 1 }, hint: 'read_mark_expiry', limit: 500, batchSize: 500,+ singleBatch: true },+ { delete: 'SuperTabReadMark', deletes: [{ q: { _id: { $in: ['a', 'b'] }, ...cutoff }, limit: 0, hint: { _id: 1 } }] },+ ])+ expect(log.warn).toHaveBeenCalledTimes(1)+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('[read-marks]'))+ expect(log.info).toHaveBeenCalledWith('[read-marks] pass', { removed: 2, removedSinceStart: 2 })+ })++ it('takes one bounded chunk every 30 s and never stops by itself: marks keep ageing', async () => {+ vi.useFakeTimers()+ const { db, commands } = database()+ const stop = startReadMarkSweep(db, false, { now: () => now, log: quiet(), chunk: 3 })+ await vi.advanceTimersByTimeAsync(3 * 30_000)+ stop()+ const finds = commands.filter(command => 'find' in command)+ // One at start, then one each 30 s; an empty pass is that one find and no delete.+ expect(finds).toHaveLength(4)+ expect(finds.every(command => command.limit === 3)).toBe(true)+ expect(commands.filter(command => 'delete' in command)).toEqual([])+ })+})diff --git a/backend/src/superTabs/readMarks.ts b/backend/src/superTabs/readMarks.tsindex 585015cc7..db3e1c472 100644--- a/backend/src/superTabs/readMarks.ts+++ b/backend/src/superTabs/readMarks.ts@@ -4,6 +4,8 @@* marks' collection). A person's marks go only to their own reads (read/service.ts); agents, Buddies included, have none. */import { Prisma, type PrismaClient } from '@prisma/client'import { ensureIndex } from '../lib/db/indexes.js'+import { removeChunk, startChunkSweep } from '../lib/chunkSweep.js'+import { logger } from '../utils/logger.js'import { fail, stableId } from './model.js'import { readBy } from './parts/indexed.js'import { ms } from './parts/light.js'@@ -15,10 +17,34 @@ export const READ_MARK_EXPIRY_MS = 180 * 24 * 60 * 60_000* mark went reads as far as its conversation's mark, as on a device that never kept one. */export const THREAD_MARK_CAP = 500-/** Run by the singleton worker at startup, like the mention expiry. Thread marks need no index option: the hourly sweep- * deletes them (sweepThreadMarks), as the app user may not set one on an index `db push` built (#2238). */-export async function ensureReadMarkExpiry(db: PrismaClient): Promise<void> {- await ensureIndex(db, 'SuperTabReadMark', { key: { updatedAt: 1 }, name: 'read_mark_expiry', expireAfterSeconds: READ_MARK_EXPIRY_MS / 1000 })+/** Run by the singleton worker at startup, like the mention expiry; answers whether the expiry is set. Where the database user+ * may not set it (production's, no collMod), startReadMarkSweep removes the old marks instead. Thread marks need no index+ * option: the hourly sweep deletes them (sweepThreadMarks), as the app user may not set one on an index `db push` built (#2238). */+export async function ensureReadMarkExpiry(db: Pick<PrismaClient, '$runCommandRaw'>): Promise<boolean> {+ return await ensureIndex(db, 'SuperTabReadMark', { key: { updatedAt: 1 }, name: 'read_mark_expiry',+ expireAfterSeconds: READ_MARK_EXPIRY_MS / 1000 }) === 'ready'+}++/** Where the expiry is refused: one chunk of 500 marks every 30 s, as the usage-receipt sweep (lib/productUsageReceiptSweep.ts). */+export const READ_MARK_SWEEP = { chunk: 500, everyMs: 30_000 } as const++/** Removes up to [chunk] marks untouched for READ_MARK_EXPIRY_MS, oldest first, by the expiry index, and answers how many went.+ * A mark moved between the read of the chunk and its delete stays (lib/chunkSweep.ts). */+export async function sweepReadMarks(db: Pick<PrismaClient, '$runCommandRaw'>, now: Date, chunk: number = READ_MARK_SWEEP.chunk): Promise<number> {+ return removeChunk(db, { collection: 'SuperTabReadMark', sort: { updatedAt: 1 }, hint: 'read_mark_expiry', chunk,+ filter: { updatedAt: { $lt: { $date: new Date(now.getTime() - READ_MARK_EXPIRY_MS).toISOString() } } } })+}++/** In the singleton worker, where the database refused the expiry (ensureReadMarkExpiry false: production's app user may not+ * run collMod, Ken's prod scan 11-04), removes old marks itself: one chunk now and every READ_MARK_SWEEP.everyMs, for as long+ * as the worker runs, since marks keep ageing. Where the expiry is set, it runs nothing. Answers its stop. */+export function startReadMarkSweep(db: Pick<PrismaClient, '$runCommandRaw'>, expirySet: boolean,+ settings: Partial<{ chunk: number; everyMs: number; now: () => Date; log: Pick<typeof logger, 'info' | 'warn'> }> = {}): () => void {+ if (expirySet) return () => {}+ const { chunk, everyMs, now, log } = { ...READ_MARK_SWEEP, now: () => new Date(), log: logger, ...settings }+ log.warn(`[read-marks] the database refused the read-mark expiry: removing marks untouched for ${READ_MARK_EXPIRY_MS / 86_400_000} days `+ + `here instead, ${chunk} every ${everyMs / 1000} s`)+ return startChunkSweep({ label: '[read-marks]', everyMs, log, pass: async () => ({ removed: await sweepReadMarks(db, now(), chunk), done: false }) })}export interface ReadMarkWrite { tabId: string; personId: string; conversationId: string; sequence: number; now: number }diff --git a/backend/src/worker.ts b/backend/src/worker.tsindex 75cd8e3ac..3df5eafef 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -34,6 +34,7 @@ import { env } from './config/env.js'import { machineBillingWorkerService } from './services/MachineBillingWorkerService.js'import { productUsagePeopleRollupService } from './services/ProductUsagePeopleRollupService.js'import { startReceiptSweep } from './lib/productUsageReceiptSweep.js'+import { startReadMarkSweep } from './superTabs/readMarks.js'import { startPendingUploadSweep } from './lib/pendingUploadSweep.js'import { startSwarmPurge } from './superTabs/purge.js'import { startAttachmentSweepFrom } from './lib/attachmentSweep.js'@@ -55,7 +56,7 @@ async function start(): Promise<void> {await migrateUserIdentityByEmail()// Same reason: the old (user, day) unique must be gone before the push installs its replacement.await migrateUserPresencePerMachine()- await releaseSchema()+ const schema = await releaseSchema()// After the push, which adds the finished mark: parts written before it are marked once, so the archive pass finds them.await markFinishedGroups(prisma)// AFTER the push: it creates the new collections + their unique indexes, and the copy uses $merge@@ -78,6 +79,7 @@ async function start(): Promise<void> {let stopCompaction = (): void => {}let stopThreadBackfill = (): void => {}let stopReceiptSweep = (): void => {}+ let stopReadMarkSweep = (): void => {}let stopPendingUploads = (): void => {}let stopSwarmPurge = (): void => {}let stopAttachmentSweep = (): void => {}@@ -95,6 +97,7 @@ async function start(): Promise<void> {stopDeliveries()stopCompaction()stopReceiptSweep()+ stopReadMarkSweep()stopPendingUploads()stopSwarmPurge()stopAttachmentSweep()@@ -112,6 +115,8 @@ async function start(): Promise<void> {productUsagePeopleRollupService.start()// Usage receipts from when they lived 36 days, a few at a time until none are left (lib/productUsageReceiptSweep.ts).stopReceiptSweep = startReceiptSweep(prisma)+ // Read marks untouched for 180 days, where the database refused their index expiry, a chunk every 30 s (superTabs/readMarks.ts).+ stopReadMarkSweep = startReadMarkSweep(prisma, schema.readMarkExpirySet)// Uploads begun on a link and never finished go an hour after the link expired, with what they stored (lib/pendingUploadSweep.ts).stopPendingUploads = startPendingUploadSweep(prisma, env)// Deleted Swarms past their 7 days go with their records and stored files (superTabs/purge.ts).diff --git a/cli/src/backendSocket.gridReads.spec.ts b/cli/src/backendSocket.gridReads.spec.tsindex e5f4c58ba..3e78cae28 100644--- a/cli/src/backendSocket.gridReads.spec.ts+++ b/cli/src/backendSocket.gridReads.spec.ts@@ -8,7 +8,7 @@*/import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { randomUUID } from 'node:crypto'-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { createServer, type IncomingHttpHeaders, type Server } from 'node:http'import { tmpdir } from 'node:os'import { join } from 'node:path'@@ -40,6 +40,8 @@ let overview: { status: number; body: unknown }let modelsDelayMs: numberlet root: string, gridHome: string, previousData: string, grid: FakeGrid, service: GridModelsService, clock: numberlet socket: BackendSocket, frames: Array<{ type: string; payload: Record<string, unknown> }>+/** Every read the daemon has sent the fake relay and not yet seen end, so the cleanup can wait them out. */+const relayReads = new Set<Promise<unknown>>()const TOKEN = fakeGridAnswers().token@@ -64,6 +66,24 @@ async function ask(type: string, payload: Record<string, unknown> = {}): Promisereturn frames.find((f) => f.payload.requestId === requestId)!.payload}+/**+ * Removes a test's folder with [remove], tried again while something still finishes writing into it:+ * the agent_retarget prewarm runs on purpose after the move answers, and the fake grid it may start+ * appends to its call log (#2917's CI, 11-04: ENOTEMPTY).+ */+async function removeSettling(remove: () => void, attempts = 10): Promise<void> {+ for (let attempt = 1; ; attempt++) {+ try {+ remove()+ return+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code+ if (attempt >= attempts || (code !== 'ENOTEMPTY' && code !== 'EBUSY')) throw error+ await new Promise((resolve) => setTimeout(resolve, 20 * attempt))+ }+ }+}+function expectNoCredential(): void {for (const request of seen) {expect(request.headers.authorization).toBeUndefined()@@ -101,7 +121,10 @@ beforeEach(async () => {if (new URL(url).origin !== relayOrigin) return externalFetch(input, init)const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined))headers.set('x-harness-test-client', clientId)- return externalFetch(input, { ...init, headers })+ const read = externalFetch(input, { ...init, headers })+ const tracked = read.catch(() => {}).finally(() => relayReads.delete(tracked))+ relayReads.add(tracked)+ return read})root = mkdtempSync(join(tmpdir(), 'grid-reads-rpc-'))gridHome = join(root, 'grid-home')@@ -136,17 +159,21 @@ beforeEach(async () => {})afterEach(async () => {+ // A read still held (agent_retarget's prewarm, which the move does not wait on) ends here, and the+ // service has nothing left to save, before anything is removed.+ server.closeAllConnections()+ await Promise.allSettled([...relayReads])await service.settled()await socket.unregisterLocalClient('local:grid-reads')await socket.stop()- grid.dispose()+ // The fake grid a background read started may still be appending to its call log.+ await removeSettling(() => grid.dispose())clearGridMcpUrlCache()env.ADAPTER_DATA_DIR = previousDatavi.unstubAllEnvs()- server.closeAllConnections()await new Promise<void>((resolve) => server.close(() => resolve()))vi.unstubAllGlobals()- rmSync(root, { recursive: true, force: true })+ await removeSettling(() => rmSync(root, { recursive: true, force: true }))})describe('grid_models_list', () => {@@ -343,3 +370,24 @@ describe('agent_retarget', () => {expect(modelReads()).toEqual([])})})++describe('a test folder something still writes into', () => {+ it('is removed once the write lands, not left behind with an error', async () => {+ const folder = mkdtempSync(join(tmpdir(), 'grid-reads-late-'))+ let late = true+ // A write that lands between a removal emptying the folder and removing it, as the fake grid's did.+ await removeSettling(() => {+ if (late) {+ late = false+ writeFileSync(join(folder, 'calls.jsonl'), '["info"]\n')+ throw Object.assign(new Error(`ENOTEMPTY: directory not empty, rmdir '${folder}'`), { code: 'ENOTEMPTY' })+ }+ rmSync(folder, { recursive: true, force: true })+ })+ expect(existsSync(folder)).toBe(false)+ })++ it('still fails on anything else', async () => {+ await expect(removeSettling(() => { throw Object.assign(new Error('EACCES'), { code: 'EACCES' }) })).rejects.toThrow('EACCES')+ })+})diff --git a/cli/src/team/command.spec.ts b/cli/src/team/command.spec.tsindex 8d35299a6..693ef46bb 100644--- a/cli/src/team/command.spec.ts+++ b/cli/src/team/command.spec.ts@@ -938,6 +938,20 @@ describe('on Windows', () => {expect(text).toContain('✓ Private')})+ // Task #2686: on Windows the sign-in and the daemon's start come after the elevated script, from the owner.+ it('setup says the sign-in and the daemon steps around the handover, then waits for the report', async () => {+ const handed: string[] = []+ const steps: string[] = []+ const f = onWindows({ handedOver: handed, progress: (step) => steps.push(step), readStatus: () => handed.length ? reported(1_000_000) : null })+ f.admin.mockImplementationOnce(async (build, _prompt, _via, progress) => {+ build(`${WIN_HOME}\\AppData\\Local\\Temp\\harness-team-stage`)+ progress?.('account'); progress?.('engines')+ return { ok: true, stdout: '' }+ })+ expect(await teamCommand(['setup', '--json'], f.deps)).toBe(0)+ expect(steps).toEqual(['password', 'account', 'engines', 'sign-in', 'daemon', 'report'])+ })+it('setup starts the task again up to five times, and keeps a sign-in already there unless asked again', async () => {let tries = 0const f = onWindows({ statusAfter: reported, startTeamTask: vi.fn(async () => ++tries >= 3) })diff --git a/cli/src/team/command.ts b/cli/src/team/command.tsindex 61814680f..a9e8f33c9 100644--- a/cli/src/team/command.ts+++ b/cli/src/team/command.ts@@ -319,6 +319,7 @@ const TASK_START_TRIES = 5async function windowsHandOver(deps: TeamCommandDeps, layout: TeamLayout, signInAgain: boolean): Promise<{ handedOver: boolean } | { failed: string }> {let handedOver = falselet noSignIn: string | null = null+ deps.progress?.('sign-in')if (signInAgain || deps.readStatus(layout.statusFile)?.signIn?.state !== 'signed-in') {try {const { code } = await mintTeamHandoff(() => deps.auth(), deps.post)@@ -330,6 +331,7 @@ async function windowsHandOver(deps: TeamCommandDeps, layout: TeamLayout, signIn}}// Started whether or not a code went over, as the Mac's script starts its daemon: with the sign-in it had, or none.+ deps.progress?.('daemon')for (let tries = 1; ; tries++) {if (await deps.startTeamTask?.()) breakif (tries >= TASK_START_TRIES) return { failed: `Task Scheduler would not start the team daemon's task ${layout.service.label}` }diff --git a/cli/src/team/script.spec.ts b/cli/src/team/script.spec.tsindex fb4f4528c..9bfd2b8be 100644--- a/cli/src/team/script.spec.ts+++ b/cli/src/team/script.spec.ts@@ -642,6 +642,21 @@ describe('Linux', () => {expect(script).not.toMatch(/dscl|launchctl|plutil|stat -f|\/Library\/|\/Users\//)})+ // Task #2686, after Scholes's new member waited ~7 minutes with no sign of progress (#2921 did the Mac).+ it('says each step, as the owner, in the stage the owner\'s Harness reads, before the step runs', () => {+ const script = buildLinuxSetupScript(linuxInput())+ expect(script).toContain(`step() { printf '%s\\n' "$1" | as_owner /bin/sh -c ${sh(WRITE_PRIVATE)} sh "$STAGE/progress" >/dev/null 2>&1 || true; }`)+ const order = ['account', 'home', 'privacy', 'runtime', 'engines', 'sign-in', 'daemon'].map((name) => script.indexOf(`\nstep ${name}\n`))+ for (const at of order) expect(at).toBeGreaterThan(0)+ expect([...order].sort((a, b) => a - b)).toEqual(order)+ expect(order[0]).toBeLessThan(at(script, 'useradd -m'))+ expect(order[4]).toBeLessThan(script.indexOf(`as_team /bin/sh -c ${sh(TEAM_ENGINES_INSTALL)}`))+ expect(order[6]).toBeLessThan(at(script, 'systemctl enable --now "$UNIT_NAME"'))+ // The engines go through the same bounded install as a Mac's (8 minutes, one run, missing engines said).+ expect(script).toContain(`as_team /bin/sh -c ${sh(TEAM_ENGINES_INSTALL)} sh "$TEAM_HOME" "$NODE_NAME" '@anthropic-ai/claude-code' '@openai/codex' || true`)+ parses(script)+ })+it('makes a standard listed user with a locked password, and never a sudoer', () => {const script = buildLinuxSetupScript(linuxInput())expect(script).toContain('useradd -m -d "$TEAM_HOME" -g "$TEAM_GROUP" -s /bin/bash -c "$TEAM_NAME" "$TEAM"')@@ -757,7 +772,7 @@ describe('Linux', () => {const script = buildLinuxSetupScript(linuxInput())const order = ['owned_by_root "$dir"', 'useradd -m', 'passwd -l "$TEAM"', 'chmod 700 "$TEAM_HOME"', OWNER_HOME_PRIVATE,- 'as_owner /bin/sh -c', 'systemctl stop "$UNIT_NAME"', 'mktemp -d /var/tmp/harness-team.XXXXXX', 'as_team /bin/sh -c',+ 'sh "$SENTINEL"', 'systemctl stop "$UNIT_NAME"', 'mktemp -d /var/tmp/harness-team.XXXXXX', 'as_team /bin/sh -c','npm" install --global --prefix "$home/.local"', 'install -o 0 -g 0 -m 0644 "$STAGE/team.json" "$CONFIG"','chown "$TEAM:$TEAM_GROUP" "$STATUS_DIR"', 'chmod 700 "$RELAY_DIR"', 'team __handoff', 'as_team /bin/sh -c \'umask 077','install -o 0 -g 0 -m 0644 "$STAGE/team.service" "$UNIT"', 'systemctl daemon-reload', 'systemctl enable --now "$UNIT_NAME"',diff --git a/cli/src/team/script.ts b/cli/src/team/script.tsindex 7289db9bf..7559f98c2 100644--- a/cli/src/team/script.ts+++ b/cli/src/team/script.ts@@ -715,6 +715,9 @@ export function buildLinuxSetupScript(input: SetupScriptInput): string {// util-linux's, wherever systemd runs; sudo may not be installed (pkexec asked for root).'as_team() { runuser -u "$TEAM" -- "$@"; }','as_owner() { runuser -u "$OWNER" -- "$@"; }',+ // The step under way, for Desktop's waiting screen (./admin.ts reads it), as on a Mac: written as the owner, in the+ // owner's own private stage, so root never writes through a link someone put there. Never a failure.+ `step() { printf '%s\\n' "$1" | as_owner /bin/sh -c ${sh(WRITE_PRIVATE)} sh "$STAGE/progress" >/dev/null 2>&1 || true; }`,LINUX_ROOT_CHECKS,'','[ "$(id -u)" = 0 ] || die "run as root"',@@ -736,6 +739,7 @@ export function buildLinuxSetupScript(input: SetupScriptInput): string {'[ -f "$CLI_SRC/cli.js" ] || die "no installed Harness CLI at $CLI_SRC"','[ -x "$NODE_SRC/bin/node" ] || die "no Harness Node runtime at $NODE_SRC"','',+ 'step account','# 1. The account: a standard user named Harness Team, with a user id from 1000 up like a person\'s, so it is listed.','# Its password is locked: nobody can sign in to it. An account by this name that is not ours is left alone.','if entry=$(getent passwd "$TEAM"); then',@@ -752,6 +756,7 @@ export function buildLinuxSetupScript(input: SetupScriptInput): string {'done','team_uid=$(id -u "$TEAM")','',+ 'step home','# 2. Its home folder, private to it.','[ ! -L "$TEAM_HOME" ] || die "$TEAM_HOME is a symbolic link" 4','[ -d "$TEAM_HOME" ] || mkdir "$TEAM_HOME"',@@ -760,6 +765,7 @@ export function buildLinuxSetupScript(input: SetupScriptInput): string {'chown "$TEAM:$TEAM_GROUP" "$TEAM_HOME"','chmod 700 "$TEAM_HOME"','',+ 'step privacy','# 3. The owner\'s home folder, private: Debian, and Ubuntu before 21.04, make home folders readable by everyone. The','# sentinel inside is readable by everyone on purpose, so the privacy check proves the folder\'s own mode keeps it out.','# Its three base entries, not `chmod 700`: on a home with ACL entries chmod sets their mask to ---, which turns off',@@ -768,6 +774,7 @@ export function buildLinuxSetupScript(input: SetupScriptInput): string {'setfacl -n -m u::rwx,g::---,o::--- "$OWNER_HOME"',`printf '%s\\n' ${sh(SENTINEL_TEXT)} | as_owner /bin/sh -c ${sh(WRITE_PUBLIC)} sh "$SENTINEL"`,'',+ 'step runtime','# 4. The team daemon stops while its files are replaced. Its agents keep running in tmux (KillMode=process).','systemctl stop "$UNIT_NAME" >/dev/null 2>&1 || true','',@@ -782,6 +789,7 @@ export function buildLinuxSetupScript(input: SetupScriptInput): string {// No tmux of its own: the system's serves every account (checked above).`as_team /bin/sh -c ${sh(TEAM_COPY)} sh "$RT" "$TEAM_HOME" "$NODE_NAME" ''`,'',+ 'step engines','# 5b. Claude Code and Codex, installed by the team account itself into its own home: the owner\'s copies are inside the','# owner\'s private home. None of the owner\'s sign-ins is copied.',`as_team /bin/sh -c ${sh(TEAM_ENGINES_INSTALL)} sh "$TEAM_HOME" "$NODE_NAME" ${TEAM_ENGINES.map((e) => sh(e.packageName)).join(' ')} || true`,@@ -807,11 +815,13 @@ export function buildLinuxSetupScript(input: SetupScriptInput): string {'chown "$owner_uid:$owner_gid" "$RELAY_DIR"','chmod 700 "$RELAY_DIR"','',+ 'step sign-in','# 7. Sign-in: a single-use code minted from the owner\'s own sign-in now, so its 90 seconds start here, and','# written where only the team account can read it. The team daemon redeems it as it starts and deletes it.','# A code that cannot be had is reported after step 8, once the daemon step 4 stopped runs again.',...signInStep(mintEnv),'',+ 'step daemon','# 8. The systemd unit, root\'s, which runs the team daemon as the team account from boot.','install -o 0 -g 0 -m 0644 "$STAGE/team.service" "$UNIT"','systemctl daemon-reload || die "systemd would not read the team daemon\'s unit" 8',diff --git a/cli/src/team/windowsScript.spec.ts b/cli/src/team/windowsScript.spec.tsindex d0ba7b584..d29d41d48 100644--- a/cli/src/team/windowsScript.spec.ts+++ b/cli/src/team/windowsScript.spec.ts@@ -169,7 +169,7 @@ describe('the Windows setup script', () => {if (/TEAM_HOME/.test(line) && /Copy|Set-Content|WriteAll|Move-Item|New-Item|CreateDirectory/.test(line)) throw new Error(`writes in the team home: ${line}`)}expect(script).toContain("$copied = As-Team 'copy' (& $asScript (Join-Path $RT 'copy.ps1')) 15")- expect(script).toContain("$installed = As-Team 'engines' (& $asScript (Join-Path $RT 'engines.ps1')) 30")+ expect(script).toContain("$installed = As-Team 'engines' (& $asScript (Join-Path $RT 'engines.ps1')) 10 ")// What it says goes to a file in the stage folder, which this script made and the team account may only write.expect(script).toContain('& $ICACLS $out /grant "*$($teamSid):(R,W)" /L /q')})@@ -210,6 +210,27 @@ describe('the Windows setup script', () => {it.skipIf(!pwsh)('parses', () => parses(buildWindowsSetupScript(input())))})+describe('the Windows setup script\'s steps and engines (task #2686)', () => {+ it('says each step before it runs, writing a fresh file and renaming it over the step file, never through what is there', () => {+ const script = buildWindowsSetupScript(input())+ expect(script).toContain('function Step([string]$name) {')+ expect(script).toContain("$next = Join-Path $STAGE ('progress.' + [guid]::NewGuid().ToString('N'))")+ expect(script).toContain("Move-Item -LiteralPath $next -Destination (Join-Path $STAGE 'progress') -Force")+ const order = ['account', 'home', 'privacy', 'runtime', 'engines'].map((name) => script.indexOf(`\nStep '${name}'\n`))+ for (const at of order) expect(at).toBeGreaterThan(0)+ expect([...order].sort((a, b) => a - b)).toEqual(order)+ expect(order[0]).toBeLessThan(script.indexOf('# 2. The account'))+ expect(order[4]).toBeLessThan(script.indexOf("$installed = As-Team 'engines'"))+ })++ it('gives the engines 10 minutes, inside User Account Control\'s 15, and goes on without them when they are late', () => {+ const script = buildWindowsSetupScript(input())+ expect(script).toContain('function As-Team([string]$what, [string]$line, [int]$minutes, [string]$lateSay = \'\') {')+ expect(script).toContain(' if ($late -and $lateSay) { return @(-1, @($lateSay)) }')+ expect(script).toContain("$installed = As-Team 'engines' (& $asScript (Join-Path $RT 'engines.ps1')) 10 'harness: Claude Code and Codex did not finish installing in 10 minutes; the Harness Team account works without them, and harness team setup installs them'")+ })+})+describe('the scripts the team account runs itself', () => {it('copies the staged runtime and CLI into its own home, through a next folder, keeping a runtime already there', () => {const script = windowsTeamCopyScript({ home: 'C:\\Users\\harnessteam', nodeName: 'node-v22.23.2-win32-x64', cliVersion: '0.4.97' })@@ -260,7 +281,24 @@ describe('the scripts the team account runs itself', () => {it('installs Claude Code and Codex with its own npm under its own home, and never fails setup', () => {const script = windowsTeamEnginesScript({ home: 'C:\\Users\\harnessteam', nodeName: 'node-v22.23.2-win32-x64', packages: ['@anthropic-ai/claude-code', '@openai/codex'] })expect(script).toContain("$Packages = @('@anthropic-ai/claude-code', '@openai/codex')")- expect(script).toContain('install --global --prefix $prefix --no-fund --no-audit --loglevel=error $pkg')+ expect(script).toContain('install --global --prefix `"$prefix`" --no-fund --no-audit --loglevel=error $($pkgs -join')+ expect(script).toContain('exit 0')+ })++ // Task #2686: the Mac's limit on Windows (#2921). A new Mac waited ~7 minutes on ~320 MB from npm; here the engines+ // had 30 minutes, past User Account Control's 15, and a late run failed setup instead of finishing the account.+ it('installs both in one npm run, then each alone, within 8 minutes in all, and stops the whole tree at the limit', () => {+ const script = windowsTeamEnginesScript({ home: 'C:\\Users\\harnessteam', nodeName: 'node-v22.23.2-win32-x64', packages: ['@anthropic-ai/claude-code', '@openai/codex'] })+ expect(script).toContain('$limit = 480')+ expect(script).toContain('$deadline = (Get-Date).AddSeconds($limit)')+ // npm.cmd through cmd, its output on NUL: nothing it leaves running writes into what the elevated setup prints.+ expect(script).toContain('>NUL 2>&1')+ expect(script).toContain('$p.WaitForExit($left)')+ expect(script).toContain('taskkill.exe /T /F /PID $p.Id')+ expect(script).toContain('$got = Install $Packages')+ expect(script).toContain('foreach ($pkg in $Packages) {')+ expect(script).toContain("harness: Claude Code and Codex did not finish installing in $limit seconds; the Harness Team account works without them, and harness team setup installs them")+ expect(script.indexOf('$got = Install $Packages')).toBeLessThan(script.indexOf('foreach ($pkg in $Packages) {'))expect(script).toContain('exit 0')})diff --git a/cli/src/team/windowsScript.ts b/cli/src/team/windowsScript.tsindex b6d6c6dec..3a320736c 100644--- a/cli/src/team/windowsScript.ts+++ b/cli/src/team/windowsScript.ts@@ -256,6 +256,10 @@ export function windowsTeamCopyScript(input: { home: string; nodeName: string; c* Claude Code and Codex for the team account, installed by that account itself with its own copy of Harness's Node and* npm under its own home (`.local`): the twin of ./script.ts `TEAM_ENGINES_INSTALL`. A package that fails is said and* left, never failing setup.+ *+ * As on a Mac (task #2686, after #2921): both in one npm run first, so their downloads overlap, then each alone when that+ * run fails; 8 minutes for the whole step, inside User Account Control's 15. npm.cmd runs through cmd with its output on+ * NUL, and at the limit its whole process tree is stopped (`taskkill /T`), said, and setup goes on without the engines.*/export function windowsTeamEnginesScript(input: { home: string; nodeName: string; packages: readonly string[] }): string {const home = checkWindowsPath(input.home, 'team home')@@ -272,9 +276,30 @@ export function windowsTeamEnginesScript(input: { home: string; nodeName: string"if (-not (Test-Path -LiteralPath $npm)) { [Console]::Out.Write(\"harness: the team account's Node has no npm; Claude Code and Codex were not installed`n\"); exit 0 }",'$env:PATH = "$nodeDir;$env:SystemRoot\\System32;$env:SystemRoot"','Set-Location -LiteralPath $TeamHome',+ '$limit = 480',+ '$deadline = (Get-Date).AddSeconds($limit)',+ // 0 installed, 1 failed, 2 out of time (nothing more is tried).+ 'function Install([string[]]$pkgs) {',+ ' $psi = New-Object System.Diagnostics.ProcessStartInfo',+ ' $psi.FileName = $env:ComSpec',+ ' $psi.Arguments = "/d /s /c `"`"$npm`" install --global --prefix `"$prefix`" --no-fund --no-audit --loglevel=error $($pkgs -join \' \') >NUL 2>&1`""',+ ' $psi.UseShellExecute = $false',+ ' $psi.CreateNoWindow = $true',+ ' $psi.WorkingDirectory = $TeamHome',+ ' $p = [Diagnostics.Process]::Start($psi)',+ ' $left = [int][Math]::Max(0, ($deadline - (Get-Date)).TotalMilliseconds)',+ ' if (-not $p.WaitForExit($left)) { & taskkill.exe /T /F /PID $p.Id *> $null; return 2 }',+ ' if ($p.ExitCode -eq 0) { return 0 }',+ ' return 1',+ '}',+ "function Out-Of-Time { [Console]::Out.Write(\"harness: Claude Code and Codex did not finish installing in $limit seconds; the Harness Team account works without them, and harness team setup installs them`n\"); exit 0 }",+ '$got = Install $Packages',+ 'if ($got -eq 0) { foreach ($pkg in $Packages) { [Console]::Out.Write("harness: installed $pkg for the team account`n") }; exit 0 }',+ 'if ($got -eq 2) { Out-Of-Time }','foreach ($pkg in $Packages) {',- ' & $npm install --global --prefix $prefix --no-fund --no-audit --loglevel=error $pkg *> $null',- ' if ($LASTEXITCODE -eq 0) { [Console]::Out.Write("harness: installed $pkg for the team account`n") }',+ ' $got = Install @($pkg)',+ ' if ($got -eq 2) { Out-Of-Time }',+ ' if ($got -eq 0) { [Console]::Out.Write("harness: installed $pkg for the team account`n") }',' else { [Console]::Out.Write("harness: could not install $pkg for the team account; harness team setup tries again`n") }','}','exit 0',@@ -389,7 +414,8 @@ export function buildWindowsSetupScript(input: WindowsSetupScriptInput): string// The output is appended to a file this process made in the stage folder, writable by the team account alone, so// nothing is written in the team account's home as the administrator.WINDOWS_CLEAN_LINE,- 'function As-Team([string]$what, [string]$line, [int]$minutes) {',+ // [lateSay]: a run that may be late without failing setup (the engines): what is said instead, and setup goes on.+ 'function As-Team([string]$what, [string]$line, [int]$minutes, [string]$lateSay = \'\') {'," if (-not $script:scheduler) { $script:scheduler = New-Object -ComObject Schedule.Service; $script:scheduler.Connect() }",' $out = Join-Path $script:RT "$what.out"'," [IO.File]::WriteAllText($out, '')",@@ -413,6 +439,7 @@ export function buildWindowsSetupScript(input: WindowsSetupScriptInput): string' if ($late) { $registered.Stop(0) }',' $status = $registered.LastTaskResult',' } finally { $root.DeleteTask($name, 0) }',+ ' if ($late -and $lateSay) { return @(-1, @($lateSay)) }',' if ($late) { die "the team account\'s $what did not finish in $minutes minutes" }',// The Team account wrote these, and they go to the administrator\'s console (audit W7).' $lines = @(Get-Content -LiteralPath $out -ErrorAction SilentlyContinue | ForEach-Object { Clean-Line $_ } | Where-Object { $_ })',@@ -432,6 +459,13 @@ export function buildWindowsSetupScript(input: WindowsSetupScriptInput): string"if (-not (Test-Path -LiteralPath (Join-Path $CLI_SRC 'cli.js'))) { die \"no installed Harness CLI at $CLI_SRC\" }","if (-not (Test-Path -LiteralPath (Join-Path $NODE_SRC 'node.exe'))) { die \"no Harness Node runtime at $NODE_SRC\" }",'',+ // The step under way, for Desktop's waiting screen (./admin.ts reads it), as on a Mac (task #2686): a fresh file under a+ // new name, renamed over the step file, so nothing is written through a link someone put there. Never a failure.+ 'function Step([string]$name) {',+ " try { $next = Join-Path $STAGE ('progress.' + [guid]::NewGuid().ToString('N')); [IO.File]::WriteAllText($next, \"$name`n\")",+ " Move-Item -LiteralPath $next -Destination (Join-Path $STAGE 'progress') -Force } catch { }",+ '}',+ "Step 'account'",'# 2. The account: a standard user named Harness Team, listed on the sign-in screen. Its password is random and nobody','# knows it, so nobody signs in to it. An account by this name that is not ours is left alone.','$account = Get-LocalUser -Name $TEAM -ErrorAction SilentlyContinue',@@ -474,6 +508,7 @@ export function buildWindowsSetupScript(input: WindowsSetupScriptInput): string// The account runs only as Task Scheduler's tasks, whose password logon is a batch logon.'Set-BatchLogon $teamSid $true','',+ "Step 'home'",'# 3. Its profile, made by Windows with its own private ACL: the account signs in once to run nothing.','$teamProfile = @(Get-CimInstance Win32_UserProfile | Where-Object { $_.SID -eq $teamSid })','if ($teamProfile.Count -eq 0) {',@@ -483,6 +518,7 @@ export function buildWindowsSetupScript(input: WindowsSetupScriptInput): string'}','if ($teamProfile.Count -ne 1 -or $teamProfile[0].LocalPath -ne $TEAM_HOME) { die "Windows did not make the profile of $TEAM at $TEAM_HOME" 4 }','',+ "Step 'privacy'",'# 4. The owner\'s profile, private: an explicit ACE that lets Everyone, Users or Authenticated Users in is taken off,','# and said. The sentinel keeps the ACL it inherits, not a world-readable one as on a Mac: every account has','# "Bypass traverse checking", so a file that grants Everyone read opens by its full path in a folder the reader',@@ -518,6 +554,7 @@ export function buildWindowsSetupScript(input: WindowsSetupScriptInput): string' if (@($sentinelAcl.GetAccessRules($true, $false, [Security.Principal.SecurityIdentifier])).Count -ne 0) { die "$SENTINEL has ACEs of its own" 6 }','} finally { $sentinelFile.Dispose() }','',+ "Step 'runtime'",'# 5. The team daemon stops while its files are replaced.','if (Get-ScheduledTask -TaskPath $TASK_PATH -TaskName $TASK_NAME -ErrorAction SilentlyContinue) {',' Stop-ScheduledTask -TaskPath $TASK_PATH -TaskName $TASK_NAME',@@ -535,11 +572,12 @@ export function buildWindowsSetupScript(input: WindowsSetupScriptInput): string"$copied = As-Team 'copy' (& $asScript (Join-Path $RT 'copy.ps1')) 15",'if ($copied[0] -ne 0) { die "the team account could not copy the Harness runtime into its home (exit $($copied[0])): $($copied[1] -join \' \')" }','',+ "Step 'engines'",'# 6b. Claude Code and Codex, installed by the team account itself into its own home: the owner\'s copies are inside the','# owner\'s private profile. None of the owner\'s sign-ins is copied.',`$enginesScript = ${hereString(windowsTeamEnginesScript({ home, nodeName, packages: TEAM_ENGINES.map((e) => e.packageName) }))}`,"[IO.File]::WriteAllText((Join-Path $RT 'engines.ps1'), $enginesScript)",- "$installed = As-Team 'engines' (& $asScript (Join-Path $RT 'engines.ps1')) 30",+ "$installed = As-Team 'engines' (& $asScript (Join-Path $RT 'engines.ps1')) 10 'harness: Claude Code and Codex did not finish installing in 10 minutes; the Harness Team account works without them, and harness team setup installs them'",'foreach ($line in $installed[1]) { [Console]::Out.Write("$line`n") }','','# 7. What setup made (Administrators\' and SYSTEM\'s, every account may read it), and the team account\'s status folder.',diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 86dd7452c..7c1c875e6 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -1669,10 +1669,23 @@ class SuperTabController extends ChangeNotifier {/// replies" reads on, a page at a time.static const threadPagesOnOpen = 5;+ /// The read of earlier replies under way ([readingEarlierReplies]).+ Future<void>? _earlierRead;+/// Reads the open thread: from its newest reply back through/// [threadPagesOnOpen] pages, or with [earlier] the page before those read,- /// and its root when no page brought it.- Future<void> loadThread({bool earlier = false}) async {+ /// and its root when no page brought it. With [earlier] while a read of+ /// them is under way, that read: a caller waiting for the page gets it.+ Future<void> loadThread({bool earlier = false}) {+ if (earlier && readingEarlierReplies) {+ return _earlierRead ?? Future.value();+ }+ final read = _loadThread(earlier: earlier);+ if (earlier) _earlierRead = read;+ return read;+ }++ Future<void> _loadThread({bool earlier = false}) async {final open = openedThread;if (open == null || _disposed || accessRevoked) return;if (earlier && (!hasEarlierReplies(open.root) || readingEarlierReplies)) {diff --git a/desktop/lib/super_tabs/day_jump.dart b/desktop/lib/super_tabs/day_jump.dartnew file mode 100644index 000000000..6c0c5dbf3--- /dev/null+++ b/desktop/lib/super_tabs/day_jump.dart@@ -0,0 +1,34 @@+import 'dart:math' as math;++import 'package:flutter/material.dart';++/// The date pill's Jump to choices, as Slack's (Huy 11-04).+enum SuperTabJumpTo {+ yesterday('Yesterday'),+ lastWeek('Last week'),+ lastMonth('Last month'),+ beginning('The very beginning');++ const SuperTabJumpTo(this.label);++ final String label;+}++/// The local midnight [choice] jumps to from [now]: yesterday's, 7 days+/// ago's, or the same day a month ago (the month's last day when it is+/// shorter). Null for the very beginning, which has no time.+DateTime? superTabJumpStart(SuperTabJumpTo choice, DateTime now) {+ final day = DateTime(now.year, now.month, now.day);+ switch (choice) {+ case SuperTabJumpTo.yesterday:+ return DateTime(day.year, day.month, day.day - 1);+ case SuperTabJumpTo.lastWeek:+ return DateTime(day.year, day.month, day.day - 7);+ case SuperTabJumpTo.lastMonth:+ final month = DateTime(day.year, day.month - 1);+ final last = DateUtils.getDaysInMonth(month.year, month.month);+ return DateTime(month.year, month.month, math.min(day.day, last));+ case SuperTabJumpTo.beginning:+ return null;+ }+}diff --git a/desktop/lib/super_tabs/day_pill.dart b/desktop/lib/super_tabs/day_pill.dartindex 618a72d00..5ba70eff8 100644--- a/desktop/lib/super_tabs/day_pill.dart+++ b/desktop/lib/super_tabs/day_pill.dart@@ -1,7 +1,11 @@import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import '../shared/theme/app_icons.dart';import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_menu.dart';import '../widgets/desktop_chrome.dart';+import 'day_jump.dart';/// The day of the message at the top of a list, in a small pill over the/// list's top while the reader is scrolled into it, as Slack's (Huy 11-03).@@ -22,10 +26,16 @@ class SuperTabStickyDay extends StatefulWidget {required this.child,this.pillKey,this.hidden = false,+ this.onJump,});final Widget child;+ /// Makes the pill a button that opens the Jump to menu (Huy 11-04): called+ /// with a choice's start ([superTabJumpStart]), null for the very+ /// beginning, or a picked day's midnight.+ final ValueChanged<DateTime?>? onJump;+/// The pill's key, so a chat and its thread can be told apart.final Key? pillKey;@@ -153,14 +163,23 @@ class _SuperTabStickyDayState extends State<SuperTabStickyDay> {top: SuperTabDayPill.top,left: 0,right: 0,- child: IgnorePointer(- // The day lines in the list say it to a screen reader.- child: ExcludeSemantics(- child: Center(- child: SuperTabDayPill(key: widget.pillKey, day: day),+ child: switch (widget.onJump) {+ final onJump? => Center(+ child: _SuperTabDayJump(+ pillKey: widget.pillKey,+ day: day,+ onJump: onJump,),),- ),+ null => IgnorePointer(+ // The day lines in the list say it to a screen reader.+ child: ExcludeSemantics(+ child: Center(+ child: SuperTabDayPill(key: widget.pillKey, day: day),+ ),+ ),+ ),+ },),],),@@ -301,12 +320,165 @@ class _SuperTabDayMarkState extends State<SuperTabDayMark> {}}+/// The pill as a button: it opens the Jump to menu, whose last choice turns+/// the menu into a calendar in the same place, as Slack's (Huy 11-04).+class _SuperTabDayJump extends StatefulWidget {+ const _SuperTabDayJump({+ required this.day,+ required this.onJump,+ this.pillKey,+ });++ final DateTime day;++ /// The pill's key, on the button a screen reader and a test find.+ final Key? pillKey;+ final ValueChanged<DateTime?> onJump;++ @override+ State<_SuperTabDayJump> createState() => _SuperTabDayJumpState();+}++class _SuperTabDayJumpState extends State<_SuperTabDayJump> {+ final _menu = MenuController();+ final _focus = FocusNode(debugLabel: 'Swarm day pill');+ final _first = FocusNode(debugLabel: 'Swarm day pill first choice');+ bool _picking = false;++ /// The keys that open it, as a button's.+ static final _opens = {+ LogicalKeyboardKey.enter,+ LogicalKeyboardKey.numpadEnter,+ LogicalKeyboardKey.space,+ };++ /// The calendar's size: Material's month header (52) over its grid of+ /// seven rows of 42 (weekdays and up to six weeks), 7 columns of 42 with+ /// its 8 of padding each side. Taller than a menu may be by default.+ static const _calendar = Size(7 * 42 + 2 * 8, 52 + 7 * 42 + 8);++ @override+ void dispose() {+ _focus.dispose();+ _first.dispose();+ super.dispose();+ }++ void _jump(DateTime? at) {+ _menu.close();+ widget.onJump(at);+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final today = DateUtils.dateOnly(DateTime.now());+ final day = widget.day.isAfter(today) ? today : widget.day;+ return MenuAnchor(+ controller: _menu,+ childFocusNode: _focus,+ // Opened from the keyboard, the first choice is the next key's target;+ // a click leaves none lit, with the keys on the pill, so Esc still+ // closes it.+ onOpen: () {+ final keyboard = _focus.hasPrimaryFocus;+ WidgetsBinding.instance.addPostFrameCallback(+ (_) => (keyboard ? _first : _focus).requestFocus(),+ );+ },+ onClose: () {+ if (mounted) setState(() => _picking = false);+ },+ consumeOutsideTap: true,+ alignmentOffset: const Offset(0, grid.AppControl.menuGap),+ style: grid.AppMenu.style(+ minWidth: 220,+ maxHeight: _picking+ ? _calendar.height + grid.AppMenu.panelPadding.vertical+ : null,+ ),+ menuChildren: _picking+ ? [+ SizedBox.fromSize(+ size: _calendar,+ child: CalendarDatePicker(+ initialDate: day,+ firstDate: DateTime(2000),+ lastDate: today,+ onDateChanged: (picked) => _jump(DateUtils.dateOnly(picked)),+ ),+ ),+ ]+ : [+ Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.controlGap + grid.AppDesktop.menuInset,+ grid.AppDesktop.menuInset,+ grid.AppDesktop.controlGap + grid.AppDesktop.menuInset,+ grid.AppDesktop.listRowGap,+ ),+ child: Text(+ 'Jump to…',+ style: grid.AppType.label(+ color: grid.AppPalette.textSecondary,+ ),+ ),+ ),+ for (final (index, choice) in SuperTabJumpTo.values.indexed)+ AppMenuItem(+ focusNode: index == 0 ? _first : null,+ label: choice.label,+ expandLabel: true,+ onPressed: () =>+ _jump(superTabJumpStart(choice, DateTime.now())),+ ),+ const AppMenuDivider(),+ AppMenuItem(+ label: 'Jump to a specific date',+ expandLabel: true,+ onPressed: () => setState(() => _picking = true),+ ),+ ],+ builder: (context, menu, _) => Semantics(+ key: widget.pillKey,+ button: true,+ label: 'Jump to…',+ value: MaterialLocalizations.of(context).formatMediumDate(widget.day),+ excludeSemantics: true,+ onTap: () => menu.isOpen ? menu.close() : menu.open(),+ child: MouseRegion(+ cursor: SystemMouseCursors.click,+ child: GestureDetector(+ onTap: () => menu.isOpen ? menu.close() : menu.open(),+ child: Focus(+ focusNode: _focus,+ // Enter or Space opens it, as a button.+ onKeyEvent: (_, event) {+ if (event is! KeyDownEvent ||+ !_opens.contains(event.logicalKey)) {+ return KeyEventResult.ignored;+ }+ menu.isOpen ? menu.close() : menu.open();+ return KeyEventResult.handled;+ },+ child: SuperTabDayPill(day: widget.day, chevron: true),+ ),+ ),+ ),+ ),+ );+ }+}+/// The pill: the day as the chat's day lines say it.class SuperTabDayPill extends StatelessWidget {- const SuperTabDayPill({super.key, required this.day});+ const SuperTabDayPill({super.key, required this.day, this.chevron = false});final DateTime day;+ /// It opens the Jump to menu.+ final bool chevron;+/// The pill's distance from the list's top.static const top = grid.AppDesktop.controlGap;@@ -336,10 +508,24 @@ class SuperTabDayPill extends StatelessWidget {),child: Padding(padding: _padding,- child: Text(- MaterialLocalizations.of(context).formatMediumDate(day),- maxLines: 1,- style: DesktopChrome.metadata(),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ MaterialLocalizations.of(context).formatMediumDate(day),+ maxLines: 1,+ style: DesktopChrome.metadata(),+ ),+ if (chevron) ...[+ const SizedBox(width: grid.AppDesktop.listRowGap * 2),+ // Smaller than the text's line, so the pill keeps its height.+ Icon(+ AppIcons.chevronDown,+ size: grid.AppControl.iconSizeChip,+ color: DesktopChrome.muted,+ ),+ ],+ ],),),);diff --git a/desktop/lib/super_tabs/leaderboard/person_row.dart b/desktop/lib/super_tabs/leaderboard/person_row.dartindex f963341a6..fb656a2e6 100644--- a/desktop/lib/super_tabs/leaderboard/person_row.dart+++ b/desktop/lib/super_tabs/leaderboard/person_row.dart@@ -2,6 +2,7 @@ import 'package:clock/clock.dart';import 'package:flutter/material.dart';import 'package:url_launcher/url_launcher.dart';+import '../../shared/theme/app_icons.dart';import '../../shared/theme/app_theme.dart' as grid;import '../../widgets/desktop_chrome.dart';import '../identity.dart';@@ -96,6 +97,7 @@ class LeaderboardPersonRow extends StatelessWidget {required this.onTap,this.columns,this.own = false,+ this.noMachine = false,});final SuperTabPerson person;final SuperTabPersonScore? score;@@ -107,6 +109,10 @@ class LeaderboardPersonRow extends StatelessWidget {/// Whether this is the viewer's own row.final bool own;+ /// Whether they have no machine in this Swarm: a quiet mark after the name+ /// (Scholes, task #2699). One only offline still counts.+ final bool noMachine;+@overrideWidget build(BuildContext context) {final score = this.score;@@ -148,35 +154,71 @@ class LeaderboardPersonRow extends StatelessWidget {/// system).Widget _name() => SuperTabUntil(until: person.status?.until,- builder: (context) => Tooltip(- message: [- leaderboardName(person, score),- if (person.name != null) '@${person.username}',- person.email,- ?person.statusAt(clock.now())?.text,- ].join('\n'),- child: Text.rich(- TextSpan(- text: leaderboardName(person, score),- children: [- if (leaderboardCrowned(score))- WidgetSpan(- alignment: PlaceholderAlignment.middle,- child: LeaderboardCrown(- id: person.id,- weekName: score!.spanName,- ),+ builder: (context) => Row(+ children: [+ Flexible(+ child: Tooltip(+ message: [+ leaderboardName(person, score),+ if (person.name != null) '@${person.username}',+ person.email,+ ?person.statusAt(clock.now())?.text,+ ].join('\n'),+ child: Text.rich(+ TextSpan(+ text: leaderboardName(person, score),+ children: [+ if (leaderboardCrowned(score))+ WidgetSpan(+ alignment: PlaceholderAlignment.middle,+ child: LeaderboardCrown(+ id: person.id,+ weekName: score!.spanName,+ ),+ ),+ ],),- ],+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(),+ ),+ ),),- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: DesktopChrome.control(),- ),+ // After the name, which gives way first (task #2699).+ if (noMachine) _NoMachineMark(id: person.id),+ ],),);}+/// After the name of someone with no machine in this Swarm: the crossed-out+/// monitor, muted and at the metadata size so the row keeps its height, with+/// why on hover (Scholes, task #2699).+class _NoMachineMark extends StatelessWidget {+ const _NoMachineMark({required this.id});+ final String id;++ static const _why = 'No machine shared yet';++ @override+ Widget build(BuildContext context) {+ final style = DesktopChrome.metadata();+ return Padding(+ padding: const EdgeInsets.only(left: _halfGap),+ child: Tooltip(+ message: _why,+ child: Icon(+ AppIcons.monitorOff,+ key: ValueKey('super-person-no-machine-$id'),+ size: style.fontSize,+ color: style.color,+ semanticLabel: _why,+ ),+ ),+ );+ }+}+/// Number one's crown beside their name: content artwork, said in words, at/// the metadata size so a crowned row is as tall as any other (Team and/// celebration, design system). [id] keys it per row.diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dartindex e8440a946..b03d9d9e2 100644--- a/desktop/lib/super_tabs/roster.dart+++ b/desktop/lib/super_tabs/roster.dart@@ -696,6 +696,10 @@ class _SuperTabRosterState extends State<SuperTabRoster>score: scores[person.id],columns: columns,own: person.id == c.accountId,+ // Any machine of theirs in this Swarm, offline ones too (task #2699).+ noMachine:+ !(c.snapshot?.machines.any((m) => m['contributorId'] == person.id) ??+ true),onTap: () => _person(person, scores[person.id]),);diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dartindex ccd84ebf2..702b6341d 100644--- a/desktop/lib/super_tabs/thread_panel.dart+++ b/desktop/lib/super_tabs/thread_panel.dart@@ -14,7 +14,7 @@ import 'composer_toggle.dart';import 'day_pill.dart';import 'reply_box.dart';import 'controller.dart';-import 'message_row.dart' show SuperTabMessageRow;+import 'message_row.dart' show SuperTabMessageHighlight, SuperTabMessageRow;import 'jump_to_latest.dart';import 'model.dart';import 'thread_scroll.dart';@@ -89,14 +89,87 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {SuperTabController get c => widget.controller;+ // The day pill's jump (Huy 11-04): the row it lands on, and the one lit.+ final _targetKey = GlobalKey();+ String? _target, _lit;+ Timer? _litTimer;+ int _jumps = 0;+/// [row] with its message's time, for the day pill over the list. Keyed/// by the message, so the list keeps each row's place as replies arrive.Widget _dated(SuperTabMessage message, Widget row) => SuperTabDayMark(key: ValueKey('super-thread-day-${message.id}'),time: message.createdAt,- child: row,+ child: KeyedSubtree(+ key: message.id == _target ? _targetKey : null,+ child: SuperTabMessageHighlight(on: message.id == _lit, child: row),+ ),);+ /// The day pill's choice, as in the chat: the first of the root and its+ /// replies on or after [from], lit; the root for the very beginning (null),+ /// the newest reply for a time after everything said. Earlier replies are+ /// read until one from before [from] is held, at most 50 pages.+ Future<void> _jumpToTime(DateTime? from) async {+ final jump = ++_jumps;+ bool before(SuperTabMessage m) =>+ from == null || (m.createdAt?.isBefore(from) ?? false);+ List<SuperTabMessage> held() => c.threadMessages(widget.root);+ void say(String text) =>+ ScaffoldMessenger.maybeOf(context)+ ?.showSnackBar(SnackBar(content: Text(text)));+ // They read on from the row they land on, not the newest.+ _scroll.holdPlace();+ // The root is always held, at the top: the very beginning reads nothing.+ for (var page = 0; from != null; page++) {+ final reached = held().any((m) => m.id != widget.root && before(m));+ if (reached || !c.hasEarlierReplies(widget.root)) break;+ if (page == 50) {+ say('That day is too far back to open.');+ return;+ }+ // A read that fails keeps its error and its place: nothing came.+ final loaded = held().length;+ await c.loadThread(earlier: true);+ if (!mounted || jump != _jumps) return;+ if (held().length == loaded) {+ say('Couldn’t load earlier replies.');+ return;+ }+ }+ final messages = held();+ final target = from == null+ ? messages.firstOrNull+ : messages.where((m) => !before(m)).firstOrNull ?? messages.lastOrNull;+ if (target == null) return;+ _litTimer?.cancel();+ setState(() => _target = _lit = target.id);+ _litTimer = Timer(const Duration(seconds: 2), () {+ if (mounted) setState(() => _lit = null);+ });+ _reveal(jump, messages.indexOf(target) / messages.length, 0);+ }++ /// The list is lazy: jump near the target's place ([at], its share of the+ /// thread) until its row is built, then bring it into view.+ void _reveal(int jump, double at, int attempt) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || jump != _jumps || !_scroll.hasClients) return;+ if (_targetKey.currentContext case final row?) {+ unawaited(Scrollable.ensureVisible(row, alignment: .3));+ return;+ }+ if (attempt > 20) return;+ final position = _scroll.position;+ _scroll.jumpTo(+ position.minScrollExtent ++ at * (position.maxScrollExtent - position.minScrollExtent),+ );+ _reveal(jump, at, attempt + 1);+ });+ WidgetsBinding.instance.scheduleFrame();+ }+/// The conversation this thread is in.String get _conversationId => c.openedThread?.conversationId ?? c.selectedId;@@ -130,6 +203,7 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {@overridevoid dispose() {+ _litTimer?.cancel();widget.onScroll?.call(null);_scroll.dispose();_composer.dispose();@@ -397,6 +471,7 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {children: [SuperTabStickyDay(pillKey: const ValueKey('super-thread-day-pill'),+ onJump: (from) => unawaited(_jumpToTime(from)),// As in the chat, a message's text can be selected and// copied.child: SelectionArea(diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 6c4933061..5d35fbd32 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -1845,6 +1845,77 @@ class _SuperTabViewState extends State<SuperTabView>return message;}+ /// The date pill's choice (day_jump.dart): [id]'s first message on or+ /// after [from], lit, as a link opens one. The very beginning (null) is+ /// its first message, and a time after everything said is its newest.+ /// Older pages are read until one from before [from] is held, at most 50+ /// as a link reads; past them it says so, and the list stays.+ Future<void> _jumpToTime(String id, DateTime? from) async {+ void say(String text) =>+ ScaffoldMessenger.maybeOf(context)+ ?.showSnackBar(SnackBar(content: Text(text)));+ final request = ++_jumpRequest;+ bool current() =>+ mounted &&+ request == _jumpRequest &&+ c.selectedId == id &&+ !c.accessRevoked;+ bool before(SuperTabMessage m) =>+ from != null && (m.createdAt?.isBefore(from) ?? false);+ try {+ if (from == null) {+ await c.loadBackTo(id, 0);+ } else {+ // A copy read back to an early page holds nothing from then on: the+ // latest first, then back from there.+ final newest = _shownMessages(id).lastOrNull;+ if (c.hasNewer(id) && (newest == null || before(newest))) {+ await c.showLatest(id);+ }+ for (var page = 0; !_shownMessages(id).any(before); page++) {+ if (!current() || !c.hasOlder(id)) break;+ if (page == 50) {+ say('That day is too far back to open.');+ return;+ }+ // A read that fails keeps its error and its place: nothing came.+ final loaded = c.messages(id).length;+ await c.loadMessages(id, older: true);+ if (current() && c.messages(id).length == loaded) {+ say('Couldn’t load earlier messages.');+ return;+ }+ }+ }+ } catch (_) {+ if (current()) say('Messages could not be read.');+ return;+ }+ if (!current()) return;+ final shown = _shownMessages(id);+ final target = from == null+ ? shown.firstOrNull+ : shown.where((m) => !before(m)).firstOrNull ?? shown.lastOrNull;+ if (target == null) return;+ final row = _rowShowing(id, target.id) ?? target.id;+ setState(() {+ _target = row;+ // Stop following the end: that day's message is what to see.+ _scrollRequest++;+ _jumpingToEnd = false;+ _follow(id, false);+ });+ _revealTarget(+ id,+ 0,+ arrived: (at) {+ unawaited(Scrollable.ensureVisible(at, alignment: .3));+ _light(row);+ },+ );+ _focus.requestFocus();+ }+/// What the reader asked to open by a message link ([SuperTabController.openMessageLink]).void _takeMessageRequest() {final request = c.messageRequest;@@ -4177,6 +4248,8 @@ class _SuperTabViewState extends State<SuperTabView>SuperTabStickyDay(pillKey: const ValueKey('super-day-pill'),hidden: finding != null,+ onJump: (from) =>+ unawaited(_jumpToTime(c.selectedId, from)),child: NotificationListener<ScrollNotification>(onNotification: (event) {if (event.depth != 0) return false;diff --git a/desktop/test/super_tab_day_jump_test.dart b/desktop/test/super_tab_day_jump_test.dartnew file mode 100644index 000000000..c43369b8f--- /dev/null+++ b/desktop/test/super_tab_day_jump_test.dart@@ -0,0 +1,672 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_icons.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/day_jump.dart';+import 'package:harness/super_tabs/day_pill.dart';+import 'package:harness/super_tabs/message_row.dart';+import 'package:harness/super_tabs/view.dart';++import 'box_render_preview_test.dart' show loadPreviewFonts;+import 'support/super_tab_fixture.dart';++/// Set to a folder to write the PR's screenshots there.+final shots = Platform.environment['SUPER_TAB_DAY_JUMP_SHOTS'];++const _pill = ValueKey('super-day-pill');++/// A list of 40 rows on Oct 20 and 21, 2026 under a sticky day that jumps+/// with [onJump], scrolled so its pill shows.+Future<void> _list(WidgetTester tester, ValueChanged<DateTime?> onJump) async {+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SizedBox(+ height: 400,+ child: SuperTabStickyDay(+ pillKey: _pill,+ onJump: onJump,+ child: ListView(+ children: [+ for (var i = 0; i < 40; i++)+ SuperTabDayMark(+ time: DateTime(2026, 10, i < 20 ? 20 : 21, 9, i),+ child: SizedBox(height: 40, child: Text('Row $i')),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ await tester.drag(find.byType(ListView), const Offset(0, -300));+ await tester.pumpAndSettle();+}++void main() {+ setUpAll(() async {+ if (shots != null) await loadPreviewFonts();+ });++ group('the time each choice starts at', () {+ final wednesday = DateTime(2026, 11, 4, 15, 30);++ test('Yesterday, Last week and Last month start at their midnight', () {+ expect(+ superTabJumpStart(SuperTabJumpTo.yesterday, wednesday),+ DateTime(2026, 11, 3),+ );+ expect(+ superTabJumpStart(SuperTabJumpTo.lastWeek, wednesday),+ DateTime(2026, 10, 28),+ );+ expect(+ superTabJumpStart(SuperTabJumpTo.lastMonth, wednesday),+ DateTime(2026, 10, 4),+ );+ });++ test('The very beginning has no time', () {+ expect(superTabJumpStart(SuperTabJumpTo.beginning, wednesday), isNull);+ });++ test('Last month from a day a shorter month lacks is its last day', () {+ expect(+ superTabJumpStart(SuperTabJumpTo.lastMonth, DateTime(2026, 3, 31, 9)),+ DateTime(2026, 2, 28),+ );+ expect(+ superTabJumpStart(SuperTabJumpTo.lastMonth, DateTime(2027, 1, 15, 9)),+ DateTime(2026, 12, 15),+ );+ });+ });++ group('the pill opens the Jump to menu', () {+ testWidgets('the pill is a button with a chevron', (tester) async {+ await _list(tester, (_) {});+ expect(find.byKey(_pill), findsOneWidget);+ expect(+ find.descendant(+ of: find.byKey(_pill),+ matching: find.byIcon(AppIcons.chevronDown),+ ),+ findsOneWidget,+ );+ expect(+ tester.getSemantics(find.byKey(_pill)),+ matchesSemantics(+ isButton: true,+ hasTapAction: true,+ label: 'Jump to…',+ value: 'Tue, Oct 20',+ ),+ );+ });++ testWidgets('a click opens its choices, and each jumps from its time', (+ tester,+ ) async {+ DateTime? jumped;+ var calls = 0;+ await _list(tester, (at) {+ jumped = at;+ calls++;+ });+ for (final choice in SuperTabJumpTo.values) {+ await tester.tap(find.byKey(_pill));+ await tester.pumpAndSettle();+ for (final label in [+ 'Jump to…',+ 'Yesterday',+ 'Last week',+ 'Last month',+ 'The very beginning',+ 'Jump to a specific date',+ ]) {+ expect(find.text(label), findsOneWidget, reason: label);+ }+ final before = calls;+ await tester.tap(find.text(choice.label));+ await tester.pumpAndSettle();+ expect(calls, before + 1);+ expect(jumped, superTabJumpStart(choice, DateTime.now()));+ expect(find.text('Jump to…'), findsNothing);+ }+ });++ testWidgets('Jump to a specific date picks a day on a calendar', (+ tester,+ ) async {+ final jumped = <DateTime?>[];+ await _list(tester, jumped.add);+ await tester.tap(find.byKey(_pill));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Jump to a specific date'));+ await tester.pumpAndSettle();+ expect(find.byType(CalendarDatePicker), findsOneWidget);+ // It opens at the pill's month.+ expect(find.text('October 2026'), findsOneWidget);+ await tester.tap(find.text('15'));+ await tester.pumpAndSettle();+ expect(jumped, [DateTime(2026, 10, 15)]);+ expect(find.byType(CalendarDatePicker), findsNothing);+ });++ testWidgets(+ 'Enter and Space open it from the keyboard, at its first choice',+ (tester) async {+ await _list(tester, (_) {});+ final pill = tester+ .widget<Focus>(+ find.descendant(+ of: find.byKey(_pill),+ matching: find.byType(Focus),+ ),+ )+ .focusNode!;+ for (final key in [+ LogicalKeyboardKey.enter,+ LogicalKeyboardKey.space,+ ]) {+ pill.requestFocus();+ await tester.pump();+ await tester.sendKeyEvent(key);+ await tester.pumpAndSettle();+ expect(find.text('Jump to…'), findsOneWidget);+ expect(+ FocusManager.instance.primaryFocus?.debugLabel,+ 'Swarm day pill first choice',+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(find.text('Jump to…'), findsNothing);+ }+ },+ );++ testWidgets(+ 'a click lights no choice, and the calendar shows its whole month',+ (tester) async {+ await _list(tester, (_) {});+ await tester.tap(find.byKey(_pill));+ await tester.pumpAndSettle();+ expect(+ FocusManager.instance.primaryFocus?.debugLabel,+ 'Swarm day pill',+ );+ await tester.tap(find.text('Jump to a specific date'));+ await tester.pumpAndSettle();+ // October 2026 ends on a Saturday, in its sixth week: its last day is+ // inside the panel.+ final panel = tester.getRect(+ find+ .ancestor(+ of: find.byType(CalendarDatePicker),+ matching: find.byType(SizedBox),+ )+ .first,+ );+ expect(panel.contains(tester.getCenter(find.text('31'))), isTrue);+ },+ );++ testWidgets('Esc closes the menu, and nothing jumps', (tester) async {+ final jumped = <DateTime?>[];+ await _list(tester, jumped.add);+ await tester.tap(find.byKey(_pill));+ await tester.pumpAndSettle();+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(find.text('Jump to…'), findsNothing);+ expect(jumped, isEmpty);+ });+ });++ group('the chat lands on the first message from that time', () {+ /// The Lead chat with [said] in order, everything read, [page] messages+ /// to a page.+ Future<SuperTabController> chat(+ WidgetTester tester,+ List<(String, DateTime)> said, {+ int page = 20,+ }) async {+ final server = ConversationServer()..messagePage = page;+ for (final (text, at) in said) {+ server.append(text);+ server.messages.last['createdAt'] = at.toUtc().toIso8601String();+ }+ server.markReadElsewhere('lead', said.length);+ final c = server.controller();+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ return c;+ }++ final now = DateTime.now();+ final today = DateTime(now.year, now.month, now.day);+ DateTime daysAgo(int days, [int minute = 0]) =>+ DateTime(today.year, today.month, today.day - days, 10, minute);+ List<(String, DateTime)> run(+ String name,+ int count,+ DateTime Function(int) at,+ ) => [for (var i = 1; i <= count; i++) ('$name $i', at(i))];++ Finder row(String text) => find+ .ancestor(+ of: find.text(text),+ matching: find.byWidgetPredicate(+ (w) =>+ w.key is ValueKey<String> &&+ (w.key! as ValueKey<String>).value.startsWith(+ 'super-message-message-',+ ),+ ),+ )+ .first;+ bool lit(WidgetTester tester, String text) => tester+ .widget<SuperTabMessageHighlight>(+ find.ancestor(+ of: row(text),+ matching: find.byType(SuperTabMessageHighlight),+ ),+ )+ .on;+ bool onScreen(WidgetTester tester, String text) {+ final list = tester.getRect(+ find.byKey(const PageStorageKey('super-messages-tab-lead')),+ );+ final at = tester.getRect(row(text));+ return at.top >= list.top - 1 && at.top < list.bottom;+ }++ Future<void> choose(WidgetTester tester, String label) async {+ await tester.tap(find.byKey(_pill));+ await tester.pumpAndSettle();+ await tester.tap(find.text(label));+ // The highlight lasts 2 seconds: look while it is on.+ for (var i = 0; i < 20; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ }++ // Older days first, then yesterday and today: one page holds today alone.+ List<(String, DateTime)> days() => [+ ...run('Old', 40, (i) => daysAgo(20, i)),+ ...run('Week', 20, (i) => daysAgo(7, i)),+ ...run('Yesterday', 20, (i) => daysAgo(1, i)),+ ...run('Today', 20, (i) => now.subtract(Duration(minutes: 40 - i))),+ ];++ testWidgets(+ 'Yesterday lands on yesterday\'s first message, and lights it',+ (tester) async {+ await chat(tester, days(), page: 40);+ await choose(tester, 'Yesterday');+ expect(onScreen(tester, 'Yesterday 1'), isTrue);+ expect(lit(tester, 'Yesterday 1'), isTrue);+ await tester.pumpAndSettle(const Duration(seconds: 3));+ },+ );++ testWidgets('Last week reads older pages to reach its first message', (+ tester,+ ) async {+ final c = await chat(tester, days());+ expect(c.messages('lead').any((m) => m.text == 'Week 1'), isFalse);+ await choose(tester, 'Last week');+ await tester.pumpAndSettle(const Duration(milliseconds: 100));+ expect(onScreen(tester, 'Week 1'), isTrue);+ expect(lit(tester, 'Week 1'), isTrue);+ await tester.pumpAndSettle(const Duration(seconds: 3));+ });++ testWidgets('The very beginning lands on the chat\'s first message', (+ tester,+ ) async {+ await chat(tester, days(), page: 10);+ await choose(tester, 'The very beginning');+ await tester.pumpAndSettle(const Duration(milliseconds: 100));+ expect(onScreen(tester, 'Old 1'), isTrue);+ expect(lit(tester, 'Old 1'), isTrue);+ await tester.pumpAndSettle(const Duration(seconds: 3));+ });++ testWidgets('with nothing said since, it lands on the newest message', (+ tester,+ ) async {+ await chat(tester, run('Earlier', 40, (i) => daysAgo(3, i)));+ await choose(tester, 'Yesterday');+ expect(onScreen(tester, 'Earlier 40'), isTrue);+ expect(lit(tester, 'Earlier 40'), isTrue);+ await tester.pumpAndSettle(const Duration(seconds: 3));+ });++ testWidgets('a time more than 50 pages back says so, and the list stays', (+ tester,+ ) async {+ await chat(tester, [+ ...run('Old', 2, (i) => daysAgo(40, i)),+ ...run('Recent', 120, (i) => daysAgo(20, i)),+ ...run('Today', 20, (i) => now.subtract(Duration(minutes: 40 - i))),+ ], page: 2);+ expect(onScreen(tester, 'Today 20'), isTrue);+ await choose(tester, 'Last month');+ await tester.pumpAndSettle();+ expect(find.text('That day is too far back to open.'), findsOneWidget);+ expect(find.text('Recent 1'), findsNothing);+ // Where the reader was: at the newest message, none of them lit.+ expect(onScreen(tester, 'Today 20'), isTrue);+ expect(lit(tester, 'Today 20'), isFalse);+ });+ });++ group('a read that fails on the way back', () {+ final now = DateTime.now();+ DateTime daysAgo(int days, [int minute = 0]) =>+ DateTime(now.year, now.month, now.day - days, 10, minute);++ Future<(SuperTabController, ConversationServer)> open(+ WidgetTester tester,+ ConversationServer server,+ ) async {+ final c = server.controller();+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ return (c, server);+ }++ Future<void> choose(WidgetTester tester, Key pill, String label) async {+ await tester.tap(find.byKey(pill));+ await tester.pumpAndSettle();+ await tester.tap(find.text(label));+ await tester.pumpAndSettle();+ }++ bool anyLit(WidgetTester tester) => tester+ .widgetList<SuperTabMessageHighlight>(+ find.byType(SuperTabMessageHighlight),+ )+ .any((h) => h.on);++ testWidgets(+ 'in the chat, it says so after the one read, lighting nothing',+ (tester) async {+ final server = ConversationServer()..messagePage = 20;+ for (var i = 1; i <= 60; i++) {+ server.append('Update $i');+ server.messages.last['createdAt'] = daysAgo(+ i <= 40 ? 20 : 0,+ i,+ ).toUtc().toIso8601String();+ }+ server.markReadElsewhere('lead', 60);+ await open(tester, server);+ server.failReadsOf = 'before=';+ await choose(tester, _pill, 'Last week');+ expect(find.text('Couldn’t load earlier messages.'), findsOneWidget);+ expect(find.text('That day is too far back to open.'), findsNothing);+ expect(anyLit(tester), isFalse);+ },+ );++ testWidgets(+ 'in a thread, it says so after the one read, lighting nothing',+ (tester) async {+ final server = ConversationServer()+ ..threads = true+ ..messagePage = 4;+ server.append('Should we cache the reads?');+ server.messages.last['createdAt'] = daysAgo(30)+ .toUtc()+ .toIso8601String();+ for (var i = 1; i <= 40; i++) {+ server.append('Reply $i');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1'+ ..['createdAt'] = daysAgo(+ i <= 20 ? 20 : 1,+ i,+ ).toUtc().toIso8601String();+ }+ server.markReadElsewhere('lead', server.messages.length);+ final (c, _) = await open(tester, server);+ c.openThread('message-1');+ await tester.pumpAndSettle();+ server.failReadsOf = 'before=';+ await choose(+ tester,+ const ValueKey('super-thread-day-pill'),+ 'Last week',+ );+ expect(find.text('Couldn’t load earlier replies.'), findsOneWidget);+ expect(anyLit(tester), isFalse);+ },+ );+ });++ group('the thread lands on its first reply from that time', () {+ final now = DateTime.now();+ DateTime daysAgo(int days, [int minute = 0]) =>+ DateTime(now.year, now.month, now.day - days, 10, minute);+ const pill = ValueKey('super-thread-day-pill');+ const root = 'Should we cache the reads?';++ /// A thread of 40 replies over three weeks, four to a page: it opens+ /// with the newest 20, yesterday's.+ Future<SuperTabController> thread(WidgetTester tester) async {+ final server = ConversationServer()+ ..threads = true+ ..messagePage = 4;+ server.append(root);+ server.messages.last['createdAt'] = daysAgo(30).toUtc().toIso8601String();+ for (final (name, days, count) in [+ ('Old', 20, 10),+ ('Week', 7, 10),+ ('Recent', 1, 20),+ ]) {+ for (var i = 1; i <= count; i++) {+ server.append('$name reply $i');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1'+ ..['createdAt'] = daysAgo(days, i).toUtc().toIso8601String();+ }+ }+ server.markReadElsewhere('lead', server.messages.length);+ final c = server.controller();+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ c.openThread('message-1');+ await tester.pumpAndSettle();+ return c;+ }++ Finder inThread(String text) => find.descendant(+ of: find.byKey(const ValueKey('super-thread-panel')),+ matching: find.text(text),+ );+ bool lit(WidgetTester tester, String text) => tester+ .widget<SuperTabMessageHighlight>(+ find+ .ancestor(+ of: inThread(text),+ matching: find.byType(SuperTabMessageHighlight),+ )+ .first,+ )+ .on;+ bool onScreen(WidgetTester tester, String text) {+ final list = tester.getRect(+ find+ .descendant(+ of: find.byKey(const ValueKey('super-thread-panel')),+ matching: find.byType(Scrollable),+ )+ .first,+ );+ final at = tester.getRect(inThread(text));+ return at.top >= list.top - 1 && at.top < list.bottom;+ }++ Future<void> choose(WidgetTester tester, String label) async {+ await tester.tap(find.byKey(pill));+ await tester.pumpAndSettle();+ await tester.tap(find.text(label));+ for (var i = 0; i < 20; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ }++ testWidgets('Last week reads earlier replies to its first, and lights it', (+ tester,+ ) async {+ await thread(tester);+ expect(inThread('Week reply 1'), findsNothing);+ await choose(tester, 'Last week');+ expect(onScreen(tester, 'Week reply 1'), isTrue);+ expect(lit(tester, 'Week reply 1'), isTrue);+ await tester.pumpAndSettle(const Duration(seconds: 3));+ });++ testWidgets('The very beginning lands on the root', (tester) async {+ await thread(tester);+ await choose(tester, 'The very beginning');+ expect(onScreen(tester, root), isTrue);+ expect(lit(tester, root), isTrue);+ await tester.pumpAndSettle(const Duration(seconds: 3));+ });+ });++ for (final brightness in Brightness.values) {+ testWidgets('screenshots for review (${brightness.name})', (tester) async {+ if (shots == null) return;+ final before = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = before);+ // The menu's lift as the app draws it, not the test's solid outline.+ await tester.binding.setSurfaceSize(const Size(900, 640));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final now = DateTime.now();+ final server = ConversationServer()..messagePage = 40;+ const updates = [+ 'Reading the offline queue before the reconnect.',+ 'The reconnect keeps every queued edit in order.',+ 'Two devices editing at once settle on the newest edit.',+ 'Pushed the branch; the checks are running.',+ ];+ for (var i = 0; i < 40; i++) {+ server.append(updates[i % updates.length]);+ server.messages.last+ ..['author'] = {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'}+ ..['createdAt'] = DateTime(+ now.year,+ now.month,+ now.day - 6 + i ~/ 8,+ 9,+ i,+ ).toUtc().toIso8601String();+ }+ server.markReadElsewhere('lead', 40);+ final c = server.controller();+ await c.refresh();+ final picture = GlobalKey();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) =>+ RepaintBoundary(key: picture, child: child),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ Future<void> shoot(String name) => tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/$name.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ debugDisableShadows = false;+ try {+ await tester.tap(find.byKey(_pill));+ await tester.pumpAndSettle();+ await shoot('jump-menu-${brightness.name}');+ await tester.tap(find.text('Jump to a specific date'));+ await tester.pumpAndSettle();+ await shoot('jump-calendar-${brightness.name}');+ } finally {+ // Back before the test ends, which checks it was.+ debugDisableShadows = true;+ }+ });+ }+}diff --git a/desktop/test/super_tab_no_machine_mark_shots_test.dart b/desktop/test/super_tab_no_machine_mark_shots_test.dartnew file mode 100644index 000000000..a11553271--- /dev/null+++ b/desktop/test/super_tab_no_machine_mark_shots_test.dart@@ -0,0 +1,42 @@+import 'dart:io';++import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';++import 'super_tab_leaderboard_shots_test.dart' show showHumans;+import 'support/capture.dart';+import 'support/super_tab_members.dart';++/// Set to a folder to write the People list's no-machine mark there, in light+/// and dark, and its hover (task #2699): the real right pane over the+/// in-memory Swarm, never a backend or the live app.+final shots = Platform.environment['SUPER_TAB_NO_MACHINE_SHOTS'];++void main() {+ setUpAll(() => loadCaptureFonts(shots));++ testWidgets('screenshots for review', (tester) async {+ for (final (brightness, name) in [+ (Brightness.light, 'light'),+ (Brightness.dark, 'dark'),+ ]) {+ await showHumans(tester, brightness);+ await openSuperTabMembers(tester);+ await captureWindow(tester, shots, 'people-no-machine-$name');+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse.addPointer(location: Offset.zero);+ await mouse.moveTo(+ tester.getCenter(+ find.byKey(const ValueKey('super-person-no-machine-tony')),+ ),+ );+ await tester.pump(const Duration(seconds: 2));+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, 'people-no-machine-hover-$name');+ await mouse.removePointer();+ await tester.pumpWidget(const SizedBox());+ await tester.pumpAndSettle();+ }+ }, skip: shots == null);+}diff --git a/desktop/test/super_tab_no_machine_mark_test.dart b/desktop/test/super_tab_no_machine_mark_test.dartnew file mode 100644index 000000000..8d581a206--- /dev/null+++ b/desktop/test/super_tab_no_machine_mark_test.dart@@ -0,0 +1,109 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/humans_fixture.dart';+import 'support/super_tab_fixture.dart';+import 'support/super_tab_members.dart';++/// Scholes (11-04): the project lists 32 people and 21 machines, and nothing+/// showed who had not shared one. In the People list, a quiet mark after the+/// name of anyone with no machine in this Swarm. A machine that is only+/// offline still counts, and the mark goes once they add one (task #2699).+void main() {+ Future<SuperTabController> show(+ WidgetTester tester,+ ConversationServer server,+ ) async {+ await tester.binding.setSurfaceSize(const Size(1300, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final controller = server.controller(+ account: 'peer',+ initial: {'tabId': 'tab', 'accountId': 'peer', 'selectedId': 'lead'},+ );+ await controller.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SuperTabView(+ controller: controller,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await openSuperTabMembers(tester);+ return controller;+ }++ Future<void> close(WidgetTester tester, SuperTabController controller) async {+ await tester.pumpWidget(const SizedBox());+ await controller.flush();+ controller.dispose();+ }++ Finder mark(String id) => find.byKey(ValueKey('super-person-no-machine-$id'));++ testWidgets('marks a person with no machine, says why on hover', (+ tester,+ ) async {+ // A screen reader hears why, as hover says it.+ final semantics = tester.ensureSemantics();+ final controller = await show(tester, membersSwarm());+ expect(mark('peer'), findsOneWidget);+ expect(mark('tony'), findsOneWidget);+ // Inside their row, after the name.+ final row = find.byKey(const ValueKey('super-person-peer'));+ expect(find.descendant(of: row, matching: mark('peer')), findsOneWidget);+ expect(+ find.descendant(+ of: row,+ matching: find.byTooltip('No machine shared yet'),+ ),+ findsOneWidget,+ );+ // The row reads as one: the name, then why, then the points.+ expect(+ tester.getSemantics(mark('peer')).label,+ contains('dee\nNumber one this week\nNo machine shared yet'),+ );+ await close(tester, controller);+ semantics.dispose();+ });++ testWidgets('a machine that is only offline still counts', (tester) async {+ // Ken's Mac Studio has sent no reading: offline, but in the Swarm.+ final server = membersSwarm();+ final studio = (server.state['machines'] as List).single as Map;+ expect(studio['observation'], isNull);+ final controller = await show(tester, server);+ expect(find.byKey(const ValueKey('super-person-owner')), findsOneWidget);+ expect(mark('owner'), findsNothing);+ await close(tester, controller);+ });++ testWidgets('the mark goes once they add a machine', (tester) async {+ final controller = await show(tester, membersSwarm());+ expect(mark('peer'), findsOneWidget);+ await controller.command({+ 'type': 'machine.contribute',+ 'machineId': 'dee-mac',+ 'name': 'Dee’s Mac',+ 'cwd': '/work',+ 'scope': 'swarm',+ 'engines': ['claude'],+ 'maxAgents': 2,+ });+ await tester.pumpAndSettle();+ expect(mark('peer'), findsNothing);+ expect(mark('tony'), findsOneWidget);+ await close(tester, controller);+ });+}diff --git a/docs/plans/2026-11-04-date-pill-jump-to-plan.md b/docs/plans/2026-11-04-date-pill-jump-to-plan.mdnew file mode 100644index 000000000..916be7137--- /dev/null+++ b/docs/plans/2026-11-04-date-pill-jump-to-plan.md@@ -0,0 +1,120 @@+# The date pill's Jump to menu — plan++**Goal:** Clicking the sticky date pill of a Swarm chat or thread (#2425) opens a Jump to menu, as Slack's: Yesterday,+Last week, Last month, The very beginning, then Jump to a specific date. Each choice scrolls to the first message on or+after its time, reading older messages as needed, and lights it briefly (Huy 11-04, task #2608).++**Way of working:** this project's Engineer flow: plan first, then each task's failing test before its code, one pull+request, one independent review. Built on #2906 (one label where the pill meets a day line), whose overlap logic it+leaves alone.++**Architecture:** A pure function turns a choice into the local midnight it starts at (`day_jump.dart`). The pill+(`day_pill.dart`) becomes a button with a chevron when its list gives it `onJump`. It opens a `MenuAnchor` built from+`AppMenuItem`s, as the message More menu is, and its last item swaps the menu for a `CalendarDatePicker` in the same+popover. The chat (`view.dart`) jumps the way a message link already does (`_findMessage`, `_revealTarget`, `_light`).+It reads the latest first when the time is past what it holds, then older pages until the oldest one held is before the+time, at most 50 pages as a link does. The first message on or after the time becomes the target and is lit.+The very beginning reads back with `loadBackTo(id, 0)`, which takes the first page alone when it is far back. The thread+pane (`thread_panel.dart`) does the same with its earlier replies and lights the row itself.++**Tech stack:** Flutter widgets; flutter_test widget tests with the Super Tab fixture (memory store, fake sign-in).++**Spec:** task #2608 brief, with Huy's Slack screenshot.++```+ ┌──────────────────┐+ │ Wed, Oct 29 ⌄ │ ← the sticky pill, now a button+ └──────────────────┘+ ┌──────────────────────────┐+ │ Jump to… │ ← muted heading+ │ Yesterday │+ │ Last week │+ │ Last month │+ │ The very beginning │+ ├──────────────────────────┤+ │ Jump to a specific date │ → a month calendar in the same spot+ └──────────────────────────┘+```++## Global constraints++- Harness Design Language (desktop/design/desktop-design-system.md): tokens only, `AppMenu` style and `AppMenuItem`+ rows, flat, no explanatory sentences.+- The pill still floats over the list: no row moves when it shows, changes, opens its menu or hides.+- #2906's day-line covering is unchanged.+- Times are the reader's local days: Yesterday, 7 days ago and a month ago, each from its midnight.+- Desktop and web build the same widgets; nothing platform-specific.+- Tests use the memory store and fake sign-in of `test/support/super_tab_fixture.dart`; no test signs the Mac out.++## Review focus++- A time past the newest message (nothing said since) lands on the newest message, not nowhere.+- A time older than 50 pages back says "That day is too far back to open." instead of landing on the wrong message.+- The very beginning of a chat far back lands on its first message, with the newer pages waiting as after a far-back+ unread line.+- Last month from the 31st lands on the last day of a shorter month, not in the month after.+- A choice made while an earlier jump is still reading wins over it (the jump request, as links use).++## Task 1: the times each choice starts at++**Files:** create `desktop/lib/super_tabs/day_jump.dart`; test `desktop/test/super_tab_day_jump_test.dart`.++**Interfaces:** `enum SuperTabJumpTo { yesterday, lastWeek, lastMonth, beginning }`;+`DateTime? superTabJumpStart(SuperTabJumpTo choice, DateTime now)`: the local midnight it starts at, null for the very+beginning.++- [ ] Failing tests: from Wed Nov 4 2026 15:30, Yesterday is Nov 3 00:00, Last week Oct 28 00:00, Last month Oct 4+ 00:00, The very beginning null. Last month from Mar 31 is Feb 28 00:00, and from Jan 15 it is Dec 15 of the year+ before.+- [ ] Run them, see them fail.+- [ ] Implement `superTabJumpStart`.+- [ ] Run them, see them pass. Commit.++## Task 2: the pill opens the menu++**Files:** `desktop/lib/super_tabs/day_pill.dart`; test `desktop/test/super_tab_day_jump_test.dart`.++**Interfaces:** `SuperTabStickyDay({..., ValueChanged<DateTime?>? onJump})`: called with a choice's start, null for the+very beginning, or a picked day's midnight. Without it the pill is as today (no chevron, not hit).++- [ ] Failing widget tests on a `SuperTabStickyDay` over a scrolled list: the pill shows a chevron and is a button.+ A click opens "Jump to…", Yesterday, Last week, Last month and The very beginning, a divider, and Jump to a+ specific date. Each choice closes the menu and calls `onJump` with Task 1's time. Jump to a specific date shows+ a calendar, and picking a day calls `onJump` with that day's midnight. Esc closes the menu without a call.+- [ ] Run them, see them fail.+- [ ] Implement the pill button, the menu and the calendar.+- [ ] Run them and the #2906 day pill tests, see them pass. Commit.++## Task 3: the chat lands on the first message from that time++**Files:** `desktop/lib/super_tabs/view.dart`; test `desktop/test/super_tab_day_jump_test.dart`.++**Interfaces:** consumes `SuperTabStickyDay.onJump`, `superTabJumpStart`; adds `_jumpToTime(String id, DateTime? from)`+in the view.++- [ ] Failing widget tests in a chat with messages over several days (fixture `messagePage` small):+ - Yesterday lands on yesterday's first message, held already, and lights it.+ - Last week lands on its first message when that needs older pages read.+ - The very beginning lands on the chat's first message, far back.+ - A specific date with nothing said since lands on the newest message.+ - A time more than 50 pages back says "That day is too far back to open." and does not move the list.+- [ ] Run them, see them fail.+- [ ] Implement `_jumpToTime` and give the chat's pill `onJump`.+- [ ] Run them, the day pill tests and the Jump to unread tests, see them pass. Commit.++## Task 4: the thread lands on its first reply from that time++**Files:** `desktop/lib/super_tabs/thread_panel.dart`; test `desktop/test/super_tab_day_jump_test.dart`.++- [ ] Failing widget test: in a thread with earlier replies not read yet, Last week lands on its first reply from then+ (reading earlier replies) and lights it. The very beginning lands on the root.+- [ ] Run it, see it fail.+- [ ] Implement the thread pill's `onJump`: earlier replies until reached (at most 50 pages), then scroll to the row and+ light it.+- [ ] Run it and the thread tests, see them pass. Commit.++## Task 5: screenshots next to Slack's++- [ ] A screenshot test (env `SUPER_TAB_DAY_JUMP_SHOTS`) renders the open menu over a chat in light and dark.+- [ ] Put them next to Huy's Slack screenshot in the pull request. Run Desktop's guard tests+ (`scripts/check-ui-style.py`, `test/laid_out_list_test.dart`) before Ready.diff --git a/docs/plans/2026-11-04-people-no-machine-mark-plan.md b/docs/plans/2026-11-04-people-no-machine-mark-plan.mdnew file mode 100644index 000000000..1c873213e--- /dev/null+++ b/docs/plans/2026-11-04-people-no-machine-mark-plan.md@@ -0,0 +1,53 @@+# People list: a no-machine mark Implementation Plan++> Written by the Engineer of task #2699 by the project's way of working (Engineer role, instructions revision 58): test+> first, one pull request, its review step the one independent review. No execution handoff: the Engineer implements it.++**Goal:** In the Desktop People list, a person with no machine shared in this Swarm shows a small muted no-machine mark+after their name, with "No machine shared yet" on hover, so it is clear at a glance who has not shared one (Scholes,+2026-11-04: 32 people, 21 machines).++**Architecture:** `LeaderboardPersonRow` (desktop/lib/super_tabs/leaderboard/person_row.dart) takes a `noMachine` flag+and puts the mark after the name, where number one's crown sits. The roster (roster.dart `_personRow`) sets it from the+Swarm's machines: a person has a machine when any listed machine names them as its contributor. A machine that is only+offline is still listed, so it still counts; one added drops the mark on the next state.++**Tech Stack:** Flutter Desktop, flutter_test widget tests with the Super Tab fixture (memory store, fake sign-in).++**Spec:** task #2699 brief and the mockup posted in its conversation (2026-11-04).++## Global Constraints++- The existing icon `AppIcons.monitorOff`, at the metadata size, in the muted token (`DesktopChrome.metadata()`'s+ colour); nothing hard-coded.+- The rest of the row is unchanged: name hover card, crown, points.+- No backend or wire change. The phone app is out of scope.++## Review Focus++1. A person with no machine shows the mark; one whose machine is offline (no reading) does not.+2. The mark goes when the person adds a machine.+3. The mark says "No machine shared yet" on hover and to a screen reader.++## Design++- growth, read cost, scale, migration, identity: N/A because nothing is stored, read or sent that is not already.+- audience: N/A because it reads only the machines this reader is already sent. A reader who sees only the Swarm-wide+ machines (no access to the Lead project) sees the mark for someone whose only machine is kept for a project they+ cannot read; that machine is not theirs to know about either.+- failure: N/A because no new call.+- platforms: Desktop (macOS, Linux, Windows) and the web build, which share this list.++## Task 1: The no-machine mark++**Files:**+- Modify: `desktop/lib/super_tabs/leaderboard/person_row.dart`, `desktop/lib/super_tabs/roster.dart`+- Test: `desktop/test/super_tab_no_machine_mark_test.dart`, `desktop/test/super_tab_no_machine_mark_shots_test.dart`++**Interfaces:** `LeaderboardPersonRow({..., bool noMachine = false})`; the mark keyed `super-person-no-machine-{id}`.++- [ ] Step 1: Failing widget tests: the mark shows for a person with no machine, not for one whose machine is offline,+ says "No machine shared yet", and goes away once they add a machine.+- [ ] Step 2: Run them; expect FAIL. Commit.+- [ ] Step 3: Implement the flag and the mark; the roster sets it.+- [ ] Step 4: Run the tests and the People list's own tests; expect PASS. Light and dark screenshots offscreen. Commit.diff --git a/docs/plans/2026-11-04-read-mark-expiry-sweep-plan.md b/docs/plans/2026-11-04-read-mark-expiry-sweep-plan.mdnew file mode 100644index 000000000..f802160bb--- /dev/null+++ b/docs/plans/2026-11-04-read-mark-expiry-sweep-plan.md@@ -0,0 +1,131 @@+# Read-mark expiry sweep Implementation Plan++> Implemented by the task's Engineer, task by task, test first (project instructions, Engineer role). One independent+> review on the pull request.++**Goal:** Read marks untouched for 180 days are removed in production too, where the API's database user may not set the+`read_mark_expiry` index's expiry (collMod refused).++**Architecture:** `ensureIndex` answers whether the expiry was refused. Where `read_mark_expiry`'s was, the singleton+worker runs a sweep that removes one bounded chunk of marks older than `READ_MARK_EXPIRY_MS` every 30 s, by the existing+`{updatedAt}` index (`read_mark_expiry`), the way #2912/#2923 remove old usage receipts. The chunk removal (find ids by the+index, then delete exactly those by `_id`, range checked again) and the timer loop move out of+`productUsageReceiptSweep.ts` into one shared `lib/chunkSweep.ts` that both sweeps use. Where the expiry is set, nothing+runs.++**Tech Stack:** TypeScript, Prisma `$runCommandRaw` on MongoDB 7, vitest (unit fakes in `src/`, a loopback replica set in+`integration/`).++**Spec:** Task #2696 brief (Ken's prod scan 11-04, item 7): "when ensureIndex for read_mark_expiry reports that collMod+was refused, the API runs a sweep that deletes SuperTabReadMark rows whose updatedAt is older than READ_MARK_EXPIRY_MS, one+bounded chunk every 30 s, served by the existing {updatedAt} index, on one worker only if #2912 does so. Where the expiry+is set, nothing extra runs. Reuse #2912's sweep code rather than copying it."++## Global Constraints++- Chunk 500 marks, one chunk per pass, a pass every 30 000 ms (as `RECEIPT_SWEEP`).+- Runs only in the singleton worker (`src/worker.ts`), as `startReceiptSweep` does; never in the PM2 API cluster.+- Query by the `read_mark_expiry` index (`{updatedAt: 1}`), delete by `_id` (`hint: {_id: 1}`), as #2923 learned.+- No env switches. No production access. No schema or index change.+- The receipt sweep's behavior and log lines stay exactly as they are (`integration/productUsageReceipts.test.ts`).++## Design++- growth: this is what deletes read marks past 180 days where the TTL is refused.+- concurrency: one worker; a pass still running when the next is due skips it; each delete re-checks `updatedAt < cutoff`,+ so a mark moved between the find and the delete stays.+- read cost: one index range seek of ≤500 keys a pass; an empty pass reads one key.+- scale: 10x marks → 10x passes to catch up; the warning metric is the `[read-marks] pass` removed count staying at 500.+- compatibility: no data shape changes; old and new servers read marks alike.+- migration + rollback: none; a rollback stops the sweep and the marks simply stay, as today.+- audience / identity: N/A because no request path changes.+- failure: a refused expiry already warns once (`ensureIndex`); the sweep logs its start, each pass that removed marks, and+ each failed pass, then retries.+- platforms: backend only.++## Review Focus++1. A mark exactly 180 days old stays (`$lt`, not `$lte`) — integration test in Task 3.+2. A mark raised between the sweep's find and its delete stays — unit test in Task 2 (delete filter carries the range).+3. A set expiry starts no timer and runs no command — unit test in Task 3.+4. The sweep never stops by itself (marks keep ageing); an empty pass must stay one index seek — unit test in Task 3.+5. The receipt sweep's log lines and stop-when-done stay unchanged — the existing receipt integration tests, run in Task 2.++---++### Task 1: ensureIndex answers a refused expiry++**Files:**+- Modify: `backend/src/lib/db/indexes.ts` (`ensureIndex`)+- Modify: `backend/src/superTabs/readMarks.ts` (`ensureReadMarkExpiry`)+- Modify: `backend/src/lib/db/schemaRelease.ts` (`releaseSchema`)+- Test: `backend/src/lib/db/indexes.test.ts`, `backend/src/superTabs/readMarks.test.ts` (new)++**Interfaces:**+- Produces: `type IndexOutcome = 'ready' | 'expiry-refused'`; `ensureIndex(db, collection, index): Promise<IndexOutcome>`;+ `ensureReadMarkExpiry(db): Promise<boolean>` (true when the expiry is set); `releaseSchema(db?, target?):+ Promise<{ readMarkExpirySet: boolean }>`.++- [ ] **Step 1: Write the failing tests** — in `indexes.test.ts` the refused-collMod case resolves `'expiry-refused'` and+ the collMod case `'ready'`; in `readMarks.test.ts`, `ensureReadMarkExpiry` on a fake whose collMod throws code 13 resolves+ `false`, and on one whose index already has `expireAfterSeconds: 15_552_000` resolves `true`.+- [ ] **Step 2: Run** `npm test -- src/lib/db/indexes.test.ts src/superTabs/readMarks.test.ts` — expect FAIL (undefined).+- [ ] **Step 3: Implement** the return values; `releaseSchema` keeps its order and returns `ensureReadMarkExpiry`'s answer.+- [ ] **Step 4: Run** the same command — expect PASS.+- [ ] **Step 5: Commit** test, then code.++### Task 2: one shared chunk sweep++**Files:**+- Create: `backend/src/lib/chunkSweep.ts`+- Modify: `backend/src/lib/productUsageReceiptSweep.ts` (`removeChunk`, `startReceiptSweep` use it)+- Test: `backend/src/lib/chunkSweep.test.ts` (new)++**Interfaces:**+- Produces:+ - `removeChunk(db: Pick<PrismaClient, '$runCommandRaw'>, chunk: { collection: string; filter: Record<string, unknown>;+ sort: Record<string, 1 | -1>; hint: string; chunk: number }): Promise<number>` — `find` with `filter`, `sort`, `hint`,+ `projection {_id: 1}`, `limit = batchSize = chunk`, `singleBatch`; then one `delete` of `{_id: {$in: ids}, ...filter}`+ with `hint {_id: 1}`, `limit 0`; throws on `writeErrors`; 0 without a delete when nothing was found.+ - `startChunkSweep(sweep: { label: string; everyMs: number; pass: () => Promise<{ removed: number; done: boolean }>;+ doneMessage?: string; log: Pick<typeof logger, 'info' | 'warn'>; handle?: (error: unknown) => boolean }): () => void`+ — runs `pass` now and every `everyMs` (unref'd), skips while one runs, logs `${label} pass` with `{ removed,+ removedSinceStart }` when it removed any, stops and logs `${label} ${doneMessage}` on `done`, and on an error not+ `handle`d logs `${label} pass failed; retrying next pass` with `{ error }`.++- [ ] **Step 1: Write the failing tests** — `removeChunk` sends a find with `limit` and `batchSize` both equal to `chunk`+ and the given hint, then a delete whose `q` is `{_id: {$in: ids}, ...filter}` with `hint {_id: 1}`; finds nothing → no+ delete; `startChunkSweep` skips an overlapping pass, stops after `done`, logs a failed pass and runs the next.+- [ ] **Step 2: Run** `npm test -- src/lib/chunkSweep.test.ts` — expect FAIL (module missing).+- [ ] **Step 3: Implement** `chunkSweep.ts` from #2912/#2923's code; the receipt sweep calls it with its own range, hint+ `product_usage_expiry`, label `[usage-receipts]`, done message `done: no old receipts left`, and a `handle` that turns+ `ReceiptRuleRefused` into its one warning and `withoutRule`.+- [ ] **Step 4: Run** `npm test -- src/lib/chunkSweep.test.ts` and `npx vitest run --config vitest.super-tabs.config.ts+ integration/productUsageReceipts.test.ts` — expect PASS, unchanged receipt behavior.+- [ ] **Step 5: Commit** test, then code.++### Task 3: the read-mark sweep++**Files:**+- Modify: `backend/src/superTabs/readMarks.ts` (`READ_MARK_SWEEP`, `sweepReadMarks`, `startReadMarkSweep`)+- Modify: `backend/src/worker.ts` (start and stop it)+- Test: `backend/src/superTabs/readMarks.test.ts`, `backend/integration/superTabReadMarks.test.ts`++**Interfaces:**+- Consumes: `removeChunk`, `startChunkSweep` (Task 2); `releaseSchema(...).readMarkExpirySet` (Task 1).+- Produces: `READ_MARK_SWEEP = { chunk: 500, everyMs: 30_000 }`; `sweepReadMarks(db, now: Date, chunk?: number):+ Promise<number>` (filter `{updatedAt: {$lt: now − READ_MARK_EXPIRY_MS}}`, sort `{updatedAt: 1}`, hint+ `read_mark_expiry`); `startReadMarkSweep(db, expirySet: boolean, settings?: Partial<{ chunk; everyMs; now: () => Date;+ log }>): () => void` — a no-op stop, with no command and no timer, when `expirySet`; otherwise logs its start once and runs+ `startChunkSweep` with label `[read-marks]`, never done.++- [ ] **Step 1: Write the failing tests** — unit: `startReadMarkSweep(fake, true)` runs no command; `(fake, false)` sends+ a find on `SuperTabReadMark` with hint `read_mark_expiry`, `limit 500`, and the cutoff `now − 180 d`, then a delete of+ the found ids; an empty find sends no delete. Integration (real Mongo): marks at 181 d, exactly 180 d and 179 d → one+ `sweepReadMarks` removes only the 181 d ones; 7 old marks with `chunk 3` → a pass removes 3 and leaves 4.+- [ ] **Step 2: Run** `npm test -- src/superTabs/readMarks.test.ts` and `npx vitest run --config+ vitest.super-tabs.config.ts integration/superTabReadMarks.test.ts` — expect FAIL.+- [ ] **Step 3: Implement** the sweep; `worker.ts` keeps `releaseSchema()`'s answer and calls `startReadMarkSweep(prisma,+ schema.readMarkExpirySet)` next to `startReceiptSweep`, stopping it on shutdown.+- [ ] **Step 4: Run** the Step 2 commands — expect PASS; then `npm test` (backend unit suite) once before Ready.+- [ ] **Step 5: Commit** test, then code.diff --git a/docs/plans/2026-11-04-team-setup-steps-windows-linux-plan.md b/docs/plans/2026-11-04-team-setup-steps-windows-linux-plan.mdnew file mode 100644index 000000000..ce40016b2--- /dev/null+++ b/docs/plans/2026-11-04-team-setup-steps-windows-linux-plan.md@@ -0,0 +1,51 @@+# Harness Team setup on Windows and Linux: a bounded engine install and its steps, as on a Mac: plan++> Way of working: this project's Engineer role (project instructions): test-driven development, each failing spec+> committed before the code that passes it, one pull request, one independent review.++**Goal:** a new member on Windows or Linux never waits on the Harness Team setup screen with no sign of progress. The+Claude Code and Codex install has the Mac's limit (one run, 8 minutes, missing engines said plainly, the account still+finished), and the setup screen shows each step (task #2686, follow-up to #2667/#2921).++**Architecture:** #2921 added the step file (`progress` in the setup's private staging folder, read by+cli/src/team/admin.ts while the script runs), the `password`/`report` steps in cli/src/team/command.ts, and the Desktop+words for each step. This adds the writers on the two other systems: the Linux setup script (cli/src/team/script.ts+`buildLinuxSetupScript`) and the Windows one (cli/src/team/windowsScript.ts `buildWindowsSetupScript`; on Windows the+sign-in and the daemon's start happen after the script, in command.ts `windowsHandOver`, which says those two steps).+Linux already runs the bounded `TEAM_ENGINES_INSTALL`; Windows gets a PowerShell twin.++**Tech Stack:** TypeScript + vitest; the built scripts are checked as text (and parsed where `pwsh` exists). Nothing+runs UAC, pkexec, sudo, an elevated PowerShell script or a real setup.++**Spec:** task #2686's brief.++## Global constraints++- Everything system-touching goes through AdminDeps and TeamCommandDeps fakes.+- Swarm code stays out of cli/src/core. Desktop does not change: its step words already cover every step named here.++## Review focus++- Windows: the install stops its whole process tree (`taskkill /T`) at the limit, and a late engines run no longer+ fails setup (As-Team gives up on it and says so, instead of `die`).+- The step file is written without following a link: as the owner on Linux (`runuser`, write-then-rename), and on+ Windows by write-then-rename with a fresh name, where `Move-Item -Force` replaces a link rather than writing through it.++## Task 1: Linux says its steps++**Files:** cli/src/team/script.ts, cli/src/team/script.spec.ts++- [ ] Failing spec: the Linux setup script has the `step` helper (as the owner, into `$STAGE/progress`) and says+ account, home, privacy, runtime, engines, sign-in, daemon in order, before each runs; it runs the bounded install.+- [ ] The helper and the markers.++## Task 2: Windows bounds its engine install and says its steps++**Files:** cli/src/team/windowsScript.ts, cli/src/team/windowsScript.spec.ts, cli/src/team/command.ts,+cli/src/team/command.spec.ts++- [ ] Failing specs: the engines script installs both packages in one npm run, then each alone, within 480 seconds in+ all, stops the tree at the limit and says the engines are missing and how to add them; As-Team gives the engines+ 10 minutes and goes on when they are late; the setup script says account, home, privacy, runtime, engines in+ order; setup on Windows says sign-in and daemon around the handover, then report.+- [ ] The code that passes them.