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 b1310: #2894 #2917 #2904 #2922 #2916 #2927 #2926 #2928 (#2938)
0xken1573f5c5602920
diff --git a/backend/integration/ci-durations.json b/backend/integration/ci-durations.jsonindex a06d45442..f28b77b33 100644--- a/backend/integration/ci-durations.json+++ b/backend/integration/ci-durations.json@@ -41,6 +41,7 @@"integration/superTabLiveness.test.ts": 105300,"integration/superTabMachineNames.test.ts": 1500,"integration/superTabMachineRemovals.test.ts": 900,+ "integration/superTabMachineLiveness.test.ts": 3000,"integration/superTabMachineReports.test.ts": 20300,"integration/superTabDigestHour.test.ts": 1500,"integration/superTabMessagePages.test.ts": 1500,diff --git a/backend/integration/superTabCommandLoads.test.ts b/backend/integration/superTabCommandLoads.test.tsindex 5fac70dbe..def511b08 100644--- a/backend/integration/superTabCommandLoads.test.ts+++ b/backend/integration/superTabCommandLoads.test.ts@@ -73,13 +73,15 @@ const FEW = 100describe('a refused command in the log', () => {const secret = 'do-not-log-this'it('writes one line, its code and type and no values; one that passes writes none (Ken, 2026-11-04)', async () => {- const { execute } = await swarm()+ const { execute, tab } = await swarm()const said = vi.spyOn(logger, 'warn').mockImplementation(() => {})try {await execute({ type: 'conversation.create', title: secret, brief: secret, checks: [] })expect(said.mock.calls.filter(([line]) => line === REFUSED)).toEqual([])await expect(execute({ type: 'conversation.rename', conversationId: secret, title: secret })).rejects.toMatchObject({ code: 'NOT_FOUND' })- expect(said.mock.calls.filter(([line]) => line === REFUSED)).toEqual([[REFUSED, { code: 'NOT_FOUND', type: 'conversation.rename' }]])+ // And whose (#2675): its Swarm, no agent, and no declared client; never its words.+ expect(said.mock.calls.filter(([line]) => line === REFUSED)).toEqual([[REFUSED, { code: 'NOT_FOUND', type: 'conversation.rename',+ tabId: tab, agentId: null, asAgent: false, client: 'other', version: null }]])expect(JSON.stringify(said.mock.calls)).not.toContain(secret)} finally {said.mockRestore()@@ -87,6 +89,21 @@ describe('a refused command in the log', () => {})})+describe('a refused command from an agent, in the log (#2675)', () => {+ it('names the agent the command names, that an agent sent it, and the client and version it declared', async () => {+ const { store, tab, lead } = await swarm()+ const said = vi.spyOn(logger, 'warn').mockImplementation(() => {})+ try {+ await expect(store.execute(owner, tab, { operationId: randomUUID(), command: { type: 'agent.alert', agentId: 'gone-agent', alert: 'prompt', active: true } },+ lead, undefined, { kind: 'cli', version: '0.5.34' })).rejects.toBeTruthy()+ expect(said.mock.calls.filter(([line]) => line === REFUSED)).toEqual([[REFUSED, expect.objectContaining({ type: 'agent.alert', tabId: tab,+ agentId: 'gone-agent', asAgent: true, client: 'cli', version: '0.5.34' })]])+ } finally {+ said.mockRestore()+ }+ })+})+describe('a command naming the coordinator', () => {it('agent.alert reads none of its 1,000 dormant groups, and its row still lands', async () => {const f = await swarm(1000)diff --git a/backend/integration/superTabGroupPlans.test.ts b/backend/integration/superTabGroupPlans.test.tsindex 73766821f..a80c6a954 100644--- a/backend/integration/superTabGroupPlans.test.ts+++ b/backend/integration/superTabGroupPlans.test.ts@@ -15,6 +15,7 @@ import { DIRECT, readLight } from '../src/superTabs/cachedReads.js'import * as parts from '../src/superTabs/parts/index.js'import { HeldParts } from '../src/superTabs/parts/held.js'import { recentDormantGroups } from '../src/superTabs/leaderboard/read.js'+import { weekStart } from '../src/superTabs/leaderboard/week.js'import { decisionsWaiting, listDecisions } from '../src/superTabs/decisions.js'import { GROUP_INDEX, groupsBy, listGroupIndexes, retryStaleIndex } from '../src/superTabs/parts/indexed.js'import { logger } from '../src/utils/logger.js'@@ -296,11 +297,14 @@ describe('hot SwarmGroup reads name their index and read only what they return (const recent = (rows: typeof s.quietLead) => rows.filter(r => r.lastActivityAt.getTime() >= since).map(r => r.key).sort()for (const [projectId, expected] of [['lead', recent(s.quietLead)], [s.other, recent(s.quietOther)], [s.empty, []]] as const) {let found: string[] = []- const reads = await profiled(async () => { found = (await db.$transaction(tx => recentDormantGroups(tx, s.tabId, projectId, since))).map(g => g.id).sort() })+ const reads = await profiled(async () => { found = (await db.$transaction(tx => recentDormantGroups(tx, DIRECT, s.tabId, projectId, since))).map(g => g.id).sort() })expect(found).toEqual(expected)expect(reads).toHaveLength(1)expectIndexed(reads)- expect(reads[0]!.docsExamined, `${projectId} ${JSON.stringify(reads)}`).toBeLessThanOrEqual(expected.length)+ // The read cache holds the board's groups from the Monday its window starts in (cachePatch.ts boardRule, task #2674): Mongo+ // examines those, at most six days more than the window, and the read keeps the window.+ const held = [...s.quietLead, ...s.quietOther].filter(r => r.lastActivityAt.getTime() >= weekStart(since) && (projectId === 'lead' ? s.quietLead : projectId === s.other ? s.quietOther : []).includes(r)).length+ expect(reads[0]!.docsExamined, `${projectId} ${JSON.stringify(reads)}`).toBeLessThanOrEqual(held)}})diff --git a/backend/integration/superTabMachineLiveness.test.ts b/backend/integration/superTabMachineLiveness.test.tsnew file mode 100644index 000000000..83d010ad8--- /dev/null+++ b/backend/integration/superTabMachineLiveness.test.ts@@ -0,0 +1,177 @@+import { randomUUID } from 'node:crypto'+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import type { PrismaClient } from '@prisma/client'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { SuperTabStore } from '../src/superTabs/store.js'+import type { Command } from '../src/superTabs/commands.js'+import type { MachineObservation } from '../src/superTabs/machines.js'+import { localReportMemory, type ReportMemory } from '../src/superTabs/machineReports.js'+import { clock as stamps } from '../src/superTabs/parts/index.js'+import { SwarmReads } from '../src/superTabs/read/service.js'+import { poolRows } from './hostRows.test-support.js'+import { planDatabase } from './plans.test-support.js'++// Ken's machine-cap plan, 2026-11-04: every reading sent every poller the whole machine part, 397 MB an hour in GET changes, a+// cost that grows with the square of the machines. A client that asks now gets one line for a reading, and the part when its+// content changes. Clients of today get what they always got.+const owner: AuthUser = { sub: '510000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const host: AuthUser = { sub: '510000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const outsider: AuthUser = { sub: '510000000000000000000004', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const MINUTE = 60_000+let replica: MongoMemoryReplSet+let db: PrismaClient++beforeAll(async () => {+ ({ replica, db } = await planDatabase('swarm_liveness_test'))+ for (const user of [owner, host, outsider]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: 'prod' } })+ await db.machine.create({ data: { machineId: 'mac', userId: host.sub, apiKey: 'fixture-mac', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ await db.machineShare.create({ data: { machineId: 'mac', ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email] } })+})+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})++// Only Date, with part stamps read from it too (parts/clock.ts holds the real Date.now), so a stamp and a cursor read one clock.+const clock = { get now() { return Date.now() }, set now(at: number) { vi.setSystemTime(at) } }+let start = Date.now(), stamped = 0+beforeEach(() => {+ start += 3_600_000+ vi.useFakeTimers({ toFake: ['Date'], now: start })+ vi.spyOn(stamps, 'next').mockImplementation(() => stamped = Math.max(Date.now(), stamped + 1))+})+afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers() })++/** A server that remembers no full report: every reading runs in full. */+const never: ReportMemory = { get: async () => undefined, set: async () => {}, sweepDue: async () => false }++async function swarm(memory: 'fast' | 'full' = 'fast') {+ const local = localReportMemory(() => clock.now)+ const reports: ReportMemory = memory === 'full' ? never : { get: (t, m) => local.get(t, m), set: (t, m, r) => local.set(t, m, r), sweepDue: async () => false }+ const store = new SuperTabStore(db, () => clock.now, null, { reports })+ const reads = new SwarmReads(store)+ const tab = (await store.create(owner, randomUUID(), 'Liveness', 'public')).id+ const execute = (command: Command, user = owner) => store.execute(user, tab, { operationId: randomUUID(), command })+ const invitation = await execute({ type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })+ await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)+ await execute({ type: 'machine.contribute', machineId: 'mac', name: 'Mac', cwd: '/repo', engines: ['codex'], maxAgents: 4 }, host)+ const generation = (await poolRows(store, host, 'mac')).find(p => p.tabId === tab)!.machine.generation+ const reading = (extra: Partial<MachineObservation> = {}): MachineObservation => ({ generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,+ diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },+ quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [], ...extra })+ const beat = (extra: Partial<MachineObservation> = {}) => store.observeMachine(host, tab, 'mac', reading(extra))+ // Two beats so the next can go the fast way when the memory allows it, then past the cursor's overlap.+ await beat()+ clock.now += 15_000+ await beat()+ clock.now += 5 * MINUTE+ await beat()+ const cursor = (await reads.firstLoad(owner, tab) as { cursor: string }).cursor+ clock.now += MINUTE+ const row = () => db.swarmMachine.findUniqueOrThrow({ where: { id: `${tab}:mac` } })+ const light = (as = owner, asAgentId?: string) => reads.changes(as, tab, cursor, asAgentId, { lightMachines: true }) as Promise<Record<string, unknown> & { machines: Array<{ key: string; deleted?: boolean; data?: { observation?: { receivedAt: number } } }>; machineReadings?: Array<{ key: string; version: number; receivedAt: number }> }>+ const today = () => reads.changes(owner, tab, cursor) as Promise<Record<string, unknown> & { machines: Array<{ key: string; data: { observation?: { receivedAt: number; resources: { cpuPercent: number } } } }> }>+ return { clock, store, reads, tab, execute, reading, beat, row, light, today }+}+const busier = { resources: { cpuPercent: 77, memoryTotalBytes: 32e9, memoryUsedBytes: 9e9, diskFreeBytes: 110e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 110e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null } }++describe.each(['fast', 'full'] as const)('a reading stored the %s way', memory => {+ it('reaches a client that asks as one line, with the machine\'s last reading, and no part', async () => {+ const f = await swarm(memory)+ const before = await f.row()+ await f.beat(busier)+ const after = await f.row()+ expect(after.changedAt).toEqual(before.changedAt)+ const changes = await f.light()+ expect(changes.machines).toEqual([])+ expect(changes.machineReadings).toEqual([{ key: 'mac', version: after.version, receivedAt: f.clock.now }])+ })++ it('reaches today\'s clients as the whole part, at a higher version, as ever', async () => {+ const f = await swarm(memory)+ const before = await f.row()+ await f.beat(busier)+ const changes = await f.today()+ expect(changes.machines.map(m => m.key)).toEqual(['mac'])+ expect(changes.machines[0]).toMatchObject({ version: before.version + 1 })+ expect(changes.machines[0]!.data.observation).toMatchObject({ receivedAt: f.clock.now, resources: { cpuPercent: 77 } })+ expect(changes).not.toHaveProperty('machineReadings')+ })++ it('still sends the whole part when what it says beyond the volatile fields changed', async () => {+ const f = await swarm(memory)+ await f.beat({ tools: { git: true } } as Partial<MachineObservation>)+ const changes = await f.light()+ expect(changes.machines.map(m => m.key)).toEqual(['mac'])+ expect(changes.machineReadings).toEqual([])+ })+})++describe('a client that asks', () => {+ it.each<[string, Partial<MachineObservation>]>([+ ['quotas', { quotas: [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 10, resetsAt: null }] }] }],+ ['resources', busier],+ ])('gets a line for a change of %s alone', async (_field, extra) => {+ const f = await swarm()+ await f.beat(extra)+ const changes = await f.light()+ expect(changes.machines).toEqual([])+ expect(changes.machineReadings!.map(r => r.key)).toEqual(['mac'])+ })++ it('gets the whole part when a person changes the machine, and a later reading alone is a line again', async () => {+ const f = await swarm()+ await f.execute({ type: 'machine.contribute', machineId: 'mac', name: 'Mac', cwd: '/repo', engines: ['codex'], maxAgents: 6 }, host)+ const changes = await f.light()+ expect(changes.machines.map(m => m.key)).toEqual(['mac'])+ expect(changes.machineReadings).toEqual([])+ // Saving a machine again starts a new generation, whose first reading is content too. Then past the cursor's overlap.+ const generation = (await poolRows(f.store, host, 'mac')).find(p => p.tabId === f.tab)!.machine.generation+ await f.beat({ generation })+ f.clock.now += MINUTE+ const cursor = (await f.reads.firstLoad(owner, f.tab) as { cursor: string }).cursor+ f.clock.now += MINUTE+ await f.beat({ ...busier, generation })+ const next = await f.reads.changes(owner, f.tab, cursor, undefined, { lightMachines: true }) as { machines: unknown[]; machineReadings: Array<{ key: string }> }+ expect(next.machines).toEqual([])+ expect(next.machineReadings.map(r => r.key)).toEqual(['mac'])+ })++ it('reads the same time as a whole part says, so online and offline come out the same', async () => {+ const f = await swarm()+ await f.beat(busier)+ const line = (await f.light()).machineReadings![0]!+ const part = (await f.today()).machines[0]!+ expect(line.receivedAt).toBe(part.data.observation!.receivedAt)+ // A machine that stopped reporting has no new line, and what the client holds goes stale as a part would.+ f.clock.now += MINUTE+ const cursor = (await f.reads.firstLoad(owner, f.tab) as { cursor: string }).cursor+ f.clock.now += 5 * MINUTE+ const silent = await f.reads.changes(owner, f.tab, cursor, undefined, { lightMachines: true }) as { machines: unknown[]; machineReadings: unknown[] }+ expect(silent).toMatchObject({ machines: [], machineReadings: [] })+ })++ it('costs a small part of the whole part', async () => {+ const f = await swarm()+ await f.beat(busier)+ const line = JSON.stringify((await f.light()).machineReadings![0]), part = JSON.stringify((await f.today()).machines[0])+ console.log(`bytes per reading: whole part ${part.length}, line ${line.length}`)+ expect(line.length).toBeLessThan(part.length / 8)+ })+})++describe('the whole readings on demand', () => {+ it('gives a member every machine with its whole reading', async () => {+ const f = await swarm()+ await f.beat(busier)+ const { machines } = await f.reads.machineReadings(owner, f.tab) as { machines: Array<{ key: string; data: { observation: { receivedAt: number; resources: { cpuPercent: number } } } }> }+ expect(machines.map(m => m.key)).toEqual(['mac'])+ expect(machines[0]!.data.observation).toMatchObject({ receivedAt: f.clock.now, resources: { cpuPercent: 77 } })+ })++ it('reads nothing for someone outside the Swarm', async () => {+ const f = await swarm()+ await expect(f.reads.machineReadings(outsider, f.tab)).rejects.toThrow()+ })+})diff --git a/backend/integration/superTabNotAvailable.test.ts b/backend/integration/superTabNotAvailable.test.tsindex 7004090af..aaee418c2 100644--- a/backend/integration/superTabNotAvailable.test.ts+++ b/backend/integration/superTabNotAvailable.test.ts@@ -88,6 +88,7 @@ function calls(tab: string, chat: string, project: string) {json('GET', 'GET /api/super-tabs/:tabId/changes', `${t}/changes?cursor=abc`),json('GET', 'GET /api/super-tabs/:tabId/activity', `${t}/activity`),json('POST', 'POST /api/super-tabs/:tabId/activity/read', `${t}/activity/read`, { through: '2026-11-01T00:00:00.000Z' }),+ json('GET', 'GET /api/super-tabs/:tabId/reminders', `${t}/reminders`),json('GET', 'GET /api/super-tabs/:tabId/inbox', `${t}/inbox`),json('GET', 'GET /api/super-tabs/:tabId/threads', `${t}/threads`),json('POST', 'POST /api/super-tabs/:tabId/commands', `${t}/commands`,@@ -95,6 +96,7 @@ function calls(tab: string, chat: string, project: string) {json('GET', 'GET /api/super-tabs/:tabId/mentions', `${t}/mentions?state=waiting`),json('GET', 'GET /api/super-tabs/:tabId/decisions', `${t}/decisions?state=open`),json('GET', 'GET /api/super-tabs/:tabId/leaderboard', `${t}/leaderboard?projectId=${project}`),+ json('GET', 'GET /api/super-tabs/:tabId/machine-readings', `${t}/machine-readings`),json('GET', 'GET /api/super-tabs/:tabId/proposals', `${t}/proposals?projectId=${project}`),json('GET', 'GET /api/super-tabs/:tabId/sharing', `${t}/sharing`),json('POST', 'POST /api/super-tabs/:tabId/sharing', `${t}/sharing`, { operationId: op(), revision: 0, access: { mode: 'link', role: 'viewer' } }),@@ -109,7 +111,10 @@ function calls(tab: string, chat: string, project: string) {json('GET', 'GET /api/super-tabs/:tabId/conversations/:conversationId/messages/:messageId/attachments/:attachmentId',`${t}/conversations/${chat}/messages/${MISSING}/attachments/${MISSING}`),json('POST', 'POST /api/super-tabs/:tabId/conversations/:conversationId/read', `${t}/conversations/${chat}/read`, { sequence: 1 }),+ json('POST', 'POST /api/super-tabs/:tabId/conversations/:conversationId/unread', `${t}/conversations/${chat}/unread`, { sequence: 1 }),json('POST', 'POST /api/super-tabs/:tabId/conversations/:conversationId/threads/:threadId/read', `${t}/conversations/${chat}/threads/${MISSING}/read`, { sequence: 1 }),+ json('POST', 'POST /api/super-tabs/:tabId/conversations/:conversationId/messages/:messageId/reminder', `${t}/conversations/${chat}/messages/${MISSING}/reminder`,+ { at: new Date(Date.now() + 60 * 60_000).toISOString() }),json('POST', 'POST /api/super-tabs/:tabId/conversations/:conversationId/notifications', `${t}/conversations/${chat}/notifications`, { notify: 'all' }),json('POST', 'POST /api/super-tabs/:tabId/conversations/:conversationId/threads/:threadId/follow', `${t}/conversations/${chat}/threads/${MISSING}/follow`,{ follow: true }),diff --git a/backend/integration/superTabReadMarks.test.ts b/backend/integration/superTabReadMarks.test.tsindex 2fcdf5e44..050901264 100644--- a/backend/integration/superTabReadMarks.test.ts+++ b/backend/integration/superTabReadMarks.test.ts@@ -172,6 +172,91 @@ describe('read marks (one per person and conversation)', () => {})})+describe('Mark unread (the one write that moves a mark back)', () => {+ const unread = (tabId: string, conversationId: string, sequence: number, as: AuthUser = owner, query = '') =>+ call('POST', `/api/super-tabs/${tabId}/conversations/${conversationId}/unread${query}`, as, { sequence })+ const changed = async (tabId: string, cursor: string, as: AuthUser = owner) =>+ (await call('GET', `/api/super-tabs/${tabId}/changes?cursor=${cursor}`, as)).body.data.derived as { readMarks?: Record<string, number>; unreadMarks?: Record<string, number> }++ it('mark unread restores the unread line: the mark goes to just before the message, and the person\'s other device takes it', async () => {+ const s = await scene()+ clock = NOW+ await mark(s.tabId, s.web, 60)+ // The other device's last read, a minute later (the cursor overlaps the last 30 s, read/cursor.ts).+ clock = NOW + 60_000+ const cursor = (await firstLoad(s.tabId, owner)).cursor as string+ clock = NOW + 62_000+ expect(await unread(s.tabId, s.web, 41)).toMatchObject({ status: 200, body: { data: { sequence: 40 } } })+ clock = NOW + 63_000+ // That device holds 60: `unreadMarks` tells it to take the lower mark instead of keeping the higher one.+ expect(await changed(s.tabId, cursor)).toMatchObject({ readMarks: { [s.web]: 40 }, unreadMarks: { [s.web]: 40 } })+ expect((await firstLoad(s.tabId, owner)).derived).toMatchObject({ readMarks: { [s.web]: 40 }, unreadMarks: { [s.web]: 40 } })+ // Another person's read never carries it.+ expect((await firstLoad(s.tabId, peer)).derived.unreadMarks).toBeUndefined()+ clock = NOW+ })++ it('never moves a mark forward: a chat already unread from earlier stays as it is', async () => {+ const s = await scene()+ await mark(s.tabId, s.web, 40)+ expect((await unread(s.tabId, s.web, 70)).body.data).toEqual({ sequence: 40 })+ expect(await marksOf(s.tabId, owner)).toEqual({ [s.web]: 40 })+ expect((await firstLoad(s.tabId, owner)).derived.unreadMarks).toBeUndefined()+ })++ it('gives a chat never marked read a mark before the message: without one the chat counts as read', async () => {+ const s = await scene()+ expect((await unread(s.tabId, s.web, 41)).body.data).toEqual({ sequence: 40 })+ expect((await firstLoad(s.tabId, owner)).derived).toMatchObject({ readMarks: { [s.web]: 40 }, unreadMarks: { [s.web]: 40 } })+ expect(await db.superTabReadMark.count({ where: { tabId: s.tabId } })).toBe(1)+ })++ it('is undone by a later read alone: an older read arriving after it changes nothing, a newer one raises it', async () => {+ const s = await scene()+ clock = NOW+ await mark(s.tabId, s.web, 60)+ await unread(s.tabId, s.web, 41)+ expect((await mark(s.tabId, s.web, 30)).body.data).toEqual({ sequence: 40 })+ expect((await firstLoad(s.tabId, owner)).derived.unreadMarks).toEqual({ [s.web]: 40 })+ clock = NOW + 60_000+ const cursor = (await firstLoad(s.tabId, owner)).cursor as string+ clock = NOW + 62_000+ expect((await mark(s.tabId, s.web, 60)).body.data).toEqual({ sequence: 60 })+ clock = NOW + 63_000+ const derived = await changed(s.tabId, cursor)+ expect(derived.readMarks).toEqual({ [s.web]: 60 })+ expect(derived.unreadMarks).toBeUndefined()+ expect((await firstLoad(s.tabId, owner)).derived.unreadMarks).toBeUndefined()+ // Even a read in the same millisecond as the Mark unread ends it.+ await unread(s.tabId, s.web, 51)+ await mark(s.tabId, s.web, 55)+ expect((await firstLoad(s.tabId, owner)).derived).toMatchObject({ readMarks: { [s.web]: 55 } })+ expect((await firstLoad(s.tabId, owner)).derived.unreadMarks).toBeUndefined()+ clock = NOW+ })++ it('refuses a chat the person cannot read, a Team session and an agent, storing nothing', async () => {+ const s = await scene()+ expect((await unread(s.tabId, s.secretGroup, 10, outsider)).status).toBe(404)+ expect((await unread(s.tabId, 'no-such-group', 10, outsider)).status).toBe(404)+ expect((await unread(s.tabId, s.web, 10, ownerTeam)).status).toBe(403)+ expect((await unread(s.tabId, s.web, 10, owner, '?asAgentId=some-agent')).status).toBe(400)+ expect(await db.superTabReadMark.count({ where: { tabId: s.tabId } })).toBe(0)+ })++ it('stops sending an unread mark once the person can no longer read its chat', async () => {+ const s = await scene()+ await unread(s.tabId, s.web, 31, peer)+ expect((await firstLoad(s.tabId, peer)).derived.unreadMarks).toEqual({ [s.web]: 30 })+ await swarmTransaction(db, async tx => {+ const current = (await parts.loadActive(tx, s.tabId, { groupIds: [s.web] })).groups.find(g => g.key === s.web)!+ const data = { ...structuredClone(current.data!), audience: { people: [{ id: owner.sub, generation: 0 }] } } as Conversation+ await guardedWrite(tx, s.tabId, { op: 'update', kind: 'group', key: s.web, seen: current.version, data }, clock)+ })+ expect((await firstLoad(s.tabId, peer)).derived.unreadMarks).toBeUndefined()+ })+})+describe('catch-up summary (what the reader missed since their mark)', () => {const lead = { kind: 'agent', id: 'lead-agent', name: 'Lead', displayName: 'River', membershipGeneration: 'g' }/** Rows written as the store writes them, numbered from 1 in `conversationId`; scenes repeat conversation ids, so the tab names them. */diff --git a/backend/integration/superTabReminders.test.ts b/backend/integration/superTabReminders.test.tsnew file mode 100644index 000000000..00e6d40ce--- /dev/null+++ b/backend/integration/superTabReminders.test.ts@@ -0,0 +1,281 @@+import { randomUUID } from 'node:crypto'+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import type { PrismaClient } from '@prisma/client'+import Fastify, { type FastifyInstance } from 'fastify'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { SuperTabStore } from '../src/superTabs/store.js'+import { superTabRoutes } from '../src/routes/superTabs.js'+import { errorHandler } from '../src/middlewares/errorHandler.js'+import { migrateSwarm } from '../src/superTabs/migration/migrate.js'+import { SwarmReads } from '../src/superTabs/read/service.js'+import { HostReads } from '../src/superTabs/read/host.js'+import { listNamedIndexes } from '../src/superTabs/parts/indexed.js'+import { REMINDER_CAP, REMINDER_EXPIRY_MS, REMINDER_READS, resetReminderReads, sweepReminders } from '../src/superTabs/reminders.js'+import { stableId, type Command, type SuperTabState } from '../src/superTabs/model.js'+import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'+import { NOW, outsider as outsiderActor, owner as ownerActor, peer as peerActor, swarm } from '../src/superTabs/read/fixture.test-support.js'+import { plan, planDatabase, profiled, reads } from './plans.test-support.js'++// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.+let replica: MongoMemoryReplSet+let db: PrismaClient+let app: FastifyInstance+let store: SuperTabStore+let clock = NOW+const MINUTE = 60_000, DAY = 24 * 60 * MINUTE+const user = (actor: { userId: string; email: string }): AuthUser => ({ sub: actor.userId, email: actor.email, autonomousEnv: 'prod', role: 'user' })+const [owner, peer, outsider] = [ownerActor, peerActor, outsiderActor].map(user) as [AuthUser, AuthUser, AuthUser]+const ownerTeam: AuthUser = { ...owner, harnessSessionId: 'owner-team-session', harnessSessionKind: 'team' }+const signedIn = (authorization: string | undefined) =>+ authorization === 'Bearer team' ? ownerTeam : [owner, peer, outsider].find(u => `Bearer ${u.sub}` === authorization)+const MIGRATED = NOW - MINUTE++beforeAll(async () => {+ ({ replica, db } = await planDatabase('swarm_reminders_test'))+ for (const each of [owner, peer, outsider]) await db.user.create({ data: { id: each.sub, externalId: `fixture-${each.sub}`, email: each.email, autonomousEnv: 'prod' } })+ await db.machine.create({ data: { machineId: 'host', userId: owner.sub, apiKey: 'fixture-only', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ store = new SuperTabStore(db, () => clock)+ app = Fastify()+ app.setErrorHandler(errorHandler)+ // External SSO is replaced with fixture accounts; every permission and write below is real.+ app.addHook('onRequest', async (request, reply) => {+ const found = signedIn(request.headers.authorization)+ if (!found) return reply.code(401).send({ success: false })+ request.user = found+ })+ await app.register(superTabRoutes, { store, github: null, reads: new SwarmReads(store, { now: () => clock }), hosts: new HostReads(store, { now: () => clock }) })+ await app.ready()+})+afterAll(async () => {+ await app?.close()+ await db?.$disconnect()+ await replica?.stop()+})+beforeEach(() => {+ clock = NOW+ resetReminderReads()+})++/** A Swarm in parts: a public chat ("Web", with a worker on the owner's machine), a project shared with the owner alone+ * ("Secret work"), and a public project the owner can make private later ("Open chat"). */+async function scene() {+ const s = swarm(MIGRATED)+ s.join(peerActor)+ s.join(outsiderActor)+ const secret = s.run({ type: 'project.create', name: 'Secret', visibility: 'private', brief: '' }).projectId as string+ const open = s.run({ type: 'project.create', name: 'Open', visibility: 'public', brief: '' }).projectId as string+ const openChat = s.group('Open chat', open)+ const web = s.group('Web')+ const worker = s.add('worker-harness', web, false, ownerActor, 'host', owner.sub)+ s.run({ type: 'work.assign', conversationId: web, agentId: worker })+ const secretGroup = s.group('Secret work', secret)+ const tabId = `tab-${randomUUID()}`+ await writeLegacySwarm(db, { state: { ...structuredClone(s.state), id: tabId } as SuperTabState, revision: 3 })+ const report = await migrateSwarm(db, tabId, { now: () => MIGRATED })+ if (!report.ok) throw new Error(report.error)+ return { tabId, web, worker, secret, secretGroup, open, openChat }+}++const run = async (tabId: string, command: Command, as: AuthUser = owner, asAgentId?: string) =>+ (await store.execute(as, tabId, { operationId: randomUUID(), command }, asAgentId)) as { result: Record<string, unknown> }+const send = async (tabId: string, conversationId: string, text: string, as: AuthUser = owner, replyTo: string | null = null, asAgentId?: string) =>+ (await run(tabId, { type: 'message.send', conversationId, text, replyTo, recipientIds: [] }, as, asAgentId)).result.messageId as string+const call = async (method: 'GET' | 'POST', url: string, as: AuthUser = owner, payload?: unknown) => {+ const response = await app.inject({ method, url, headers: { authorization: as === ownerTeam ? 'Bearer team' : `Bearer ${as.sub}` },+ ...(payload === undefined ? {} : { payload: payload as never }) })+ return { status: response.statusCode, body: response.json() as { data: any; error?: { code: string; message: string } }, headers: response.headers }+}+const iso = (at: number) => new Date(at).toISOString()+const reminderUrl = (tabId: string, conversationId: string, messageId: string, query = '') =>+ `/api/super-tabs/${tabId}/conversations/${conversationId}/messages/${messageId}/reminder${query}`+const set = (tabId: string, conversationId: string, messageId: string, at: number | string, as: AuthUser = owner, query = '') =>+ call('POST', reminderUrl(tabId, conversationId, messageId, query), as, { at: typeof at === 'number' ? iso(at) : at })+const clear = (tabId: string, conversationId: string, messageId: string, as: AuthUser = owner, query = '') =>+ // Desktop reaches the backend through the daemon, which forwards only GET and POST: a clear is a POST of no time.+ call('POST', reminderUrl(tabId, conversationId, messageId, query), as, { at: null })+const list = (tabId: string, as: AuthUser = owner, query = '') => call('GET', `/api/super-tabs/${tabId}/reminders${query}`, as)+const due = async (tabId: string, as: AuthUser = owner) => {+ const answer = await list(tabId, as)+ expect(answer.status).toBe(200)+ return answer.body.data as { due: any[]; next: string | null }+}+const derived = async (tabId: string, as: AuthUser = owner, query = '') => (await call('GET', `/api/super-tabs/${tabId}/parts${query}`, as)).body.data.derived++describe('Reminders: a message brought back to its person at a time', () => {+ it('a due reminder shows in Activity once: not before its time, then once, with its message, author and chat', async () => {+ const s = await scene()+ const message = await send(s.tabId, s.web, 'Should a reminder clear when opened?', owner, null, s.worker)+ const at = NOW + 20 * MINUTE+ const stored = await set(s.tabId, s.web, message, at)+ expect(stored).toMatchObject({ status: 200, body: { data: { id: expect.any(String), dueAt: iso(at) } } })+ // Not before its time: the list is empty and says when the next one is due, so the client wakes then.+ expect(await due(s.tabId)).toEqual({ due: [], next: iso(at) })+ clock = at - 1+ expect((await due(s.tabId)).due).toEqual([])+ clock = at+ const item = { id: stored.body.data.id, conversationId: s.web, conversationTitle: 'Web', projectName: expect.any(String), messageId: message,+ messageSequence: expect.any(Number), threadId: null, author: { kind: 'agent', id: s.worker, name: 'worker-harness' },+ text: 'Should a reminder clear when opened?', dueAt: iso(at) }+ expect(await due(s.tabId)).toEqual({ due: [item], next: null })+ // Two reads, also racing, give the same one row.+ const [first, second] = await Promise.all([due(s.tabId), due(s.tabId)])+ expect(first).toEqual({ due: [item], next: null })+ expect(second).toEqual(first)+ })++ it('names the thread of a reply that lives only there, and the person who wrote it, newest due first', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Owner root')+ const reply = await send(s.tabId, s.web, 'Peer answers in the thread', peer, root)+ await run(s.tabId, { type: 'member.name', name: 'Peer Person' }, peer)+ await set(s.tabId, s.web, root, NOW + 10 * MINUTE)+ await set(s.tabId, s.web, reply, NOW + 20 * MINUTE)+ clock = NOW + 30 * MINUTE+ const listed = (await due(s.tabId)).due+ expect(listed.map(i => [i.messageId, i.threadId, i.author.kind, i.author.name])).toEqual([[reply, root, 'person', 'Peer Person'], [root, null, 'person', expect.any(String)]])+ })++ it('replaces the time when set again, removes it when cleared, and moves the digest on each', async () => {+ const s = await scene()+ const message = await send(s.tabId, s.web, 'Remind me')+ const empty = (await derived(s.tabId)).remindersDigest+ expect(typeof empty).toBe('string')+ await set(s.tabId, s.web, message, NOW + 60 * MINUTE)+ const once = (await derived(s.tabId)).remindersDigest+ expect(once).not.toBe(empty)+ expect((await set(s.tabId, s.web, message, NOW + 120 * MINUTE)).body.data.dueAt).toBe(iso(NOW + 120 * MINUTE))+ const again = (await derived(s.tabId)).remindersDigest+ expect(again).not.toBe(once)+ expect(await db.superTabReminder.count({ where: { tabId: s.tabId } })).toBe(1)+ expect(await due(s.tabId)).toEqual({ due: [], next: iso(NOW + 120 * MINUTE) })+ // Another person's digest, and an agent's read, never move with it: an agent has none.+ expect((await derived(s.tabId, peer)).remindersDigest).toBe(empty)+ expect((await derived(s.tabId, owner, `?asAgentId=${s.worker}`)).remindersDigest).toBeUndefined()+ expect((await clear(s.tabId, s.web, message)).body.data).toEqual({ cleared: true })+ expect((await derived(s.tabId)).remindersDigest).toBe(empty)+ expect(await due(s.tabId)).toEqual({ due: [], next: null })+ expect((await clear(s.tabId, s.web, message)).body.data).toEqual({ cleared: false })+ })++ it('refuses a time that is not in the future or more than 30 days ahead', async () => {+ const s = await scene()+ const message = await send(s.tabId, s.web, 'Remind me')+ for (const at of [NOW, NOW - MINUTE, NOW + 30 * DAY + 1]) {+ const refused = await set(s.tabId, s.web, message, at)+ expect(refused.status, iso(at)).toBe(400)+ expect(refused.body.error?.code).toBe('INVALID_REMINDER')+ }+ expect((await set(s.tabId, s.web, message, 'tomorrow')).status).toBe(400)+ expect((await set(s.tabId, s.web, message, NOW + 30 * DAY)).status).toBe(200)+ })++ it('is the person\'s alone: another member, an agent and a Team session never read, set or clear it', async () => {+ const s = await scene()+ const message = await send(s.tabId, s.web, 'Owner asks')+ await set(s.tabId, s.web, message, NOW + 20 * MINUTE)+ clock = NOW + 20 * MINUTE+ expect(await due(s.tabId, peer)).toEqual({ due: [], next: null })+ expect((await clear(s.tabId, s.web, message, peer)).body.data).toEqual({ cleared: false })+ for (const answer of [await list(s.tabId, ownerTeam), await set(s.tabId, s.web, message, NOW + 40 * MINUTE, ownerTeam), await clear(s.tabId, s.web, message, ownerTeam)]) {+ expect(answer.status).toBe(403)+ }+ for (const answer of [await list(s.tabId, owner, `?asAgentId=${s.worker}`), await set(s.tabId, s.web, message, NOW + 40 * MINUTE, owner, `?asAgentId=${s.worker}`),+ await clear(s.tabId, s.web, message, owner, `?asAgentId=${s.worker}`)]) {+ expect(answer.status).toBe(400)+ }+ expect((await due(s.tabId)).due.map(i => [i.messageId, i.dueAt])).toEqual([[message, iso(NOW + 20 * MINUTE)]])+ })++ it('refuses a message the person cannot read, one of another chat and one that does not exist alike, storing nothing', async () => {+ const s = await scene()+ const secret = await send(s.tabId, s.secretGroup, 'Secret question')+ const open = await send(s.tabId, s.web, 'Open question')+ // A notice for agents alone is never shown to a person (read/inbox.ts readable).+ const notice = `${s.tabId}-notice`+ await db.superTabMessage.create({ data: { id: notice, tabId: s.tabId, conversationId: s.web, sequence: 999, text: 'For the Lead',+ author: { kind: 'agent', id: s.worker, name: 'worker-harness', membershipGeneration: 'g' }, recipientIds: [s.worker], mentions: [], source: { kind: 'agent-only' } } })+ const later = NOW + 20 * MINUTE+ const refusals = [await set(s.tabId, s.secretGroup, secret, later, outsider), await set(s.tabId, s.secretGroup, open, later),+ await set(s.tabId, s.web, `${s.tabId}-missing`, later), await set(s.tabId, s.web, notice, later), await set(s.tabId, 'no-such-group', open, later, outsider)]+ expect(refusals.map(r => r.status)).toEqual([404, 404, 404, 404, 404])+ expect(new Set(refusals.map(r => JSON.stringify(r.body))).size).toBe(1)+ expect((await clear(s.tabId, s.secretGroup, secret, outsider)).status).toBe(404)+ expect(await db.superTabReminder.count({ where: { tabId: s.tabId } })).toBe(0)+ })++ it('drops a reminder of a message the person can no longer read, and lists it again only with access', async () => {+ const s = await scene()+ const message = await send(s.tabId, s.openChat, 'Owner asks in Open')+ await set(s.tabId, s.openChat, message, NOW + 20 * MINUTE, peer)+ clock = NOW + 20 * MINUTE+ expect((await due(s.tabId, peer)).due.map(i => i.messageId)).toEqual([message])+ // The owner makes the project private to themselves: peer can no longer read the chat, and the reminder says nothing.+ await run(s.tabId, { type: 'project.sharing', projectId: s.open, visibility: 'private', memberIds: [] })+ const answer = await list(s.tabId, peer)+ expect(answer.body.data).toEqual({ due: [], next: null })+ expect(JSON.stringify(answer.body)).not.toContain('Open')+ await run(s.tabId, { type: 'project.sharing', projectId: s.open, visibility: 'public', memberIds: [] })+ expect((await due(s.tabId, peer)).due.map(i => i.messageId)).toEqual([message])+ })++ it(`refuses one more than ${REMINDER_CAP} pending reminders per person and Swarm, but lets one be set again`, async () => {+ const s = await scene()+ const [kept, more] = [await send(s.tabId, s.web, 'Kept'), await send(s.tabId, s.web, 'One too many')]+ const row = (messageId: string, n: number) => ({ id: stableId(s.tabId, owner.sub, messageId), tabId: s.tabId, personId: owner.sub, conversationId: s.web,+ messageId, dueAt: new Date(NOW + (n + 1) * MINUTE), createdAt: new Date(NOW) })+ await db.superTabReminder.createMany({ data: [row(kept, 0), ...Array.from({ length: REMINDER_CAP - 1 }, (_, n) => row(`${s.tabId}-other-${n}`, n + 1))] })+ const refused = await set(s.tabId, s.web, more, NOW + 5 * MINUTE)+ expect(refused.status).toBe(409)+ expect(refused.body.error?.code).toBe('REMINDER_LIMIT')+ expect((await set(s.tabId, s.web, kept, NOW + 5 * MINUTE)).status).toBe(200)+ // Another person's reminders count apart.+ expect((await set(s.tabId, s.web, more, NOW + 5 * MINUTE, peer)).status).toBe(200)+ expect(await db.superTabReminder.count({ where: { tabId: s.tabId, personId: owner.sub } })).toBe(REMINDER_CAP)+ })++ it('sweeps reminders due more than 30 days ago, keeping later ones', async () => {+ const s = await scene()+ const [old, soon] = [await send(s.tabId, s.web, 'Old'), await send(s.tabId, s.web, 'Soon')]+ await set(s.tabId, s.web, old, NOW + MINUTE)+ await set(s.tabId, s.web, soon, NOW + 2 * DAY)+ // The sweep is every Swarm's: this one's rows are what is checked.+ await sweepReminders(db, NOW + 2 * MINUTE)+ expect(await db.superTabReminder.count({ where: { tabId: s.tabId } })).toBe(2)+ expect(await sweepReminders(db, NOW + MINUTE + REMINDER_EXPIRY_MS + 1)).toBeGreaterThanOrEqual(1)+ expect((await db.superTabReminder.findMany({ where: { tabId: s.tabId }, select: { messageId: true } })).map(r => r.messageId)).toEqual([soon])+ })++ it('is read at most REMINDER_READS times per window by one person', async () => {+ const s = await scene()+ for (let i = 0; i < REMINDER_READS; i++) expect((await list(s.tabId)).status).toBe(200)+ const refused = await list(s.tabId)+ expect(refused.status).toBe(429)+ expect(Number(refused.headers['retry-after'])).toBeGreaterThan(0)+ })++ it('reads the person\'s reminders by (tabId, personId, dueAt), and the sweep by dueAt, each on its index', async () => {+ const s = await scene()+ const [first, second] = [await send(s.tabId, s.web, 'First'), await send(s.tabId, s.web, 'Second')]+ await set(s.tabId, s.web, first, NOW + MINUTE)+ await set(s.tabId, s.web, second, NOW + 2 * DAY)+ clock = NOW + 10 * MINUTE+ await listNamedIndexes(db)+ const entries = await profiled(db, async () => {+ await due(s.tabId)+ await derived(s.tabId)+ await set(s.tabId, s.web, first, NOW + 20 * MINUTE)+ await sweepReminders(db, clock)+ })+ const person = reads(entries, 'SuperTabReminder', ['personId'])+ // The due list, the next one, the digest and the cap's count (an index-only COUNT_SCAN).+ expect(person.length, JSON.stringify(plan(person))).toBeGreaterThanOrEqual(4)+ for (const entry of person) {+ expect(entry.planSummary, JSON.stringify(plan([entry]))).toMatch(/^(IXSCAN|COUNT_SCAN) \{ tabId: 1, personId: 1, dueAt: 1 \}/)+ expect(entry.docsExamined ?? 0, JSON.stringify(plan([entry]))).toBeLessThanOrEqual(2)+ }+ const sweep = reads(entries, 'SuperTabReminder', ['dueAt'], ['personId'])+ expect(sweep.length).toBeGreaterThanOrEqual(1)+ for (const entry of sweep) expect(entry.planSummary, JSON.stringify(plan([entry]))).toMatch(/^IXSCAN \{ dueAt: 1 \}/)+ })+})diff --git a/backend/integration/superTabRequestReads.test.ts b/backend/integration/superTabRequestReads.test.tsnew file mode 100644index 000000000..d8203b468--- /dev/null+++ b/backend/integration/superTabRequestReads.test.ts@@ -0,0 +1,196 @@+/**+ * What three per-request reads cost (task #2674, Ken's prod scan of 2026-11-04 12:00 VN): the decisions list, the leaderboard+ * and the mentions list. Each answers exactly what a read straight from Mongo answers (a store without the read cache), and+ * reads only what changed since its Swarm's last stamp.+ */+import { randomUUID } from 'node:crypto'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import type { PrismaClient } from '@prisma/client'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { SuperTabStore } from '../src/superTabs/store.js'+import { migrateSwarm } from '../src/superTabs/migration/migrate.js'+import * as parts from '../src/superTabs/parts/index.js'+import { swarmTransaction } from '../src/superTabs/cache.js'+import { guardedWrite } from '../src/superTabs/parts/write.js'+import { SwarmReads } from '../src/superTabs/read/service.js'+import { stableId, type Author, type Conversation, type SuperTabState } from '../src/superTabs/model.js'+import type { DecisionList } from '../src/superTabs/decisions.js'+import { WEEK_MS, weekStart } from '../src/superTabs/leaderboard/week.js'+import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'+import { NOW, owner as ownerActor, peer as peerActor, swarm } from '../src/superTabs/read/fixture.test-support.js'+import { filterOf, planDatabase, profiled } from './plans.test-support.js'+import { profiledReads } from './profiledReads.test-support.js'++let replica: MongoMemoryReplSet+let db: PrismaClient+let cached: SuperTabStore, direct: SuperTabStore+let cachedReads: SwarmReads, directReads: SwarmReads+const user = (actor: { userId: string; email: string }): AuthUser => ({ sub: actor.userId, email: actor.email, autonomousEnv: 'prod', role: 'user' })+const [owner, peer] = [ownerActor, peerActor].map(user) as [AuthUser, AuthUser]+const WEEK = weekStart(NOW), HOUR = 3_600_000, DAY = 86_400_000+const PR = 'https://github.com/o/r/pull/9'++beforeAll(async () => {+ ({ replica, db } = await planDatabase('swarm_request_reads'))+ for (const each of [owner, peer]) await db.user.create({ data: { id: each.sub, externalId: `fixture-${each.sub}`, email: each.email, autonomousEnv: 'prod' } })+ // The read cache is on in these suites (cacheOn.test-support.ts); `direct` reads Mongo every time, as the answers to match.+ cached = new SuperTabStore(db, () => NOW)+ direct = new SuperTabStore(db, () => NOW, null, { readCache: null })+ cachedReads = new SwarmReads(cached, { now: () => NOW })+ directReads = new SwarmReads(direct, { now: () => NOW })+})+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})++/** The Swarm part collections' reads MongoDB served while `run` ran, by collection. */+const partReads = <T>(run: () => Promise<T>) => profiledReads(db, /\.Swarm(Head|Member|Agent|Group|Machine|Start|Progress)$/, run)++/** A Swarm in parts: requests of peer's shipped this week and two weeks ago (dormant since), a third shipped last week and+ * still active, a worker waiting on the owner, the owner's open and answered decisions (one in the dormant chat) and three+ * tags of the owner's, one a reply in a thread. */+async function scene() {+ const s = swarm(NOW)+ s.join(peerActor)+ const lead = s.add('lead-harness', 'lead', true)+ const fresh = s.group('Fresh'), old = s.group('Old'), lastWeek = s.group('Last week'), waiting = s.group('Waiting')+ const worker = s.add('worker-harness', waiting)+ s.run({ type: 'work.assign', conversationId: waiting, agentId: worker })+ s.edit(state => {+ const done = { id: 'done', agentId: worker, status: 'done' as const, result: PR, configuration: state.agents[0]!.configuration,+ execution: { machineId: 'host', harnessId: 'h', machineOwnerId: owner.sub } }+ const ship = (id: string, shippedAt: number) => Object.assign(state.conversations.find(c => c.id === id)!,+ { requesterId: peer.sub, assignment: done, pullRequestUrls: [PR], ledger: { askedAt: shippedAt - 2 * HOUR, shippedAt } })+ ship(fresh, NOW - HOUR)+ ship(old, WEEK - WEEK_MS - DAY)+ ship(lastWeek, WEEK - 2 * DAY)+ Object.assign(state.conversations.find(c => c.id === old)!, { dormant: true, lastActivityAt: new Date(WEEK - WEEK_MS - DAY).toISOString() })+ })+ const tabId = `tab-${randomUUID()}`+ await writeLegacySwarm(db, { state: { ...structuredClone(s.state), id: tabId } as SuperTabState, revision: 50 })+ const report = await migrateSwarm(db, tabId, { now: () => NOW - 60_000 })+ if (!report.ok) throw new Error(report.error)+ const decision = (id: string, conversationId: string, answered: boolean) => db.superTabDecision.create({ data: { id: `${tabId}-${id}`, tabId,+ batchId: `${tabId}-batch-${id}`, projectId: 'lead', conversationId, assignmentId: null, personId: owner.sub, askerAgentId: worker,+ question: `Question ${id}?`, options: ['Yes', 'No'], recommended: 0, unblocks: 'the work', createdAt: new Date(NOW - DAY),+ ...answered ? { answeredAt: new Date(NOW - HOUR), choice: 1 } : {} } })+ await decision('open', waiting, false)+ await decision('quiet', old, false)+ await decision('answered', waiting, true)+ const agent: Author = { kind: 'agent', id: worker, name: 'Worker', membershipGeneration: 'fixture' }+ const root = await say(tabId, waiting, agent, [owner])+ await say(tabId, waiting, agent, [owner], root)+ await say(tabId, fresh, agent, [owner])+ return { tabId, lead, worker, fresh, old, lastWeek, waiting }+}++/** Stores a message tagging `tags` as the store stores one (numbered after the chat's newest), with its tags; answers its id. */+async function say(tabId: string, conversationId: string, author: Author, tags: AuthUser[], thread?: string) {+ const id = `m-${randomUUID()}`+ await swarmTransaction(db, async tx => {+ const current = (await parts.loadActive(tx, tabId, { groupIds: [conversationId] })).groups.find(g => g.key === conversationId)!+ const data = structuredClone(current.data!) as Conversation+ const sequence = (data.messageSeq ?? 0) + 1+ data.messageSeq = data.lastMessageSequence = sequence+ if (!thread) data.lastMainSequence = sequence+ await tx.superTabMessage.create({ data: { id, tabId, conversationId, sequence, author: author as never, text: `Please look ${sequence}.`,+ thread: thread ?? id, recipientIds: [], mentions: tags.map(t => t.sub), createdAt: new Date(NOW - sequence * 60_000) } })+ await guardedWrite(tx, tabId, { op: 'update', kind: 'group', key: conversationId, seen: current.version, data }, Date.now())+ for (const tagged of tags) {+ await tx.superTabMention.create({ data: { id: stableId(tabId, id, tagged.sub), tabId, personId: tagged.sub, projectId: 'lead', conversationId,+ messageId: id, authorAgentId: author.id, createdAt: new Date(NOW - sequence * 60_000), resolvedAt: null, resolvedBy: null } })+ }+ })+ return id+}++/** Changes one conversation's stored data as a command would, in a transaction that moves the Swarm's stamp. */+async function edit(tabId: string, conversationId: string, change: (group: Conversation) => void) {+ await swarmTransaction(db, async tx => {+ const [row] = await parts.loadGroups(tx, tabId, 'key', { key: conversationId })+ const data = structuredClone(row!.data!) as Conversation+ change(data)+ await guardedWrite(tx, tabId, { op: 'update', kind: 'group', key: conversationId, seen: row!.version, data }, Date.now())+ })+}++describe('the decisions list (GET /decisions)', () => {+ it('reads no Swarm part again at an unchanged stamp, and answers as a read straight from Mongo', async () => {+ const s = await scene()+ for (const list of ['open', 'answered', 'settled'] as DecisionList[]) {+ const first = await cached.decisions(owner, s.tabId, list)+ expect(first, list).toEqual(await direct.decisions(owner, s.tabId, list))+ const again = await partReads(() => cached.decisions(owner, s.tabId, list))+ expect(again.value, list).toEqual(first)+ // Only the quiet conversation a decision names, by its key; never the members, agents, machines, starts or active groups.+ expect(Object.keys(again.byCollection).filter(c => c !== 'SwarmGroup'), list).toEqual([])+ expect(again.byCollection.SwarmGroup ?? 0, list).toBeLessThanOrEqual(1)+ }+ // The quiet chat's decision is read by its key and checked like any; this fixture's reader does not get it, read either way.+ expect((await cached.decisions(owner, s.tabId, 'open')).decisions.map(d => d.question)).toEqual(['Question open?'])+ expect((await cached.decisions(owner, s.tabId, 'answered')).decisions.map(d => d.question)).toEqual(['Question answered?'])+ })++ it('answers as a direct read after the Swarm changes', async () => {+ const s = await scene()+ await cached.decisions(owner, s.tabId, 'open')+ await edit(s.tabId, s.waiting, group => { group.title = 'Waiting, renamed' })+ expect(await cached.decisions(owner, s.tabId, 'open')).toEqual(await direct.decisions(owner, s.tabId, 'open'))+ expect((await cached.decisions(owner, s.tabId, 'open')).decisions.map(d => d.conversationTitle)).toContain('Waiting, renamed')+ })+})++describe('the leaderboard (GET /leaderboard)', () => {+ const boards = (s: { tabId: string }, reads: SwarmReads) => Promise.all([+ reads.leaderboard(owner, s.tabId, 'lead'),+ reads.leaderboard(owner, s.tabId, 'lead', WEEK - WEEK_MS),+ reads.leaderboard(owner, s.tabId, 'lead', WEEK - 2 * WEEK_MS),+ reads.leaderboard(owner, s.tabId, 'lead', undefined, undefined, true),+ ])++ it('reads no dormant group again at an unchanged stamp, and answers as a read straight from Mongo', async () => {+ const s = await scene()+ const first = await boards(s, cachedReads)+ expect(first).toEqual(await boards(s, directReads))+ const again = await partReads(() => cachedReads.leaderboard(owner, s.tabId, 'lead', WEEK - 2 * WEEK_MS))+ expect(again.value).toEqual(first[2])+ expect(again.byCollection.SwarmGroup ?? 0).toBe(0)+ })++ it('answers as a direct read after a conversation goes quiet, wakes, gets newer activity or is removed', async () => {+ const s = await scene()+ await boards(s, cachedReads)+ const same = async (what: string) => expect(await boards(s, cachedReads), what).toEqual(await boards(s, directReads))+ await edit(s.tabId, s.lastWeek, group => Object.assign(group, { dormant: true, lastActivityAt: new Date(WEEK - 2 * DAY).toISOString() }))+ await same('last week\'s request went quiet')+ await edit(s.tabId, s.old, group => { group.lastActivityAt = new Date(WEEK - DAY).toISOString() })+ await same('a quiet one got newer activity')+ await edit(s.tabId, s.old, group => { delete group.dormant })+ await same('a quiet one woke')+ await swarmTransaction(db, async tx => {+ const [row] = await parts.loadGroups(tx, s.tabId, 'key', { key: s.lastWeek })+ await guardedWrite(tx, s.tabId, { op: 'remove', kind: 'group', key: s.lastWeek, seen: row!.version, data: row!.data }, Date.now())+ })+ await same('a quiet one was removed')+ })+})++describe('the mentions list (GET /mentions)', () => {+ it('reads the tagged messages by one plain $in on their ids, through the id index, and answers as before', async () => {+ const s = await scene()+ const expected = await direct.mentions(owner, s.tabId, 'waiting')+ expect(expected.mentions).toHaveLength(3)+ let answer: Awaited<ReturnType<SuperTabStore['mentions']>> | undefined+ const entries = await profiled(db, async () => { answer = await cached.mentions(owner, s.tabId, 'waiting') })+ expect(answer).toEqual(expected)+ // The tagged messages' read: Prisma's `id: { in }` went as an `$expr` OR of one branch per id (slow planning on prod).+ const byId = entries.filter(e => e.ns.endsWith('.SuperTabMessage') && JSON.stringify(filterOf(e)).includes(expected.mentions[0]!.messageId))+ expect(byId).toHaveLength(1)+ const filter = JSON.stringify(filterOf(byId[0]!))+ expect(filter).not.toMatch(/\$expr|\$or/)+ expect(filter).toMatch(/"_id":\{"\$in":/)+ expect(byId[0]!.planSummary).toMatch(/^IXSCAN/)+ })+})diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex b0d24b280..165dad2cd 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -2844,7 +2844,16 @@ describe('Super Tab chat attachments', () => {const old = (n: number, size = 1) => db.superTabAttachment.createMany({ data: Array.from({ length: n }, () => ({ id: randomUUID().replaceAll('-', '').slice(0, 24),tabId: tab, conversationId: 'lead', actorKey: `person:${owner.sub}`, name: 'x', mime: 'text/plain', size, objectKey: 'x' })) })await old(190)- const answers = await Promise.all(Array.from({ length: 60 }, () => linkFor(tab, { size: 11 })))+ // 60 at once all write the sender's one allowance row, so a few may run out of the server's 8 tries and get the 503+ // SWARM_BUSY every client retries (superTabs/retry.ts). Retry it here as clients do: the limits must hold either way.+ // It failed CI twice on 11-04 (#2888, #2926) when the test counted that answer as a failure.+ const linkAsClients = async () => {+ for (let tries = 1; ; tries++) {+ const answer = await linkFor(tab, { size: 11 })+ if (answer.status !== 503 || answer.code !== 'SWARM_BUSY' || tries === 5) return answer+ }+ }+ const answers = await Promise.all(Array.from({ length: 60 }, linkAsClients))expect(answers.filter(a => a.status === 200)).toHaveLength(10)expect(answers.filter(a => a.status === 429).every(a => a.code === 'RATE_LIMITED')).toBe(true)expect(answers.filter(a => a.status !== 200 && a.status !== 429)).toEqual([])diff --git a/backend/integration/workerIndexPlans.test.ts b/backend/integration/workerIndexPlans.test.tsindex cac2148da..f5de8a5c0 100644--- a/backend/integration/workerIndexPlans.test.ts+++ b/backend/integration/workerIndexPlans.test.ts@@ -264,3 +264,33 @@ describe('the pull request watch', () => {expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(3)})})++describe('the hourly unused-upload sweep', () => {+ // Ken's prod scan of 11-04 (#2676): Performance Advisor suggested an index for it. The sweep's claim reads uploads by+ // `usedBy` and `proposedBy` (both null), `purpose` and age; its remove step reads the uploads it took by `usedBy` alone.+ // One index starting with `usedBy` bounds both; a used upload, the most of them, is never examined.+ it('reads only the unused day-old uploads, and then only the ones it took, by the usedBy index', async () => {+ const { sweepUnsentAttachments } = await import('../src/lib/attachmentSweep.js')+ const upload = (createdAt: number, fields: Record<string, unknown> = {}) => ({ id: randomUUID(), tabId: 'tab-u', conversationId: 'c', actorKey: 'a',+ name: 'f.png', mime: 'image/png', size: 1, objectKey: `k-${randomUUID()}`, createdAt: new Date(createdAt), ...fields })+ await db.superTabAttachment.createMany({ data: [+ // Sent files, a week old: a read not bounded by `usedBy` examines them all.+ ...Array.from({ length: 20 }, () => upload(NOW - 7 * DAY, { usedBy: `message-${randomUUID()}` })),+ upload(NOW - 7 * DAY, { proposedBy: 'proposal-1' }), upload(NOW - 60_000),+ upload(NOW - 2 * DAY), upload(NOW - 3 * DAY),+ ] })+ const deleted: string[] = []+ const store = { delete: async (key: string) => { deleted.push(key) } }+ const entries = await profiled(db, () => sweepUnsentAttachments(db, { store } as never, new Date(NOW), { chunk: 100, chunks: 1, pauseMs: 0 }))+ expect(deleted).toHaveLength(2)+ const claims = reads(entries, 'SuperTabAttachment', ['usedBy', 'proposedBy', 'createdAt']).filter(e => e.op === 'query')+ expect(claims, JSON.stringify(plan(claims))).toHaveLength(1)+ expect(claims[0]!.nreturned).toBe(2)+ expect(claims[0]!.docsExamined, JSON.stringify(plan(claims))).toBeLessThanOrEqual(2)+ expect(claims[0]!.planSummary, JSON.stringify(plan(claims))).toMatch(/IXSCAN \{ usedBy: 1, proposedBy: 1, purpose: 1, createdAt: 1/)+ const taken = reads(entries, 'SuperTabAttachment', ['usedBy'], ['proposedBy']).filter(e => e.op === 'query')+ expect(taken, JSON.stringify(plan(taken))).toHaveLength(1)+ expect(taken[0]!.docsExamined, JSON.stringify(plan(taken))).toBeLessThanOrEqual(2)+ expect(taken[0]!.planSummary, JSON.stringify(plan(taken))).toMatch(/IXSCAN \{ usedBy: 1/)+ })+})diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex efd6f3a14..544795ab0 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1232,12 +1232,35 @@ model SuperTabReadMark {conversationId Stringsequence IntupdatedAt DateTime+ /// When the person's Mark unread moved the mark back (readMarks.ts lowerReadMark); set with updatedAt in that write and+ /// cleared by a read that raises it, so the mark's last move was a Mark unread while the two are equal. Unset otherwise.+ loweredAt DateTime?@@index([tabId, personId, updatedAt])/// A mark untouched this long goes (superTabs/readMarks.ts ensureReadMarkExpiry). Declared so db push keeps the index.@@index([updatedAt], map: "read_mark_expiry")}+/// A person's reminder of one message (superTabs/reminders.ts): bring it back to them at `dueAt`, in Activity's Reminders. Their+/// own, never shown to others. One row per person and message: setting it again replaces its time, and opening it deletes it.+/// At most REMINDER_CAP pending per person and Swarm; the worker's hourly sweep deletes those due more than REMINDER_EXPIRY_MS+/// (30 days) ago, and a Swarm's purge its rows.+model SuperTabReminder {+ /// stableId(tabId, personId, messageId).+ id String @id @map("_id")+ tabId String+ personId String+ conversationId String+ messageId String+ dueAt DateTime+ createdAt DateTime++ /// A person's reminders: the due list, the next one after now, the digest and the cap's count (parts/indexed.ts NAMED_INDEX).+ @@index([tabId, personId, dueAt])+ /// The sweep's reminders due more than 30 days ago (reminders.ts sweepReminders); no TTL option, which the app user cannot set.+ @@index([dueAt])+}+/// How far a person has read one thread: the newest reply sequence they saw there (superTabs/readMarks.ts). Apart from/// SuperTabReadMark so a backend without thread marks never reads one as a conversation's mark. At most THREAD_MARK_CAP per/// person and Swarm; the worker's hourly sweep deletes those untouched for 180 days and those of Swarms and people gone.@@ -1352,6 +1375,11 @@ model SuperTabAttachment {@@index([tabId, actorKey, createdAt])/// Unfinished uploads by age, for the pending-upload sweep (lib/pendingUploadSweep.ts).@@index([purpose, createdAt])+ /// Unused uploads by age, for the hourly unused-upload sweep (lib/attachmentSweep.ts): its claim (usedBy and proposedBy+ /// null, purpose, createdAt) and its remove step (usedBy alone). Performance Advisor's suggestion of 11-04 with its first+ /// two keys swapped, so the remove step's read is bounded too (#2676). Built by the backend release's schema push: a+ /// production write that needs Ken's go.+ @@index([usedBy, proposedBy, purpose, createdAt])}/// One per sender per Swarm while it asks for upload links (superTabs/store.ts uploadLink): each link request writes it in the@@ -1916,6 +1944,9 @@ model SwarmMachine {/// The last write of its own reading alone (a report every 15 s): readers of changes see it, while `changedAt`, and so the/// Swarm's newest change, stays at the last change of anything else (Stability Roadmap 2.2).readAt DateTime?+ /// The last reading that changed more than its volatile fields (parts/commit.ts machineContentChanged): a client that asks gets+ /// a line for any other reading, not the part (read/changes.ts). Overwritten in place, and gone with its row. Absent before 2026-11-04.+ contentAt DateTime?@@unique([tabId, key])@@index([tabId, changedAt])diff --git a/backend/src/lib/accountName.test.ts b/backend/src/lib/accountName.test.tsnew file mode 100644index 000000000..58983dbbd--- /dev/null+++ b/backend/src/lib/accountName.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it } from 'vitest'+import { MAX_ACCOUNT_NAME_LENGTH, parseAccountName } from './accountName.js'++describe('an account name a person sets for themselves', () => {+ it('is trimmed, with one space between words', () => {+ expect(parseAccountName(' Elvis ')).toEqual({ ok: true, name: 'Elvis' })+ expect(parseAccountName('Minh\t Nguyen')).toEqual({ ok: true, name: 'Minh Nguyen' })+ expect(parseAccountName('Lê Huy')).toEqual({ ok: true, name: 'Lê Huy' })+ })++ it('is stored in one form, so the same letters are the same name', () => {+ expect(parseAccountName('Lê')).toEqual({ ok: true, name: 'Lê' })+ })++ it('is refused when empty or not words', () => {+ for (const input of ['', ' ', '\t', 42, null, undefined, ['Elvis'], { name: 'Elvis' }]) {+ expect(parseAccountName(input), JSON.stringify(input)).toMatchObject({ ok: false })+ }+ })++ it('is refused with a hidden, control or line-breaking character', () => {+ for (const input of ['ab', 'ab', 'ab', 'a\nb', 'a\rb', 'a\u0007b', 'a b', 'a b', 'Elvis']) {+ expect(parseAccountName(input), JSON.stringify(input)).toMatchObject({ ok: false })+ }+ })++ it('takes up to 60 characters, counted as people see them', () => {+ expect(MAX_ACCOUNT_NAME_LENGTH).toBe(60)+ expect(parseAccountName('😀'.repeat(60))).toEqual({ ok: true, name: '😀'.repeat(60) })+ expect(parseAccountName('😀'.repeat(61))).toMatchObject({ ok: false })+ expect(parseAccountName('a'.repeat(60))).toEqual({ ok: true, name: 'a'.repeat(60) })+ expect(parseAccountName('a'.repeat(61))).toMatchObject({ ok: false })+ })++ // Outside a Swarm the account name meets no clash check (store reviews, community comments, shares, terminal observers),+ // so it keeps the Swarm name's own refusals (superTabs/personNames.ts nameRefusal): review 1 of #2917.+ it('is refused as a web address, which would show as a link', () => {+ for (const input of ['https://ev.il', 'see http://x.y', 'www.example.com', 'WWW.example.com']) {+ expect(parseAccountName(input), input).toEqual({ ok: false, code: 'INVALID_NAME', message: 'Use a name, not a web address.' })+ }+ })++ it('is refused as a role\'s or the Swarm\'s own name, numbered or in wide letters too', () => {+ for (const input of ['Product Manager', 'PM', 'Lead', 'Lead 2', 'Engineer', 'Reviewer', 'Harness', 'admin', 'System-3', 'Harness', 'Someone', 'you']) {+ expect(parseAccountName(input), input).toEqual({ ok: false, code: 'NAME_RESERVED', message: `${input} is a role's name. Choose another.` })+ }+ })++ // Shares, the leaderboard and community comments show the name alone where people tell each other apart by email, so an+ // email-shaped name could pose as another person: review 2 of #2917.+ it('is refused with an @, so it never reads as someone\'s email', () => {+ for (const input of ['[email protected]', 'Ken @ Autonomous', '@ken', 'ken\uFF20autonomous.ai']) {+ expect(parseAccountName(input), input).toEqual({ ok: false, code: 'INVALID_NAME', message: 'Use a name, not an email address.' })+ }+ })++ it('still takes a name that only contains a role\'s word', () => {+ expect(parseAccountName('Lead Singer Elvis')).toEqual({ ok: true, name: 'Lead Singer Elvis' })+ expect(parseAccountName('Harnessa')).toEqual({ ok: true, name: 'Harnessa' })+ })+})diff --git a/backend/src/lib/accountName.ts b/backend/src/lib/accountName.tsnew file mode 100644index 000000000..15f41b0ab--- /dev/null+++ b/backend/src/lib/accountName.ts@@ -0,0 +1,36 @@+import { nameRefusal } from '../superTabs/personNames.js'+import { printable } from '../superTabs/profile.js'++/** Characters, not UTF-16 units: a name in any script, or with an emoji, gets the same room. */+export const MAX_ACCOUNT_NAME_LENGTH = 60++export const INVALID_ACCOUNT_NAME_MESSAGE = `Use 1 to ${MAX_ACCOUNT_NAME_LENGTH} characters, with no hidden ones.`++export type AccountNameRefusal = { ok: false; code: 'INVALID_NAME' | 'NAME_RESERVED'; message: string }++/**+ * The account name a person sets for themselves (`PATCH /api/auth/me`, task #2654): one form (NFC), trimmed, with one+ * space between words; 1 to 60 characters, none of them a control, format (zero-width, bidi), line or paragraph+ * separator, which would hide the name's real shape where it is shown.+ *+ * Outside a Swarm the account name meets no clash check (store reviews, community comments, machine and harness shares,+ * terminal observers), so it also takes the Swarm name's refusals (superTabs/personNames.ts nameRefusal: no web address,+ * no role's or the Swarm's own name; review 1 of #2917), and no `@`: those places show the name alone where people tell+ * each other apart by email, so an email-shaped name could pose as someone else (review 2 of #2917).+ */+export function parseAccountName(input: unknown): { ok: true; name: string } | AccountNameRefusal {+ const invalid: AccountNameRefusal = { ok: false, code: 'INVALID_NAME', message: INVALID_ACCOUNT_NAME_MESSAGE }+ if (typeof input !== 'string') return invalid+ // A tab or any space folds to one space; anything hidden is refused before trim(), which would drop a byte-order mark.+ const folded = input.normalize('NFC').replace(/[\t\p{Zs}]+/gu, ' ')+ if (!printable(folded)) return invalid+ const name = folded.trim()+ if (!name || [...name].length > MAX_ACCOUNT_NAME_LENGTH) return invalid+ // Width variants folded (NFKC), so a full-width @ is an @ too.+ if (name.normalize('NFKC').includes('@')) {+ return { ok: false, code: 'INVALID_NAME', message: 'Use a name, not an email address.' }+ }+ const refused = nameRefusal(name)+ if (refused) return { ok: false, ...refused }+ return { ok: true, name }+}diff --git a/backend/src/lib/adapterMachineWrites.test.ts b/backend/src/lib/adapterMachineWrites.test.tsnew file mode 100644index 000000000..7024a6265--- /dev/null+++ b/backend/src/lib/adapterMachineWrites.test.ts@@ -0,0 +1,143 @@+import { EventEmitter } from 'node:events'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// How many times an adapter socket writes its machine's row (Ken's prod scan of 11-04, #2676: `Machine.update` by+// machineId in background work was slow 53 times in 32 minutes). The socket's own code and dailyTracking run for real;+// Prisma, Redis and sign-in are faked, and every `machine.update` is counted.+const m = vi.hoisted(() => ({+ auth: vi.fn(), upgrade: vi.fn(),+ machineService: { resolveOrCreateForComputer: vi.fn(), resolveForTeamComputer: vi.fn() },+ machineUpdate: vi.fn(), userFindUnique: vi.fn(), nodeRole: vi.fn(), record: vi.fn(),+}))+vi.mock('./ssoAuth.js', async original => ({ ...await original<typeof import('./ssoAuth.js')>(), authenticateAccessToken: m.auth }))+vi.mock('./wsServer.js', async original => ({ ...await original<typeof import('./wsServer.js')>(), createWss: () => ({ handleUpgrade: m.upgrade }) }))+vi.mock('../services/MachineService.js', () => ({ machineService: m.machineService }))+vi.mock('./prisma.js', () => ({+ prisma: { machine: { update: m.machineUpdate }, user: { findUnique: m.userFindUnique }, swarmAgent: { aggregateRaw: vi.fn(async () => []) } },+ machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] },+}))+vi.mock('./bus.js', () => ({+ publishUp: vi.fn(async () => {}), claimMachineOwner: vi.fn(async () => true), releaseMachineOwner: vi.fn(async () => {}),+ publishDeviceE2eePair: vi.fn(), publishTerminalUp: vi.fn(), subscribeTerminalDown: vi.fn(async () => () => {}),+ setMachineAppState: vi.fn(), clearMachineAppState: vi.fn(),+}))+vi.mock('./adapterAccountPushes.js', () => ({ relayAccountPushes: vi.fn(async () => () => {}) }))+vi.mock('./deviceKeyLog.js', () => ({ appendDeviceKey: vi.fn(), touchDeviceKey: vi.fn() }))+vi.mock('./nodeRole.js', () => ({ attachNodeRole: m.nodeRole, PRESENCE_TTL_SEC: 30 }))+vi.mock('./productUsage.js', () => ({ recordRelayUsage: m.record, markActivity: vi.fn(async () => {}) }))+vi.mock('./hub.js', () => ({+ CLIENTS_FRAME: '__clients', CLIENTS_DIRTY: '__clients_dirty', LIVENESS_TICK_MS: 5_000, CLIENT_IDLE_DEADLINE_MS: 75_000,+ DEVICE_IDLE_DEADLINE_MS: 35_000, CLIENT_HEARTBEAT_MS: 25_000, deliverTerminalUpLocal: vi.fn(), deliverUpLocal: vi.fn(),+ pushDeviceRevoked: vi.fn(), sendClientsControl: vi.fn(), recomputeAndSendClients: vi.fn(), attachHubClient: vi.fn(),+ trackSocketLiveness: () => () => {},+}))++import { handleAdapterUpgrade } from './adapterWs.js'+import type { AuthUser } from './ssoAuth.js'++const COMPUTER = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+const MIN = 60_000+const t0 = new Date('2026-11-04T05:00:00.000Z')+const owner: AuthUser = { sub: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' }+// The row as the upgrade reads it: every fact the CLI sends on connect already stored, stamped a minute ago.+const row = {+ machineId: 'mac-1', userId: 'owner', name: 'MacBook Pro', billingStatus: 'not_required', sessionKind: 'computer',+ hostname: 'MacBook-Pro.local', clientVersion: '0.5.13', computerId: COMPUTER, countryCode: 'VN', lastSeenAt: new Date(t0.getTime() - MIN),+}+const flush = async () => { for (let i = 0; i < 400; i++) await Promise.resolve() }++class Socket extends EventEmitter {+ readyState = 1; bufferedAmount = 0+ send = vi.fn()+ close = vi.fn(() => { this.readyState = 3; this.emit('close') })+ terminate = vi.fn(() => this.close())+}++let ws: Socket+const connect = async (version = '0.5.13') => {+ ws = new Socket()+ m.upgrade.mockImplementation((_r, _s, _h, done) => done(ws))+ const req = { url: `/api/adapter-ws?computer=${COMPUTER}&label=MacBook-Pro.local&v=${version}&autonomousEnv=prod`,+ headers: { 'sec-websocket-protocol': 'access-token', 'cf-ipcountry': 'VN' } }+ handleAdapterUpgrade(req as never, { write: vi.fn(), destroy: vi.fn(), on: vi.fn(), once: vi.fn() } as never, Buffer.alloc(0))+ await flush()+}+const heartbeatAt = async (ms: number) => {+ vi.setSystemTime(t0.getTime() + ms)+ m.nodeRole.mock.calls.at(-1)![0].onHeartbeat(); await flush()+}+const writes = () => m.machineUpdate.mock.calls.map(c => c[0].data as Record<string, unknown>)++beforeEach(() => {+ vi.clearAllMocks()+ vi.useFakeTimers({ toFake: ['Date'] })+ vi.setSystemTime(t0)+ m.auth.mockResolvedValue(owner)+ m.machineUpdate.mockResolvedValue({})+ m.record.mockResolvedValue(undefined)+ m.userFindUnique.mockResolvedValue({ gridName: null })+ m.nodeRole.mockResolvedValue({ touch: vi.fn(), detach: vi.fn(async () => {}) })+ m.machineService.resolveOrCreateForComputer.mockResolvedValue({ machine: row, created: false })+})+afterEach(() => { ws?.close(); vi.useRealTimers() })++describe('an adapter socket\'s writes to its machine row', () => {+ it('writes nothing on a reconnect that changed no fact, a minute after the row\'s last stamp, and still counts the connect', async () => {+ await connect()+ expect(writes()).toEqual([])+ expect(m.record.mock.calls.map(c => c[2])).toEqual(['relay_machine_connections'])+ })++ it('stamps on heartbeats only once the row\'s stamp is 5 minutes old, then once per 5 minutes, and once at close', async () => {+ await connect()+ for (const at of [15_000, 2 * MIN, 3 * MIN + 59_000]) await heartbeatAt(at)+ expect(writes()).toEqual([])+ await heartbeatAt(4 * MIN) // 5 minutes after the row's stamp+ await heartbeatAt(8 * MIN)+ await heartbeatAt(9 * MIN)+ expect(writes()).toEqual([{ lastSeenAt: new Date(t0.getTime() + 4 * MIN) }, { lastSeenAt: new Date(t0.getTime() + 9 * MIN) }])+ vi.setSystemTime(t0.getTime() + 10 * MIN)+ ws.close(); await flush()+ expect(writes()).toHaveLength(3)+ expect(writes()[2]).toEqual({ lastSeenAt: new Date(t0.getTime() + 10 * MIN) })+ })++ it('writes one update on a connect after 5 minutes away, with a changed fact riding in it', async () => {+ m.machineService.resolveOrCreateForComputer.mockResolvedValue({ machine: { ...row, lastSeenAt: new Date(t0.getTime() - 10 * MIN) }, created: false })+ await connect('0.5.14')+ expect(writes()).toEqual([{ clientVersion: '0.5.14', lastSeenAt: t0 }])+ })++ it('writes a changed fact at once even when the stamp is not due', async () => {+ await connect('0.5.14')+ expect(writes()).toEqual([{ clientVersion: '0.5.14' }])+ })++ it('stamps at once a row that was never stamped, and seeds an empty name', async () => {+ m.machineService.resolveOrCreateForComputer.mockResolvedValue({ machine: { ...row, name: null, lastSeenAt: null }, created: false })+ await connect()+ expect(writes()).toEqual([{ name: 'MacBook-Pro.local', lastSeenAt: t0 }])+ })++ it('flips a former team row before it attaches, and does not write that again on connect', async () => {+ m.machineService.resolveOrCreateForComputer.mockResolvedValue({ machine: { ...row, sessionKind: 'team' }, created: false })+ await connect()+ expect(writes()).toEqual([{ sessionKind: 'computer' }])+ })++ it('retries a changed fact whose connect write failed on the next heartbeat, then stops', async () => {+ m.machineUpdate.mockRejectedValueOnce(new Error('mongo slow'))+ await connect('0.5.14')+ await heartbeatAt(15_000)+ await heartbeatAt(30_000)+ expect(writes()).toEqual([{ clientVersion: '0.5.14' }, { clientVersion: '0.5.14' }])+ })++ it('retries a failed stamp on the next heartbeat', async () => {+ m.machineService.resolveOrCreateForComputer.mockResolvedValue({ machine: { ...row, lastSeenAt: null }, created: false })+ m.machineUpdate.mockRejectedValueOnce(new Error('mongo slow'))+ await connect()+ await heartbeatAt(15_000)+ expect(writes()).toEqual([{ lastSeenAt: t0 }, { lastSeenAt: new Date(t0.getTime() + 15_000) }])+ })+})diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.tsindex a5c31edc2..5333e8618 100644--- a/backend/src/lib/adapterWs.ts+++ b/backend/src/lib/adapterWs.ts@@ -15,8 +15,9 @@* A team session (lib/teamSession.ts), a Mac's team account, connects only as its own computer's machine* and only while that row is a team machine. Its socket hears only the device-key pushes, never the* account's grid name, raises no pairing notice on the person's apps, and may take only its own key off- * the device key log. Every connect records which kind of sign-in serves the machine (`sessionKind`).+ * the device key log. A connect records which kind of sign-in serves the machine (`sessionKind`) when that changed.*/+import type { Machine } from '@prisma/client'import type { IncomingMessage } from 'http'import type { Duplex } from 'stream'import { WebSocket, type RawData } from 'ws'@@ -32,7 +33,7 @@ import { PROCESS_ID } from './registry.js'import { guardedSend, guardedSendJson } from './wsSend.js'import { trackSocket } from './wsAttribution.js'import { attachNodeRole, PRESENCE_TTL_SEC } from './nodeRole.js'-import { presenceTracker, presenceWriteDue, recordTurnStarted, touchClientOnlineDay, touchMachineOnlineDay, touchUserOnlineDay, TUI_SURFACES, type ClientSurface, type PresenceWriteState } from './dailyTracking.js'+import { machineConnectChanges, presenceStateFromRow, presenceTracker, presenceWriteDue, recordTurnStarted, touchClientOnlineDay, touchMachineOnlineDay, touchUserOnlineDay, TUI_SURFACES, type ClientSurface, type MachineConnectChanges, type PresenceWriteState } from './dailyTracking.js'import { countryCodeFromHeaders } from './clientGeo.js'import { recordCreatedAgent, recordDeletedAgent } from './agentTracker.js'import type { Frame, UpBusMsg } from './tunnel.js'@@ -96,8 +97,8 @@ const CLIENT_VERSION_RE = /^[A-Za-z0-9._+-]{1,64}$/// How often an OPEN adapter socket refreshes `machines.lastSeenAt`. Rides the node role's existing 15s// heartbeat (plus every app ping) rather than a timer of its own — this is just the floor between two-// Mongo writes, so a machine that is up all day costs ~300 updates, not ~6000. Connect and close always-// write regardless.+// Mongo writes, so a machine that is up all day costs ~300 updates, not ~6000. The floor starts from the row's own+// stamp, so a connect stamps only when that is due too (#2676); close always writes.const MACHINE_PRESENCE_WRITE_MS = 5 * 60_000// Daily presence of the PERSON (`user_daily_presence`): the daemon reports its own loopback clients —@@ -208,14 +209,17 @@ export function handleAdapterUpgrade(req: IncomingMessage, socket: Duplex, head:machine = (await machineService.resolveOrCreateForComputer(user.sub, user.autonomousEnv, computerId, label ?? 'computer', claimedMachineId, 'computer')).machine// Before it attaches: a former team machine now served by a normal sign-in must not be read as a team machine. Any// other row is stamped by the connect's own update below; until then it is not a team machine either.- if (machine.sessionKind === 'team') await prisma.machine.update({ where: { machineId: machine.machineId }, data: { sessionKind: 'computer' } })+ if (machine.sessionKind === 'team') {+ await prisma.machine.update({ where: { machineId: machine.machineId }, data: { sessionKind: 'computer' } })+ machine = { ...machine, sessionKind: 'computer' }+ }}const machineId = machine.machineIdif (!machineBillingAllowsDataPlane(machine)) { denyPayment(); return }// Single-computer claim BEFORE upgrade/attach, so a rejected second computer never supersedes the first.if (!(await claimMachineOwner(machineId, computerId, PRESENCE_TTL_SEC))) { denyBusy(); return }- const name = machine.name, owner = machine.userId- wss.handleUpgrade(req, socket, head, (ws) => void attachAdapter(ws, machineId, owner, name, label, computerId, clientVersion, countryCode, user.harnessSessionId, team))+ const row = machine+ wss.handleUpgrade(req, socket, head, (ws) => void attachAdapter(ws, row, label, computerId, clientVersion, countryCode, user.harnessSessionId, team))})().catch((err) => {if (err instanceof AppError) {// 403 is the revoked-machine answer from `resolveOrCreateForComputer`, 429 its new-id rate limit@@ -230,7 +234,12 @@ export function handleAdapterUpgrade(req: IncomingMessage, socket: Duplex, head:})}-async function attachAdapter(ws: WebSocket, machineId: string, userId: string, currentName: string | null, label?: string, computerId?: string, clientVersion?: string, countryCode?: string, harnessSessionId?: string, team = false): Promise<void> {+/** The machine row as the upgrade read it: a connect writes only the facts that differ from it, and stamps only when its+ * `lastSeenAt` is due. */+type AttachedMachine = Pick<Machine, 'machineId' | 'userId' | 'name' | 'hostname' | 'clientVersion' | 'computerId' | 'countryCode' | 'sessionKind' | 'lastSeenAt'>++async function attachAdapter(ws: WebSocket, machine: AttachedMachine, label?: string, computerId?: string, clientVersion?: string, countryCode?: string, harnessSessionId?: string, team = false): Promise<void> {+ const { machineId, userId, name: currentName } = machine// A different computer was already rejected at the upgrade (denyBusy), so this only closes our OWN// stale local socket on a same-computer reconnect landing on this worker.owners.get(machineId)?.close(4000, 'superseded')@@ -294,23 +303,15 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c// (see the upgrade handler): that key is a self-consistent liveness token nothing joins against, and// re-keying it would 409 every already-connected adapter until its old claim aged out.const boundComputer = computerId ? normalizeComputerId(computerId) : null- if (label || seededName || clientVersion || boundComputer || countryCode) {- void prisma.machine.update({- where: { machineId },- data: {- ...(label ? { hostname: label.slice(0, 120) } : {}),- ...(seededName ? { name: seededName } : {}),- // Same overwrite-every-connect rule as `hostname`; absent (old client) leaves the last value.- ...(clientVersion ? { clientVersion } : {}),- ...(boundComputer ? { computerId: boundComputer } : {}),- // Same rule again; absent (not behind Cloudflare) leaves the last value.- ...(countryCode ? { countryCode } : {}),- // Which kind of sign-in serves the machine now (lib/teamSession.ts). A team row was checked, and a former team- // row flipped, before the socket attached; this stamps every other row.- sessionKind: team ? 'team' : 'computer',- },- }).catch(() => { /* best effort */ })- }+ // Each overwrite-every-connect fact (`hostname`, `clientVersion`, `computerId`, `countryCode`: absent from an old client+ // or off Cloudflare leaves the last value), the seeded name, and which kind of sign-in serves the machine now+ // (lib/teamSession.ts; a team row was checked, and a former team row flipped, before the socket attached). Only the ones+ // that differ from the row are written, in the connect's one update with its stamp (touchMachinePresence below): a+ // reconnect used to rewrite them all and stamp separately, two updates of one row at once (#2676).+ const connectChanges = machineConnectChanges(machine, {+ hostname: label?.slice(0, 120), name: seededName ?? undefined, clientVersion, computerId: boundComputer ?? undefined, countryCode,+ sessionKind: team ? 'team' : 'computer',+ })// Tell the adapter its machine's display name (it mirrors it locally for `harness status`); null when// unnamed so a stale mirror clears. Renames while connected arrive the same way (machine_meta).// The account's private harness grid, carried on the frame the adapter already gets on connect.@@ -328,14 +329,25 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c// skip while a write is still in flight: `onHeartbeat` fires from two 15s sources (node role// interval + app ping), and before the connect write lands `presenceWriteDue` would say "due" —// without this a slow Mongo gets a second concurrent upsert precisely when it is already slow.- const lastMachinePresence: PresenceWriteState = { dayKey: null, wroteAt: 0 }+ // The floor starts from the row's own stamp, not from this socket: a reconnect a minute after the last stamp neither+ // stamps on connect nor on its first heartbeat (#2676). Close always stamps: it is the exact "offline since".+ const lastMachinePresence: PresenceWriteState = presenceStateFromRow(machine.lastSeenAt)let machinePresenceInFlight = false- const touchMachinePresence = (kind: 'connect' | 'heartbeat' | 'close'): void => {+ // The connect's changed facts until a write carries them: a failed connect write is retried by the next heartbeat.+ let pendingChanges: MachineConnectChanges = {}+ const touchMachinePresence = (kind: 'connect' | 'heartbeat' | 'close', changes?: MachineConnectChanges): void => {const now = new Date()- if (kind === 'heartbeat' && (machinePresenceInFlight || !presenceWriteDue(lastMachinePresence, now, MACHINE_PRESENCE_WRITE_MS))) return+ if (changes) pendingChanges = changes+ const carried = pendingChanges+ const due = presenceWriteDue(lastMachinePresence, now, MACHINE_PRESENCE_WRITE_MS)+ if (kind === 'heartbeat' && (machinePresenceInFlight || (!due && !Object.keys(carried).length))) return+ const stamp = kind === 'close' || duemachinePresenceInFlight = true- touchMachineOnlineDay(userId, machineId, now, { isNewConnection: kind === 'connect', countryCode })- .then(() => { lastMachinePresence.dayKey = utcDayKey(now); lastMachinePresence.wroteAt = now.getTime() })+ touchMachineOnlineDay(userId, machineId, now, { isNewConnection: kind === 'connect', countryCode, changes: carried, stamp })+ .then(() => {+ if (pendingChanges === carried) pendingChanges = {}+ if (stamp) { lastMachinePresence.dayKey = utcDayKey(now); lastMachinePresence.wroteAt = now.getTime() }+ }).catch((err) => logger.warn('machine presence tracking failed', { machineId, kind, error: String(err) })).finally(() => { machinePresenceInFlight = false })}@@ -403,7 +415,7 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, ctouchMachinePresence('heartbeat') // throttled inside — see MACHINE_PRESENCE_WRITE_MS},})- touchMachinePresence('connect')+ touchMachinePresence('connect', connectChanges)const terminalDownUnsub = await subscribeTerminalDown(machineId, (packet) => {// Terminal input toward the adapter is 'must': dropping keystrokes is not recoverable client-side.guardedSend(ws, packet, 'must', { machineId, kind: 'adapter' })diff --git a/backend/src/lib/dailyTracking.test.ts b/backend/src/lib/dailyTracking.test.tsindex 62295e467..aba27a759 100644--- a/backend/src/lib/dailyTracking.test.ts+++ b/backend/src/lib/dailyTracking.test.ts@@ -7,7 +7,7 @@ const warn = vi.hoisted(() => vi.fn())vi.mock('./productUsage.js', () => ({ recordRelayUsage: record, markActivity: mark }))vi.mock('./prisma.js', () => ({ prisma: { machine: { update: machineUpdate }, swarmAgent: { aggregateRaw: swarmAgentFind } } }))vi.mock('../utils/logger.js', () => ({ logger: { warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() } }))-import { CLIENT_SURFACES, TUI_SURFACES, mobileOpenMetrics, presenceTracker, presenceWriteDue, recordRemoteUsage, recordTurnStarted, touchClientOnlineDay, touchDeviceOnlineDay, touchMachineOnlineDay, touchUserOnlineDay } from './dailyTracking.js'+import { CLIENT_SURFACES, TUI_SURFACES, machineConnectChanges, mobileOpenMetrics, presenceStateFromRow, presenceTracker, presenceWriteDue, recordRemoteUsage, recordTurnStarted, touchClientOnlineDay, touchDeviceOnlineDay, touchMachineOnlineDay, touchUserOnlineDay } from './dailyTracking.js'beforeEach(() => {record.mockReset(); record.mockResolvedValue(undefined); mark.mockReset(); mark.mockResolvedValue(undefined)@@ -99,6 +99,22 @@ describe('a machine\'s last-seen time', () => {await expect(touchMachineOnlineDay('account', 'machine-1', now, { isNewConnection: false })).rejects.toThrow('mongo down')})+ it('writes the changed connection facts and the stamp in one update', async () => {+ await touchMachineOnlineDay('account', 'machine-1', now, { isNewConnection: true, changes: { clientVersion: '0.5.14' } })+ expect(machineUpdate.mock.calls).toEqual([[{ where: { machineId: 'machine-1' }, data: { clientVersion: '0.5.14', lastSeenAt: now } }]])+ })++ it('writes nothing to the machine when no fact changed and its stamp is not due, and still counts the connect', async () => {+ await touchMachineOnlineDay('account', 'machine-1', now, { isNewConnection: true, changes: {}, stamp: false })+ expect(machineUpdate).not.toHaveBeenCalled()+ expect(record.mock.calls.map(c => c[2])).toEqual(['relay_machine_connections'])+ })++ it('writes a changed fact without a stamp when the stamp is not due', async () => {+ await touchMachineOnlineDay('account', 'machine-1', now, { isNewConnection: true, changes: { hostname: 'new-host' }, stamp: false })+ expect(machineUpdate.mock.calls).toEqual([[{ where: { machineId: 'machine-1' }, data: { hostname: 'new-host' } }]])+ })+it('is stamped even when the connect total fails', async () => {record.mockRejectedValue(new Error('totals down'))await expect(touchMachineOnlineDay('account', 'machine-1', now, { isNewConnection: true })).rejects.toThrow('totals down')@@ -195,6 +211,34 @@ describe('presenceWriteDue', () => {})})+describe('a machine row read at a connect', () => {+ const FIVE_MIN = 5 * 60_000+ const stamped = new Date('2026-11-04T05:00:00.000Z')++ it('floors a new socket\'s stamps on the row\'s last stamp, not on the socket\'s start', () => {+ const state = presenceStateFromRow(stamped)+ expect(state).toEqual({ dayKey: '2026-11-04', wroteAt: stamped.getTime() })+ expect(presenceWriteDue(state, new Date(stamped.getTime() + 60_000), FIVE_MIN)).toBe(false)+ expect(presenceWriteDue(state, new Date(stamped.getTime() + FIVE_MIN), FIVE_MIN)).toBe(true)+ })++ it('is due at once for a row never stamped', () => {+ for (const lastSeenAt of [null, undefined]) expect(presenceStateFromRow(lastSeenAt)).toEqual({ dayKey: null, wroteAt: 0 })+ })++ it('rewrites only the connection facts that differ from the row', () => {+ const row = { hostname: 'mac', name: 'Mac', clientVersion: '0.5.13', computerId: 'c1', countryCode: 'VN', sessionKind: 'computer' }+ expect(machineConnectChanges(row, { hostname: 'mac', clientVersion: '0.5.13', computerId: 'c1', countryCode: 'VN', sessionKind: 'computer' })).toEqual({})+ expect(machineConnectChanges(row, { hostname: 'mac', clientVersion: '0.5.14', computerId: 'c1', sessionKind: 'computer' })).toEqual({ clientVersion: '0.5.14' })+ expect(machineConnectChanges({ ...row, sessionKind: null, countryCode: null }, { sessionKind: 'computer', countryCode: 'SG' }))+ .toEqual({ sessionKind: 'computer', countryCode: 'SG' })+ })++ it('leaves out a fact the connect did not send', () => {+ expect(machineConnectChanges({ hostname: 'mac' }, { hostname: undefined, sessionKind: 'team' })).toEqual({ sessionKind: 'team' })+ })+})+it('keeps Harness OS and Orange Pi connections separate without storing identity', async () => {expect([...TUI_SURFACES]).toEqual(['tui', 'harness-os', 'harness-os-pi'])for (const surface of TUI_SURFACES) expect(CLIENT_SURFACES.has(surface)).toBe(true)diff --git a/backend/src/lib/dailyTracking.ts b/backend/src/lib/dailyTracking.tsindex ea3e83e5d..c02d50502 100644--- a/backend/src/lib/dailyTracking.ts+++ b/backend/src/lib/dailyTracking.ts@@ -23,12 +23,41 @@ export async function recordRemoteUsage(userId: string, _machineId: string, now:export async function touchDeviceOnlineDay(userId: string, _deviceId: string, now: Date, opts: PresenceTouchOpts): Promise<void> {if (opts.isNewConnection) await recordRelayUsage(userId, now, 'relay_device_connections')}-/** Stamps the machine's own `lastSeenAt` on every call — the caller floors heartbeats — and counts a connect.- * Both writes start together, so a failed total never costs the stamp; either failure rejects, so the- * caller's floor does not advance and its next heartbeat retries. */-export async function touchMachineOnlineDay(userId: string, machineId: string, now: Date, opts: PresenceTouchOpts): Promise<void> {+/** The connection facts an adapter connect reports (lib/adapterWs.ts), each a `machines` field. */+export type MachineConnectChanges = Partial<Record<'hostname' | 'name' | 'clientVersion' | 'computerId' | 'countryCode' | 'sessionKind', string>>+/** Those fields as the upgrade read them from the row. */+export type MachineConnectRow = { [K in keyof MachineConnectChanges]?: string | null }++/** The facts of `next` that differ from `row`: a connect rewrites only what changed (Ken's prod scan of 11-04, #2676:+ * every reconnect rewrote the same host, version and computer). A fact the connect did not send is left as it is. */+export function machineConnectChanges(row: MachineConnectRow, next: MachineConnectChanges): MachineConnectChanges {+ const changes: MachineConnectChanges = {}+ for (const [key, value] of Object.entries(next) as Array<[keyof MachineConnectChanges, string | undefined]>) {+ if (value !== undefined && row[key] !== value) changes[key] = value+ }+ return changes+}++/** A row's `lastSeenAt` as a socket's write state: a new socket floors its stamps on the row's last stamp, so a+ * reconnect a minute after the last one does not stamp again. A row never stamped is due at once. */+export function presenceStateFromRow(lastSeenAt: Date | null | undefined): PresenceWriteState {+ return lastSeenAt ? { dayKey: utcDayKey(lastSeenAt), wroteAt: lastSeenAt.getTime() } : { dayKey: null, wroteAt: 0 }+}++export interface MachineTouchOpts extends PresenceTouchOpts {+ /** Connection facts that changed, written in the same update as the stamp. */+ changes?: MachineConnectChanges+ /** false when the row's stamp is not due: only `changes` are written. */+ stamp?: boolean+}++/** One update of the machine's row: the changed facts and its `lastSeenAt` (the caller floors it), none when both are+ * empty; and a connect's total. Both start together, so a failed total never costs the stamp; either failure rejects,+ * so the caller's floor does not advance and its next heartbeat retries. */+export async function touchMachineOnlineDay(userId: string, machineId: string, now: Date, opts: MachineTouchOpts): Promise<void> {+ const data = { ...opts.changes, ...(opts.stamp === false ? {} : { lastSeenAt: now }) }await Promise.all([- prisma.machine.update({ where: { machineId }, data: { lastSeenAt: now } }),+ Object.keys(data).length ? prisma.machine.update({ where: { machineId }, data }) : undefined,opts.isNewConnection ? recordRelayUsage(userId, now, 'relay_machine_connections') : undefined,])}diff --git a/backend/src/lib/teamSessionSockets.test.ts b/backend/src/lib/teamSessionSockets.test.tsindex f1aeee2fe..68baba073 100644--- a/backend/src/lib/teamSessionSockets.test.ts+++ b/backend/src/lib/teamSessionSockets.test.ts@@ -37,6 +37,7 @@ vi.mock('./dailyTracking.js', async original => ({ ...await original<typeof imporecordTurnStarted: m.recordTurn }))import { handleAdapterUpgrade } from './adapterWs.js'+import { touchMachineOnlineDay } from './dailyTracking.js'import { handleWebUpgrade } from './webWs.js'import { handleDeviceUpgrade } from './deviceWs.js'import { SsoAuthError, type AuthUser } from './ssoAuth.js'@@ -48,6 +49,8 @@ const owner: AuthUser = { sub: 'owner', email: '[email protected]', role: 'user'const team: AuthUser = { ...owner, harnessSessionId: 'team-session', harnessSessionKind: 'team', harnessComputerId: TEAM_COMPUTER }const teamMac = { machineId: 'team-mac', userId: 'owner', name: 'MacBook Pro · Team', billingStatus: 'not_required', sessionKind: 'team' }const ownerMac = { machineId: 'owner-mac', userId: 'owner', name: 'MacBook Pro', billingStatus: 'not_required', sessionKind: null }+/** What the connect's one update of the machine row carries beside its stamp (lib/dailyTracking.ts). */+const connectChanges = () => vi.mocked(touchMachineOnlineDay).mock.calls.find(c => c[3].isNewConnection)?.[3].changesconst flush = async () => { for (let i = 0; i < 400; i++) await Promise.resolve() }class Socket extends EventEmitter {@@ -156,10 +159,16 @@ describe('the machine socket and a team session', () => {handleAdapterUpgrade(adapter(computer) as never, raw() as never, Buffer.alloc(0)); await flush()}+ it('a computer\'s row from before the kind was kept is marked a computer in the connect\'s one update', async () => {+ await attach(owner, OWNER_COMPUTER)+ expect(connectChanges()).toMatchObject({ sessionKind: 'computer' })+ })+it('a team machine hears only its device-key pushes, never the account\'s grid name', async () => {await attach(team, TEAM_COMPUTER)expect(m.pushes).toHaveBeenCalledWith('owner', expect.any(Function), expect.objectContaining({ team: true }))- expect(m.machineUpdate).toHaveBeenCalledWith({ where: { machineId: 'team-mac' }, data: expect.objectContaining({ sessionKind: 'team' }) })+ // Its row is already marked team (resolveForTeamComputer refuses any other): the connect does not write that again.+ expect(connectChanges()).not.toHaveProperty('sessionKind')const meta = ws.sent().find(f => f.frame?.type === 'machine_meta')expect(meta.frame.payload).toEqual({ name: 'MacBook Pro · Team', gridName: null })})@@ -193,7 +202,7 @@ describe('the machine socket and a team session', () => {m.machineFindUnique.mockResolvedValue({ name: 'MacBook Pro' })await attach(owner, OWNER_COMPUTER)expect(m.pushes).toHaveBeenCalledWith('owner', expect.any(Function), expect.objectContaining({ team: false }))- expect(m.machineUpdate).toHaveBeenCalledWith({ where: { machineId: 'owner-mac' }, data: expect.objectContaining({ sessionKind: 'computer' }) })+ expect(connectChanges()).not.toHaveProperty('sessionKind')expect(ws.sent().find(f => f.frame?.type === 'machine_meta').frame.payload.gridName).toBe('grid-of-the-account')ws.frame({ t: 'up', frame: { type: 'devlog_append', payload: { requestId: 'r1', entry: { op: 'add' } } } })ws.frame({ t: 'up', userEligible: true, webEligible: false, frame: { type: 'device_e2ee_pair_pending', payload: { pairId: 'p1', label: 'Dial' } } })diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.tsindex 0da7bd614..50e7d351d 100644--- a/backend/src/routes/auth.ts+++ b/backend/src/routes/auth.ts@@ -35,6 +35,7 @@ import { machineAlive, prisma } from '../lib/prisma.js'import { pub } from '../lib/bus.js'import { TEAM_CONVERSION_PROOF_MS, teamConversionMessage } from '../lib/teamSession.js'import type { AuthUser } from '../lib/ssoAuth.js'+import { parseAccountName } from '../lib/accountName.js'/*** Whether [user] is the computer [computerId] itself, which alone may turn itself into a team machine@@ -432,4 +433,15 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {if (!user) return sendError(reply, 'user not found', 'NOT_FOUND', 404)return sendSuccess(reply, { user: userService.toPublic(user), avatarUrl: null, description: null })})++ // The signed-in person's own account name (task #2654), the one /api/auth/me answers: the session names the row, never+ // the body. A team machine's session never reaches here (lib/teamSession.ts TEAM_ROUTES): it runs other people's agents.+ // Answers as GET /api/auth/me does, so the app shows the saved name at once.+ app.patch<{ Body: { name?: unknown } }>('/api/auth/me', async (req, reply) => {+ const parsed = parseAccountName(req.body?.name)+ if (!parsed.ok) return sendError(reply, parsed.message, parsed.code, 400)+ // A row gone since sign-in answers 404 (UserService.update's NotFoundError).+ const user = await userService.update(req.user!.sub, { name: parsed.name })+ return sendSuccess(reply, { user: userService.toPublic(user), avatarUrl: null, description: null })+ })}diff --git a/backend/src/routes/authMe.test.ts b/backend/src/routes/authMe.test.tsnew file mode 100644index 000000000..65afe5b25--- /dev/null+++ b/backend/src/routes/authMe.test.ts@@ -0,0 +1,120 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'++// The real auth middleware and auth routes, with the user store in memory: a person changes their own account name+// (task #2654), and only their own.+const fakes = vi.hoisted(() => {+ const users = new Map<string, Record<string, unknown>>()+ return {+ users,+ get: vi.fn(async (id: string) => users.get(id) ?? null),+ update: vi.fn(async (id: string, input: { name?: string }) => {+ const row = users.get(id)+ if (!row) throw new Error('not found')+ if (input.name !== undefined) row.name = input.name+ return row+ }),+ }+})++vi.mock('../lib/bus.js', () => ({ pub: {} }))+vi.mock('../lib/prisma.js', () => ({ prisma: {}, machineAlive: {} }))+vi.mock('../services/index.js', () => ({+ userService: { get: fakes.get, update: fakes.update, toPublic: (u: Record<string, unknown>) => ({ ...u }) },+}))++import { authRoutes } from './auth.js'+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'+import { errorHandler } from '../middlewares/errorHandler.js'+import { SsoAuthError, type AuthUser } from '../lib/ssoAuth.js'++const elvis: AuthUser = { sub: 'u1', email: '[email protected]', role: 'user', autonomousEnv: 'prod' }+const team: AuthUser = { ...elvis, harnessSessionId: 's-team', harnessSessionKind: 'team', harnessComputerId: 'c'.repeat(32) }+const phone: AuthUser = { ...elvis, harnessSessionId: 's-phone', harnessSessionKind: 'viewer' }++const authenticate = vi.fn(async (token: string) => {+ if (token === 'elvis') return elvis+ if (token === 'phone') return phone+ if (token === 'team') return team+ throw new SsoAuthError('Invalid', 'INVALID_TOKEN')+})++describe('PATCH /api/auth/me: a person changes their own account name', () => {+ let app: FastifyInstance++ beforeEach(async () => {+ fakes.users.clear()+ fakes.update.mockClear()+ fakes.users.set('u1', { id: 'u1', email: '[email protected]', name: 'phorom12a', role: 'user' })+ fakes.users.set('u2', { id: 'u2', email: '[email protected]', name: 'Ken', role: 'admin' })+ app = Fastify()+ app.setErrorHandler(errorHandler)+ registerAuthMiddleware(app, authenticate as never)+ await app.register(authRoutes)+ await app.ready()+ })++ const patch = (token: string | null, payload: unknown) => app.inject({+ method: 'PATCH', url: '/api/auth/me', payload: payload as never,+ headers: token ? { authorization: `Bearer ${token}` } : {},+ })+ const me = async (token: string) =>+ (await app.inject({ method: 'GET', url: '/api/auth/me', headers: { authorization: `Bearer ${token}` } })).json().data++ it('saves the name, answers as /api/auth/me does, and /api/auth/me reads it at once', async () => {+ const response = await patch('elvis', { name: ' Elvis ' })+ expect(response.statusCode).toBe(200)+ expect(response.json().data).toEqual({ user: expect.objectContaining({ id: 'u1', name: 'Elvis' }), avatarUrl: null, description: null })+ expect((await me('elvis')).user.name).toBe('Elvis')+ })++ it('changes only the caller\'s own row, whatever the body names', async () => {+ const response = await patch('elvis', { name: 'Elvis', id: 'u2', userId: 'u2', email: '[email protected]', role: 'admin' })+ expect(response.statusCode).toBe(200)+ expect(fakes.update).toHaveBeenCalledTimes(1)+ expect(fakes.update).toHaveBeenCalledWith('u1', { name: 'Elvis' })+ expect(fakes.users.get('u2')).toEqual({ id: 'u2', email: '[email protected]', name: 'Ken', role: 'admin' })+ expect(fakes.users.get('u1')).toMatchObject({ email: '[email protected]', role: 'user' })+ })++ it('refuses a name that is not one, and writes nothing', async () => {+ for (const name of [' ', '', 'ab', 'x'.repeat(61), 7, null]) {+ const response = await patch('elvis', { name })+ expect(response.statusCode, JSON.stringify(name)).toBe(400)+ expect(response.json().error).toEqual({ code: 'INVALID_NAME', message: 'Use 1 to 60 characters, with no hidden ones.' })+ }+ expect(await patch('elvis', {})).toHaveProperty('statusCode', 400)+ expect(fakes.update).not.toHaveBeenCalled()+ expect(fakes.users.get('u1')!.name).toBe('phorom12a')+ })++ it('refuses a web address, an email-shaped name or a role\'s name, and writes nothing', async () => {+ const link = await patch('elvis', { name: 'https://ev.il' })+ expect(link.statusCode).toBe(400)+ expect(link.json().error).toEqual({ code: 'INVALID_NAME', message: 'Use a name, not a web address.' })+ const email = await patch('elvis', { name: '[email protected]' })+ expect(email.statusCode).toBe(400)+ expect(email.json().error).toEqual({ code: 'INVALID_NAME', message: 'Use a name, not an email address.' })+ const role = await patch('elvis', { name: 'Product Manager' })+ expect(role.statusCode).toBe(400)+ expect(role.json().error).toEqual({ code: 'NAME_RESERVED', message: 'Product Manager is a role\'s name. Choose another.' })+ expect(fakes.update).not.toHaveBeenCalled()+ })++ it('needs a sign-in', async () => {+ expect((await patch(null, { name: 'Elvis' })).statusCode).toBe(401)+ expect(fakes.update).not.toHaveBeenCalled()+ })++ it('takes the phone\'s sign-in, which is the same person', async () => {+ expect((await patch('phone', { name: 'Elvis' })).statusCode).toBe(200)+ expect(fakes.users.get('u1')!.name).toBe('Elvis')+ })++ it('refuses a team machine\'s sign-in: it runs other people\'s agents under the owner\'s account', async () => {+ const response = await patch('team', { name: 'Elvis' })+ expect(response.statusCode).toBe(403)+ expect(response.json().error.code).toBe('TEAM_SESSION_LIMITED')+ expect(fakes.update).not.toHaveBeenCalled()+ })+})diff --git a/backend/src/routes/superTabs.test.ts b/backend/src/routes/superTabs.test.tsindex 19701decf..1fee25446 100644--- a/backend/src/routes/superTabs.test.ts+++ b/backend/src/routes/superTabs.test.ts@@ -307,6 +307,39 @@ describe('a machine\'s readings for all its Swarms in one call (DB 2.5)', () =>})})+// A client that asks takes a machine's reading as one line (read/changes.ts); no other client's reply changes.+describe('the machine lines of a change read', () => {+ let app: FastifyInstance+ const changes = vi.fn(async (..._args: unknown[]) => ({ reload: true })), machineReadings = vi.fn(async (..._args: unknown[]) => ({ machines: [] }))+ beforeEach(async () => {+ changes.mockClear(); machineReadings.mockClear()+ app = Fastify()+ app.setErrorHandler(errorHandler)+ app.addHook('onRequest', async request => { request.user = { sub: 'u1', email: '[email protected]', autonomousEnv: 'prod', role: 'user' } as never })+ await app.register(superTabRoutes, { store: {} as never, github: null, reads: { changes, machineReadings } as never, hosts: {} as never })+ await app.ready()+ })+ afterEach(async () => { await app.close() })+ const get = (url: string) => app.inject({ method: 'GET', url })++ it('asks for lines only when the client does', async () => {+ expect((await get('/api/super-tabs/tab1/changes?cursor=abc')).statusCode).toBe(200)+ expect(changes.mock.calls[0]!.slice(2)).toEqual(['abc', undefined, {}])+ expect((await get('/api/super-tabs/tab1/changes?cursor=abc&machines=light')).statusCode).toBe(200)+ expect(changes.mock.calls[1]!.slice(2)).toEqual(['abc', undefined, { lightMachines: true }])+ })++ it('refuses any other value', async () => {+ expect((await get('/api/super-tabs/tab1/changes?cursor=abc&machines=all')).statusCode).toBe(400)+ expect(changes).not.toHaveBeenCalled()+ })++ it('serves the whole readings on demand, for an agent too', async () => {+ expect((await get('/api/super-tabs/tab1/machine-readings?asAgentId=agent1')).statusCode).toBe(200)+ expect(machineReadings.mock.calls[0]!.slice(1)).toEqual(['tab1', 'agent1'])+ })+})+// The Tasks view's Proposals (#2569): one project's open Buddy proposals, read by the store as the project chat's reader.describe('a project\'s open proposals', () => {let app: FastifyInstancediff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex bb796a393..2d24154f4 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -1,3 +1,4 @@+import { declaredHttpClient } from '../superTabs/refusalLog.js'import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'import { z, ZodError } from 'zod'import { prisma } from '../lib/prisma.js'@@ -32,6 +33,7 @@ import { SwarmReads } from '../superTabs/read/service.js'import { inboxWait, readInbox } from '../superTabs/read/inbox.js'import { readFollowedThreads, threadsWait } from '../superTabs/read/followedThreads.js'import { activityWait } from '../superTabs/activity.js'+import { reminderWait } from '../superTabs/reminders.js'import { NOTIFY_LEVELS } from '../superTabs/chatSettings.js'import { HostReads } from '../superTabs/read/host.js'import { UPDATE_REQUIRED } from '../superTabs/read/contract.js'@@ -77,7 +79,7 @@ const workspaceJoin = z.object({ operationId: id }).strict()const personOnly = (user: AuthUser) => { if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403) }const listQuery = z.object({ after: id.optional(), mentions: z.literal('1').optional() }).strict()const cursor = z.string().min(1).max(512).regex(/^[A-Za-z0-9_-]+$/)-const changesQuery = agentQuery.extend({ cursor })+const changesQuery = agentQuery.extend({ cursor, machines: z.literal('light').optional() })const costsQuery = z.object({ days: z.coerce.number().int().min(1).max(MAX_DAYS).default(DEFAULT_DAYS), asAgentId: id.optional() }).strict()const leaderboardQuery = z.object({ projectId: id, week: z.coerce.number().int().nonnegative().safe().optional(), period: z.enum(PERIODS).optional(), scope: z.literal('all').optional() }).strict().refine(query => query.week === undefined || query.period === undefined, 'Ask for a week or a period, not both.')@@ -93,11 +95,17 @@ const nativeParams = tabParams.extend({ contextId: id })const messageParams = tabParams.extend({ conversationId: id })// A person's own read mark (superTabs/readMarks.ts): no asAgentId, since agents keep none.const readMarkBody = z.object({ sequence: z.number().int().nonnegative().safe() }).strict()+// Mark unread names the message it starts from: the mark goes to just before it.+const unreadBody = z.object({ sequence: z.number().int().positive().safe() }).strict()const followBody = z.object({ follow: z.boolean().nullable() }).strict()const notifyBody = z.object({ notify: z.enum(NOTIFY_LEVELS) }).strict()const activityReadBody = z.object({ through: z.string().datetime() }).strict()+// A time sets or replaces the reminder; null clears it. One POST, as Desktop reaches the backend through the daemon, which+// forwards only GET and POST (cli superTabs/service.ts), and the web's transport sends no other.+const reminderBody = z.object({ at: z.string().datetime({ offset: true }).nullable() }).strict()const threadParams = messageParams.extend({ threadId: id })const fileParams = messageParams.extend({ messageId: id, attachmentId: id })+const reminderParams = messageParams.extend({ messageId: id })const noQuery = z.object({}).strict()// The project whose open Buddy proposals a person reads (superTabs/proposals.ts).const proposalsQuery = z.object({ projectId: id }).strict()@@ -323,7 +331,7 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.post<{ Params: z.infer<typeof hostStartParams>; Body: z.infer<typeof operationSchema> }>('/api/super-tabs/hosts/:machineId/starts/:tabId/:startId',{ preHandler: [validateParams(hostStartParams), validateBody(operationSchema)] }, (req, reply) => respond(reply, async () => {if (!('startId' in req.body.command) || req.body.command.startId !== req.params.startId) throw new SuperTabError('FORBIDDEN', 'The host request must name this start.', 403)- return store.execute(req.user!, req.params.tabId, req.body, undefined, req.params.machineId)+ return store.execute(req.user!, req.params.tabId, req.body, undefined, req.params.machineId, declaredHttpClient(req.headers))}))// Whether teammates' agents can push to a project's repository: the Harness GitHub App installed there// (github/projectAccess.ts). `refresh=1`: a person installed it just now and checks again.@@ -497,7 +505,12 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su(req, reply) => respond(reply, () => reads.firstLoad(req.user!, req.params.tabId, req.query.asAgentId)))app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof changesQuery> }>('/api/super-tabs/:tabId/changes',{ preHandler: [validateParams(tabParams), validateQuery(changesQuery)] },- (req, reply) => respond(reply, noting(req, () => reads.changes(req.user!, req.params.tabId, req.query.cursor, req.query.asAgentId), nothingChanged)))+ (req, reply) => respond(reply, noting(req, () => reads.changes(req.user!, req.params.tabId, req.query.cursor, req.query.asAgentId,+ req.query.machines === 'light' ? { lightMachines: true } : {}), nothingChanged)))+ // The whole readings on demand, for a client that takes lines in its changes (read/changes.ts).+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/machine-readings',+ { preHandler: [validateParams(tabParams), validateQuery(agentQuery)] },+ (req, reply) => respond(reply, () => reads.machineReadings(req.user!, req.params.tabId, req.query.asAgentId)))// A person's unread threads and each chat's latest message (read/inbox.ts): read when the change feed moves, never on a timer.app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof noQuery> }>('/api/super-tabs/:tabId/inbox',{ preHandler: [validateParams(tabParams), validateQuery(noQuery)] }, async (req, reply) => {@@ -523,6 +536,13 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suif (wait) return sendError(reply.header('Retry-After', String(wait)), 'Too many Activity reads. Try again in a moment.', 'RATE_LIMITED', 429)return respond(reply, () => reads.activity(req.user!, req.params.tabId))})+ // A person's due reminders and when the next is due (superTabs/reminders.ts), read when its digest moves or at that time.+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof noQuery> }>('/api/super-tabs/:tabId/reminders',+ { preHandler: [validateParams(tabParams), validateQuery(noQuery)] }, async (req, reply) => {+ const wait = await reminderWait(req.user!, req.params.tabId)+ if (wait) return sendError(reply.header('Retry-After', String(wait)), 'Too many reminder reads. Try again in a moment.', 'RATE_LIMITED', 429)+ return respond(reply, () => reads.reminders(req.user!, req.params.tabId))+ })app.post<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof noQuery>; Body: z.infer<typeof activityReadBody> }>('/api/super-tabs/:tabId/activity/read',{ preHandler: [validateParams(tabParams), validateQuery(noQuery), validateBody(activityReadBody)] },(req, reply) => respond(reply, () => reads.markActivityRead(req.user!, req.params.tabId, req.body.through)))@@ -558,7 +578,7 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof operation> }>('/api/super-tabs/:tabId/commands',{ preHandler: [validateParams(tabParams), validateBody(operation, { named: true })] },(req, reply) => respond(reply, () => store.execute(req.user!, req.params.tabId,- { operationId: req.body.operationId, command: req.body.command }, req.body.asAgentId)))+ { operationId: req.body.operationId, command: req.body.command }, req.body.asAgentId, undefined, declaredHttpClient(req.headers))))// A chat file comes straight from the client (the desktop's and the browser's account token, or the daemon's for// `post --attach`), never through a machine or the relay. Multipart is parsed in this scope alone, so no other// Super Tab route's body handling changes.@@ -642,6 +662,10 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.post<{ Params: z.infer<typeof messageParams>; Querystring: z.infer<typeof noQuery>; Body: z.infer<typeof readMarkBody> }>('/api/super-tabs/:tabId/conversations/:conversationId/read',{ preHandler: [validateParams(messageParams), validateQuery(noQuery), validateBody(readMarkBody)] },(req, reply) => respond(reply, () => reads.markRead(req.user!, req.params.tabId, req.params.conversationId, req.body.sequence)))+ // A person's own Mark unread (superTabs/readMarks.ts lowerReadMark): the one write that moves their mark back.+ app.post<{ Params: z.infer<typeof messageParams>; Querystring: z.infer<typeof noQuery>; Body: z.infer<typeof unreadBody> }>('/api/super-tabs/:tabId/conversations/:conversationId/unread',+ { preHandler: [validateParams(messageParams), validateQuery(noQuery), validateBody(unreadBody)] },+ (req, reply) => respond(reply, () => reads.markUnread(req.user!, req.params.tabId, req.params.conversationId, req.body.sequence)))// A person's own thread mark (superTabs/readMarks.ts), as the conversation's above.app.post<{ Params: z.infer<typeof threadParams>; Querystring: z.infer<typeof noQuery>; Body: z.infer<typeof readMarkBody> }>('/api/super-tabs/:tabId/conversations/:conversationId/threads/:threadId/read',{ preHandler: [validateParams(threadParams), validateQuery(noQuery), validateBody(readMarkBody)] },@@ -650,6 +674,12 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.post<{ Params: z.infer<typeof threadParams>; Querystring: z.infer<typeof noQuery>; Body: z.infer<typeof followBody> }>('/api/super-tabs/:tabId/conversations/:conversationId/threads/:threadId/follow',{ preHandler: [validateParams(threadParams), validateQuery(noQuery), validateBody(followBody)] },(req, reply) => respond(reply, () => reads.followThread(req.user!, req.params.tabId, req.params.conversationId, req.params.threadId, req.body.follow)))+ // A person's own reminder of a message (superTabs/reminders.ts): set or replace its time, or clear it (`at` null).+ app.post<{ Params: z.infer<typeof reminderParams>; Querystring: z.infer<typeof noQuery>; Body: z.infer<typeof reminderBody> }>('/api/super-tabs/:tabId/conversations/:conversationId/messages/:messageId/reminder',+ { preHandler: [validateParams(reminderParams), validateQuery(noQuery), validateBody(reminderBody)] },+ (req, reply) => respond(reply, () => req.body.at === null+ ? reads.clearReminder(req.user!, req.params.tabId, req.params.conversationId, req.params.messageId)+ : reads.setReminder(req.user!, req.params.tabId, req.params.conversationId, req.params.messageId, req.body.at)))// A person's own notification setting for a chat (superTabs/chatSettings.ts): all, mentions or muted.app.post<{ Params: z.infer<typeof messageParams>; Querystring: z.infer<typeof noQuery>; Body: z.infer<typeof notifyBody> }>('/api/super-tabs/:tabId/conversations/:conversationId/notifications',{ preHandler: [validateParams(messageParams), validateQuery(noQuery), validateBody(notifyBody)] },diff --git a/backend/src/superTabs/activity.ts b/backend/src/superTabs/activity.tsindex d93a8ab55..5096b83a1 100644--- a/backend/src/superTabs/activity.ts+++ b/backend/src/superTabs/activity.ts@@ -122,23 +122,47 @@ export async function listActivity(db: PrismaClient, tabId: string, state: Superconst rows = await db.superTabActivity.findMany({ where: { tabId, personId: actor.userId, createdAt: { gt: new Date(now - ACTIVITY_EXPIRY_MS) } },orderBy: { createdAt: 'desc' }, take: ACTIVITY_LIST + 1 })const more = rows.length > ACTIVITY_LIST- const listed = rows.slice(0, ACTIVITY_LIST)- if (!listed.length) return { items: [], more }+ const present = (kind: string, id: string) => kind === 'person' ? state.people.some(p => p.id === id) : state.agents.some(a => a.id === id)+ // A reaction by someone no longer here drops out, as its count does (reactions.ts reactionCounts).+ const kept = rows.slice(0, ACTIVITY_LIST).filter(r => r.kind !== 'reaction' || present(r.actorKind, r.actorId))+ if (!kept.length) return { items: [], more }+ const shown = await readableMessages(db, tabId, state, actor, kept)+ const items = kept.flatMap(r => {+ const seen = shown(r)+ // A reaction's message must still be theirs.+ if (!seen || (r.kind === 'reaction' && !own(seen.message.author, actor.userId))) return []+ const { group, message } = seen+ return [{ id: r.id, kind: r.kind as ActivityKind, conversationId: r.conversationId, conversationTitle: group.title,+ projectName: projectOf(state, group.projectId ?? 'lead').name, messageId: r.messageId, messageSequence: message.sequence,+ threadId: threadOf(message), actor: { kind: r.actorKind as 'person' | 'agent', id: r.actorId,+ name: actorName(state, r.actorKind, r.actorId, r.kind === 'reply' ? message.author : undefined) },+ emoji: r.emoji ?? null, text: message.text, createdAt: r.createdAt.toISOString(), read: !!r.readAt }]+ })+ return { items, more }+}++/** A row naming one message of one chat, as Activity's and reminders' (reminders.ts) do. */+export interface MessageRef { conversationId: string; messageId: string }++/** What the person reads now of the messages `rows` name (the file's comment): a lookup giving a row its chat and message, or+ * null for a chat they cannot read (a quiet one is read by id, as tags read theirs, mentions.ts readable), a message a page+ * would not show them, or one no longer in the chat the row names. The messages by id in one read. */+export async function readableMessages(db: PrismaClient, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>,+ rows: MessageRef[]): Promise<(row: MessageRef) => { group: Conversation; message: Row } | null> {const groups = new Map(state.conversations.map(c => [c.id, c]))- const missing = [...new Set(listed.map(r => r.conversationId))].filter(id => !groups.has(id))+ const missing = [...new Set(rows.map(r => r.conversationId))].filter(id => !groups.has(id))if (missing.length) {- // A quiet chat by id through its index (parts/indexed.ts), as tags read theirs (mentions.ts readable).+ // A quiet chat by id through its index (parts/indexed.ts).for (const row of await groupsBy(db, 'key', [{ $match: { tabId, deleted: false, key: { $in: missing } } }, { $project: { _id: 0, key: 1, data: 1 } }])) {groups.set(row.key as string, row.data as unknown as Conversation)}}- const present = (kind: string, id: string) => kind === 'person' ? state.people.some(p => p.id === id) : state.agents.some(a => a.id === id)- const kept = listed.filter(r => {- const group = groups.get(r.conversationId)- // A reaction by someone no longer here drops out, as its count does (reactions.ts reactionCounts).- return group && !isLeads(group) && canReadGroup(state, actor, group) && (r.kind !== 'reaction' || present(r.actorKind, r.actorId))- })- if (!kept.length) return { items: [], more }+ const readableGroup = (id: string) => {+ const group = groups.get(id)+ return group && !isLeads(group) && canReadGroup(state, actor, group) ? group : null+ }+ const kept = rows.filter(r => readableGroup(r.conversationId))+ if (!kept.length) return () => nullconst found = (await readBy(db, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: [...new Set(kept.map(r => r.messageId))] }, tabId } },{ $project: { ...FIELDS, conversationId: 1 } }])).map(messageRow)// As a page filters rows (read/inbox.ts readable), Buddy-session rows included: against the state with the quiet chats read@@ -146,28 +170,22 @@ export async function listActivity(db: PrismaClient, tabId: string, state: Superconst held = new Set(state.conversations.map(c => c.id))const withQuiet: SuperTabState = { ...state, conversations: [...state.conversations, ...[...groups.values()].filter(g => !held.has(g.id))] }const messages = new Map((await readable(db, tabId, found, withQuiet)).map(m => [m.id, m]))- const items = kept.flatMap(r => {- const message = messages.get(r.messageId)- // The message must still be in the chat the row names, and be one the person reads; a reaction's must still be theirs.- if (!message || message.conversationId !== r.conversationId || (r.kind === 'reaction' && !own(message.author, actor.userId))) return []- const group = groups.get(r.conversationId)!- return [{ id: r.id, kind: r.kind as ActivityKind, conversationId: r.conversationId, conversationTitle: group.title,- projectName: projectOf(state, group.projectId ?? 'lead').name, messageId: r.messageId, messageSequence: message.sequence,- threadId: threadOf(message), actor: { kind: r.actorKind as 'person' | 'agent', id: r.actorId, name: actorName(state, r.actorKind, r.actorId, message, r.kind) },- emoji: r.emoji ?? null, text: message.text, createdAt: r.createdAt.toISOString(), read: !!r.readAt }]- })- return { items, more }+ return row => {+ const group = readableGroup(row.conversationId), message = messages.get(row.messageId)+ return group && message && message.conversationId === row.conversationId ? { group, message } : null+ }}/** A reply that lives only in its thread names its root; a top-level message or one also sent to the chat names none. */-const threadOf = (m: Row) => m.thread && m.thread !== m.id && !m.alsoInChat ? m.thread : null+export const threadOf = (m: Row) => m.thread && m.thread !== m.id && !m.alsoInChat ? m.thread : null-/** A person by the name the Swarm shows for them (personNames.ts); an agent by its name, or the reply's author name when it left. */-function actorName(state: SuperTabState, kind: string, id: string, message: Row, rowKind: string): string {+/** A person by the name the Swarm shows for them (personNames.ts); an agent by its name, or by `author`'s (the message it+ * wrote) when it left. */+export function actorName(state: SuperTabState, kind: string, id: string, author?: Author): string {if (kind === 'person') return shownNameOf(state, id) ?? 'Someone'const agent = state.agents.find(a => a.id === id) as { displayName?: string | null; name?: string } | undefined- const author = rowKind === 'reply' ? message.author as Author & { displayName?: string } : undefined- return agent?.displayName ?? agent?.name ?? author?.displayName ?? author?.name ?? 'An agent'+ const wrote = author as Author & { displayName?: string } | undefined+ return agent?.displayName ?? agent?.name ?? wrote?.displayName ?? wrote?.name ?? 'An agent'}/** Marks the person's rows made at or before `through` read, on every device. Only their own. */diff --git a/backend/src/superTabs/cachePatch.test.ts b/backend/src/superTabs/cachePatch.test.tsindex 8c54dc100..f1dc4be6f 100644--- a/backend/src/superTabs/cachePatch.test.ts+++ b/backend/src/superTabs/cachePatch.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'import { stableId } from './model.js'-import { baseRule, cacheDigest, dormantAgentRule, lightDormantAgentRule, feedRule, startsOfRule, dormantProjectRule, dormantRule, finishedStartsRule, groupRule, machinesRule } from './cachePatch.js'+import { baseRule, boardRule, cacheDigest, dormantAgentRule, lightDormantAgentRule, feedRule, startsOfRule, dormantProjectRule, dormantRule, finishedStartsRule, groupRule, machinesRule } from './cachePatch.js'import type { GroupData, Part, PartKind, SwarmParts } from './parts/index.js'import { projectLightGroup } from './parts/lightSelect.js'import type { SwarmDelta } from './parts/load.js'@@ -197,3 +197,36 @@ describe('startsOfRule (spec 2026-11-02 poll cost, Part 1.4)', () => {expect(rule.apply(held, delta([start('s3', 1, 'h7')]))).toBe(held)})})++describe('boardRule (task #2674)', () => {+ const FLOOR = Date.UTC(2026, 8, 28)+ const at = (days: number) => new Date(FLOOR + days * 86_400_000).toISOString()+ const group = (key: string, version: number, opts: { dormant?: boolean; projectId?: string; lastActivityAt?: string; deleted?: boolean } = {}) =>+ part('group', key, version, { id: key, title: key, kind: 'task', brief: 'a long brief', agentIds: ['a1'], checks: [], archived: false,+ requesterId: 'p1', pullRequestUrls: ['https://github.com/o/r/pull/1'], ledger: { askedAt: 1, shippedAt: 2 },+ assignment: { id: 'w1', status: 'done', result: 'a long result', execution: { machineId: 'm' } },+ ...opts.projectId ? { projectId: opts.projectId } : {}, lastActivityAt: opts.lastActivityAt ?? at(3) },+ { ...opts.dormant === false ? {} : { dormant: true }, ...opts.deleted ? { deleted: true } : {} }) as Part<GroupData>++ it('holds a quiet conversation of the projects active since the floor with the board\'s fields only', () => {+ const [held] = boardRule(['lead'], FLOOR).apply([], delta([group('g1', 2)])) as Part<GroupData>[]+ expect(held).toMatchObject({ key: 'g1', version: 2, dormant: true })+ expect(held!.data).toEqual({ id: 'g1', title: 'g1', kind: 'task', archived: false, requesterId: 'p1',+ pullRequestUrls: ['https://github.com/o/r/pull/1'], ledger: { askedAt: 1, shippedAt: 2 }, assignment: { id: 'w1', status: 'done' },+ lastActivityAt: at(3) })+ })++ it('leaves out one of another project, one quiet since before the floor, one awake and one removed', () => {+ const rule = boardRule(['lead', 'p2'], FLOOR)+ expect(rule.apply([], delta([group('g1', 1, { projectId: 'p3' }), group('g2', 1, { lastActivityAt: at(-1) }),+ group('g3', 1, { dormant: false }), group('g4', 1, { deleted: true })]))).toEqual([])+ expect((rule.apply([], delta([group('g5', 1, { projectId: 'p2' })])) as Part[]).map(g => g.key)).toEqual(['g5'])+ })++ it('lets go of a held one that woke, moved project or was removed, and keeps the held list when nothing newer came', () => {+ const rule = boardRule(['lead'], FLOOR)+ const held = rule.apply([], delta([group('g1', 1), group('g2', 1), group('g3', 1)])) as Part<GroupData>[]+ expect(rule.apply(held, delta([group('g1', 2, { dormant: false }), group('g2', 2, { projectId: 'p9' }), group('g3', 2, { deleted: true })]))).toEqual([])+ expect(rule.apply(held, delta([group('g1', 1), group('g9', 1, { projectId: 'p9' })]))).toBe(held)+ })+})diff --git a/backend/src/superTabs/cachePatch.ts b/backend/src/superTabs/cachePatch.tsindex 161b91704..451fae57d 100644--- a/backend/src/superTabs/cachePatch.ts+++ b/backend/src/superTabs/cachePatch.ts@@ -14,6 +14,7 @@ import type { SwarmDelta } from './parts/load.js'import { startFinished } from './parts/write.js'import { projectLightGroup } from './parts/lightSelect.js'import { stableId, type AgentStart } from './model.js'+import { boardGroup, lastActive } from './leaderboard/boardGroups.js'export interface PatchRule<T> {/** The part kinds whose changes this entry holds: a refresh reads only those. */@@ -25,10 +26,10 @@ export interface PatchRule<T> {comparable?(patched: T, fresh: T): [unknown, unknown]}-/** A changed part as a load would have given it: a change read adds `readAt`, which no load carries. */+/** A changed part as a load would have given it: a change read adds `readAt` and `contentAt`, which no load carries. */function asLoaded<T>(changed: Part): Part<T> {- if (changed.readAt === undefined) return changed as Part<T>- const { readAt: _readAt, ...loaded } = changed+ if (changed.readAt === undefined && changed.contentAt === undefined) return changed as Part<T>+ const { readAt: _readAt, contentAt: _contentAt, ...loaded } = changedreturn loaded as Part<T>}@@ -152,6 +153,16 @@ export function dormantProjectRule(projectId: string): PatchRule<Part<GroupData>return { kinds: ['group'], apply: (held, delta) => applyByKey(held, delta.parts, 'group', p => asleep(p) && ((p.data as GroupData).projectId ?? 'lead') === projectId) }}+/** A `board:{floor}:{projects}` entry (leaderboard/read.ts): the projects' quiet conversations last active since `floor`, each+ * with the board's fields only (leaderboard/boardGroups.ts), as `loadBoardGroups` loads them; a group stored with no project+ * is the default one's. One that wakes, moves project or is removed goes. */+export function boardRule(projectIds: readonly string[], floor: number): PatchRule<Part<GroupData>[]> {+ const projects = new Set(projectIds)+ const keep = (p: Part) => asleep(p) && projects.has((p.data as GroupData).projectId ?? 'lead') && lastActive(p.data as GroupData) >= floor+ return { kinds: ['group'], apply: (held, delta) => applyByKey(held, delta.parts.map(p => p.kind === 'group' && keep(p) ? boardGroup(p as Part<GroupData>) : p),+ 'group', keep) }+}+/** A `group:{id}` entry: that live group, dormant or not, or none. */export function groupRule(key: string): PatchRule<Part<GroupData>[]> {return { kinds: ['group'], apply: (held, delta) => applyByKey(held, delta.parts.filter(p => p.key === key), 'group', live) }diff --git a/backend/src/superTabs/checkVerdicts.ts b/backend/src/superTabs/checkVerdicts.tsindex a8037e843..54f4856bd 100644--- a/backend/src/superTabs/checkVerdicts.ts+++ b/backend/src/superTabs/checkVerdicts.ts@@ -5,16 +5,20 @@*/import type { Check, CheckVerdict } from './model.js'-/** Records [verdict] on [check], in place of its checker's earlier one, which it returns (undefined on its first). The- * verdicts are kept oldest first. A pass kept from before verdicts were is its checker's verdict; a failure from then names- * no checker, so it is not kept. */-export function recordCheckVerdict(check: Check, verdict: CheckVerdict): CheckVerdict | undefined {+/** Records [verdict] on [check], in place of its checker's earlier one (`earlier`, undefined on its first). The verdicts are+ * kept oldest first. A pass kept from before verdicts were is its checker's verdict; a failure from then names no checker,+ * so it is not kept. A pass also drops the failures of the checkers [clears] names, and returns them (`cleared`) for the+ * caller to record: those who left the Swarm, when someone accountable for the task passes it (#2656), as nobody else+ * could ever pass it in their place. */+export function recordCheckVerdict(check: Check, verdict: CheckVerdict, clears: (by: string) => boolean = () => false):+ { earlier: CheckVerdict | undefined; cleared: CheckVerdict[] } {const kept = check.verdicts ?? (check.passedBy ? [{ by: check.passedBy, passed: true, evidence: check.evidence ?? '', at: 0 }] : [])const earlier = kept.find(v => v.by === verdict.by)- const verdicts = check.verdicts = [...kept.filter(v => v !== earlier), verdict]+ const cleared = verdict.passed ? kept.filter(v => v !== earlier && !v.passed && clears(v.by)) : []+ const verdicts = check.verdicts = [...kept.filter(v => v !== earlier && !cleared.includes(v)), verdict]// The check passes only while no checker's latest verdict failed: its latest passer, else the latest failure's evidence.const failed = verdicts.findLast(v => !v.passed)check.passedBy = failed ? null : verdict.bycheck.evidence = (failed ?? verdict).evidence- return earlier+ return { earlier, cleared }}diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 89250200f..8b6ea5f6d 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -3547,7 +3547,24 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// records a verdict, its assignee too, and a failed one leaves the work's status as its agent set it. A verdict counts as a// review only from someone other than the assignee (leaderboard/record.ts).const by = actorKey(actor)- const first = !recordCheckVerdict(check, { by, passed: command.passed, evidence: command.evidence, at: context.now })+ // A checker who left the Swarm can never pass its failure again: the task's PM or an owner passing the check clears+ // it (Diego, 2026-11-04, #2656). A live checker's failure stands whoever passes. The PM is the project's coordinator+ // now, not the task's lead: a replaced PM's removal clears its lead on every task it led (review of #2916).+ const project = groupProject(state, group)+ const accountable = actor.kind === 'agent' ? ledProject(state, actor.agentId)?.id === project.id+ : [state.ownerId, project.ownerId].includes(actor.userId)+ const departed = (key: string) => key.startsWith('agent:') ? !state.agents.some(a => `agent:${a.id}` === key)+ : key.startsWith('person:') && !state.people.some(p => `person:${p.id}` === key)+ const name = actor.kind === 'agent' ? agentDisplayName(state.agents, actor.agentId) ?? agent(state, actor.agentId).name : actor.email+ const { earlier, cleared } = recordCheckVerdict(check, { by, passed: command.passed, evidence: command.evidence, at: context.now, name },+ accountable ? departed : undefined)+ const first = !earlier+ // A cleared failure stays on the record, in the task's own chat (security reviews of #2916): whose it was, its evidence's+ // first line, and who cleared it. A checker's name from before verdicts kept one is not known.+ for (const failure of cleared) {+ message(group.id, `${name} cleared ${failure.name ? `${failure.name}'s` : 'a checker\'s'} failure of “${check.description}”, as they left the Swarm: `+ + (failure.evidence.split('\n')[0] ?? '').trim().slice(0, 300), [], null, SYSTEM_ROW)+ }const run = group.ledger?.runs?.find(r => r.assignmentId === group.assignment!.id), reviewed = run?.firstReviewconst byAssignee = actor.kind === 'agent' && actor.agentId === group.assignment.agentId// A checker's verdict on a check counts once per attempt.diff --git a/backend/src/superTabs/hotFilters.allowed.json b/backend/src/superTabs/hotFilters.allowed.jsonindex 936f8806e..9188c1e93 100644--- a/backend/src/superTabs/hotFilters.allowed.json+++ b/backend/src/superTabs/hotFilters.allowed.json@@ -1,7 +1,6 @@{"src/superTabs/confidential.ts swarmAgent.findMany": 1,"src/superTabs/decisions.ts superTabDecision.findMany": 1,- "src/superTabs/mentions.ts superTabMessage.findMany": 1,"src/superTabs/migration/links.ts superTabAttempt.findMany": 1,"src/superTabs/migration/links.ts superTabMessage.findMany": 1,"src/superTabs/migration/workspaces.ts superTab.findMany": 1,diff --git a/backend/src/superTabs/leaderboard/boardGroups.ts b/backend/src/superTabs/leaderboard/boardGroups.tsnew file mode 100644index 000000000..429a53089--- /dev/null+++ b/backend/src/superTabs/leaderboard/boardGroups.ts@@ -0,0 +1,68 @@+/**+ * The quiet conversations the leaderboard sums (read.ts recentDormantGroups), as the read cache holds them (cachePatch.ts+ * boardRule): only the fields the board reads, and when the conversation was last active, which keeps the week it counts in.+ * Every open board reads them about once a minute; at prod's scale that was 86,610 documents in 2 h (Ken's scan, 2026-11-04).+ */+import type { Prisma } from '@prisma/client'+import type { GroupData, Part } from '../parts/index.js'+import { groupsBy, quietSince } from '../parts/indexed.js'+import { ms } from '../parts/light.js'++/** What the board reads of a group (stats.ts, record.ts waitsNow) and its read check (projects.ts canReadGroup); the title+ * names it in a person's details. */+export const BOARD_FIELDS = ['id', 'kind', 'projectId', 'title', 'leadId', 'audience', 'requesterId', 'reviewOf', 'step', 'archived', 'pullRequestUrls', 'ledger',+ 'assignment.id', 'assignment.status'] as const++/** The board's fields; the held entry also keeps the group's last activity (`lastActivityAt`), which it is trimmed by. */+const HELD_FIELDS = BOARD_FIELDS++/** The row's indexed `lastActivityAt` column (parts/write.ts), which the window is matched on, not the data's copy. */+const BOARD_GROUP = { _id: 0, key: 1, version: 1, changedAt: 1, ordinal: 1, dormant: 1, lastActivityAt: 1,+ ...Object.fromEntries(HELD_FIELDS.map(field => [`data.${field}`, 1])) }++/** A group's data as Mongo's `$project` of HELD_FIELDS gives it: a field that is absent stays absent, and `assignment` keeps+ * only its own named fields, and only when it is a document. */+export function boardData(data: GroupData): GroupData {+ const source = data as unknown as Record<string, unknown>+ const out: Record<string, unknown> = {}+ for (const field of HELD_FIELDS) {+ const [top, sub] = field.split('.') as [string, string | undefined]+ const value = source[top]+ if (value === undefined) continue+ if (!sub) { out[top] = value; continue }+ if (!value || typeof value !== 'object' || Array.isArray(value)) continue+ const inner = (value as Record<string, unknown>)[sub]+ if (inner === undefined) continue+ out[top] = { ...(out[top] as Record<string, unknown> | undefined), [sub]: inner }+ }+ return out as unknown as GroupData+}++/** A changed group part as the entry holds it, with the last activity its row is indexed by: the data's, else the write's+ * time (parts/write.ts extracted). */+export function boardGroup(part: Part<GroupData>): Part<GroupData> {+ const lastActivityAt = part.data!.lastActivityAt ?? new Date(part.changedAt).toISOString()+ return { kind: 'group', key: part.key, version: part.version, changedAt: part.changedAt, ordinal: part.ordinal,+ ...part.dormant ? { dormant: true as const } : {}, data: { ...boardData(part.data!), lastActivityAt } }+}++/** When a held conversation was last active: the time its row is indexed by (parts/write.ts). */+export const lastActive = (data: GroupData): number => data.lastActivityAt ? Date.parse(data.lastActivityAt) : Number.POSITIVE_INFINITY++/** These projects' quiet conversations last active since `floor`, through the project index (parts/indexed.ts), board fields+ * only. Planned without the index name, this read could take the dormancy index and read every quiet conversation. */+export async function loadBoardGroups(tx: Prisma.TransactionClient, tabId: string, projectIds: string[], floor: number): Promise<Part<GroupData>[]> {+ const rows = await groupsBy(tx, 'project', [{ $match: quietSince(tabId, projectIds, floor) }, { $project: BOARD_GROUP }])+ return rows.map(row => ({ kind: 'group', key: row.key as string, version: row.version as number, changedAt: ms(row.changedAt),+ ordinal: row.ordinal as number, ...row.dormant ? { dormant: true as const } : {},+ data: { ...(row.data ?? {}) as GroupData, lastActivityAt: new Date(ms(row.lastActivityAt)).toISOString() } }))+}++/** The project index's order (parts/indexed.ts `project`): project (none first), then last activity, then key. */+export function indexOrder(a: Part<GroupData>, b: Part<GroupData>): number {+ const pa = a.data!.projectId ?? null, pb = b.data!.projectId ?? null+ if (pa !== pb) return pa === null ? -1 : pb === null ? 1 : pa < pb ? -1 : 1+ const ta = lastActive(a.data!), tb = lastActive(b.data!)+ if (ta !== tb) return ta - tb+ return a.key < b.key ? -1 : a.key > b.key ? 1 : 0+}diff --git a/backend/src/superTabs/leaderboard/read.test.ts b/backend/src/superTabs/leaderboard/read.test.tsindex 1d210fa48..88597a00c 100644--- a/backend/src/superTabs/leaderboard/read.test.ts+++ b/backend/src/superTabs/leaderboard/read.test.ts@@ -1,6 +1,8 @@import { describe, expect, it } from 'vitest'import type { Prisma } from '@prisma/client'import { profileNames, recentDormantGroups } from './read.js'+import { DIRECT } from '../cachedReads.js'+import { weekStart } from './week.js'// Diego's issue file (2026-10-27): the board loaded every dormant group of the last 5 weeks whole, once a minute per open// column. It reads only what the board and its read check use (stats.ts, projects.ts canReadGroup).@@ -15,18 +17,23 @@ describe('the dormant groups the leaderboard sums', () => {return { tx, asked }}- it('reads only the fields the board uses, never a group whole', async () => {- const { tx, asked } = reading([{ data: { id: 'g1', requesterId: 'peer', ledger: { shippedAt: since + 1 }, assignment: { id: 'a1', status: 'done' } } }])- expect(await recentDormantGroups(tx, 'tab', 'web', since)).toEqual([{ id: 'g1', requesterId: 'peer', ledger: { shippedAt: since + 1 }, assignment: { id: 'a1', status: 'done' } }])+ const row = (id: string, lastActivityAt: number) => ({ key: id, version: 1, changedAt: { $date: new Date(since).toISOString() }, ordinal: 0, dormant: true,+ lastActivityAt: { $date: new Date(lastActivityAt).toISOString() },+ data: { id, requesterId: 'peer', ledger: { shippedAt: since + 1 }, assignment: { id: 'a1', status: 'done' } } })++ it('reads only the fields the board uses, never a group whole, from the Monday its window starts in', async () => {+ const { tx, asked } = reading([row('g1', since + 1), row('g0', since - 1)])+ // Held from the week's Monday (cachePatch.ts boardRule); answered for the window alone, without the activity it was kept by.+ expect(await recentDormantGroups(tx, DIRECT, 'tab', 'web', since)).toEqual([{ id: 'g1', requesterId: 'peer', ledger: { shippedAt: since + 1 }, assignment: { id: 'a1', status: 'done' } }])const [{ pipeline }] = asked as [{ pipeline: Array<Record<string, Record<string, unknown>>> }]- expect(pipeline[0]!.$match).toEqual({ tabId: 'tab', deleted: false, dormant: true, lastActivityAt: { $gte: { $date: new Date(since).toISOString() } }, projectId: { $in: ['web'] } })- expect(Object.keys(pipeline[1]!.$project!).sort()).toEqual(['_id', ...['archived', 'assignment.id', 'assignment.status', 'audience', 'id', 'kind', 'leadId', 'ledger',+ expect(pipeline[0]!.$match).toEqual({ tabId: 'tab', deleted: false, dormant: true, lastActivityAt: { $gte: { $date: new Date(weekStart(since)).toISOString() } }, projectId: { $in: ['web'] } })+ expect(Object.keys(pipeline[1]!.$project!).sort()).toEqual(['_id', 'key', 'version', 'changedAt', 'ordinal', 'dormant', 'lastActivityAt', ...['archived', 'assignment.id', 'assignment.status', 'audience', 'id', 'kind', 'leadId', 'ledger','projectId', 'pullRequestUrls', 'requesterId', 'reviewOf', 'step', 'title'].map(field => `data.${field}`)].sort())})it('reads the default project\'s groups stored with no project too', async () => {const { tx, asked } = reading([])- await recentDormantGroups(tx, 'tab', 'lead', since)+ await recentDormantGroups(tx, DIRECT, 'tab', 'lead', since)expect((asked[0] as { pipeline: Array<Record<string, Record<string, unknown>>> }).pipeline[0]!.$match).toMatchObject({ projectId: { $in: ['lead', null] } })})})diff --git a/backend/src/superTabs/leaderboard/read.ts b/backend/src/superTabs/leaderboard/read.tsindex ec3a72402..3854d7ff8 100644--- a/backend/src/superTabs/leaderboard/read.ts+++ b/backend/src/superTabs/leaderboard/read.ts@@ -2,7 +2,9 @@import type { Prisma } from '@prisma/client'import type { Conversation } from '../model.js'import { fail } from '../model.js'-import { groupsBy, quietSince } from '../parts/indexed.js'+import type { CacheView } from '../cache.js'+import { boardRule } from '../cachePatch.js'+import { indexOrder, lastActive, loadBoardGroups } from './boardGroups.js'import { LEDGER_WEEKS } from './record.js'import { WEEK_MS, weekStart } from './week.js'@@ -15,20 +17,20 @@ export function readableWeek(week: number | undefined, now: number): number {return week}-/** What the board reads of a group (stats.ts, record.ts waitsNow) and its read check (projects.ts canReadGroup); the title- * names it in a person's details. */-const BOARD_FIELDS = ['id', 'kind', 'projectId', 'title', 'leadId', 'audience', 'requesterId', 'reviewOf', 'step', 'archived', 'pullRequestUrls', 'ledger',- 'assignment.id', 'assignment.status'] as const--/** Dormant groups of one project active since [since]: a request shipped in a week the board sums wrote its Done row then.- * Only the fields the board reads: every open board reads them once a minute (Diego's issue file, 2026-10-27). */-export async function recentDormantGroups(tx: Prisma.TransactionClient, tabId: string, projectId: string | string[], since: number): Promise<Conversation[]> {- // Through the project index by name (parts/indexed.ts): planned, this read could take the dormancy one and read every quiet- // conversation of the Swarm to return none.- const rows = await groupsBy(tx, 'project', [{ $match: quietSince(tabId, projectId, since) },- { $project: { _id: 0, ...Object.fromEntries(BOARD_FIELDS.map(field => [`data.${field}`, 1])) } },- ]) as unknown as Array<{ data: Conversation }>- return rows.map(row => row.data)+/** The quiet conversations of these projects last active since [since], board fields only (boardGroups.ts): a request shipped+ * in a week the board sums wrote its Done row then. Through the read cache (cachePatch.ts boardRule): held from the Monday the+ * window starts in, patched from each change, so a board read at an unchanged stamp reads none (task #2674). Answered in the+ * project index's order, as the read straight from Mongo gives them. */+export async function recentDormantGroups(tx: Prisma.TransactionClient, cached: CacheView, tabId: string, projectId: string | string[],+ since: number): Promise<Conversation[]> {+ const projects = [...new Set([projectId].flat())].sort()+ const floor = weekStart(since)+ const held = await cached.get(tabId, `board:${floor}:${projects.join(',')}`, 'main', () => loadBoardGroups(tx, tabId, projects, floor),+ boardRule(projects, floor))+ return held.filter(p => lastActive(p.data!) >= since).sort(indexOrder).map(p => {+ const { lastActivityAt: _lastActivityAt, ...data } = p.data!+ return data as Conversation+ })}/** The profile names of the board's people (contract.ts displayName), one read by id for the few people of a Swarm. A member iddiff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.tsindex e59adff9c..bb49e0527 100644--- a/backend/src/superTabs/mentions.ts+++ b/backend/src/superTabs/mentions.ts@@ -305,8 +305,12 @@ export function mentionsDigest(ids: string[]): string {export async function listMentions(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, now: number, open: boolean) {const tagged = await readable(tx, tabId, state, actor, now, open)- const messages = tagged.length ? await tx.superTabMessage.findMany({ where: { tabId, id: { in: tagged.map(t => t.row.messageId) } },- select: { id: true, text: true, author: true, conversationId: true, thread: true, alsoInChat: true, sequence: true } }) : []+ // By id with a plain `$in` (parts/indexed.ts readBy): Prisma's `id: { in }` goes as an `$expr` OR of one branch per id, which+ // planned slowly (1,640 ms on prod, Ken's scan of 2026-11-04, task #2674).+ const messages = tagged.length ? (await readBy(tx, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: [...new Set(tagged.map(t => t.row.messageId))] }, tabId } },+ { $project: { text: 1, author: 1, conversationId: 1, thread: 1, alsoInChat: 1, sequence: 1 } }])).map(r => ({ id: r._id as string,+ text: r.text as string, author: r.author, conversationId: r.conversationId as string, thread: (r.thread as string | undefined) ?? null,+ alsoInChat: (r.alsoInChat as boolean | undefined) ?? null, sequence: r.sequence as number })) : []const threads = await threadsOf(tx, tabId, messages)return tagged.map(({ row, group }) => {const message = messages.find(m => m.id === row.messageId)diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex bd0425921..9db793b37 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -238,7 +238,10 @@ export interface Check {verdicts?: CheckVerdict[]}/** One checker's verdict on a check: its actor key (`agent:ID` or `person:ID`), what it found and when. */-export interface CheckVerdict { by: string; passed: boolean; evidence: string; at: number }+export interface CheckVerdict { by: string; passed: boolean; evidence: string; at: number+ /** The checker's name when it gave the verdict: once it leaves the Swarm, the line that clears its failure still names it+ * (#2656). Absent on verdicts given before. */+ name?: string }export interface Assignment {id: stringagentId: stringdiff --git a/backend/src/superTabs/parts/commit.ts b/backend/src/superTabs/parts/commit.tsindex 446b6dfd8..ad61ebc07 100644--- a/backend/src/superTabs/parts/commit.ts+++ b/backend/src/superTabs/parts/commit.ts@@ -141,6 +141,20 @@ const withoutReading = (data: unknown) => {return machine && { ...machine, contribution: machine.contribution && { ...machine.contribution, observation: undefined, lent: undefined, lentDays: undefined } }}+/** What a reading moves all the time, measured on production (2026-11-04: of 128 parts moved in 40 s, `resources` in all of them): a+ * client that asks gets a line for these, and reads them on demand (read/changes.ts, read/service.ts machineReadings). */+const VOLATILE_READING = ['receivedAt', 'resources', 'quotas', 'quotaReasons', 'profiles', 'privacy', 'harnessProgress', 'harnessTokens', 'harnessUncommitted'] as const+const steadyPart = (data: unknown) => {+ const machine = data as MachineData | undefined+ const observation = machine?.contribution?.observation+ if (!machine?.contribution) return machine+ const steady: Record<string, unknown> | undefined = observation && { ...observation }+ for (const field of VOLATILE_READING) if (steady) delete steady[field]+ return { ...machine, contribution: { ...machine.contribution, observation: steady, lent: undefined, lentDays: undefined } }+}+/** Whether a machine's write changes anything beyond those fields: running sessions, tools, readiness and all the rest. */+export const machineContentChanged = (before: unknown, after: unknown): boolean => !sameData(steadyPart(before), steadyPart(after))+/*** What a part write tells host reads (read/host.ts, review round 1), from the part's data before and after (undefined for* an insert or a removal): a machine's settings or ledger changed, not only its own reading; and which machines' hosts a@@ -251,7 +265,8 @@ export async function commitParts(tx: Transaction, loaded: { parts: SwarmParts;writes.push({ op: 'insert', kind, key, data: part.data, ordinal: stamp + added++ / 1000, first, ...host(kind, undefined, part.data) })if (kind !== 'group' && kind !== 'start' && kind !== 'progress') referencesChanged = true} else if (!sameData(prior.data, part.data)) {- writes.push({ op: 'update', kind, key, seen: prior.version, data: part.data, ...host(kind, prior.data, part.data) })+ writes.push({ op: 'update', kind, key, seen: prior.version, data: part.data, ...host(kind, prior.data, part.data),+ ...kind === 'machine' && machineContentChanged(prior.data, part.data) ? { content: true as const } : {} })}}for (const [key, prior] of before) {diff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.tsindex 0091d7fbb..dc8104ad7 100644--- a/backend/src/superTabs/parts/indexed.ts+++ b/backend/src/superTabs/parts/indexed.ts@@ -96,6 +96,12 @@ export const NAMED_INDEX = {SuperTabActivity: { age: { createdAt: 1 } },/** `age`: chat settings back at the default, untouched for a week (chatSettings.ts sweepChatSettings). */SuperTabChatSetting: { age: { updatedAt: 1 } },+ /** A person's reminders (reminders.ts): `person`, the due list, the next one, the digest and the cap's count; `due`, the+ * sweep's reminders due more than 30 days ago. */+ SuperTabReminder: {+ person: { tabId: 1, personId: 1, dueAt: 1 },+ due: { dueAt: 1 },+ },} as constexport type NamedCollection = keyof typeof NAMED_INDEXexport type NamedIndex<C extends NamedCollection> = keyof typeof NAMED_INDEX[C] & stringdiff --git a/backend/src/superTabs/parts/load.ts b/backend/src/superTabs/parts/load.tsindex accb8d984..62f0ca41b 100644--- a/backend/src/superTabs/parts/load.ts+++ b/backend/src/superTabs/parts/load.ts@@ -185,8 +185,8 @@ async function changedRows(tx: Transaction, tabIds: string[], since: Date, kinds}const changedPart = (kind: PartKind, row: Record<string, unknown>): Part => {- const readAt = row.readAt == null ? null : ms(row.readAt)- return { ...toPart(kind, rawPartRow(row)), ...readAt ? { readAt } : {} }+ const readAt = row.readAt == null ? null : ms(row.readAt), contentAt = row.contentAt == null ? null : ms(row.contentAt)+ return { ...toPart(kind, rawPartRow(row)), ...readAt ? { readAt } : {}, ...contentAt ? { contentAt } : {} }}/** What changed in one Swarm after `since`, for the read cache to patch what it holds (cache.ts; spec 2026-11-02 Phase 1):@@ -225,7 +225,7 @@ export async function loadStartsOfAgents(tx: Transaction, tabId: string, agentIdconst COLLECTION = { head: 'SwarmHead', member: 'SwarmMember', agent: 'SwarmAgent', group: 'SwarmGroup', machine: 'SwarmMachine', start: 'SwarmStart',progress: 'SwarmProgress' } as const satisfies Record<PartKind, NamedCollection>/** What a changed part is made of: its other fields are indexed copies of its data. */-const CHANGED_FIELDS = { tabId: 1, key: 1, version: 1, changedAt: 1, deleted: 1, ordinal: 1, data: 1, dormant: 1, readAt: 1,+const CHANGED_FIELDS = { tabId: 1, key: 1, version: 1, changedAt: 1, deleted: 1, ordinal: 1, data: 1, dormant: 1, readAt: 1, contentAt: 1,// A group's stored host digest (no other kind has one): the host signature's entry patches from it.hostDigest: 1,// The head's own columns (no other kind has them): a patched base keeps them too.diff --git a/backend/src/superTabs/parts/types.ts b/backend/src/superTabs/parts/types.tsindex b33781dc6..faefc0261 100644--- a/backend/src/superTabs/parts/types.ts+++ b/backend/src/superTabs/parts/types.ts@@ -16,6 +16,8 @@ export interface Part<T = unknown> {changedAt: number/** A machine part's last write of its own reading alone, when there was one (change reads only). */readAt?: number+ /** A machine part's last reading that changed more than its volatile fields, when there was one (change reads only). */+ contentAt?: numberdeleted?: truedormant?: trueordinal: numberdiff --git a/backend/src/superTabs/parts/write.ts b/backend/src/superTabs/parts/write.tsindex e24db3c0e..3ee51f38a 100644--- a/backend/src/superTabs/parts/write.ts+++ b/backend/src/superTabs/parts/write.ts@@ -23,7 +23,8 @@ export interface HeadColumns { groupCounter: number; visibilityEpoch: number; seexport type PartWrite =/** `first`: a new key's version, the Swarm's sequence base + 1 (design section 2.1). */| { op: 'insert'; kind: PartKind; key: string; data: unknown; ordinal: number; first?: number; head?: HeadColumns; host?: HostColumns }- | { op: 'update'; kind: PartKind; key: string; seen: number; data: unknown; head?: HeadColumns; host?: HostColumns }+ /** `content`: a machine's own reading that changed more than its volatile fields (commit.ts machineContentChanged). */+ | { op: 'update'; kind: PartKind; key: string; seen: number; data: unknown; head?: HeadColumns; host?: HostColumns; content?: true }| { op: 'remove'; kind: PartKind; key: string; seen: number; data: unknown; host?: HostColumns }| { op: 'touch'; kind: PartKind; key: string; seen: number }@@ -137,7 +138,7 @@ export async function guardedWrite(tx: Transaction, tabId: string, write: PartWr}const data = write.op === 'touch' ? {}: write.op === 'remove' ? { changedAt: new Date(stamp), deleted: true, purgeAt: new Date(stamp + RETENTION_MS), data: json(write.data), ...write.host }- : { ...reading ? { readAt: new Date(stamp) } : { changedAt: new Date(stamp) }, data: json(write.data), ...(write.kind === 'start'+ : { ...reading ? { readAt: new Date(stamp), ...write.content ? { contentAt: new Date(stamp) } : {} } : { changedAt: new Date(stamp) }, data: json(write.data), ...(write.kind === 'start'? await keepFinishedAt(tx, id, extracted(write.kind, write.data, stamp)) : extracted(write.kind, write.data, stamp)), ...write.head, ...write.host }const updated = await model.updateMany({ where: { id, version: write.seen, deleted: false }, data: { version: write.seen + 1, ...data } })if (!updated.count) throw new PartConflict(write.kind, write.key)diff --git a/backend/src/superTabs/personNames.ts b/backend/src/superTabs/personNames.tsindex 9c23cea4d..0888f7d9e 100644--- a/backend/src/superTabs/personNames.ts+++ b/backend/src/superTabs/personNames.ts@@ -7,6 +7,23 @@ import { agentNamesSeenBy, nameKey, swarmUsernames, usernameOf } from './usernam/** Characters, not UTF-16 units: a name in any script, or with an emoji, gets the same room. */export const MAX_NAME_LENGTH = 40+/**+ * Why [name] (already trimmed) cannot be a name people see for a person, or null: a web address, or a role's or the+ * Swarm's own name. A Swarm name (setName below) and the account name (lib/accountName.ts, review 1 of #2917) refuse+ * the same ones.+ */+export function nameRefusal(name: string): { code: 'INVALID_NAME' | 'NAME_RESERVED'; message: string } | null {+ // Read as every compare here reads it: width variants folded (NFKC), so `PM` is `PM` (review 2 of #2794).+ const folded = name.normalize('NFKC')+ // A web address would show as a link in the lines the server writes (review 2 of #2794).+ if (/:\/\/|^www\./i.test(folded)) return { code: 'INVALID_NAME', message: 'Use a name, not a web address.' }+ // A role's or the Swarm's own voice, as a Buddy may not take (buddies.ts), and the words readers put in place of a name.+ if (isRoleName(folded) || reserved(folded) || /^(?:tester|you|someone)(?:[\s#-]+\d+)?$/i.test(folded)) {+ return { code: 'NAME_RESERVED', message: `${name} is a role's name. Choose another.` }+ }+ return null+}+/*** `member.name`: a person sets the name the Swarm shows for them ("Minh Nguyen"), or clears it to show their username* again. Their username stays the handle a tag types. Trimmed, with one space between words, and never another member's@@ -22,14 +39,8 @@ export function setName(state: SuperTabState, actor: Actor, input: string | nullif (!name || [...name].length > MAX_NAME_LENGTH || !printable(name)) {fail('INVALID_NAME', `Use 1 to ${MAX_NAME_LENGTH} characters, with no hidden ones.`, 400)}- // Read as every compare here reads it: width variants folded (NFKC), so `PM` is `PM` (review 2 of #2794).- const folded = name.normalize('NFKC')- // A web address would show as a link in the lines the server writes (review 2 of #2794).- if (/:\/\/|^www\./i.test(folded)) fail('INVALID_NAME', 'Use a name, not a web address.', 400)- // A role's or the Swarm's own voice, as a Buddy may not take (buddies.ts), and the words readers put in place of a name.- if (isRoleName(folded) || reserved(folded) || /^(?:tester|you|someone)(?:[\s#-]+\d+)?$/i.test(folded)) {- fail('NAME_RESERVED', `${name} is a role's name. Choose another.`, 400)- }+ const refused = nameRefusal(name)+ if (refused) fail(refused.code, refused.message, 400)const key = nameKey(name)const usernames = swarmUsernames(state)const others = state.people.filter(p => p.id !== member.id)diff --git a/backend/src/superTabs/purge.ts b/backend/src/superTabs/purge.tsindex adb3ca0e6..25f294abc 100644--- a/backend/src/superTabs/purge.ts+++ b/backend/src/superTabs/purge.ts@@ -16,7 +16,7 @@ export const PURGE_RETRY_MS = 6 * 60 * 60 * 1000/** The records of one Swarm, each by its Swarm id (every one has an index led by it, schema.prisma). Attachments are* removed apart, with their files. */-export const PURGED_BY_TAB_ID = ['superTabMessage', 'superTabMention', 'superTabReaction', 'superTabActivity', 'superTabChatSetting', 'superTabReadMark',+export const PURGED_BY_TAB_ID = ['superTabMessage', 'superTabMention', 'superTabReaction', 'superTabActivity', 'superTabChatSetting', 'superTabReminder', 'superTabReadMark','superTabThreadMark', 'superTabThread', 'superTabDecision', 'superTabOperation', 'superTabNativeContext', 'superTabDelivery', 'superTabReceipt','superTabRun', 'superTabAttempt', 'superTabRouteDecision', 'superTabModelEvidence', 'superTabModelRecent', 'superTabStopReceipt','superTabRoleText', 'superTabInstructions', 'superTabInstructionsRevision', 'superTabPmNote', 'superTabConfiguration', 'superTabTerminalRequest',diff --git a/backend/src/superTabs/read/changes.test.ts b/backend/src/superTabs/read/changes.test.tsindex 1f90ab981..1932f757d 100644--- a/backend/src/superTabs/read/changes.test.ts+++ b/backend/src/superTabs/read/changes.test.ts@@ -144,3 +144,67 @@ describe('changes since a cursor (design 4.4)', () => {expect(requires(receive(fresh, changed, owner).groups)).toEqual({ machines: ['secret-mac', 'mac'] })})})++// A client that asks for it gets a line for a machine's own reading (Ken's machine-cap plan, 2026-11-04).+describe('a machine\'s reading, for a client that asks for lines', () => {+ const SINCE = NOW + 1_000+ const lightly = (parts: SwarmParts, changed: Part[], actor: Actor) => {+ const view = readerView(parts, actor, LATER, { teamMachines: [] })+ return changesFor(view, changed, actor, { since: SINCE })+ }+ const reading = (parts: SwarmParts, change: (p: Part) => void = () => {}) => {+ const part = parts.machines.find(p => p.key === 'mac')! as Part+ part.version += 1+ part.readAt = LATER+ const data = part.data as { contribution: { observation?: unknown } }+ data.contribution.observation = { receivedAt: LATER, resources: {}, quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [] }+ change(part)+ return part+ }++ it('is a line when only the reading moved', () => {+ const { parts } = scene()+ const out = lightly(parts, [reading(parts)], peer)+ expect(out.machines).toEqual([])+ expect(out.machineReadings).toEqual([{ key: 'mac', version: R + 1, receivedAt: LATER }])+ })++ it('is the whole part when its content changed since the cursor', () => {+ const { parts } = scene()+ const out = lightly(parts, [reading(parts, p => { p.contentAt = LATER })], peer)+ expect(keys(out.machines)).toEqual(['mac'])+ expect(out.machineReadings).toEqual([])+ })++ it('is the whole part when anything else changed since the cursor, and a line when its content changed before it', () => {+ const { parts } = scene()+ expect(keys(lightly(parts, [reading(parts, p => { p.changedAt = LATER })], peer).machines)).toEqual(['mac'])+ const { parts: older } = scene()+ expect(lightly(older, [reading(older, p => { p.contentAt = SINCE - 1 })], peer).machines).toEqual([])+ })++ it('is a removal, never a line, when the machine left', () => {+ const { parts } = scene()+ const gone = write(parts, 'machines', 'mac', p => { p.deleted = true; p.readAt = LATER })+ const out = changesFor(readerView({ ...parts, machines: [] }, peer, LATER, { teamMachines: [] }), [gone], peer, { since: SINCE })+ expect(out.machines).toEqual([{ key: 'mac', version: R + 1, changedAt: LATER, deleted: true }])+ expect(out.machineReadings).toEqual([])+ })++ it('tells a Buddy nothing, and anyone nothing of a Buddy-only machine', () => {+ const { parts, s } = scene()+ s.edit(state => { state.agents.push({ ...state.agents[0]!, id: 'buddy', buddyOf: { personId: peer.userId, generation: 'g' } } as never) })+ const withBuddy = store.split(s.state, { tabId: 'tab', version: R, now: NOW })+ const buddy: Actor = { kind: 'agent', agentId: 'buddy', machineOwnerId: `${owner.userId}-machine` }+ expect(lightly(withBuddy, [reading(withBuddy)], buddy).machineReadings).toEqual([])+ const hidden = reading(parts, p => { (p.data as { contribution: { buddyOnly?: true } }).contribution.buddyOnly = true })+ expect(lightly(parts, [hidden], peer).machineReadings).toEqual([])+ })++ it('leaves the reply as it was for a client that did not ask', () => {+ const { parts } = scene()+ const out = receive(parts, [reading(parts)], peer)+ expect(keys(out.machines)).toEqual(['mac'])+ expect(out).not.toHaveProperty('machineReadings')+ })+})diff --git a/backend/src/superTabs/read/changes.ts b/backend/src/superTabs/read/changes.tsindex ec38cecd1..5e7b9c46e 100644--- a/backend/src/superTabs/read/changes.ts+++ b/backend/src/superTabs/read/changes.ts@@ -7,17 +7,18 @@ import { groupForBuddy, type Actor, type Agent, type AgentStart, type Conversatiimport { isBuddyReader } from '../buddies.js'import { canReadAgent, canReadGroup } from '../projects.js'import { knownKind, type MachineData, type Part } from '../parts/index.js'-import type { ChangesDelta, DormantStub, Tombstone } from './contract.js'+import type { ChangesDelta, DormantStub, MachineView, Tombstone } from './contract.js'import { envelope, progressView, seenIn, visibleGroupView, type ReaderView } from './views.js'-export type PartChanges = Pick<ChangesDelta, 'head' | 'members' | 'agents' | 'groups' | 'machines' | 'starts' | 'progress'>+export type PartChanges = Pick<ChangesDelta, 'head' | 'members' | 'agents' | 'groups' | 'machines' | 'machineReadings' | 'starts' | 'progress'>const stub = (part: Part): Tombstone => ({ key: part.key, version: part.version, changedAt: part.changedAt, deleted: true })const dormantStub = (part: Part): DormantStub => ({ key: part.key, version: part.version, changedAt: part.changedAt, dormant: true })/** A read check that names a project which no longer exists answers no. */const safely = (check: () => boolean): boolean => { try { return check() } catch { return false } }-export function changesFor(view: ReaderView, changed: Part[], actor: Actor): PartChanges {+/** [light]: the reader asked for a line for a machine's own reading, and its cursor's time: anything else since then sends the part. */+export function changesFor(view: ReaderView, changed: Part[], actor: Actor, light?: { since: number }): PartChanges {const { state, parts: seen } = viewconst live = <T>(list: Array<{ key: string } & T>, key: string) => list.find(p => p.key === key)const groupReadable = (group: Conversation) => safely(() => canReadGroup(state, actor, group))@@ -25,7 +26,7 @@ export function changesFor(view: ReaderView, changed: Part[], actor: Actor): Par?? changed.find(p => p.kind === 'group' && p.key === id)?.data as Conversation | undefinedconst visibleAgents = new Set(seen.agents.map(a => a.key))const seenMachines = seenIn(seen), buddy = isBuddyReader(state, actor)- const out: PartChanges = { head: null, members: [], agents: [], groups: [], machines: [], starts: [], progress: [] }+ const out: PartChanges = { head: null, members: [], agents: [], groups: [], machines: [], ...light ? { machineReadings: [] } : {}, starts: [], progress: [] }for (const part of changed) {switch (part.kind) {case 'head': out.head = seen.head; break@@ -61,7 +62,10 @@ export function changesFor(view: ReaderView, changed: Part[], actor: Actor): Parconst data = part.data as MachineData | nullif (data?.contribution?.buddyOnly || data?.cleanups?.some(c => c.buddyOnly) || data?.closingSessions?.some(c => c.buddyOnly)) breakconst machine = live(seen.machines, part.key)- if (machine && !part.deleted) out.machines.push(machine)+ const receivedAt = (machine?.data as MachineView | undefined)?.observation?.receivedAt+ if (machine && !part.deleted && light && receivedAt !== undefined && Math.max(part.changedAt, part.contentAt ?? 0) <= light.since) {+ out.machineReadings!.push({ key: part.key, version: part.version, receivedAt })+ } else if (machine && !part.deleted) out.machines.push(machine)// Machine ids are no secret among members, unlike conversations: a contribution that ended reads as a removal.else if (part.deleted || !(part.data as MachineData | null)?.contribution) out.machines.push(stub(part))breakdiff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex ca23f11cf..32bdc521a 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -87,10 +87,19 @@ export interface Derived {/** A person only: a digest of which of their Activity rows are unread (activity.ts), moving when one is written, read or* removed. No count and no chat: the client reads its list again when it moves. Absent from an older backend. */activityDigest?: string+ /** A person only: a digest of their reminders and when each is due (reminders.ts), moving when one is set, replaced or+ * cleared. No count and no chat: the client reads its reminders again when it moves, and at the `next` time that read+ * gave it. Absent from an older backend. */+ remindersDigest?: string/** A person only: their own read marks (readMarks.ts), the newest message sequence read by conversation. A first load has* every one of the conversations it holds; a changes read only those moved since its cursor, kept by the client as the* higher of the two. Never another person's. */readMarks?: Record<string, number>+ /** A person only: those of their `readMarks` whose last move was their own Mark unread (readMarks.ts lowerReadMark), which+ * a client takes in place of a higher mark it holds, where it keeps the higher of the two for every other mark. Like+ * `readMarks`: a first load has every one of the conversations it holds, a changes read those moved since its cursor; a read+ * that raises the mark again ends it. Absent when there are none, and from an older backend. Never another person's. */+ unreadMarks?: Record<string, number>/** A person only: their own thread marks (readMarks.ts), the newest message sequence read by thread root, by conversation.* Like `readMarks`: a first load has those of the conversations it holds, a changes read those moved since its cursor.* Absent when there are none, and from an older backend. Never another person's. */@@ -150,6 +159,11 @@ export interface FirstLoad extends ReadMeta {export type Changes = ChangesReload | ChangesDelta/** Drop the store and do a first load: bad or old cursor, another epoch, or older than tombstones are kept. */export interface ChangesReload { reload: true }+/** A machine's own reading, as one line, for a client that asked (`machines=light`): when it last reported, from which it works out+ * online or offline as it does from a part. The rest of the reading is read on demand (MachineReadings). */+export interface MachineReading { key: string; version: number; receivedAt: number }+/** GET /api/super-tabs/:tabId/machine-readings[?asAgentId=]: every machine the reader sees, whole, for the route and the machine panel. */+export interface MachineReadings { format: number; serverTime: number; machines: LivePart<MachineView>[] }export interface ChangesDelta extends ReadMeta {reload: falsehead: LivePart<HeadView> | null@@ -157,6 +171,8 @@ export interface ChangesDelta extends ReadMeta {agents: PartChange<AgentView>[]groups: GroupChange[]machines: PartChange<MachineView>[]+ /** Only for a client that asked: machines whose reading alone moved, which `machines` then leaves out. */+ machineReadings?: MachineReading[]starts: PartChange<StartView>[]progress: PartChange<ProgressView>[]derived: Deriveddiff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex 8f88bbe6d..ed3091fa5 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -6,14 +6,16 @@ import { startsOfRule } from '../cachePatch.js'import type { PrismaClient } from '@prisma/client'import type { AuthUser } from '../../lib/ssoAuth.js'import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../../lib/teamSession.js'-import { agentOnly, author, fail, groupForBuddy, isLeads, seenMachineIds, stableId, SuperTabError, visibleState, type Actor, type AgentStart, type SuperTabState } from '../model.js'+import { agentOnly, author, fail, groupForBuddy, isLeads, seenMachineIds, stableId, SuperTabError, visibleState, type Actor, type AgentStart, type Conversation, type SuperTabState } from '../model.js'import { logger } from '../../utils/logger.js'import { mentionsDigest, resolveRead, swarmsWithTags, waitingMentions, waitingTagConversations } from '../mentions.js'import { decisionsWaiting } from '../decisions.js'-import { readMarks, readThreadMarks, writeThreadFollow, writeThreadMark } from '../readMarks.js'+import { lowerReadMark, readMarkRows, readThreadMarks, writeThreadFollow, writeThreadMark, type ReadMarkRow } from '../readMarks.js'import { activityDigest, listActivity, markActivityRead, markActivityThreadRead, type ActivityItem } from '../activity.js'+import { clearReminder, listReminders, REMINDER_AHEAD_MS, remindersDigest, setReminder, type ReminderItem } from '../reminders.js'import { readChatSettings, writeChatSetting, type NotifyLevel } from '../chatSettings.js'import { deliveredCopies } from '../pageReads.js'+import { FIELDS, readable, row as messageRow } from './inbox.js'import { readBy } from '../parts/indexed.js'import type { SuperTabStore } from '../store.js'import { transaction } from '../store.js'@@ -31,7 +33,7 @@ import { LEDGER_WEEKS } from '../leaderboard/record.js'import type { PeriodName } from '../leaderboard/rolling.js'import { leaderboard } from '../leaderboard/stats.js'import { WEEK_MS } from '../leaderboard/week.js'-import { READ_FORMAT, SWARM_MIGRATING, type Changes, type Derived, type DormantGroups, type FirstLoad, type OneGroup, type SwarmList } from './contract.js'+import { READ_FORMAT, SWARM_MIGRATING, type Changes, type Derived, type MachineReadings, type DormantGroups, type FirstLoad, type OneGroup, type SwarmList } from './contract.js'import { AvatarLinks } from '../avatarLinks.js'import { cursorFor, readCursor } from './cursor.js'import { changesFor } from './changes.js'@@ -54,14 +56,17 @@ function readableGroups(read: Read): Set<string> {}/** The reader's marks of the conversations and threads they can read now: a mark never names a conversation the reader has- * lost. Only in a person's read; nothing for an agent. A read with no thread marks says none (`threadMarks` absent). */-function readableMarks(read: Read, marks: Map<string, number>, threads: Map<string, Map<string, number>>, settings: Map<string, NotifyLevel> = new Map()):- Pick<Derived, 'readMarks' | 'threadMarks' | 'chatSettings'> {+ * lost. Only in a person's read; nothing for an agent. A read with no thread marks says none (`threadMarks` absent), and one+ * with no mark their Mark unread moved last none either (`unreadMarks` absent). */+function readableMarks(read: Read, marks: ReadMarkRow[], threads: Map<string, Map<string, number>>, settings: Map<string, NotifyLevel> = new Map()):+ Pick<Derived, 'readMarks' | 'unreadMarks' | 'threadMarks' | 'chatSettings'> {if (read.actor.kind !== 'person') return {}const readable = readableGroups(read)+ const kept = marks.filter(mark => readable.has(mark.conversationId))+ const unreadMarks = Object.fromEntries(kept.filter(mark => mark.lowered).map(mark => [mark.conversationId, mark.sequence]))const threadMarks = Object.fromEntries([...threads].filter(([id]) => readable.has(id)).map(([id, held]) => [id, Object.fromEntries(held)]))const chatSettings = Object.fromEntries([...settings].filter(([id]) => readable.has(id)))- return { readMarks: Object.fromEntries([...marks].filter(([id]) => readable.has(id))),+ return { readMarks: Object.fromEntries(kept.map(mark => [mark.conversationId, mark.sequence])), ...(Object.keys(unreadMarks).length ? { unreadMarks } : {}),...(Object.keys(threadMarks).length ? { threadMarks } : {}), ...(Object.keys(chatSettings).length ? { chatSettings } : {}) }}@@ -141,7 +146,18 @@ export class SwarmReads {return Object.keys(avatars).length ? { ...view.derived, avatars } : view.derived}- async changes(user: AuthUser, tabId: string, cursor: string, asAgentId?: string): Promise<Changes> {+ /** Every machine the reader sees, whole: what a client that asks for lines in its changes reads when it needs more than liveness. */+ async machineReadings(user: AuthUser, tabId: string, asAgentId?: string): Promise<MachineReadings> {+ const t0 = this.now()+ return this.read(user, tabId, async (tx, cached) => {+ const base = await readLight(tx, cached, tabId, LIGHT)+ const read = await this.load(tx, cached, user, tabId, asAgentId, t0, {}, async () => base)+ // A Buddy reads no machines (read/changes.ts).+ return { format: READ_FORMAT, serverTime: t0, machines: isBuddyReader(read.view.state, read.actor) ? [] : read.view.parts.machines }+ })+ }++ async changes(user: AuthUser, tabId: string, cursor: string, asAgentId?: string, options: { lightMachines?: boolean } = {}): Promise<Changes> {const t0 = this.now()return this.read(user, tabId, async (tx, cached) => {// Light (parts/light.ts): changed parts come whole from the change feed; the rest is read only to check visibility and@@ -156,7 +172,7 @@ export class SwarmReads {const person = asAgentId ? null : user.subconst [changed, tagged, marks, threadMarks, settings] = await Promise.all([readChanged(tx, cached, tabId, from.since),person ? waitingTagConversations(tx, tabId, person, t0) : [],- person ? readMarks(tx, tabId, person, from.since) : new Map<string, number>(),+ person ? readMarkRows(tx, tabId, person, from.since) : [],person ? readThreadMarks(tx, tabId, person, from.since) : new Map<string, Map<string, number>>(),person ? readChatSettings(tx, tabId, person, from.since) : new Map<string, NotifyLevel>()])// Starts: only unfinished ones whole in the base, then the poll's own.@@ -167,11 +183,11 @@ export class SwarmReads {// moved, so the mark goes only to a reader who can still read it.const held = new Set(base.groups.map(g => g.key))const named = [...new Set([...tagged, ...[...changed.filter(p => p.kind === 'start'), ...extra].map(p => (p.data as AgentStart).request.conversationId),- ...marks.keys(), ...threadMarks.keys(), ...settings.keys()])].filter(id => !held.has(id))+ ...marks.map(mark => mark.conversationId), ...threadMarks.keys(), ...settings.keys()])].filter(id => !held.has(id))const read = await this.load(tx, cached, user, tabId, asAgentId, t0, {},async () => withStarts(withGroups(base, await readLightGroups(tx, cached, tabId, named)), extra))return { format: READ_FORMAT, reload: false, cursor: cursorFor(t0, read.parts.visibilityEpoch), serverTime: t0, lastChangedAt: read.lastChangedAt,- epoch: read.parts.visibilityEpoch, ...changesFor(read.view, changed, read.actor),+ epoch: read.parts.visibilityEpoch, ...changesFor(read.view, changed, read.actor, options.lightMachines ? { since: from.since } : undefined),derived: { ...await this.withAvatars(read.view, t0), ...readableMarks(read, marks, threadMarks, settings) } }})}@@ -246,6 +262,17 @@ export class SwarmReads {return { sequence: stored }}+ /** The person's Mark unread from the message at `sequence`: their mark of a conversation they can read goes to just before it,+ * never forward (readMarks.ts lowerReadMark), and never past the conversation's newest message. Checked as markRead: only a+ * person reading as themselves, and every chat they cannot read is the same refusal. Tags it resolved and Activity it read+ * stay so; a reply only in a thread keeps its thread's mark. */+ async markUnread(user: AuthUser, tabId: string, conversationId: string, sequence: number): Promise<{ sequence: number }> {+ if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)+ const { group } = await this.readGroup(user, tabId, conversationId)+ const target = Math.min(sequence - 1, group.data!.lastMessageSequence)+ return { sequence: await lowerReadMark(this.db, { tabId, personId: user.sub, conversationId, sequence: target, now: this.now() }) }+ }+/** Moves the person's mark of thread `threadId` in a conversation they can read forward, never past the conversation's* newest message (readMarks.ts), which the reader sees already: a hidden reply's sequence never shows in the answer.* Checked as a page of messages is (store.ts messages): the Swarm read with that conversation alone, then the root by its@@ -273,15 +300,7 @@ export class SwarmReads {private async readableThread(user: AuthUser, tabId: string, conversationId: string, threadId: string): Promise<number> {if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)const unavailable = () => fail('NOT_FOUND', 'This conversation is unavailable.', 404)- const { state } = await this.store.readLoad(user, tabId, { groupIds: [conversationId] })- const actor = await this.store.actor(this.db, user, state)- let newest: number- try {- newest = readConversation(state, actor, conversationId).lastMessageSequence- } catch (error) {- if (error instanceof SuperTabError && error.status === 404) unavailable()- throw error- }+ const newest = (await this.readableChat(user, tabId, conversationId)).conversation.lastMessageSequenceconst [found] = await readBy(this.db, 'SuperTabMessage', 'id', [{ $match: { _id: threadId, tabId, conversationId } },{ $project: { source: 1, recipientIds: 1, thread: 1 } }])const root = found && { id: found._id as string, source: found.source ?? null, recipientIds: (found.recipientIds as string[] | undefined) ?? [], thread: found.thread }@@ -313,6 +332,52 @@ export class SwarmReads {return await listActivity(this.db, tabId, state, actor, this.now())}+ /** The person's due reminders in this Swarm and when the next one is due (reminders.ts), those they can read now. A person+ * reading as themselves only. */+ async reminders(user: AuthUser, tabId: string): Promise<{ due: ReminderItem[]; next: string | null }> {+ if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)+ const { state } = await this.store.readLoad(user, tabId)+ const actor = await this.store.actor(this.db, user, state)+ author(state, actor)+ if (actor.kind !== 'person') return fail('FORBIDDEN', 'Only a person has reminders.', 403)+ return await listReminders(this.db, tabId, state, actor, this.now())+ }++ /** Sets the person's reminder of one message to `at` (reminders.ts), replacing one they set before: a time after now and at+ * most REMINDER_AHEAD_MS ahead, on a message they read as a page shows it, in that chat. Every miss (a chat they cannot read,+ * another chat's message, one that does not exist or that a page would not show them) is the same refusal. Only a person+ * reading as themselves. */+ async setReminder(user: AuthUser, tabId: string, conversationId: string, messageId: string, at: string): Promise<{ id: string; dueAt: string }> {+ if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)+ const now = this.now(), dueAt = Date.parse(at)+ if (!(dueAt > now) || dueAt > now + REMINDER_AHEAD_MS) fail('INVALID_REMINDER', 'Choose a time in the next 30 days.', 400)+ const { state } = await this.readableChat(user, tabId, conversationId)+ const [found] = await readBy(this.db, 'SuperTabMessage', 'id', [{ $match: { _id: messageId, tabId, conversationId } }, { $project: { ...FIELDS, conversationId: 1 } }])+ if (!found || !(await readable(this.db, tabId, [messageRow(found)], state)).length) fail('NOT_FOUND', 'This message is unavailable.', 404)+ return await setReminder(this.db, { tabId, personId: user.sub, conversationId, messageId, dueAt, now })+ }++ /** Clears the person's reminder of one message of a chat they can read (reminders.ts), as Activity's Reminders does when they+ * open it, and answers whether there was one. Only their own, as themselves. */+ async clearReminder(user: AuthUser, tabId: string, conversationId: string, messageId: string): Promise<{ cleared: boolean }> {+ if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)+ await this.readableChat(user, tabId, conversationId)+ return { cleared: await clearReminder(this.db, { tabId, personId: user.sub, conversationId, messageId }) }+ }++ /** Conversation `conversationId` and the Swarm's state, for a person reading as themselves who reads it: every conversation+ * they cannot read, or that does not exist, is the same refusal. The Swarm is read with that conversation alone. */+ private async readableChat(user: AuthUser, tabId: string, conversationId: string): Promise<{ state: SuperTabState; conversation: Conversation }> {+ const { state } = await this.store.readLoad(user, tabId, { groupIds: [conversationId] })+ const actor = await this.store.actor(this.db, user, state)+ try {+ return { state, conversation: readConversation(state, actor, conversationId) }+ } catch (error) {+ if (error instanceof SuperTabError && error.status === 404) fail('NOT_FOUND', 'This conversation is unavailable.', 404)+ throw error+ }+ }+/** Marks the person's Activity made at or before `through` read on every device, never past now. */async markActivityRead(user: AuthUser, tabId: string, through: string): Promise<{ marked: number }> {if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)@@ -330,8 +395,8 @@ export class SwarmReads {}/** A person's own read marks (an agent has none), every one or those moved since `since`. */- private async marksOf(tx: PrismaClient, tabId: string, actor: Actor, since?: number): Promise<Map<string, number>> {- return actor.kind === 'person' ? readMarks(tx, tabId, actor.userId, since) : new Map()+ private async marksOf(tx: PrismaClient, tabId: string, actor: Actor, since?: number): Promise<ReadMarkRow[]> {+ return actor.kind === 'person' ? readMarkRows(tx, tabId, actor.userId, since) : []}/** One project's leaderboard for a week (leaderboard/stats.ts), for the people who read the project. It sums only the@@ -345,7 +410,7 @@ export class SwarmReads {readProject(state, actor, projectId)// Every project this reader reads, by the same check as the one asked for; what they may not read is never loaded.const readable = allProjects ? projectsOf(state).filter(p => canReadProject(state, actor, p)).map(p => p.id) : undefined- const dormant = await recentDormantGroups(tx, tabId, readable ?? projectId, now - LEDGER_WEEKS * WEEK_MS)+ const dormant = await recentDormantGroups(tx, cached, tabId, readable ?? projectId, now - LEDGER_WEEKS * WEEK_MS)const groups = [...state.conversations.filter(g => !g.dormant), ...dormant].filter(g => !isLeads(g) && canReadGroup(state, actor, g))const names = await profileNames(tx, state.people.map(p => p.id))// Which machines the reader sees, with the daily rows no other read carries.@@ -423,13 +488,13 @@ export class SwarmReads {const [[teamMachines, otherWorkspaceMachines, machineVersions], counts, newest] = await Promise.all([this.machineLookups(state),actor.kind === 'person' ? Promise.all([waitingMentions(tx, tabId, state, actor, t0), decisionsWaiting(tx, tabId, state, actor),- activityDigest(tx, tabId, actor.userId, t0)]) : undefined,+ activityDigest(tx, tabId, actor.userId, t0), remindersDigest(tx, tabId, actor.userId)]) : undefined,readLastChangedAt(tx, cached, tabId),])return { parts: loaded, actor, lastChangedAt: newest,view: readerView(loaded, actor, t0, { teamMachines, otherWorkspaceMachines, machineVersions, teamAccountsIdle: this.store.teamAccountsIdle,...(counts ? { mentionsWaiting: counts[0].count, mentionsDigest: counts[0].digest, decisionsWaiting: counts[1].count,- decisionsDigest: counts[1].digest, activityDigest: counts[2] } : {}) }, state) }+ decisionsDigest: counts[1].digest, activityDigest: counts[2], remindersDigest: counts[3] } : {}) }, state) }}/** Which of the Swarm's machines are signed in as a team account, and which serve another Workspace's Swarm too (store.ts): thediff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.tsindex 0543412ed..f8549a903 100644--- a/backend/src/superTabs/read/views.ts+++ b/backend/src/superTabs/read/views.ts@@ -50,6 +50,8 @@ export interface ReadExtras {decisionsDigest?: string/** Which of their Activity rows are unread, as a digest (activity.ts). */activityDigest?: string+ /** Which reminders they have and when each is due, as a digest (reminders.ts). */+ remindersDigest?: string}const HEAD_FIELDS = ['version', 'id', 'name', 'project', 'projects', 'leadsConversationId', 'ownerId', 'environment',@@ -151,6 +153,7 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:...(actor.kind === 'person' && extras.decisionsWaiting !== undefined ? { decisionsWaiting: extras.decisionsWaiting } : {}),...(actor.kind === 'person' && extras.decisionsDigest !== undefined ? { decisionsDigest: extras.decisionsDigest } : {}),...(actor.kind === 'person' && extras.activityDigest !== undefined ? { activityDigest: extras.activityDigest } : {}),+ ...(actor.kind === 'person' && extras.remindersDigest !== undefined ? { remindersDigest: extras.remindersDigest } : {}),threadSessions: true as const,sessionsFromChat: true as const,// One Buddy per person per Swarm (Dee, 10-31): an app shows # buddy and New session in a project only when the server says so.diff --git a/backend/src/superTabs/readMarks.ts b/backend/src/superTabs/readMarks.tsindex 7482f513a..585015cc7 100644--- a/backend/src/superTabs/readMarks.ts+++ b/backend/src/superTabs/readMarks.ts@@ -26,7 +26,7 @@ export interface ThreadMarkWrite extends ReadMarkWrite { threadId: string }/** The calls `raise` makes, which both mark collections answer alike. */interface MarkRows {- updateMany(args: { where: { id: string; sequence: { lt: number } }; data: { sequence: number; updatedAt: Date } }): Promise<{ count: number }>+ updateMany(args: { where: { id: string; sequence: { lt: number } }; data: { sequence: number; updatedAt: Date } & Record<string, unknown> }): Promise<{ count: number }>findUnique(args: { where: { id: string }; select: { sequence: true } }): Promise<{ sequence: number } | null>create(args: { data: Record<string, unknown> & { id: string } }): Promise<unknown>}@@ -34,11 +34,12 @@ interface MarkRows {/** Moves row `id` forward to `sequence` and answers the mark as stored, with whether this call created the row. An older* mark never replaces a newer one: the update matches only a lower mark. When another device's write lands between the* update and the look after it (two first writes racing to create the row, or one raising it), the update runs again;- * every retry follows a write that raised the mark, so a few settle it. */-async function raise(rows: MarkRows, id: string, sequence: number, updatedAt: Date, data: Record<string, unknown>): Promise<{ sequence: number; created: boolean }> {+ * every retry follows a write that raised the mark, so a few settle it. `moved` is set on the row with the mark. */+async function raise(rows: MarkRows, id: string, sequence: number, updatedAt: Date, data: Record<string, unknown>, moved: Record<string, unknown> = {}):+ Promise<{ sequence: number; created: boolean }> {for (let attempt = 0; attempt < 4; attempt++) {- const moved = await rows.updateMany({ where: { id, sequence: { lt: sequence } }, data: { sequence, updatedAt } })- if (moved.count) return { sequence, created: false }+ const raised = await rows.updateMany({ where: { id, sequence: { lt: sequence } }, data: { ...moved, sequence, updatedAt } })+ if (raised.count) return { sequence, created: false }const held = await rows.findUnique({ where: { id }, select: { sequence: true } })if (held && held.sequence >= sequence) return { sequence: held.sequence, created: false }if (held) continue@@ -52,11 +53,35 @@ async function raise(rows: MarkRows, id: string, sequence: number, updatedAt: Dareturn fail('READ_MARK_BUSY', 'This conversation is being marked read on another device. Try again.', 503)}-/** Moves the person's mark of a conversation forward to `sequence` and answers the mark as stored (`raise`). */+/** Moves the person's mark of a conversation forward to `sequence` and answers the mark as stored (`raise`). A read that moves+ * it ends a Mark unread: the mark no longer reads as lowered (lowerReadMark). */export async function writeReadMark(db: PrismaClient, mark: ReadMarkWrite): Promise<number> {const { tabId, personId, conversationId, sequence } = markreturn (await raise(db.superTabReadMark as unknown as MarkRows, stableId(tabId, conversationId, personId), sequence, new Date(mark.now),- { tabId, personId, conversationId })).sequence+ { tabId, personId, conversationId }, { loweredAt: null })).sequence+}++/** The person's Mark unread: moves their mark of a conversation back to `sequence`, never forward (a chat already unread from+ * earlier stays as it is), and answers the mark as stored. The one write that lowers a mark. It sets `loweredAt` with+ * `updatedAt`, so their other devices, which keep the higher of a mark and the one they hold, take this one instead+ * (readMarkRows `lowered`). A chat with no mark counts as read (read/inbox.ts), so it gets one. One conditional update; when+ * another device creates or moves the row between it and the look after it, it runs again, as `raise` does. */+export async function lowerReadMark(db: PrismaClient, mark: ReadMarkWrite): Promise<number> {+ const { tabId, personId, conversationId, sequence } = mark+ const id = stableId(tabId, conversationId, personId), at = new Date(mark.now)+ for (let attempt = 0; attempt < 4; attempt++) {+ if ((await db.superTabReadMark.updateMany({ where: { id, sequence: { gt: sequence } }, data: { sequence, updatedAt: at, loweredAt: at } })).count) return sequence+ const held = await db.superTabReadMark.findUnique({ where: { id }, select: { sequence: true } })+ if (held && held.sequence <= sequence) return held.sequence+ if (held) continue+ try {+ await db.superTabReadMark.create({ data: { id, tabId, personId, conversationId, sequence, updatedAt: at, loweredAt: at } })+ return sequence+ } catch (error) {+ if (!(error instanceof Prisma.PrismaClientKnownRequestError) || error.code !== 'P2002') throw error+ }+ }+ return fail('READ_MARK_BUSY', 'This conversation is being marked read on another device. Try again.', 503)}/** Moves the person's mark of one thread forward to `sequence` and answers the mark as stored (`raise`). A new mark past@@ -141,11 +166,20 @@ async function capThreadMarks(db: PrismaClient, tabId: string, personId: string)await db.$runCommandRaw({ delete: 'SuperTabThreadMark', deletes: [{ q: { _id: { $in: oldest.map(row => row._id as string) } }, limit: 0 }] })}+/** One of the person's read marks; `lowered` when its last move was their Mark unread (lowerReadMark). */+export interface ReadMarkRow { conversationId: string; sequence: number; lowered: boolean }++/** The person's marks in this tab; with `since`, only those moved at or after it. A Mark unread is its row's last move while+ * `loweredAt` equals `updatedAt`: a read since clears it, and one from a backend that did not clear it moves `updatedAt`. */+export async function readMarkRows(db: PrismaClient, tabId: string, personId: string, since?: number): Promise<ReadMarkRow[]> {+ const rows = await db.superTabReadMark.findMany({ where: { tabId, personId, ...(since === undefined ? {} : { updatedAt: { gte: new Date(since) } }) },+ select: { conversationId: true, sequence: true, updatedAt: true, loweredAt: true } })+ return rows.map(row => ({ conversationId: row.conversationId, sequence: row.sequence, lowered: row.loweredAt?.getTime() === row.updatedAt.getTime() }))+}+/** The person's marks in this tab, by conversation; with `since`, only those moved at or after it. */export async function readMarks(db: PrismaClient, tabId: string, personId: string, since?: number): Promise<Map<string, number>> {- const rows = await db.superTabReadMark.findMany({ where: { tabId, personId, ...(since === undefined ? {} : { updatedAt: { gte: new Date(since) } }) },- select: { conversationId: true, sequence: true } })- return new Map(rows.map(row => [row.conversationId, row.sequence]))+ return new Map((await readMarkRows(db, tabId, personId, since)).map(row => [row.conversationId, row.sequence]))}/** The person's thread marks in this tab, by conversation then thread root: every one (at most THREAD_MARK_CAP), or withdiff --git a/backend/src/superTabs/refusalLog.test.ts b/backend/src/superTabs/refusalLog.test.tsnew file mode 100644index 000000000..19d0ea41b--- /dev/null+++ b/backend/src/superTabs/refusalLog.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest'+import { declaredHttpClient, refusalLogFields } from './refusalLog.js'++/** Ken's prod scan (11-04): 615 agent.configuration refusals in 32 minutes, and the log could not say whose. Each refusal now+ * names its Swarm, the agent it names or acts as, and the client that sent it, never what the command says. */+describe('refusal log', () => {+ it('names the Swarm, the agent a host acts as, and the CLI and its version', () => {+ const client = declaredHttpClient({ 'user-agent': 'node', 'x-harness-client': 'cli/0.5.34' })+ expect(refusalLogFields('tab1', { type: 'agent.configuration' }, 'AGENT_UNAVAILABLE', { asAgentId: 'agent7', client, machineId: 'm1' }))+ .toEqual({ code: 'AGENT_UNAVAILABLE', type: 'agent.configuration', tabId: 'tab1', agentId: 'agent7', asAgent: true,+ client: 'cli', version: '0.5.34', machineId: 'm1' })+ })++ it('names the agent a command names over the one it acts as', () => {+ const fields = refusalLogFields('tab1', { type: 'agent.alert', agentId: 'agent9' }, 'AGENT_UNAVAILABLE',+ { asAgentId: 'agent7', client: declaredHttpClient({}) })+ expect(fields.agentId).toBe('agent9')+ expect(fields.asAgent).toBe(true)+ })++ it('a person’s message: no agent, the app by its user agent, and none of its words', () => {+ const command = { type: 'message.send', conversationId: 'g1', text: 'secret plan for [email protected]', recipientIds: ['a1'] }+ const fields = refusalLogFields('tab1', command, 'NOT_FOUND', { client: declaredHttpClient({ 'user-agent': 'Dart/3.13 (dart:io)' }) })+ expect(fields).toEqual({ code: 'NOT_FOUND', type: 'message.send', tabId: 'tab1', agentId: null, asAgent: false, client: 'app', version: null })+ expect(JSON.stringify(fields)).not.toMatch(/secret|ken@example|g1|a1/)+ })++ it('a declared client is believed only in its own shape', () => {+ expect(declaredHttpClient({ 'x-harness-client': 'cli/0.5.34' })).toEqual({ kind: 'cli', version: '0.5.34' })+ expect(declaredHttpClient({ 'x-harness-client': 'desktop/1.3.57' })).toEqual({ kind: 'desktop', version: '1.3.57' })+ for (const bad of ['cli', 'robot/1.0', 'cli/1.0 <script>', `cli/${'9'.repeat(60)}`, ['cli/1.0', 'cli/2.0']]) {+ expect(declaredHttpClient({ 'user-agent': 'node', 'x-harness-client': bad })).toEqual({ kind: 'cli', version: null })+ }+ expect(declaredHttpClient({ 'user-agent': 'Mozilla/5.0' })).toEqual({ kind: 'web', version: null })+ expect(declaredHttpClient({})).toEqual({ kind: 'other', version: null })+ })+})diff --git a/backend/src/superTabs/refusalLog.ts b/backend/src/superTabs/refusalLog.tsnew file mode 100644index 000000000..2cc9e4957--- /dev/null+++ b/backend/src/superTabs/refusalLog.ts@@ -0,0 +1,28 @@+import { clientKind } from '../lib/routeLatency.js'++/** What a client declares itself on an HTTP request (`x-harness-client: cli/0.5.34`; the CLI sends it since #2675, as its+ * sockets declare `?client=&v=`, lib/wsAttribution.ts). Believed only in its own shape, so a header never writes into the+ * log; otherwise the kind is the user agent's (lib/routeLatency.ts) and the version unknown. */+export interface DeclaredClient { kind: string; version: string | null }+const DECLARED = /^(cli|desktop|phone|web)\/([0-9A-Za-z.+-]{1,32})$/++export function declaredHttpClient(headers: Record<string, string | string[] | undefined>): DeclaredClient {+ const declared = headers['x-harness-client']+ const match = typeof declared === 'string' ? DECLARED.exec(declared) : null+ if (match) return { kind: match[1]!, version: match[2]! }+ const agent = headers['user-agent']+ return { kind: clientKind(typeof agent === 'string' ? agent : undefined, false), version: null }+}++/** The 'Swarm command refused' line (Ken's prod scan, 11-04: 615 refusals in 32 minutes that nobody could attribute): its+ * code and type as before, the Swarm, the agent the command names or else acts as, whether it acts as one, the client and+ * its version, and a host route's machine. Never what the command says: no text, conversation, recipient or email. */+export function refusalLogFields(tabId: string, command: { type: string; agentId?: unknown }, code: string,+ from: { asAgentId?: string; client?: DeclaredClient; machineId?: string } = {}): Record<string, unknown> {+ const named = typeof command.agentId === 'string' ? command.agentId : undefined+ return {+ code, type: command.type, tabId, agentId: named ?? from.asAgentId ?? null, asAgent: !!from.asAgentId,+ client: from.client?.kind ?? 'other', version: from.client?.version ?? null,+ ...(from.machineId ? { machineId: from.machineId } : {}),+ }+}diff --git a/backend/src/superTabs/reminders.ts b/backend/src/superTabs/reminders.tsnew file mode 100644index 000000000..74153fa78--- /dev/null+++ b/backend/src/superTabs/reminders.ts@@ -0,0 +1,151 @@+/**+ * A person's reminders in one Swarm (Desktop's Remind me on a message): the message comes back to them at a time, under+ * Activity's Reminders, until they open it. One row per person and message (SuperTabReminder): setting it again replaces its+ * time, opening it deletes it. Rows live outside the tab state, so writing one wakes no other reader; the person's own read+ * carries a digest of theirs (remindersDigest), and their client reads the list again when it moves or when the next one is due.+ *+ * Privacy: read, set and cleared only by their person, as themselves (read/service.ts). A list keeps only what they can read+ * now, as Activity's does (activity.ts readableMessages): the chat by canReadGroup, a quiet one read by id, and the message as a+ * page shows it to a person, still in the chat the row names.+ *+ * Growth: opening one deletes it; at most REMINDER_CAP per person and Swarm, due or not; the hourly sweep deletes those due+ * more than REMINDER_EXPIRY_MS ago (sweepReminders), and a Swarm's purge the rest (purge.ts). A row is at most+ * REMINDER_AHEAD_MS + REMINDER_EXPIRY_MS old.+ *+ * Reads: each of a person's reads is one range of the (tabId, personId, dueAt) index (`person`): the due ones newest first,+ * the next one after now, the digest's at most REMINDER_CAP and the cap's count. The sweep reads by `due`.+ */+import { createHash } from 'node:crypto'+import { Prisma, type PrismaClient } from '@prisma/client'+import type { AuthUser } from '../lib/ssoAuth.js'+import { createRateLimiter } from '../lib/rateLimit.js'+import { fail, stableId, type Actor, type SuperTabState } from './model.js'+import { projectOf } from './projects.js'+import { readBy } from './parts/indexed.js'+import { ms } from './parts/light.js'+import { actorName, readableMessages, threadOf } from './activity.js'++/** Reminders one person keeps in one Swarm, due or not: one more is refused (REMINDER_LIMIT). The list reads at most these. */+export const REMINDER_CAP = 200+/** How far ahead a reminder may be set. */+export const REMINDER_AHEAD_MS = 30 * 24 * 60 * 60_000+/** A reminder due this long ago, never opened, is deleted by the sweep. */+export const REMINDER_EXPIRY_MS = 30 * 24 * 60 * 60_000+/** Rows one sweep deletes at most, in batches; the rest wait for the next hour. */+export const REMINDER_SWEEP = 20_000+const SWEEP_BATCH = 1_000++const at = (time: number) => ({ $date: new Date(time).toISOString() })+export const reminderId = (tabId: string, personId: string, messageId: string) => stableId(tabId, personId, messageId)++export interface ReminderWrite { tabId: string; personId: string; conversationId: string; messageId: string; dueAt: number; now: number }++/** Sets the person's reminder of a message to `dueAt`, replacing the time of one they set before, and answers it. The caller has+ * checked the time and that they read the message. A new one past REMINDER_CAP is refused; two first ones racing at the cap+ * may both land, one over it. */+export async function setReminder(db: PrismaClient, write: ReminderWrite): Promise<{ id: string; dueAt: string }> {+ const { tabId, personId, conversationId, messageId } = write+ const id = reminderId(tabId, personId, messageId), dueAt = new Date(write.dueAt)+ const [counted] = await readBy(db, 'SuperTabReminder', 'person', [{ $match: { tabId, personId } }, { $count: 'n' }])+ if (Number(counted?.n ?? 0) >= REMINDER_CAP && !(await db.superTabReminder.findUnique({ where: { id }, select: { id: true } }))) {+ fail('REMINDER_LIMIT', `You have ${REMINDER_CAP} reminders in this Swarm. Open or clear one first.`, 409)+ }+ const upsert = () => db.superTabReminder.upsert({ where: { id }, update: { dueAt },+ create: { id, tabId, personId, conversationId, messageId, dueAt, createdAt: new Date(write.now) } })+ try {+ await upsert()+ } catch (error) {+ // Two devices setting it at once: the loser's create meets the winner's row, and its time replaces it.+ if (!(error instanceof Prisma.PrismaClientKnownRequestError) || error.code !== 'P2002') throw error+ await upsert()+ }+ return { id, dueAt: dueAt.toISOString() }+}++/** Deletes the person's reminder of a message of this chat, and answers whether there was one. Only their own: the id names them. */+export async function clearReminder(db: PrismaClient, ref: { tabId: string; personId: string; conversationId: string; messageId: string }): Promise<boolean> {+ const reply = await db.$runCommandRaw({ delete: 'SuperTabReminder', deletes: [{ q: { _id: reminderId(ref.tabId, ref.personId, ref.messageId),+ conversationId: ref.conversationId }, limit: 1 }] }) as { n?: number }+ return Number(reply.n ?? 0) > 0+}++/** A digest of the person's reminders and their times, moving when one is set, replaced or cleared: the client reads its list+ * again when it moves, and at the `next` time a list gave it, never on a timer. No count and no chat. */+export async function remindersDigest(db: PrismaClient, tabId: string, personId: string): Promise<string> {+ const rows = await readBy(db, 'SuperTabReminder', 'person', [{ $match: { tabId, personId } }, { $sort: { dueAt: 1 } }, { $limit: REMINDER_CAP },+ { $project: { _id: 1, dueAt: 1 } }])+ return createHash('sha256').update(rows.map(r => `${r._id as string} ${ms(r.dueAt)}`).sort().join('\n')).digest('base64url').slice(0, 16)+}++export interface ReminderItem {+ id: string+ conversationId: string+ conversationTitle: string+ projectName: string+ messageId: string+ /** Where the message is in its chat. */+ messageSequence: number+ /** The thread the message is in, when it is a reply that lives only there; null for one in the chat's main stream. */+ threadId: string | null+ /** Who wrote the message. */+ author: { kind: 'person' | 'agent'; id: string; name: string }+ /** The message's text, cut by the database. */+ text: string+ dueAt: string+}++/** The person's due reminders, newest due first, those they can read now (see the file's comment), and when the next one is+ * due after now (null when none is). */+export async function listReminders(db: PrismaClient, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, now: number):+ Promise<{ due: ReminderItem[]; next: string | null }> {+ const personId = actor.userId+ const [rows, upcoming] = await Promise.all([+ readBy(db, 'SuperTabReminder', 'person', [{ $match: { tabId, personId, dueAt: { $lte: at(now) } } }, { $sort: { dueAt: -1 } }, { $limit: REMINDER_CAP },+ { $project: { _id: 1, conversationId: 1, messageId: 1, dueAt: 1 } }]),+ readBy(db, 'SuperTabReminder', 'person', [{ $match: { tabId, personId, dueAt: { $gt: at(now) } } }, { $sort: { dueAt: 1 } }, { $limit: 1 },+ { $project: { _id: 0, dueAt: 1 } }]),+ ])+ const next = upcoming[0] ? new Date(ms(upcoming[0].dueAt)).toISOString() : null+ const listed = rows.map(r => ({ id: r._id as string, conversationId: r.conversationId as string, messageId: r.messageId as string, dueAt: ms(r.dueAt) }))+ if (!listed.length) return { due: [], next }+ const shown = await readableMessages(db, tabId, state, actor, listed)+ const due = listed.flatMap(r => {+ const seen = shown(r)+ if (!seen) return []+ const { group, message } = seen+ return [{ id: r.id, conversationId: r.conversationId, conversationTitle: group.title, projectName: projectOf(state, group.projectId ?? 'lead').name,+ messageId: r.messageId, messageSequence: message.sequence, threadId: threadOf(message),+ author: { kind: message.author.kind, id: message.author.id, name: actorName(state, message.author.kind, message.author.id, message.author) },+ text: message.text, dueAt: new Date(r.dueAt).toISOString() }]+ })+ return { due, next }+}++/** The hourly sweep (sweeps.ts): deletes reminders due more than REMINDER_EXPIRY_MS ago by the due index, in batches. No TTL+ * index: the app user may not set one on an index `db push` built (#2238), as Activity. */+export async function sweepReminders(db: PrismaClient, now: number): Promise<number> {+ let deleted = 0+ const before = at(now - REMINDER_EXPIRY_MS)+ while (deleted < REMINDER_SWEEP) {+ const rows = await readBy(db, 'SuperTabReminder', 'due', [{ $match: { dueAt: { $lt: before } } }, { $limit: SWEEP_BATCH }, { $project: { _id: 1 } }])+ if (rows.length) {+ const reply = await db.$runCommandRaw({ delete: 'SuperTabReminder', deletes: [{ q: { _id: { $in: rows.map(r => r._id as string) } }, limit: 0 }] }) as { n?: number }+ deleted += Number(reply.n ?? 0)+ }+ if (rows.length < SWEEP_BATCH) break+ }+ return deleted+}++/** Reminder list reads a person may make in one Swarm per window, as Activity's (activity.ts ACTIVITY_READS). */+export const REMINDER_READS = 10+export const REMINDER_WINDOW_MS = 10_000+const reminderReads = createRateLimiter('swarm-reminders', REMINDER_WINDOW_MS, REMINDER_READS)++/** Seconds a person must wait before reading this Swarm's reminders again, or 0 when they may now (as activityWait). */+export async function reminderWait(user: AuthUser, tabId: string, now = Date.now()): Promise<number> {+ if (await reminderReads.allows(`${user.sub}:${tabId}`, now)) return 0+ return Math.max(1, Math.ceil((REMINDER_WINDOW_MS - now % REMINDER_WINDOW_MS) / 1000))+}+/** Test seam: forget this process's counts. */+export const resetReminderReads = () => reminderReads.reset()diff --git a/backend/src/superTabs/steps.test.ts b/backend/src/superTabs/steps.test.tsindex 5da0ae4b6..250d15f1a 100644--- a/backend/src/superTabs/steps.test.ts+++ b/backend/src/superTabs/steps.test.ts@@ -599,8 +599,8 @@ describe('checks with several checkers', () => {check(reviewer, true, 'Diff reads right')expect(read()).toMatchObject({ passedBy: null, evidence: 'Crashes offline\nlog' })expect(read().verdicts).toEqual([- { by: `agent:${tester}`, passed: false, evidence: 'Crashes offline\nlog', at: f.now - 1000 },- { by: `agent:${reviewer}`, passed: true, evidence: 'Diff reads right', at: f.now },+ { by: `agent:${tester}`, passed: false, evidence: 'Crashes offline\nlog', at: f.now - 1000, name: expect.any(String) },+ { by: `agent:${reviewer}`, passed: true, evidence: 'Diff reads right', at: f.now, name: expect.any(String) },])})@@ -642,6 +642,96 @@ describe('checks with several checkers', () => {[`agent:${tester}`, false, 'Crashes offline'], [`agent:${reviewer}`, true, 'Still right']])})+ // Diego, 2026-11-04 (#2656): a check failed by a checker who then left the Swarm could never pass again in that attempt.+ // A later pass by the task's PM or an owner clears departed checkers' failures; nobody else's does.+ describe('a failure by a checker who left the Swarm', () => {+ const departed = () => {+ const c = checkers()+ c.check(c.reviewer, false, 'Drops the session')+ c.f.run({ type: 'agent.remove', agentId: c.reviewer } as Command)+ const second = c.f.add('reviewer-2', c.f.task)+ c.check(second, true, 'Session kept')+ return { ...c, second }+ }++ it('stays failed after another checker passes it', () => {+ const { f, check, read } = departed()+ expect(read()).toMatchObject({ passedBy: null, evidence: 'Drops the session' })+ check(f.dev, true, 'Fixed it')+ expect(read()).toMatchObject({ passedBy: null, evidence: 'Drops the session' })+ })++ it('is cleared by the owner\'s pass, which then names the check\'s passer and evidence', () => {+ const { f, second, read } = departed()+ f.run({ type: 'work.check', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id,+ checkId: read().id, passed: true, evidence: 'Reviewer left; Reviewer 2 passed it' } as Command)+ expect(read()).toMatchObject({ passedBy: 'person:owner', evidence: 'Reviewer left; Reviewer 2 passed it' })+ expect(read().verdicts!.map(v => [v.by, v.passed])).toEqual([[`agent:${second}`, true], ['person:owner', true]])+ })++ it('is cleared by the task\'s PM\'s pass', () => {+ const { f, check, read } = departed()+ check(f.lead, true, 'Reviewer left; passed on the second review')+ expect(read()).toMatchObject({ passedBy: `agent:${f.lead}`, evidence: 'Reviewer left; passed on the second review' })+ })++ // Review of #2916 (Alder2878): removing a PM clears its lead on every task it led, so "the task's PM" is the project's+ // coordinator now, not the task's lead.+ it('is cleared by a new PM\'s pass after the PM who opened the task was replaced', () => {+ const { f, check, read } = departed()+ // As a PM switch lands (commands.ts, leadFor.switchId): the new agent leads the project chat, then the old one goes.+ const pm = f.add('pm-2')+ f.group('lead').leadId = pm+ f.run({ type: 'agent.remove', agentId: f.lead } as Command)+ expect(f.group(f.task).leadId).toBeNull()+ f.run({ type: 'conversation.agent', conversationId: f.task, agentId: pm, present: true, lead: false } as Command)+ check(pm, true, 'Reviewer left; passed on the second review')+ expect(read()).toMatchObject({ passedBy: `agent:${pm}`, evidence: 'Reviewer left; passed on the second review' })+ })++ // Security reviews 1 and 2 of #2916 (Heron2639, Grebe2639): a cleared failure must stay on the record, and only an owner+ // among people clears.+ const ownerCheck = (f: ReturnType<typeof departed>['f'], actor: Actor, evidence: string) => f.run({ type: 'work.check',+ conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, checkId: f.group(f.task).checks[0]!.id,+ passed: true, evidence } as Command, actor)++ it('leaves a line in the task naming the departed checker, its evidence and who cleared it', () => {+ const c = checkers()+ const name = c.f.state.agents.find(a => a.id === c.reviewer)!+ c.check(c.reviewer, false, 'Drops the session\nfull log')+ c.f.run({ type: 'agent.remove', agentId: c.reviewer } as Command)+ const effects = ownerCheck(c.f, owner, 'Reviewer left; passed on the second review')+ expect(effects.messages).toContainEqual(expect.objectContaining({ conversationId: c.f.task, recipients: [],+ text: `[email protected] cleared ${name.displayName ?? name.name}'s failure of “Signs in offline”, as they left the Swarm: Drops the session` }))+ })++ it('stays failed after a collaborator\'s pass: only an owner among people clears it', () => {+ const { f, read } = departed()+ f.state.people.push({ id: 'peer', email: '[email protected]', role: 'collaborator', generation: 'first' })+ const effects = ownerCheck(f, { kind: 'person', userId: 'peer', email: '[email protected]' }, 'Looks fine')+ expect(read()).toMatchObject({ passedBy: null, evidence: 'Drops the session' })+ expect(effects.messages.filter(m => m.text.includes('cleared'))).toEqual([])+ })++ it('is cleared by the project\'s owner who doesn\'t own the Swarm', () => {+ const { f, read } = departed()+ f.state.people.push({ id: 'peer', email: '[email protected]', role: 'collaborator', generation: 'first' })+ f.state.projects = [{ id: 'lead', name: 'Pilot', ownerId: 'peer', leadConversationId: 'lead', visibility: 'public', members: [], updateMinutes: 5 }]+ ownerCheck(f, { kind: 'person', userId: 'peer', email: '[email protected]' }, 'Reviewer left; I own this project')+ expect(read()).toMatchObject({ passedBy: 'person:peer', evidence: 'Reviewer left; I own this project' })+ })++ it('leaves a live checker\'s failure standing, whoever passes', () => {+ const { f, tester, check, read } = departed()+ check(tester, false, 'Crashes offline')+ check(f.lead, true, 'Looks fine')+ f.run({ type: 'work.check', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id,+ checkId: read().id, passed: true, evidence: 'Looks fine' } as Command)+ expect(read()).toMatchObject({ passedBy: null, evidence: 'Crashes offline' })+ expect(read().verdicts!.map(v => v.by)).toEqual(expect.arrayContaining([`agent:${tester}`]))+ })+ })+it('a new attempt starts with no verdicts', () => {const { f, tester, check, read } = checkers()check(tester, false, 'Crashes offline')diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 5cca2795c..da10c1c91 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1,3 +1,4 @@+import { refusalLogFields, type DeclaredClient } from './refusalLog.js'import { writeReactionActivity, writeReplyActivity } from './activity.js'import { accountMachineName, expireRemovals, followAccountName, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, slotCounter, machineTeamWork, preparableStart, readingOnly, refusableStart, recordAgentPresence, renamedBy, removalPreview, startPreparing, storedObservation, swarmGridRow, teamAccountRequired, teamWorkRefusal, type MachineObservation } from './machines.js'import { readingClearsSuspensions, suspendedEngines } from './engineHealth.js'@@ -55,7 +56,7 @@ import { clock, insertParts, loadActive, loadGroups, loadLightGroups, loadMachinimport { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'import { autoJoinSwarms, machineSwarms, memberSwarms } from './swarmRows.js'import type { MachineRename } from './machineRenames.js'-import { commitParts, indexesOf, numberMessages, type Touch, type Written } from './parts/commit.js'+import { commitParts, indexesOf, machineContentChanged, numberMessages, type Touch, type Written } from './parts/commit.js'import { loadDeliveryParts, ms } from './parts/light.js'import { endSteps, ownerOf, stepEndedRows, stepsOf } from './steps.js'import { pullRequestEvents, type PullRequestWatch } from './pullRequestEvents.js'@@ -1306,7 +1307,8 @@ export class SuperTabStore {})}- async execute(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string) {+ async execute(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string,+ client?: DeclaredClient) {try {const done = await this.executeOnce(user, tabId, input, asAgentId, hostMachineId)// Buddy thread sessions' first warning (spec Design 4): starts, refusals by code and ends by reason, ids only, in the@@ -1314,8 +1316,11 @@ export class SuperTabStore {if (input.command?.type === 'message.send' && input.command.newSession && done.result.startId) logger.info('Buddy session started', { tabId, startId: done.result.startId })return done} catch (error) {- // Its code and type alone, no values: a Swarm refusing a machine went unseen (MACHINES_FULL, Ken, 2026-11-04).- if (error instanceof SuperTabError && input.command?.type) logger.warn('Swarm command refused', { code: error.code, type: input.command.type })+ // Its code and type, and whose: the Swarm, the agent and the client, never the command's words. A Swarm refusing a machine+ // went unseen (MACHINES_FULL, Ken, 2026-11-04), then 615 refusals in 32 minutes that nobody could attribute (#2675).+ if (error instanceof SuperTabError && input.command?.type) {+ logger.warn('Swarm command refused', refusalLogFields(tabId, input.command, error.code, { asAgentId, client, machineId: hostMachineId }))+ }if (input.command?.type === 'message.send' && input.command.newSession && error instanceof SuperTabError) logger.info('Buddy session refused', { tabId, code: error.code })// A refusal for a bot's push rolled its mark back. The mark stays, so a post or a join that reads no GitHub is refused next (review 1 of #2559).const pushedOn = input.command && 'conversationId' in input.command ? input.command.conversationId : undefined@@ -2814,12 +2819,12 @@ export class SuperTabStore {* those asked in its project), still open or answered. A light load: the quiet conversations its decisions are in are* read with them (decisions.ts conversationsOf), never the Swarm's whole history, read again on every change. */async decisions(user: AuthUser, tabId: string, state: DecisionList, asAgentId?: string) {- return transaction(this.db, async tx => {- const { state: tab } = await this.load(tx, user, tabId)- const actor = await this.actor(tx, user, tab, asAgentId)- author(tab, actor)- return await listDecisions(tx, tabId, tab, actor, state)- })+ // Through the read cache, as every read (task #2674): only what the Swarm's stamp says changed is read again. It loaded+ // the whole active Swarm on every request, ~540 ms a part on prod (Ken's scan, 2026-11-04).+ const { state: tab } = await this.readLoad(user, tabId)+ const actor = await this.actor(this.db, user, tab, asAgentId)+ author(tab, actor)+ return listDecisions(this.db, tabId, tab, actor, state)}/**@@ -3145,7 +3150,8 @@ export class SuperTabStore {const stamp = clock.next()let version: numbertry {- version = await swarmTransaction(this.db, tx => guardedWrite(tx, tabId, { op: 'update', kind: 'machine', key: machineId, seen: part.version, data }, stamp))+ version = await swarmTransaction(this.db, tx => guardedWrite(tx, tabId, { op: 'update', kind: 'machine', key: machineId, seen: part.version, data,+ ...machineContentChanged(part.data, data) ? { content: true as const } : {} }, stamp))} catch (error) {// A conflict, or Mongo's transient refusal, is the full report's to retry.if (retryable(error)) return nulldiff --git a/backend/src/superTabs/sweeps.ts b/backend/src/superTabs/sweeps.tsindex d7b08de2f..d86ae185e 100644--- a/backend/src/superTabs/sweeps.ts+++ b/backend/src/superTabs/sweeps.ts@@ -13,6 +13,7 @@ import { expireEvidence } from './evidence/store.js'import { sweepThreadMarks } from './readMarks.js'import { sweepActivity } from './activity.js'import { sweepChatSettings } from './chatSettings.js'+import { sweepReminders } from './reminders.js'import { purgeAgentTombstones } from './agentTombstones.js'/** Parts whose key is never used twice (conversations, starts, projects' progress) lose their tombstone at `purgeAt`.@@ -194,11 +195,21 @@ export async function chatSettings(db: PrismaClient, now: number) {}}+/** The reminder sweep (reminders.ts), its failure said and kept to itself, as Activity's. */+export async function reminderRows(db: PrismaClient, now: number) {+ try {+ return { expired: await sweepReminders(db, now) }+ } catch (error) {+ logger.warn('[swarm-sweeps] reminders failed', { error: error instanceof Error ? error.message : String(error) })+ return { failed: true as const }+ }+}+/** One pass of every sweep (spec, Archive). Each part it changes is a guarded write, so a command in between wins. */export async function sweepSwarms(db: PrismaClient, now = Date.now()) {return { slept: await sleepQuietGroups(db, now), startsExpired: await expireStarts(db, now), invitationsExpired: await expireInvitations(db, now),tombstonesCompacted: await compactTombstones(db, now), agentTombstones: await purgeAgentTombstones(db, now), evidenceExpired: await expireEvidence(db, now), threadMarks: await threadMarks(db, now),- activity: await activityRows(db, now), chatSettings: await chatSettings(db, now) }+ activity: await activityRows(db, now), chatSettings: await chatSettings(db, now), reminders: await reminderRows(db, now) }}/** Runs the sweeps every hour in the singleton worker. `finishWorkspaceRemovals` finishes Workspace removals whose Swarm removalsdiff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex ef17be8e6..6020f4dee 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -1,12 +1,12 @@import { defineConfig } from 'vitest/config'export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabAutoJoin.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts',- 'integration/superTabRead.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabInbox.test.ts', 'integration/superTabFollowedThreads.test.ts', 'integration/superTabActivity.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts',+ 'integration/superTabRead.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabInbox.test.ts', 'integration/superTabFollowedThreads.test.ts', 'integration/superTabActivity.test.ts', 'integration/superTabReminders.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts','integration/superTabTidy.test.ts', 'integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts', 'integration/superTabIndexes.test.ts', 'integration/superTabRouteDecisions.test.ts',- 'integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabCacheDelta.test.ts', 'integration/superTabHostGroups.test.ts', 'integration/superTabMachineReports.test.ts', 'integration/superTabHeldParts.test.ts',+ 'integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabCacheDelta.test.ts', 'integration/superTabHostGroups.test.ts', 'integration/superTabMachineReports.test.ts', 'integration/superTabMachineLiveness.test.ts', 'integration/superTabHeldParts.test.ts','integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabNotAvailable.test.ts','integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabPersonalLead.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts','integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts','integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',- 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],+ 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 4584e520c..cabbc99a0 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -2190,6 +2190,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {onMachineRename: (machineId, name) => proxyBackend('PATCH', `/api/machines/${encodeURIComponent(machineId)}`, { name }),onMachineDelete: (machineId) => proxyBackend('DELETE', `/api/machines/${encodeURIComponent(machineId)}`),onAuthMe: () => proxyBackend('GET', '/api/auth/me'),+ onAuthMeUpdate: (body) => proxyBackend('PATCH', '/api/auth/me', body),onAuthHandoff: () => proxyBackend('POST', '/api/auth/handoff', {}),...daemonStopRoute({ askMaster: () => coreLink.stopAll(), stopHere: () => daemonBoot.stopHere('harness stop') }),// Signed out there is nothing shared WITH this computer and nobody to ask: a share is made on thediff --git a/cli/src/gateway/accountHttp.spec.ts b/cli/src/gateway/accountHttp.spec.tsindex 88d205a6d..b4c616313 100644--- a/cli/src/gateway/accountHttp.spec.ts+++ b/cli/src/gateway/accountHttp.spec.ts@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import type { GatewayAccount } from '../core/api.js'import { AuthSessionError } from '../lib/authSession.js'import { createAccountHttp, retryAfterMs } from './accountHttp.js'+import { VERSION } from '../version.js'const roots: string[] = []afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })@@ -39,7 +40,8 @@ describe('account HTTP in the gateway', () => {expect(await api.backend('PATCH', '/api/machines/local', { name: 'Renamed' })).toEqual({ status: 409, body: { error: { code: 'CONFLICT' } } })expect(request).toHaveBeenCalledWith('https://backend.invalid/api/machines/local', expect.objectContaining({method: 'PATCH', body: JSON.stringify({ name: 'Renamed' }),- headers: { authorization: 'Bearer token', 'x-autonomous-env': 'test', 'content-type': 'application/json' }, signal: expect.any(AbortSignal),+ // The CLI and its version, so a refusal the backend logs names its sender (#2675; backend superTabs/refusalLog.ts).+ headers: { authorization: 'Bearer token', 'x-autonomous-env': 'test', 'x-harness-client': `cli/${VERSION}`, 'content-type': 'application/json' }, signal: expect.any(AbortSignal),}))await api.backend('GET', '/api/auth/me')expect(request.mock.calls[1][1]?.headers).not.toHaveProperty('content-type')diff --git a/cli/src/gateway/accountHttp.ts b/cli/src/gateway/accountHttp.tsindex 737880b04..722e4b42b 100644--- a/cli/src/gateway/accountHttp.ts+++ b/cli/src/gateway/accountHttp.ts@@ -1,4 +1,5 @@/** Backend HTTP and the single writer of machines.json, owned by the gateway. */+import { VERSION } from '../version.js'import type { GatewayAccount, GatewayMachines, HttpAnswer } from '../core/api.js'import { MachineListCache } from '../device/machineList.js'import { AuthSessionError } from '../lib/authSession.js'@@ -61,8 +62,10 @@ export function createAccountHttp(deps: AccountHttpDeps) {try {res = await request(`${(deps.base ?? backendHttpBase)()}${path}`, {method,+ // The CLI and its version, as its sockets declare them (lib/declaredClient.ts): the backend's refusal log names the+ // sender of a refused command with it (#2675, 615 refusals in 32 minutes nobody could attribute).headers: { authorization: `Bearer ${accessToken}`, 'x-autonomous-env': deps.account().autonomousEnv ?? deps.environment,- ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },+ 'x-harness-client': `cli/${VERSION}`, ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },...(body !== undefined ? { body: JSON.stringify(body) } : {}),signal: AbortSignal.timeout(timeoutMs),})diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex b82025df2..0600b0eb7 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -373,6 +373,34 @@ describe('process-owned hook server', () => {})})+describe('the account name proxy', () => {+ it('passes the signed-in person\'s new name on only with the local header, body and answer verbatim', async () => {+ const update = vi.fn(async (body: unknown) => ({ status: 200, body: { success: true, data: { user: { id: 'u1', name: 'Elvis' }, echo: body } } }))+ const { base } = await start({ onAuthMeUpdate: update })+ const refused = await fetch(`${base}/api/auth/me`, { method: 'PATCH', headers: { 'content-type': 'application/json' }, body: '{"name":"Elvis"}' })+ expect(refused.status).toBe(403)+ expect(update).not.toHaveBeenCalled()++ const saved = await fetch(`${base}/api/auth/me`, { method: 'PATCH', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: '{"name":"Elvis"}' })+ expect(saved.status).toBe(200)+ expect(((await saved.json()) as { data: unknown }).data).toEqual({ user: { id: 'u1', name: 'Elvis' }, echo: { name: 'Elvis' } })+ expect(update).toHaveBeenCalledWith({ name: 'Elvis' })++ const bad = await fetch(`${base}/api/auth/me`, { method: 'PATCH', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: '{nope' })+ expect(bad.status).toBe(400)+ expect(update).toHaveBeenCalledTimes(1)+ })++ it('answers a refusal as the backend gave it, so the app can say why', async () => {+ const { base } = await start({+ onAuthMeUpdate: async () => ({ status: 400, body: { success: false, error: { code: 'INVALID_NAME', message: 'Use 1 to 60 characters, with no hidden ones.' } } }),+ })+ const response = await fetch(`${base}/api/auth/me`, { method: 'PATCH', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: '{"name":" "}' })+ expect(response.status).toBe(400)+ expect(((await response.json()) as { error: { code: string } }).error.code).toBe('INVALID_NAME')+ })+})+describe('the desk proxy', () => {it('reads the desk ungated and writes its ops only with the local header, body passed through', async () => {const ops = vi.fn(async (body: unknown) => ({ status: 200, body: { success: true, data: { revision: 2, tabs: [], echo: body } } }))diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex aa53f6351..bddfa1649 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -163,6 +163,9 @@ export interface HookServerHandlers {onMachineDelete?: (machineId: string) => Promise<PairOutcome>/** GET /api/auth/me — proxy the signed-in user's profile from backend. */onAuthMe?: () => Promise<PairOutcome>+ /** PATCH /api/auth/me — the signed-in person's own account name (`{ name }`, task #2654), passed to the backend, which+ * validates it and answers the profile as GET does; a local write, so CSRF-guarded like the desk's ops. */+ onAuthMeUpdate?: (body: unknown) => Promise<PairOutcome>/** POST /api/auth/handoff — a one-time code that signs a phone in to this account (the desktop's* Add Phone QR), minted by backend against this daemon's own session. */onAuthHandoff?: () => Promise<PairOutcome>@@ -1201,6 +1204,13 @@ export function startHookServer(if (!me) { json(503, { error: 'UNAVAILABLE' }); return }await proxied(me); return}+ if (req.method === 'PATCH' && url === '/api/auth/me') {+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }+ if (!handlers.onAuthMeUpdate) { json(503, { error: 'UNAVAILABLE' }); return }+ let body: unknown+ try { body = JSON.parse(await readBody(req)) } catch { json(400, { error: { code: 'BAD_REQUEST', message: 'Invalid JSON body' } }); return }+ await proxied(() => handlers.onAuthMeUpdate!(body)); return+ }// Add Phone: a code that SIGNS A PHONE IN to this account — the one local route whose answer is// a credential. So not the CSRF header, which any local process can send, but the daemon's// owner-only socket: the filesystem has already said this is the user who signed in. Anotherdiff --git a/cli/src/superTabs/agentContext.spec.ts b/cli/src/superTabs/agentContext.spec.tsindex 52af57564..a0321dbf9 100644--- a/cli/src/superTabs/agentContext.spec.ts+++ b/cli/src/superTabs/agentContext.spec.ts@@ -234,4 +234,12 @@ describe('a check with several checkers', () => {const group = withCheck({ evidence: 'Crashes', passedBy: null, verdicts: [verdict('agent:gone', false, 'Crashes', 1)] })expect(unknownAgents(group, swarm([group]), [])).toContain('gone')})++ // Diego, 2026-11-04 (#2656): a departed checker's failure is read by its last known name, not a bare id.+ it('names a stopped checker\'s failure by its last known name', () => {+ const group = withCheck({ evidence: 'Crashes', passedBy: null,+ verdicts: [verdict('agent:gone', false, 'Crashes', 1), verdict('agent:rev1', true, 'Diff reads right', 2)] })+ expect(taskText(group, swarm([group]), [], changed({}), NOW, new Map([['gone', 'Plover']])))+ .toContain('✗ Signs in offline — failed by Plover: Crashes; passed by Rev1')+ })})diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex d19063ac8..0b4ebdd60 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -577,6 +577,53 @@ describe('Super Tab native delivery handoff', () => {host.stop(); release()await Promise.resolve()})+ // Ken's prod scan (11-04): 615 agent.configuration refusals in 32 minutes, AGENT_UNAVAILABLE, about 19 a minute: a host+ // re-posts every 5 s an observation the Swarm will never take (an agent that must be shared again, or is gone).+ describe('a configuration report the Swarm refuses (#2675)', () => {+ const refusing = (t: ReturnType<typeof setup>, status: number, code: string) => {+ vi.mocked(t.core.agents.byAgent).mockReturnValue({ agentId: 'harness', engine: 'claude' } as never)+ vi.mocked(t.core.agents.runtimeProfile).mockReturnValue('runtime-v1:harness:claude:sonnet@high')+ const original = vi.mocked(t.call).getMockImplementation()!+ const sent: string[] = []+ vi.mocked(t.call).mockImplementation(async (...args) => {+ const body = args[2] as { operationId?: string; command?: { type?: string } } | undefined+ if (args[1].endsWith('/commands') && body?.command?.type === 'agent.configuration') {+ sent.push(body.operationId!)+ return { status, body: { success: false, error: { code, message: 'Refused.' } } }+ }+ return original(...args)+ })+ return sent+ }+ const passes = async (host: SuperTabHost, t: ReturnType<typeof setup>, count: number) => {+ for (let i = 0; i < count; i++) {+ await host.tick()+ await new Promise(resolve => setImmediate(resolve))+ t.wait(5_000)+ }+ }++ it('is not sent again after a permanent refusal, and a new reading is reported once', async () => {+ const t = setup(), host = t.open()+ const sent = refusing(t, 400, 'AGENT_UNAVAILABLE')+ await passes(host, t, 12)+ expect(sent).toHaveLength(1)+ vi.mocked(t.core.agents.runtimeProfile).mockReturnValue('runtime-v1:harness:claude:opus@high')+ await passes(host, t, 12)+ expect(sent).toHaveLength(2)+ expect(new Set(sent).size).toBe(2)+ })++ it('backs off after a passing failure instead of sending every 5 seconds', async () => {+ const t = setup(), host = t.open()+ const sent = refusing(t, 503, 'BACKEND_UNAVAILABLE')+ // Two minutes of passes: 24 at the old pace.+ await passes(host, t, 24)+ expect(sent.length).toBeGreaterThanOrEqual(2)+ expect(sent.length).toBeLessThanOrEqual(6)+ })+ })+it('retires a human-resolved journal entry without resubmitting its native input', async () => {const t = setup(), host = t.open()await host.tick(); t.event('unknown', 'lost acknowledgement'); await host.tick()@@ -3282,7 +3329,7 @@ describe('built-in skill text after a CLI update', () => {let inFlight = 0/** A notice the backend refuses (an older backend, an outage), and every refused request. */let refuse: ((request: any) => { status: number; body: Record<string, unknown> } | undefined) | undefined- const refused: Array<{ operationId: string; command: Record<string, any> }> = []+ const refused: Array<{ operationId: string; asAgentId?: string; command: Record<string, any> }> = []t.core.agents.byAgent = vi.fn(id => sessions[id] as never)t.core.agents.terminalAvailable = vi.fn(() => true)t.core.account.backend = vi.fn(async (method, path, body) => {@@ -3466,6 +3513,18 @@ describe('built-in skill text after a CLI update', () => {expect(f.sent).toHaveLength(3)})+ // Ken's prod scan (11-04): 125 message.send refused with BUDDY_SESSION_THREAD in 32 minutes. A Buddy session's notice is+ // a top-level post the backend refuses (a session answers only in its own thread), and the host tried it every minute.+ it('stops a skill notice the Swarm refuses for good, and still tells the other agents (#2675)', async () => {+ const f = syncFixture()+ f.setRefuse(request => request.asAgentId === 'a-builder' ? { status: 403, body: { success: false,+ error: { code: 'BUDDY_SESSION_THREAD', message: 'Answer only in your own thread: post with --reply-to a message in it.' } } } : undefined)+ const host = await f.pass()+ for (let i = 1; i <= 5; i++) await f.pass(host, 60_000)+ expect(f.refused.filter(r => r.asAgentId === 'a-builder')).toHaveLength(1)+ expect(f.sent.map(s => s.asAgentId).sort()).toEqual(['a-lead', 'a-reviewer'])+ })+it('drops the skills mark, once, when a backend refuses it, and keeps the notice agent-only', async () => {const f = syncFixture()f.setRefuse(request => 'notice' in request.command ? { status: 400, body: { success: false,diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex 48ebb1d1c..241e22f78 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -3,6 +3,7 @@ import { ContributedMachines, uncommittedIn, type MachineDeps } from './machinesimport { SwarmGrids } from './swarmGrids.js'import { retainContributions } from './retention.js'import { configurationObservation } from './configuration.js'+import { CommandRetries, permanentRefusal } from './retries.js'import { NativeRecorder, nativeJournalFile } from './native.js'import { attachedFiles, attachmentsOf, formatSize, type FilesInFlight, type Relink } from './attachments.js'import { createHash, randomUUID } from 'node:crypto'@@ -531,6 +532,7 @@ export class SuperTabHost {/** Asked once, on the first delivery: the answer cannot change while this daemon runs (superTabs/shortCommand.ts). */private prefix: Promise<string> | null = nullprivate configurationsRunning: Promise<void> | null = null+ private readonly configurationRetries = new CommandRetries(() => this.now())private nextConfigurationsAt = 0private replacementsRunning: Promise<void> | null = nullprivate nextReplacementsAt = 0@@ -1693,7 +1695,12 @@ export class SuperTabHost {} catch (error) {// The notice was sent, but its record was lost (a crash, a restart, another daemon) and its group has changed since:// the same operation id now names a different request. It was delivered once; record it rather than retry forever.- if (!(error instanceof SuperTabHostError) || error.code !== 'OPERATION_REUSED') throw error+ if (error instanceof SuperTabHostError && error.code === 'OPERATION_REUSED') return true+ // A notice the Swarm refuses for good is settled, not tried every minute: a Buddy session may post only in its own+ // thread, so its top-level notice was refused once a minute for as long as it ran (Ken, 11-04: 125+ // BUDDY_SESSION_THREAD refusals in 32 minutes, #2675).+ if (!permanentRefusal(error)) throw error+ this.log(`The skills notice for ${id} was refused (${(error as SuperTabHostError).code}); it is not sent again.`)}return true}@@ -2149,15 +2156,25 @@ export class SuperTabHost {}private async recordConfigurations(rows: unknown[]): Promise<void> {+ const owed: string[] = []for (const row of rows) {if (this.stopped) return+ let key: string | undefinedtry {const observation = configurationObservation(this.core, this.machineId, row)- if (observation) await backend(this.core, 'POST', observation.path, observation.body)+ if (!observation) continue+ key = observation.body.operationId+ owed.push(key)+ // A reading the Swarm refused for good goes no more; a new reading is a new operation, sent once (#2675).+ if (!this.configurationRetries.due(key)) continue+ await backend(this.core, 'POST', observation.path, observation.body)+ this.configurationRetries.sent(key)} catch (error) {+ if (key) this.configurationRetries.failed(key, error)this.log(error instanceof Error ? error.message : String(error))}}+ this.configurationRetries.keep(owed)}private async recordReplacements(rows: unknown[]): Promise<void> {diff --git a/cli/src/superTabs/retries.ts b/cli/src/superTabs/retries.tsnew file mode 100644index 000000000..32e94c106--- /dev/null+++ b/cli/src/superTabs/retries.ts@@ -0,0 +1,41 @@+import { SuperTabHostError } from './wire.js'++/** Refusals no resend of the same command can change (Ken's prod scan, 11-04, #2675): an agent gone or to be shared again, a+ * conversation gone or unreadable, a Buddy session's post outside its thread, a Buddy machine no longer listed. */+export const PERMANENT_REFUSALS: ReadonlySet<string> = new Set(['AGENT_UNAVAILABLE', 'NOT_FOUND', 'BUDDY_SESSION_THREAD', 'BUDDY_MACHINE'])+export const permanentRefusal = (error: unknown): boolean => error instanceof SuperTabHostError && PERMANENT_REFUSALS.has(error.code)++const FIRST_WAIT_MS = 5_000+const LONGEST_WAIT_MS = 5 * 60_000++/** Whether a command a host sends on its own clock may go now, by key (its operation id: a changed command is a new key).+ * Never again after a permanent refusal; after any other failure, a wait from 5 s doubling to 5 minutes. Until 11-04 the+ * host's configuration reports went every 5 s and its alerts every 15 s however the backend answered: 615 and 116 refusals+ * in 32 minutes. */+export class CommandRetries {+ private readonly held = new Map<string, { failures: number; at: number }>()+ constructor(private readonly now: () => number) {}++ due(key: string): boolean {+ const held = this.held.get(key)+ return !held || this.now() >= held.at+ }++ failed(key: string, error: unknown): void {+ if (permanentRefusal(error)) { this.held.set(key, { failures: 0, at: Infinity }); return }+ const failures = (this.held.get(key)?.failures ?? 0) + 1+ this.held.set(key, { failures, at: this.now() + Math.min(LONGEST_WAIT_MS, FIRST_WAIT_MS * 2 ** (failures - 1)) })+ }++ sent(key: string): void { this.held.delete(key) }++ /** Forgets every key not in [keys]: a command no longer owed (its agent gone, its reading changed) holds nothing. */+ keep(keys: Iterable<string>): void {+ const kept = new Set(keys)+ this.keepIf(key => kept.has(key))+ }++ keepIf(test: (key: string) => boolean): void {+ for (const key of this.held.keys()) if (!test(key)) this.held.delete(key)+ }+}diff --git a/cli/src/superTabs/terminal.spec.ts b/cli/src/superTabs/terminal.spec.tsindex c5561e17e..e3749b6f0 100644--- a/cli/src/superTabs/terminal.spec.ts+++ b/cli/src/superTabs/terminal.spec.ts@@ -8,13 +8,16 @@ import { capScreen, limitOf, modelFailing, TerminalHost, typedKeys } from './terconst row = (agentId = 'a1', harnessId = 'h1', over: Record<string, unknown> = {}) => ({ tabId: 'tab', agent: { id: agentId, harnessId, machineId: 'm1' }, ...over })type Sent = { path: string; body: Record<string, any> }-function setup(options: { live?: string[]; screen?: (harnessId: string) => SuperTabScreen; requests?: unknown[] } = {}) {+function setup(options: { live?: string[]; screen?: (harnessId: string) => SuperTabScreen; requests?: unknown[];+ refuse?: (command: Record<string, any>) => { status: number; code: string } | null } = {}) {let clock = 1_000_000const sent: Sent[] = []let pending = options.requests ?? []const backend: CoreApi['account']['backend'] = vi.fn(async (method, path, body) => {if (path === '/api/super-tabs/hosts/m1/terminal') { const rows = pending; pending = []; return { status: 200, body: { success: true, data: rows } } }sent.push({ path, body: body as Record<string, any> })+ const refused = options.refuse?.((body as Record<string, any>).command)+ if (refused) return { status: refused.status, body: { success: false, error: { code: refused.code, message: 'Refused.' } } }return { status: 200, body: { success: true, data: { result: {} } } }})let screen = options.screen ?? (() => ({ ok: true as const, text: '> ', hold: null }))@@ -192,6 +195,27 @@ describe('the stuck and usage-limit alerts', () => {const prompt = (): SuperTabScreen => ({ ok: true, text: 'Do you want to proceed?\n❯ 1. Yes\n 2. No', hold: 'permission_open' })const idle = (): SuperTabScreen => ({ ok: true, text: '> ', hold: null })+ // Ken's prod scan (11-04): 116 agent.alert refusals in 32 minutes, AGENT_UNAVAILABLE: an alert the Swarm will never take+ // (its agent gone or to be shared again) was tried again on every 15-second read.+ it('does not send again an alert the Swarm refused for good (#2675)', async () => {+ const t = setup({ screen: prompt, refuse: command => command.type === 'agent.alert' ? { status: 400, code: 'AGENT_UNAVAILABLE' } : null })+ await t.host.tick([row()])+ t.wait(180_000); await t.host.tick([row()])+ expect(t.alerts()).toHaveLength(1)+ for (let i = 0; i < 20; i++) { t.wait(15_000); await t.host.tick([row()]) }+ expect(t.alerts()).toHaveLength(1)+ })++ it('backs off an alert the backend could not take for now (#2675)', async () => {+ const t = setup({ screen: prompt, refuse: command => command.type === 'agent.alert' ? { status: 503, code: 'BACKEND_UNAVAILABLE' } : null })+ await t.host.tick([row()])+ t.wait(180_000); await t.host.tick([row()])+ // Ten minutes of reads: 40 tries at the old pace.+ for (let i = 0; i < 40; i++) { t.wait(15_000); await t.host.tick([row()]) }+ expect(t.alerts().length).toBeGreaterThanOrEqual(2)+ expect(t.alerts().length).toBeLessThanOrEqual(8)+ })+it('alerts once when a prompt has waited 3 minutes, and ends the episode when it is answered', async () => {const t = setup({ screen: prompt })await t.host.tick([row()])diff --git a/cli/src/superTabs/terminal.ts b/cli/src/superTabs/terminal.tsindex 3f3b81407..6590336bd 100644--- a/cli/src/superTabs/terminal.ts+++ b/cli/src/superTabs/terminal.ts@@ -7,6 +7,7 @@* a usage limit. The same reads tell the machine report when each agent's screen last changed: the backend renews the* agent's lease on its task from that (docs: swarm-never-stops, v1 liveness).*/+import { CommandRetries, permanentRefusal } from './retries.js'import { createHash } from 'node:crypto'import type { CoreApi, SuperTabScreen } from '../core/api.js'import { updateDismissKeys } from '../engines/codex/screen.js'@@ -177,6 +178,7 @@ export class TerminalHost {private here: Array<Own & { running: boolean }> = []private watching: Promise<void> | null = nullprivate readonly watched = new Map<string, Watched>()+ private readonly alertRetries = new CommandRetries(() => this.now())/** Per running harness here, its last screen's digest and when that last changed. */private readonly progress = new Map<string, { digest: string; at: number }>()private readonly now: () => number@@ -288,6 +290,8 @@ export class TerminalHost {private async watch(own: Own[]): Promise<void> {const keys = new Set(own.map(a => `${a.tabId}:${a.agentId}`))for (const key of this.watched.keys()) if (!keys.has(key)) this.watched.delete(key)+ const agents = new Set(own.map(a => a.agentId))+ this.alertRetries.keepIf(key => agents.has(key.split('-')[2] ?? ''))const harnesses = new Set(own.map(a => a.harnessId))for (const id of this.progress.keys()) if (!harnesses.has(id)) this.progress.delete(id)for (const agent of own) {@@ -334,12 +338,16 @@ export class TerminalHost {const episode = seen ? current ?? { since: now, alerted: false } : currentif (!episode) return nullif (seen === episode.alerted || (seen && !due(episode.since))) return seen ? episode : null+ const key = `terminal-alert-${agent.agentId}-${alert}-${episode.since}-${seen ? 'on' : 'off'}`+ // Each read tried a failed alert again, refused or not: 116 refusals in 32 minutes (Ken, 11-04, #2675).+ if (!this.alertRetries.due(key)) return episodetry {- await this.command(agent, `terminal-alert-${agent.agentId}-${alert}-${episode.since}-${seen ? 'on' : 'off'}`,- { type: 'agent.alert', agentId: agent.agentId, alert, active: seen, ...(seen ? extra : {}) })+ await this.command(agent, key, { type: 'agent.alert', agentId: agent.agentId, alert, active: seen, ...(seen ? extra : {}) })+ this.alertRetries.sent(key)} catch (error) {this.log(error instanceof Error ? error.message : String(error))- return episode+ // Refused for good (its agent gone or to be shared again): the episode is settled, as no resend can land it.+ if (!permanentRefusal(error)) { this.alertRetries.failed(key, error); return episode }}return seen ? { ...episode, alerted: true } : null}diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dartindex 9944e0cda..03612db2f 100644--- a/desktop/lib/api/api_client.dart+++ b/desktop/lib/api/api_client.dart@@ -315,6 +315,19 @@ class ApiClient {return unwrapApiResponse(res) as Map<String, dynamic>?;}+ /// Saves the signed-in person's own account name (backend `PATCH+ /// /api/auth/me`, task #2654) and answers the profile as [me] does. The+ /// backend validates it and says why it refused in words; a daemon or backend+ /// from before the route answers 404.+ Future<Map<String, dynamic>?> updateMe({required String name}) async {+ final res = await _dio.patch(+ '/api/auth/me',+ data: {'name': name},+ options: Options(headers: {'x-adapter-local': '1'}),+ );+ return unwrapApiResponse(res) as Map<String, dynamic>?;+ }+// -- the desk: the account's tabs, the same on every computer (proxied by the local CLI) --/// `{revision, tabs}` as the backend holds it; null when the daemon predates the desk (404) or isdiff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 22a70d443..2043bdd28 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -68,6 +68,7 @@ import '../state/status_menu.dart';import '../widgets/in_window_menu_bar.dart'show LinuxTitleBar, linuxTitleBarActions;import '../widgets/account_menu.dart';+import '../widgets/account_profile_sheet.dart';import '../widgets/notification_inbox.dart';import '../widgets/workspace_notifications_button.dart';import '../state/harness_sessions.dart';@@ -3491,6 +3492,14 @@ class _SwarmScreenState extends State<SwarmScreen> {);if (!mounted) return;switch (choice) {+ case AccountMenuChoice.profile:+ await _dialog(+ () => showAccountProfileSheet(+ context,+ app,+ swarm: accountProfileSwarm(app),+ ),+ );case AccountMenuChoice.addPhone:await _addPhone(from: AddPhoneOpening.account);case AccountMenuChoice.devices:diff --git a/desktop/lib/settings/sections/account_section.dart b/desktop/lib/settings/sections/account_section.dartindex a680920c8..88d81d82f 100644--- a/desktop/lib/settings/sections/account_section.dart+++ b/desktop/lib/settings/sections/account_section.dart@@ -5,6 +5,7 @@ import '../../screens/login_screen.dart';import '../../shared/widgets/section_scaffold.dart';import '../../shared/widgets/setting_row.dart';import '../../state/app_state.dart';+import '../../widgets/account_profile_sheet.dart';import 'saved_super_tabs_row.dart';class AccountSection extends StatelessWidget {@@ -65,13 +66,31 @@ class AccountSection extends StatelessWidget {detail:profile?.email ??(local ? 'Loopback backend' : 'Profile unavailable'),- control: OutlinedButton(- key: const Key('settings-sign-out-button'),- onPressed: () {- Navigator.of(context).pop();- notifier.logout();- },- child: Text(local ? 'Disconnect local session' : 'Sign out'),+ control: Wrap(+ alignment: WrapAlignment.end,+ spacing: 8,+ runSpacing: 8,+ children: [+ // Profile (task #2654): the same sheet the avatar menu opens.+ if (!local && profile != null)+ TextButton(+ key: const Key('settings-account-edit'),+ onPressed: () => showAccountProfileSheet(+ context,+ notifier,+ swarm: accountProfileSwarm(notifier),+ ),+ child: const Text('Edit'),+ ),+ OutlinedButton(+ key: const Key('settings-sign-out-button'),+ onPressed: () {+ Navigator.of(context).pop();+ notifier.logout();+ },+ child: Text(local ? 'Disconnect local session' : 'Sign out'),+ ),+ ],),);return SectionScaffold(diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 314a61a95..3700560dc 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -107,7 +107,7 @@ import '../super_tabs/join_machine.dart';import '../super_tabs/identity.dart' show superTabMachineName;import '../super_tabs/view_store.dart';import '../super_tabs/notifications.dart'- show superTabChatNotice, superTabMentionNotice;+ show superTabChatNotice, superTabMentionNotice, superTabReminderNotice;import '../measurement/setup_preference_store.dart';import '../devices/device_hosts.dart';import '../stats/harness_stats.dart';@@ -1925,6 +1925,7 @@ class AppNotifier extends ChangeNotifier {: uploadAvatarWith(() => api)(tabId: tabId, png: png),onMention: superTabMentionNotice(systemNotifications),onChatMessage: superTabChatNotice(systemNotifications),+ onReminder: superTabReminderNotice(systemNotifications),onTagCounts: notifyListeners,onNotices: notifyListeners,discoveryInterval: kUnderTest ? Duration.zero : const Duration(seconds: 15),@@ -5058,9 +5059,9 @@ class AppNotifier extends ChangeNotifier {// the view's _syncThreadPane calls threadPaneShown when it is.controller.openThread(root, shown: false);}- bool holds() => controller- .messages(id)- .any((m) => m.id == root || m.thread == root);++ bool holds() =>+ controller.messages(id).any((m) => m.id == root || m.thread == root);if (!holds()) await controller.refresh();bool superseded() =>_disposed ||@@ -8008,6 +8009,31 @@ class AppNotifier extends ChangeNotifier {await _profileCache.write(machineId, profile);}+ /// Saves the signed-in person's own account name (Profile, task #2654) and+ /// shows it at once; answers why it was refused, in one short line, or null+ /// once saved.+ Future<String?> setAccountName(String name) async {+ final revision = _authRevision;+ try {+ final me = await api.updateMe(name: name);+ if (me == null || !_authWorkCurrent(revision)) return null;+ final profile = CurrentUserProfile.fromMe(me);+ // Another account's answer is not this one's name: leave it for the+ // next profile read to settle.+ if (currentUser?.id != null && profile.id != currentUser?.id) return null;+ currentUser = profile;+ unawaited(_keepProfile(profile, revision));+ notifyListeners();+ return null;+ } on ApiException catch (error) {+ // A daemon (or, in a browser, a backend) from before the route.+ if (error.status == 404) return 'Update Harness to change your name.';+ return error.message;+ } catch (_) {+ return 'Your name was not saved. Try again.';+ }+ }+Future<void> _readProfile(int revision) async {try {final me = await api.me();diff --git a/desktop/lib/super_tabs/activity.dart b/desktop/lib/super_tabs/activity.dartindex 0efb80463..281bb4aa3 100644--- a/desktop/lib/super_tabs/activity.dart+++ b/desktop/lib/super_tabs/activity.dart@@ -8,6 +8,7 @@ import 'controller.dart';import 'decisions.dart';import 'model.dart';import 'notifications.dart';+import 'reminders.dart';/// What one row of Needs you is.enum SuperTabNeedKind { decision, agent, mention }@@ -49,6 +50,7 @@ class SuperTabNeed {////// * Needs you: decisions asked of them, agents waiting on them and their/// tags. Its length is Activity's number.+/// * Reminders: messages they asked to come back to, once due./// * New replies: the followed threads with replies they have not read./// * Done today: tasks that shipped today.///@@ -58,11 +60,13 @@ class SuperTabActivity extends ChangeNotifier {SuperTabActivity._(this.controller): mentions = SuperTabMentions.of(controller),decisions = SuperTabDecisions.of(controller),- attention = SuperTabAttention.of(controller) {+ attention = SuperTabAttention.of(controller),+ reminders = SuperTabReminders.of(controller) {controller.addListener(notifyListeners);controller.onDispose(dispose);mentions.addListener(notifyListeners);decisions.addListener(notifyListeners);+ reminders.addListener(notifyListeners);}@visibleForTesting@@ -77,6 +81,7 @@ class SuperTabActivity extends ChangeNotifier {final SuperTabMentions mentions;final SuperTabDecisions decisions;final SuperTabAttention attention;+ final SuperTabReminders reminders;bool _open = false, _disposed = false;SuperTabSnapshot? get _snapshot =>@@ -209,7 +214,7 @@ class SuperTabActivity extends ChangeNotifier {/// The Activity row's red number: what needs the reader, and nothing else./// A tag counts until it is read, a decision or an agent waiting until it- /// is answered. Before the tags are read the server's count stands in.+ /// is answered, a due reminder until it is opened. Before the tags are read the server's count stands in.int get count {final snapshot = _snapshot;if (snapshot == null) return 0;@@ -218,6 +223,7 @@ class SuperTabActivity extends ChangeNotifier {? snapshot.mentionsWaiting: _tags.length;return tags ++ reminders.due.length +snapshot.decisionsWaiting +snapshot.conversations.where((g) => _waiting(snapshot, g, decided))@@ -258,6 +264,7 @@ class SuperTabActivity extends ChangeNotifier {controller.removeListener(notifyListeners);mentions.removeListener(notifyListeners);decisions.removeListener(notifyListeners);+ reminders.removeListener(notifyListeners);super.dispose();}}diff --git a/desktop/lib/super_tabs/activity_view.dart b/desktop/lib/super_tabs/activity_view.dartindex bdeadc80b..51f1e4077 100644--- a/desktop/lib/super_tabs/activity_view.dart+++ b/desktop/lib/super_tabs/activity_view.dart@@ -13,10 +13,11 @@ import 'machine_status.dart' show superTabAgoShort;import 'model.dart';import 'notifications.dart';import 'private_project_lock.dart';+import 'reminders.dart';import 'section_heading.dart';/// Activity, the one place for everything new for the reader (Quiet Swarm-/// design, screens 6 and 11b): Needs you, New replies, Done today. One line+/// design, screens 6 and 11b): Needs you, Reminders, New replies, Done today. One line/// to a row, bold when it is new, no filters. A click opens the thing where/// it is; a decision opens its card to answer.class SuperTabActivityView extends StatefulWidget {@@ -26,6 +27,7 @@ class SuperTabActivityView extends StatefulWidget {required this.onOpenMention,required this.onOpenThread,required this.onOpenConversation,+ this.onOpenReminder,this.now = DateTime.now,});final SuperTabActivity activity;@@ -36,6 +38,9 @@ class SuperTabActivityView extends StatefulWidget {/// Opens the chat of an agent waiting on the reader, or of a task done.final ValueChanged<String> onOpenConversation;++ /// Opens a due reminder's message, which clears it.+ final ValueChanged<SuperTabReminder>? onOpenReminder;final DateTime Function() now;@override@@ -156,6 +161,21 @@ class _SuperTabActivityViewState extends State<SuperTabActivityView> {);}+ Widget _reminder(SuperTabReminder reminder) {+ final text = reminder.text.replaceAll(RegExp(r'\s+'), ' ').trim();+ return _Row(+ key: ValueKey('super-activity-row-reminder:${reminder.id}'),+ mark: AppIcons.clock,+ title: [+ if (reminder.authorName case final name? when name.isNotEmpty) name,+ text.isEmpty ? reminder.conversationTitle : text,+ ].join(': '),+ unread: true,+ trailing: _when(reminder.dueAt),+ onTap: () => widget.onOpenReminder?.call(reminder),+ );+ }+Widget _thread(SuperTabFollowedThread thread) {final text = thread.rootText.replaceAll(RegExp(r'\s+'), ' ').trim();return _Row(@@ -190,9 +210,14 @@ class _SuperTabActivityViewState extends State<SuperTabActivityView> {grid.AppTheme.watch(context);final a = _activity;final needs = a.needsYou;+ final reminders = a.reminders.due;final replies = a.newReplies;final done = a.doneToday;- final error = a.mentions.error ?? a.decisions.error ?? a.attention.error;+ final error =+ a.mentions.error ??+ a.decisions.error ??+ a.reminders.error ??+ a.attention.error;return LaidOutListView(key: const ValueKey('super-activity-list'),padding: const EdgeInsets.only(bottom: grid.AppDesktop.groupGap),@@ -213,18 +238,26 @@ class _SuperTabActivityViewState extends State<SuperTabActivityView> {unawaited(a.mentions.load());unawaited(a.decisions.load());unawaited(a.attention.load());+ unawaited(a.reminders.load());},child: const Text('Retry'),),],),),- if (needs.isEmpty && replies.isEmpty && done.isEmpty)+ if (needs.isEmpty &&+ reminders.isEmpty &&+ replies.isEmpty &&+ done.isEmpty)_empty("You're all caught up."),if (needs.isNotEmpty) ...[_heading('Needs you'),for (final need in needs) _need(need),],+ if (reminders.isNotEmpty) ...[+ _heading('Reminders'),+ for (final reminder in reminders) _reminder(reminder),+ ],if (replies.isNotEmpty) ...[_heading('New replies'),for (final thread in replies) _thread(thread),diff --git a/desktop/lib/super_tabs/attachment_image.dart b/desktop/lib/super_tabs/attachment_image.dartindex d204b6f80..b3d85cf31 100644--- a/desktop/lib/super_tabs/attachment_image.dart+++ b/desktop/lib/super_tabs/attachment_image.dart@@ -653,6 +653,7 @@ class _SuperTabImageViewerState extends State<SuperTabImageViewer> {widget.onClose();show();},+ choices: const [],),],),diff --git a/desktop/lib/super_tabs/backend_transport.dart b/desktop/lib/super_tabs/backend_transport.dartindex 771a59a8f..43d40e538 100644--- a/desktop/lib/super_tabs/backend_transport.dart+++ b/desktop/lib/super_tabs/backend_transport.dart@@ -20,9 +20,10 @@ final _swarmRoute = RegExp('|/$_tab/(?:parts|changes|commands|mentions|decisions|leaderboard|sharing''|routing-policy|groups|groups/$_id|join|join/preview|native''|activity|activity/read|threads|inbox|proposals'- '|conversations/$_id/(?:messages|catch-up|read|notifications'+ '|reminders'+ '|conversations/$_id/(?:messages|catch-up|read|unread|notifications''|threads/$_id/(?:read|follow)'- '|messages/$_id/attachments/$_id)'+ '|messages/$_id/attachments/$_id|messages/$_id/reminder)''|projects/$_id/(?:github|github/approve''|instructions(?:/revisions(?:/[0-9]+)?)?)''|route-decisions/$_id|machines/$_id/removal(?:/v2)?)'diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dartindex 0706f15fd..54709b834 100644--- a/desktop/lib/super_tabs/client.dart+++ b/desktop/lib/super_tabs/client.dart@@ -13,6 +13,7 @@ import 'controller.dart';import 'decisions.dart';import 'model.dart';import 'notifications.dart';+import 'reminders.dart';import 'parts.dart';import 'reading.dart';import 'saved_view.dart';@@ -37,6 +38,7 @@ class SuperTabClient {this.onSelection,this.onMention,this.onChatMessage,+ this.onReminder,this.onTagCounts,this.onNotices,this.upload = refuseUpload,@@ -74,6 +76,9 @@ class SuperTabClient {final void Function(String tabId, SuperTabConversation group, int sequence)?onChatMessage;+ /// A reminder the reader set came due in Swarm `tabId` ([SuperTabReminders]).+ final void Function(String tabId, SuperTabReminder reminder)? onReminder;+/// The waiting tags of a Swarm that is not open changed ([waitingTags]).final void Function()? onTagCounts;@@ -818,6 +823,10 @@ class SuperTabClient {SuperTabChatNotices.of(controller).onMessage = (group, sequence) =>told(id, group, sequence);}+ if (onReminder case final told?) {+ SuperTabReminders.of(controller).onArrived = (reminder) =>+ told(id, reminder);+ }if (onNotices case final changed?) {SuperTabMentions.of(controller).addListener(changed);SuperTabDecisions.of(controller).addListener(changed);diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 32d5e9ed8..86dd7452c 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -352,6 +352,8 @@ class SuperTabController extends ChangeNotifier {devicesSelected = devices;if (to != null && to != selectedId) {_leftAt[selectedId] = clock.now();+ // Marked unread while open: once left, it reads as any chat does.+ _unreadHeld.remove(selectedId);selectedId = to;}}@@ -3471,6 +3473,7 @@ class SuperTabController extends ChangeNotifier {final snapshot = this.snapshot;if (_disposed || accessRevoked || snapshot == null) return null;_markAll?._commit();+ _unreadHeld.clear();final before = <String, int?>{}, through = <String, int>{};for (final group in snapshot.conversations) {if (group.dormant || !unreadShown(group)) continue;@@ -3529,10 +3532,17 @@ class SuperTabController extends ChangeNotifier {/// A visible transcript passes the boundary it displayed. The loaded messages/// are authoritative: snapshots can arrive either before or after their tail.- void markRead(String id, {int? through}) {+ /// While the open chat is held unread ([markUnread]) only an [explicit] read+ /// (Esc) reads it.+ void markRead(String id, {int? through, bool explicit = false}) {if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {return;}+ if (explicit) {+ _unreadHeld.remove(id);+ } else if (_unreadHeld.contains(id)) {+ return;+ }final loaded = _loadedMessageSequence(id);final last = min(through ?? loaded, loaded);_serverMarks.mark(id, last, kept: snapshot?.readMarks[id] ?? 0);@@ -3542,6 +3552,71 @@ class SuperTabController extends ChangeNotifier {_changed();}+ /// The open chat the reader marked unread: nothing reads it again until they+ /// leave it, as in Slack.+ final _unreadHeld = <String>{};++ /// Marks [id] unread from [message] on: the read mark goes to just before it+ /// (backend readMarks.ts lowerReadMark), on every device of the reader, and+ /// never forward. A message only in its thread has its thread's mark, not+ /// this one. False when the server did not keep it; this device's mark is+ /// then as it was.+ Future<bool> markUnread(String id, SuperTabMessage message) async {+ if (_disposed ||+ accessRevoked ||+ snapshot?.conversation(id) == null ||+ !message.inMainStream ||+ message.sequence <= 0) {+ return false;+ }+ final target = message.sequence - 1;+ if (readMark(id) <= target) return true;+ final was = _readAt[id], wasServer = snapshot?.readMarks[id];+ if (id == selectedId) _unreadHeld.add(id);+ _readAt[id] = target;+ _parts?.lowerReadMark(id, target);+ _serverMarks.forget(id);+ _saveSoon();+ _redraw();+ try {+ final answer = superTabMap(+ await request(+ 'POST',+ '$_path/conversations/${Uri.encodeComponent(id)}/unread',+ body: {'sequence': message.sequence},+ ),+ );+ // A read that raised the held mark while this was sent: the server's+ // answer is where it stands.+ if ((answer['sequence'] as num?)?.toInt() case final stored?) {+ _parts?.lowerReadMark(id, stored);+ _redraw();+ }+ return true;+ } catch (_) {+ if (_disposed) return false;+ _unreadHeld.remove(id);+ if (was == null) {+ _readAt.remove(id);+ } else {+ _readAt[id] = was;+ }+ if (wasServer != null) _parts?.raiseReadMark(id, wasServer);+ _saveSoon();+ _redraw();+ return false;+ }+ }++ /// Marks a Mark unread moved back elsewhere: this device's own mark follows.+ void _takeLowered(Map<String, int> lowered) {+ for (final MapEntry(key: id, value: sequence) in lowered.entries) {+ if ((_readAt[id] ?? 0) > sequence) _readAt[id] = sequence;+ _serverMarks.forget(id);+ }+ if (lowered.isNotEmpty) _saveSoon();+ }+/// The zone this app last told the Swarm, or tried to: told once per zone/// and session, so an older backend's refusal is not sent again.String? _zoneTold;@@ -3666,6 +3741,7 @@ class SuperTabController extends ChangeNotifier {throw const FormatException('A different Swarm was returned.');}snapshot = next;+ _takeLowered(parts.takeLowered());_reportTimeZone(next);_notifyKept.removeWhere((_, kept) => kept.$2 < serial);final allowed = next.conversations.map((c) => c.id).toSet();diff --git a/desktop/lib/super_tabs/message_more_menu.dart b/desktop/lib/super_tabs/message_more_menu.dartindex 9edcdc8d2..7393e9baa 100644--- a/desktop/lib/super_tabs/message_more_menu.dart+++ b/desktop/lib/super_tabs/message_more_menu.dart@@ -5,11 +5,13 @@ import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_icon_button.dart';import '../shared/widgets/app_menu.dart';-/// One choice of a message's More menu.+/// One choice of a message's More menu. With [choices], it opens them beside+/// it instead (Remind me's times).typedef SuperTabMoreAction = ({String label,IconData icon,- VoidCallback onPressed,+ VoidCallback? onPressed,+ List<({String label, VoidCallback onPressed})> choices,});/// The ⋯ of a message's hover bar: the choices that have no button of their@@ -64,16 +66,39 @@ class _SuperTabMessageMoreMenuState extends State<SuperTabMessageMoreMenu> {style: grid.AppMenu.style(minWidth: 200),menuChildren: [for (final (index, action) in widget.actions.indexed)- AppMenuItem(- focusNode: index == 0 ? _first : null,- label: action.label,- icon: action.icon,- expandLabel: true,- onPressed: () {- _menu.close();- action.onPressed();- },- ),+ if (action.choices.isEmpty)+ AppMenuItem(+ focusNode: index == 0 ? _first : null,+ label: action.label,+ icon: action.icon,+ expandLabel: true,+ onPressed: () {+ _menu.close();+ action.onPressed?.call();+ },+ )+ else+ SubmenuButton(+ key: ValueKey('super-message-more-${action.label}'),+ focusNode: index == 0 ? _first : null,+ leadingIcon: Icon(action.icon, size: AppIcons.inlineSize),+ submenuIcon: const WidgetStatePropertyAll(+ Icon(AppIcons.chevronRight, size: AppIcons.inlineSize),+ ),+ menuStyle: grid.AppMenu.style(minWidth: 180),+ menuChildren: [+ for (final choice in action.choices)+ AppMenuItem(+ label: choice.label,+ expandLabel: true,+ onPressed: () {+ _menu.close();+ choice.onPressed();+ },+ ),+ ],+ child: Text(action.label),+ ),],builder: (context, menu, _) => AppIconButton(icon: AppIcons.ellipsis,diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex 2b5cf7a7e..31e6a4466 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -20,6 +20,7 @@ import 'message_text.dart';import 'model.dart';import 'pull_requests.dart';import 'reactions.dart';+import 'reminders.dart';import 'swarm_type.dart';/// The face [message]'s row shows for its sender, shown as [author]: the@@ -94,6 +95,8 @@ class SuperTabMessageRow extends StatefulWidget {this.linkTarget,this.onOpenLink,this.identity,+ this.onMarkUnread,+ this.onRemind,});final SuperTabMessage message;@@ -178,6 +181,13 @@ class SuperTabMessageRow extends StatefulWidget {final SuperTabLinkTarget Function(SwarmMessageLink)? linkTarget;final ValueChanged<SwarmMessageLink>? onOpenLink;+ /// The More menu's Mark unread: the chat reads as unread from this message+ /// on. Null where it is not offered.+ final VoidCallback? onMarkUnread;++ /// The More menu's Remind me, with when. Null where it is not offered.+ final ValueChanged<SuperTabRemindIn>? onRemind;+// Routing notes share the message body column, including grouped messages.static const horizontalInset = 24.0;static const avatarSize = grid.AppDesktop.messageAvatarSize;@@ -279,6 +289,34 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {);}+ /// The More menu's choices, in Slack's order.+ List<SuperTabMoreAction> get _moreActions => [+ if (widget.link case final link?)+ (+ label: 'Copy link to message',+ icon: AppIcons.link2,+ onPressed: () => unawaited(_copyLink(link)),+ choices: const [],+ ),+ if (widget.onMarkUnread case final markUnread?)+ (+ label: 'Mark unread',+ icon: AppIcons.mail,+ onPressed: markUnread,+ choices: const [],+ ),+ if (widget.onRemind case final remind?)+ (+ label: 'Remind me',+ icon: AppIcons.clock,+ onPressed: null,+ choices: [+ for (final when in SuperTabRemindIn.values)+ (label: when.label, onPressed: () => remind(when)),+ ],+ ),+ ];+Future<void> _copyLink(SwarmMessageLink link) async {await Clipboard.setData(ClipboardData(text: link.url));if (!mounted) return;@@ -704,21 +742,15 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {onPressed: _copy,),),- if (widget.link case final link?)+ if (_moreActions case final actions+ when actions.isNotEmpty)fingerTarget(enabled: phone,SuperTabMessageMoreMenu(key: ValueKey('super-message-more-${message.id}',),- actions: [- (- label: 'Copy link to message',- icon: AppIcons.link2,- onPressed: () =>- unawaited(_copyLink(link)),- ),- ],+ actions: actions,),),],diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex e77897846..4b6fefb9b 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -658,6 +658,7 @@ class SuperTabSnapshot {decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,decisionsDigest = row['decisionsDigest'] as String?,activityDigest = row['activityDigest'] as String?,+ remindersDigest = row['remindersDigest'] as String?,chatSettings = Map.unmodifiable({if (row['chatSettings'] case final Map settings)for (final MapEntry(:key, :value) in settings.entries)@@ -796,6 +797,10 @@ class SuperTabSnapshot {/// that moves when one comes or is read; null from a backend before Activity (superTabs/activity.ts).final String? activityDigest;+ /// Which reminders the reader has set and when each is due, as a digest that moves when one is set, replaced or+ /// cleared; null from a backend before reminders (superTabs/reminders.ts).+ final String? remindersDigest;+/// The reader's own notification setting by conversation (backend chatSettings.ts); a chat not listed is at/// [SuperTabNotify.mentions]. Never another person's.final Map<String, SuperTabNotify> chatSettings;diff --git a/desktop/lib/super_tabs/notifications.dart b/desktop/lib/super_tabs/notifications.dartindex c569e6946..2521fc32e 100644--- a/desktop/lib/super_tabs/notifications.dart+++ b/desktop/lib/super_tabs/notifications.dart@@ -12,6 +12,7 @@ import 'identity.dart';import 'machine_status.dart' show superTabAgo;import 'model.dart';import 'private_project_lock.dart';+import 'reminders.dart';import 'section_heading.dart';import '../widgets/laid_out_list.dart';@@ -90,6 +91,21 @@ superTabChatNotice(SystemNotifications system, {bool web = kIsWeb}) => webchat: (tabId: tabId, conversationId: group.id),);+/// What tells the person a reminder they set is due: the operating system, on+/// Desktop only, as tags are. A click opens its chat in its Swarm [tabId];+/// Activity holds it until it is opened.+void Function(String tabId, SuperTabReminder reminder)? superTabReminderNotice(+ SystemNotifications system, {+ bool web = kIsWeb,+}) => web+ ? null+ : (tabId, reminder) => system.postNotice(+ id: 'harness-reminder:$tabId:${reminder.key}',+ title: reminder.authorName ?? reminder.conversationTitle,+ body: reminder.text,+ chat: (tabId: tabId, conversationId: reminder.conversationId),+ );+/// The reader's tags in one Swarm: Waiting and Earlier, read from the backend/// when the count or the digest of which tags wait moves (or, from a backend/// without the digest, whenever the Swarm changes while a tag waits). One perdiff --git a/desktop/lib/super_tabs/parts.dart b/desktop/lib/super_tabs/parts.dartindex e29c12d95..06a186b3f 100644--- a/desktop/lib/super_tabs/parts.dart+++ b/desktop/lib/super_tabs/parts.dart@@ -65,6 +65,7 @@ class SuperTabParts {// Read marks are held apart from the other derived values (_readMarks).final derived = Map.of(superTabMap(answer['derived'] ?? const {}));final marks = derived.remove('readMarks');+ final unreadMarks = derived.remove('unreadMarks');final threadMarks = derived.remove('threadMarks');final chatSettings = derived.remove('chatSettings');final parts = SuperTabParts._(@@ -86,6 +87,8 @@ class SuperTabParts {}}parts._takeReadMarks(marks);+ // Every one is news to a device whose own mark is higher.+ parts._takeUnreadMarks(unreadMarks, all: true);parts._takeThreadMarks(threadMarks);parts._takeChatSettings(chatSettings);return parts;@@ -156,6 +159,44 @@ class SuperTabParts {return moved;}+ /// The marks a Mark unread moved back (backend readMarks.ts `unreadMarks`) since [takeLowered] last ran: the one+ /// way a mark goes down, on every device of the reader.+ final _lowered = <String, int>{};++ /// Takes the marks in [marks] that a Mark unread moved below the one held (or, [all], each one sent); whether any+ /// moved.+ bool _takeUnreadMarks(Object? marks, {required bool all}) {+ var moved = false;+ if (marks is! Map) return moved;+ for (final MapEntry(:key, :value) in marks.entries) {+ if (key is! String || value is! num) continue;+ final sequence = value.toInt();+ if (!all && (_readMarks[key] ?? 0) <= sequence) continue;+ _readMarks[key] = sequence;+ _lowered[key] = sequence;+ moved = true;+ }+ return moved;+ }++ /// This device marked [conversationId] unread back to [sequence]: the mark held goes there.+ void lowerReadMark(String conversationId, int sequence) {+ if ((_readMarks[conversationId] ?? sequence + 1) > sequence) {+ _readMarks[conversationId] = sequence;+ }+ }++ /// A Mark unread this device asked for was not kept: the mark held goes back to [sequence].+ void raiseReadMark(String conversationId, int sequence) =>+ _takeReadMarks({conversationId: sequence});++ /// The marks lowered by a Mark unread elsewhere since the last call, by conversation.+ Map<String, int> takeLowered() {+ final taken = Map.of(_lowered);+ _lowered.clear();+ return taken;+ }+/// The reader's own thread marks (backend readMarks.ts): by conversation, the newest message sequence read in each/// thread, by its root. Kept as read marks are: the higher of each, and gone with their conversation.final _threadMarks = <String, Map<String, int>>{};@@ -284,7 +325,9 @@ class SuperTabParts {}}final derived = Map.of(superTabMap(changes['derived'] ?? const {}));- final readMarksMoved = _takeReadMarks(derived.remove('readMarks'));+ final readMarksMoved =+ _takeReadMarks(derived.remove('readMarks')) |+ _takeUnreadMarks(derived.remove('unreadMarks'), all: false);// Both run: one moving never skips the other.final marksMoved =_takeThreadMarks(derived.remove('threadMarks')) |@@ -412,6 +455,9 @@ class SuperTabParts {if (_derived['decisionsDigest'] case final String digest) {state['decisionsDigest'] = digest;}+ if (_derived['remindersDigest'] case final String digest) {+ state['remindersDigest'] = digest;+ }if (_derived['activityDigest'] case final String digest) {state['activityDigest'] = digest;}diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dartindex f13d57120..64d5b9682 100644--- a/desktop/lib/super_tabs/project_sidebar.dart+++ b/desktop/lib/super_tabs/project_sidebar.dart@@ -230,14 +230,16 @@ class ProjectSidebar extends StatelessWidget {}) {final project = reading?.project;final selected = !_paneCovered && controller.selectedId == group.id;- // A project's row is bold for anything in it for a person (#2427), its- // tasks' too, never agents' progress alone.+ // A project's row is bold for its own chat (Huy, 11-04, task #2638): a+ // person's message or a tag of the reader there, never agents' progress+ // alone (#2427). A task's unread is on its card and in Activity, and its+ // tags count in the row's number.final unread = reading == null? controller.unreadShown(group)- : reading.unread.isNotEmpty;+ : reading.unread.contains(group.id);// Tags in its chat, which opening it clears (Dee, Slack's way), and the// tasks that need the reader, so someone in another project still sees- // them (task #2569). Tags in tasks make it bold, and are in Activity.+ // them (task #2569). Tags in tasks count here and are in Activity.final mentions = attention?.mentionsIn(group.id) ?? 0;final needsYou = reading?.needsYou ?? 0;final badge = mentions + needsYou;@@ -576,8 +578,9 @@ class ProjectSidebar extends StatelessWidget {}/// Whether the unread filter keeps [read]'s project: its chat or an open- /// workgroup is unread or tags the reader, or the open chat is in it.- /// By the rule its rows are bold by (#2427): what is for a person.+ /// workgroup is unread or tags the reader, or the open chat is in it. What+ /// is for a person (#2427), and wider than its row's bold, which is its+ /// chat's alone (task #2638): a project with an unread task stays listed.bool _hasUnread(_ProjectReading read) =>(!_paneCovered && read.sidebar.selectedProjectId == read.project.id) ||read.unread.isNotEmpty ||diff --git a/desktop/lib/super_tabs/read_marks.dart b/desktop/lib/super_tabs/read_marks.dartindex 946b62be1..df36f5845 100644--- a/desktop/lib/super_tabs/read_marks.dart+++ b/desktop/lib/super_tabs/read_marks.dart@@ -47,6 +47,13 @@ class SuperTabReadMarkSender<K> {if (_sending.add(conversationId)) _drain(conversationId);}+ /// Forgets what was sent for [conversationId]: once Mark unread moved its mark back, the next read is sent again.+ void forget(K conversationId) {+ _sent.remove(conversationId);+ _next.remove(conversationId);+ _failed.remove(conversationId);+ }+Future<void> _drain(K conversationId) async {while (!_disposed) {final sequence = _next.remove(conversationId);diff --git a/desktop/lib/super_tabs/reminders.dart b/desktop/lib/super_tabs/reminders.dartnew file mode 100644index 000000000..f6ef635b0--- /dev/null+++ b/desktop/lib/super_tabs/reminders.dart@@ -0,0 +1,210 @@+import 'dart:async';++import 'package:clock/clock.dart';+import 'package:flutter/foundation.dart';++import 'controller.dart';+import 'model.dart';++/// One of the reader's reminders that is due (backend reminders.ts): a message+/// they asked to come back to.+class SuperTabReminder {+ SuperTabReminder.fromJson(Map<String, dynamic> row)+ : id = row['id'] as String,+ conversationId = row['conversationId'] as String,+ conversationTitle = row['conversationTitle'] as String? ?? '',+ messageId = row['messageId'] as String,+ messageSequence = (row['messageSequence'] as num?)?.toInt(),+ threadId = row['threadId'] as String?,+ authorName = superTabMap(row['author'] ?? const {})['name'] as String?,+ text = row['text'] as String? ?? '',+ dueAt = DateTime.parse(row['dueAt'] as String);+ final String id, conversationId, conversationTitle, messageId, text;+ final int? messageSequence;++ /// The thread's root when the message is a reply only in its thread.+ final String? threadId;+ final String? authorName;+ final DateTime dueAt;++ /// This reminder at this time: set again on its message, it is another.+ String get key => '$id@${dueAt.toUtc().toIso8601String()}';+}++/// When Remind me brings a message back, from now in the reader's own time.+enum SuperTabRemindIn {+ twentyMinutes('In 20 minutes'),+ oneHour('In 1 hour'),+ tomorrowMorning('Tomorrow at 09:00');++ const SuperTabRemindIn(this.label);+ final String label;++ DateTime from(DateTime now) => switch (this) {+ twentyMinutes => now.add(const Duration(minutes: 20)),+ oneHour => now.add(const Duration(hours: 1)),+ tomorrowMorning => DateTime(now.year, now.month, now.day + 1, 9),+ };+}++/// The reader's due reminders in one Swarm, for Activity's Reminders. Read when+/// the Swarm's digest of them moves (one set, replaced or cleared on any+/// device), and again when the next one is due: a timer set for that time,+/// never a poll. One per controller.+class SuperTabReminders extends ChangeNotifier {+ SuperTabReminders._(this.controller) {+ controller.addListener(_changed);+ controller.onDispose(dispose);+ _changed();+ }++ static final _all = Expando<SuperTabReminders>();+ static SuperTabReminders of(SuperTabController controller) =>+ _all[controller] ??= SuperTabReminders._(controller);++ final SuperTabController controller;++ /// A reminder that came due while the app was open: its one notice.+ void Function(SuperTabReminder reminder)? onArrived;++ List<SuperTabReminder> due = const [];+ String? error;+ String? _digest;+ int? _epoch;+ Timer? _wake;+ DateTime? _next;+ Future<void>? _loading;+ bool _dirty = false, _disposed = false;++ /// The reminders already told of, by id and due time: one set again on the+ /// same message is news again. One due before this started is not news.+ final _told = <String>{};+ final DateTime _since = clock.now();++ String get _path =>+ '/api/super-tabs/${Uri.encodeComponent(controller.tabId)}';++ void _changed() {+ final snapshot = controller.snapshot;+ if (_disposed || snapshot == null || controller.accessRevoked) return;+ final epoch = controller.visibilityEpoch;+ final digest = snapshot.remindersDigest;+ // A backend before reminders sends none: there is nothing to read.+ if (digest == null) return;+ // A timer may not run while the computer sleeps: a Swarm read after the+ // due time reads the list too.+ final overdue = _next != null && !clock.now().isBefore(_next!);+ if (digest == _digest && epoch == _epoch && !overdue) return;+ _digest = digest;+ _epoch = epoch;+ unawaited(load());+ }++ /// Joins a read under way, and has it read once more when asked again.+ Future<void> load() {+ if (_loading case final running?) {+ _dirty = true;+ return running;+ }+ return _loading = () async {+ do {+ _dirty = false;+ await _read();+ } while (_dirty && !_disposed);+ }().whenComplete(() => _loading = null);+ }++ Future<void> _read() async {+ final Map<String, dynamic> answer;+ // A failed read is not tried again on each Swarm read; Retry or the next+ // digest reads it.+ _next = null;+ try {+ answer = await controller.request('GET', '$_path/reminders');+ } on SuperTabFailure catch (failure) {+ if (_disposed) return;+ if (failure.statusCode == 404) return;+ error = 'Could not load reminders. Try again.';+ notifyListeners();+ return;+ } catch (_) {+ if (_disposed) return;+ error = 'Could not load reminders. Try again.';+ notifyListeners();+ return;+ }+ if (_disposed) return;+ final fresh = [+ for (final row in answer['due'] as List? ?? const [])+ SuperTabReminder.fromJson(superTabMap(row)),+ ];+ error = null;+ due = List.unmodifiable(fresh);+ for (final reminder in fresh.reversed) {+ if (_told.add(reminder.key) && !reminder.dueAt.isBefore(_since)) {+ onArrived?.call(reminder);+ }+ }+ _schedule(DateTime.tryParse(answer['next'] as String? ?? ''));+ notifyListeners();+ }++ /// Reads the list again when the next reminder is due.+ void _schedule(DateTime? next) {+ _wake?.cancel();+ _wake = null;+ _next = next;+ if (next == null) return;+ final wait = next.difference(clock.now());+ _wake = Timer(+ wait.isNegative ? Duration.zero : wait + const Duration(seconds: 1),+ () => unawaited(load()),+ );+ }++ /// Reminds the reader of [message] at [at]. False when the server did not+ /// keep it.+ Future<bool> set(SuperTabMessage message, DateTime at) async {+ try {+ await controller.request(+ 'POST',+ '$_path/conversations/${Uri.encodeComponent(message.conversationId)}'+ '/messages/${Uri.encodeComponent(message.id)}/reminder',+ body: {'at': at.toUtc().toIso8601String()},+ );+ } catch (_) {+ return false;+ }+ // The digest moves with it; this device need not wait for a read.+ unawaited(load());+ return true;+ }++ /// [reminder] was opened: it is done, on every device.+ Future<void> open(SuperTabReminder reminder) async {+ due = List.unmodifiable(due.where((r) => r.id != reminder.id));+ notifyListeners();+ try {+ // A time of none clears it: the daemon and the web send only GET and POST.+ await controller.request(+ 'POST',+ '$_path/conversations/${Uri.encodeComponent(reminder.conversationId)}'+ '/messages/${Uri.encodeComponent(reminder.messageId)}/reminder',+ body: {'at': null},+ );+ } catch (_) {+ if (_disposed) return;+ error = 'Could not clear the reminder. Try again.';+ unawaited(load());+ }+ }++ @override+ void dispose() {+ if (_disposed) return;+ _disposed = true;+ _wake?.cancel();+ controller.removeListener(_changed);+ super.dispose();+ }+}diff --git a/desktop/lib/super_tabs/unread_line.dart b/desktop/lib/super_tabs/unread_line.dartindex 2170e8966..3d9d2fdf1 100644--- a/desktop/lib/super_tabs/unread_line.dart+++ b/desktop/lib/super_tabs/unread_line.dart@@ -81,6 +81,12 @@ class SuperTabUnreadLines {return (_at[id] = superTabFirstUnread(shown, mark, own: own)) != null;}+ /// Mark unread from [messageId]: [id]'s line goes above it, whatever came after it.+ void placeAt(String id, String messageId) {+ _at[id] = messageId;+ _seen.remove(id);+ }+/// Whether [id]'s line waits for older messages: loading, or a read back that failed and is not yet done. Nothing is/// followed or marked read meanwhile, and no line is placed short of the first unread.bool waitsForHistory(String id) =>diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 98fb6b930..6c4933061 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -4,6 +4,7 @@ import 'package:clock/clock.dart';import 'dart:math' as math;+import 'package:clock/clock.dart';import 'package:flutter/foundation.dart' show kIsWeb;import 'package:clock/clock.dart';import 'package:flutter/material.dart';@@ -47,6 +48,7 @@ import 'composer_toggle.dart';import 'activity.dart';import 'attachment_chips.dart' show superTabShowsInPlace;import 'attachment_image.dart';+import 'reminders.dart';import 'activity_view.dart';import 'attention.dart';import 'controller.dart';@@ -837,10 +839,22 @@ class _SuperTabViewState extends State<SuperTabView>_unread.clear(id);_newAfter.remove(id);});- c.markRead(id);+ c.markRead(id, explicit: true);return true;}+ /// More ▸ Mark unread: the New messages line goes above [message] at once,+ /// and back where it was if the server did not keep it.+ Future<void> _markUnread(SuperTabMessage message) async {+ final id = message.conversationId;+ final kept = c.markUnread(id, message);+ if (c.selectedId == id) setState(() => _unread.placeAt(id, message.id));+ if (await kept || !mounted) return;+ if (c.selectedId == id) setState(() => _unread.clear(id));+ ScaffoldMessenger.maybeOf(context)+ ?.showSnackBar(const SnackBar(content: Text("Couldn't mark unread")));+ }+void _jumpToLatest() {final id = c.selectedId;_focus.requestFocus();@@ -1968,8 +1982,43 @@ class _SuperTabViewState extends State<SuperTabView>/// is held is looked in first, then what arrived after it, then older pages,/// until the message is among them; one that is not found says so, and the/// list stays.- Future<void> _openMention(SuperTabMention mention) async {- final id = mention.conversationId;+ Future<void> _openMention(SuperTabMention mention) =>+ _openAtMessage(mention.conversationId, mention.messageId, answer: true);++ /// More ▸ Remind me: the message comes back in Activity at [when].+ Future<void> _remind(SuperTabMessage message, SuperTabRemindIn when) async {+ final at = when.from(clock.now());+ final kept = await SuperTabReminders.of(c).set(message, at);+ if (!mounted) return;+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ SnackBar(+ content: Text(+ kept+ ? 'Reminder set for ${MaterialLocalizations.of(context).formatTimeOfDay(TimeOfDay.fromDateTime(at))}'+ : "Couldn't set the reminder",+ ),+ duration: const Duration(seconds: 2),+ ),+ );+ }++ /// A due reminder opened from Activity: its message, which clears it.+ Future<void> _openReminder(SuperTabReminder reminder) async {+ unawaited(SuperTabReminders.of(c).open(reminder));+ await _openAtMessage(+ reminder.conversationId,+ reminder.messageId,+ answer: false,+ );+ }++ /// Opens conversation [id] at message [messageId], from Activity; [answer]+ /// replies to it (a tag).+ Future<void> _openAtMessage(+ String id,+ String messageId, {+ required bool answer,+ }) async {final request = ++_jumpRequest;// A closed or quiet conversation is asked for by id, as a message link does: the tag of a task with no worker is in one,// and a row that did nothing left the reader not knowing why it was there.@@ -1981,7 +2030,7 @@ class _SuperTabViewState extends State<SuperTabView>?.showSnackBar(const SnackBar(content: Text('Message unavailable')));return;}- final message = await _findMessage(id, mention.messageId);+ final message = await _findMessage(id, messageId);if (!mounted || request != _jumpRequest) return;if (message == null) {ScaffoldMessenger.maybeOf(context)?.showSnackBar(@@ -2005,7 +2054,8 @@ class _SuperTabViewState extends State<SuperTabView>if (!message.inMainStream) return;}setState(() {- if (c.canWrite &&+ if (answer &&+ c.canWrite &&c.selected?.archived == false &&message.thread == null) {_replies[id] = message;@@ -3490,6 +3540,11 @@ class _SuperTabViewState extends State<SuperTabView>),linkTarget: _linkTarget,onOpenLink: _openLink,+ // A reply only in its thread is read with its thread's own mark.+ onMarkUnread: inThread || !message.inMainStream+ ? null+ : () => unawaited(_markUnread(message)),+ onRemind: (when) => unawaited(_remind(message, when)),// A message with a thread is answered there; one from before threads// keeps the inline reply.onReply: !writable || inThread@@ -4859,6 +4914,8 @@ class _SuperTabViewState extends State<SuperTabView>unawaited(_openMention(mention)),onOpenThread: _openThreadFromList,onOpenConversation: _openConversation,+ onOpenReminder: (reminder) =>+ unawaited(_openReminder(reminder)),): const SizedBox.shrink(),_manageVisiblediff --git a/desktop/lib/widgets/account_menu.dart b/desktop/lib/widgets/account_menu.dartindex 5ff9b37c9..558a61ceb 100644--- a/desktop/lib/widgets/account_menu.dart+++ b/desktop/lib/widgets/account_menu.dart@@ -10,6 +10,7 @@ import 'workspace_account_button.dart';/// What the account menu was asked for.enum AccountMenuChoice {+ profile,addPhone,devices,store,@@ -19,7 +20,8 @@ enum AccountMenuChoice {signOut,}-/// The menu under the avatar: who is signed in, then Add Phone, Devices, the+/// The menu under the avatar: who is signed in, then Profile (their name and+/// @username, task #2654), Add Phone, Devices, the/// Store (moved here from the bar: Quiet Swarm, screen 0), Appearance,/// Notifications, Settings and Sign out. Each opens something the app/// already has; the caller does that once this has closed, so the two never@@ -97,6 +99,7 @@ class AccountMenu extends StatelessWidget {// same way, and a row that was there at the first opening and gone at the// next read as a fault (1.2.64 learned of the phone only when the menu opened).static const _rows = [+ (AccountMenuChoice.profile, AppIcons.user, 'Profile'),(AccountMenuChoice.addPhone, AppIcons.smartphone, 'Add Phone'),(AccountMenuChoice.devices, AppIcons.circle, 'Devices'),(AccountMenuChoice.store, AppIcons.store, 'Store'),diff --git a/desktop/lib/widgets/account_profile_sheet.dart b/desktop/lib/widgets/account_profile_sheet.dartnew file mode 100644index 000000000..e8847cbd7--- /dev/null+++ b/desktop/lib/widgets/account_profile_sheet.dart@@ -0,0 +1,236 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../state/app_state.dart';+import '../super_tabs/controller.dart';+import '../super_tabs/profile_actions.dart';+import 'desktop_chrome.dart';+import 'desktop_prompt_surface.dart';++/// The Swarm a Profile sheet edits the @username in, and its name.+typedef AccountProfileSwarm = ({SuperTabController controller, String name});++/// The Swarm open in this window, when the reader is one of its people: its+/// username is theirs to change from Profile. Null with no Swarm open.+AccountProfileSwarm? accountProfileSwarm(AppNotifier app) {+ if (app.swarms.isEmpty) return null;+ final id = app.activeSwarm.superTabId;+ if (id == null) return null;+ final controller = app.superTabs.peek(id);+ if (controller == null || controller.accessRevoked) return null;+ final member =+ controller.snapshot?.people.any((p) => p.id == controller.accountId) ==+ true;+ if (!member) return null;+ return (controller: controller, name: app.superTabName(id) ?? 'this Swarm');+}++/// Profile (task #2654), from the avatar menu and Settings ▸ Account: the+/// account's name, everywhere, and in [swarm] the @username. One flat sheet.+Future<void> showAccountProfileSheet(+ BuildContext context,+ AppNotifier app, {+ AccountProfileSwarm? swarm,+}) => showAppDialog<void>(+ context: context,+ builder: (context) => AccountProfileSheet(app: app, swarm: swarm),+);++/// The backend's rule (backend/src/lib/accountName.ts), said before sending+/// when it is plain here: an empty name, or one too long.+const _invalidName = 'Use 1 to 60 characters, with no hidden ones.';+const _maxName = 60;++class AccountProfileSheet extends StatefulWidget {+ const AccountProfileSheet({super.key, required this.app, this.swarm});++ final AppNotifier app;+ final AccountProfileSwarm? swarm;++ @override+ State<AccountProfileSheet> createState() => _AccountProfileSheetState();+}++class _AccountProfileSheetState extends State<AccountProfileSheet> {+ /// The name as it was when the sheet opened: the Swarm's name follows only+ /// a name the person changed here, so a Swarm name set on purpose stays.+ late final String _openedName = widget.app.currentUser?.name ?? '';+ late final _name = TextEditingController(text: _openedName);+ late final _username = TextEditingController(text: _currentUsername ?? '');+ bool _busy = false;+ String? _nameError, _usernameError;++ SuperTabController? get _swarm => widget.swarm?.controller;++ String? get _currentUsername {+ final c = _swarm;+ return c?.snapshot?.people+ .where((p) => p.id == c.accountId)+ .firstOrNull+ ?.username;+ }++ String? get _currentSwarmName {+ final c = _swarm;+ return c?.snapshot?.people+ .where((p) => p.id == c.accountId)+ .firstOrNull+ ?.name;+ }++ @override+ void dispose() {+ _name.dispose();+ _username.dispose();+ super.dispose();+ }++ /// One space between words, as the backend keeps it.+ static String _tidy(String text) =>+ text.replaceAll(RegExp(r'[\t\s]+'), ' ').trim();++ /// Sends only what differs from what is saved, in order: the account name,+ /// the username, then this Swarm's name. Stops at the first refusal and says+ /// why under its field; what was saved before it stays saved, so Save again+ /// sends only what is left.+ Future<void> _save() async {+ if (_busy) return;+ final name = _tidy(_name.text);+ final username = _username.text.trim();+ if (name.isEmpty || name.runes.length > _maxName) {+ setState(() => _nameError = _invalidName);+ return;+ }+ setState(() {+ _busy = true;+ _nameError = null;+ _usernameError = null;+ });+ String? failure;+ var field = 'name';+ final renamed = name != _tidy(_openedName);+ if (name != (widget.app.currentUser?.name ?? '')) {+ failure = await widget.app.setAccountName(name);+ }+ final swarm = _swarm;+ if (failure == null &&+ swarm != null &&+ username.isNotEmpty &&+ username != _currentUsername) {+ field = 'username';+ failure = await swarm.setUsername(username);+ }+ if (failure == null &&+ swarm != null &&+ renamed &&+ name != _currentSwarmName) {+ field = 'name';+ failure = await swarm.setName(name);+ }+ if (!mounted) return;+ if (failure == null) {+ Navigator.of(context).pop();+ return;+ }+ setState(() {+ _busy = false;+ if (field == 'username') {+ _usernameError = failure;+ } else {+ _nameError = failure;+ }+ });+ }++ Widget _error(String key, String text) => Padding(+ padding: const EdgeInsets.only(top: 4),+ child: Text(+ text,+ key: ValueKey(key),+ style: DesktopChrome.metadata(color: Theme.of(context).colorScheme.error),+ ),+ );++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final swarm = widget.swarm;+ void submit(String _) => unawaited(_save());+ return DesktopPromptSurface(+ key: const ValueKey('account-profile-sheet'),+ body: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text('Profile', style: DesktopChrome.heading()),+ const SizedBox(height: DesktopChrome.groupGap),+ Text('Name', style: DesktopChrome.control(medium: true)),+ const SizedBox(height: 6),+ TextField(+ key: const ValueKey('account-profile-name'),+ controller: _name,+ autofocus: true,+ enabled: !_busy,+ maxLength: _maxName,+ textInputAction: TextInputAction.done,+ decoration: const InputDecoration(counterText: ''),+ onChanged: (_) => setState(() => _nameError = null),+ onSubmitted: submit,+ ),+ if (_nameError case final error?)+ _error('account-profile-name-error', error),+ if (swarm != null) ...[+ const SizedBox(height: DesktopChrome.groupGap),+ Text('Username', style: DesktopChrome.control(medium: true)),+ const SizedBox(height: 6),+ Row(+ children: [+ Expanded(+ child: TextField(+ key: const ValueKey('account-profile-username'),+ controller: _username,+ enabled: !_busy,+ maxLength: 32,+ textInputAction: TextInputAction.done,+ decoration: const InputDecoration(+ counterText: '',+ prefixText: '@',+ ),+ onChanged: (_) => setState(() => _usernameError = null),+ onSubmitted: submit,+ ),+ ),+ const SizedBox(width: 10),+ Flexible(+ child: Text(+ 'in ${swarm.name}',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(),+ ),+ ),+ ],+ ),+ if (_usernameError case final error?)+ _error('account-profile-username-error', error),+ ],+ ],+ ),+ actions: [+ TextButton(+ key: const ValueKey('account-profile-cancel'),+ onPressed: () => Navigator.of(context).pop(),+ child: const Text('Cancel'),+ ),+ FilledButton(+ key: const ValueKey('account-profile-save'),+ onPressed: _busy ? null : () => unawaited(_save()),+ child: const Text('Save'),+ ),+ ],+ );+ }+}diff --git a/desktop/test/account_profile_sheet_shots_test.dart b/desktop/test/account_profile_sheet_shots_test.dartnew file mode 100644index 000000000..1b341d1f9--- /dev/null+++ b/desktop/test/account_profile_sheet_shots_test.dart@@ -0,0 +1,122 @@+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/settings/sections/account_section.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/widgets/account_menu.dart';+import 'package:harness/widgets/account_profile_sheet.dart';++import 'account_profile_sheet_test.dart' show NameApi, profileApp;+import 'support/capture.dart';+import 'support/super_tab_fixture.dart';++/// Set to a folder to write the Profile PR's screenshots there (task #2654):+/// the real sheet over a fake API and the in-memory Swarm, never a backend.+final shots = Platform.environment['ACCOUNT_PROFILE_SHOTS'];++Widget _frame(Brightness brightness, Widget body) => MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(body: body),+);++Future<void> _theme(WidgetTester tester, Brightness brightness) async {+ await tester.binding.setSurfaceSize(const Size(900, 560));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.dark);+}++void main() {+ setUpAll(() => loadCaptureFonts(shots));++ for (final brightness in Brightness.values) {+ final mode = brightness.name;+ testWidgets(+ 'screenshots for review ($mode)',+ (tester) async {+ await _theme(tester, brightness);+ final app = profileApp(NameApi(), name: 'phorom12a');+ addTearDown(app.dispose);+ final server = ConversationServer();+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();++ // The avatar menu, Profile at its head.+ await tester.pumpWidget(+ _frame(+ brightness,+ Align(+ alignment: Alignment.topRight,+ child: Padding(+ padding: const EdgeInsets.all(12),+ child: SizedBox(+ width: AccountMenu.width,+ child: Material(+ child: AccountMenu(+ name: 'phorom12a',+ email: '[email protected]',+ onChoose: (_) {},+ ),+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, 'avatar-menu-$mode');++ // The sheet, then a taken username said under its field.+ await tester.pumpWidget(+ _frame(+ brightness,+ Builder(+ builder: (context) => TextButton(+ onPressed: () => showAccountProfileSheet(+ context,+ app,+ swarm: (controller: c, name: 'openharness'),+ ),+ child: const Text('Open'),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ await tester.enterText(+ find.byKey(const ValueKey('account-profile-name')),+ 'Elvis',+ );+ await tester.enterText(+ find.byKey(const ValueKey('account-profile-username')),+ 'elvis',+ );+ await tester.pump();+ await captureWindow(tester, shots, 'profile-sheet-$mode');+ server.refuse = {+ 'code': 'USERNAME_TAKEN',+ 'message': 'elvis is taken.',+ };+ await tester.tap(find.byKey(const ValueKey('account-profile-save')));+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, 'profile-sheet-taken-$mode');+ await tester.tap(find.byKey(const ValueKey('account-profile-cancel')));+ await tester.pumpAndSettle();++ // Settings ▸ Account: the name, with Edit beside Sign out.+ await tester.pumpWidget(+ _frame(brightness, AccountSection(notifier: app)),+ );+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, 'settings-account-$mode');+ },+ skip: shots == null,+ // A Mac's text fields: no touch selection handle under the caret.+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),+ );+ }+}diff --git a/desktop/test/account_profile_sheet_test.dart b/desktop/test/account_profile_sheet_test.dartnew file mode 100644index 000000000..fc8520eb8--- /dev/null+++ b/desktop/test/account_profile_sheet_test.dart@@ -0,0 +1,317 @@+// The avatar menu's Profile (task #2654): a person changes their own account+// name and, in the Swarm they are in, their @username, from one sheet. The+// account name goes to the backend's PATCH /api/auth/me through a fake API;+// the Swarm's two through the fixture server's commands. A memory store and a+// fake sign-in: nothing here reaches the real CLI or signs this Mac out.+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/api/api_client.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/settings/sections/account_section.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/widgets/account_profile_sheet.dart';++import 'support/super_tab_fixture.dart';+import 'swarm_screen_test.dart' show mount;+import 'swarm_state_test.dart' show MemoryStore, createApp;++/// The backend's account name route, as the daemon answers it.+class NameApi extends ApiClient {+ NameApi() : super(config: AppConfig.dev, session: AuthSession());++ final sent = <String>[];++ /// The next answer's refusal: (HTTP status, message).+ (int, String)? refuse;++ @override+ Future<Map<String, dynamic>?> updateMe({required String name}) async {+ sent.add(name);+ if (refuse case (final status, final message)) {+ refuse = null;+ throw ApiException(message, status: status);+ }+ return {+ 'user': {'id': 'owner', 'email': '[email protected]', 'name': name},+ 'avatarUrl': null,+ 'description': null,+ };+ }+}++final _name = find.byKey(const ValueKey('account-profile-name'));+final _username = find.byKey(const ValueKey('account-profile-username'));+final _save = find.byKey(const ValueKey('account-profile-save'));++Map<String, dynamic> _command(Map<String, dynamic> post) =>+ Map<String, dynamic>.from(post['command'] as Map);++List<String> _types(ConversationServer server) => [+ for (final post in server.posts) _command(post)['type'] as String,+];++AppNotifier profileApp(NameApi api, {String? name = 'phorom12a'}) {+ final app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ )..signedIn = true;+ app.api = api;+ app.currentUser = CurrentUserProfile(+ id: 'owner',+ name: name,+ email: '[email protected]',+ );+ return app;+}++Future<void> _open(+ WidgetTester tester,+ AppNotifier app, {+ SuperTabController? swarm,+}) async {+ await tester.binding.setSurfaceSize(const Size(1200, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Builder(+ builder: (context) => TextButton(+ onPressed: () => showAccountProfileSheet(+ context,+ app,+ swarm: swarm == null+ ? null+ : (controller: swarm, name: 'openharness'),+ ),+ child: const Text('Open'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+}++Future<SuperTabController> _swarm(ConversationServer server) async {+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ return c;+}++/// The line said under a field, by its key.+String? _said(WidgetTester tester, String key) =>+ tester.widget<Text>(find.byKey(ValueKey(key))).data;++String _text(WidgetTester tester, Finder field) =>+ tester.widget<TextField>(field).controller!.text;++void main() {+ testWidgets('shows the account name and this Swarm\'s @username', (+ tester,+ ) async {+ final api = NameApi();+ final app = profileApp(api);+ addTearDown(app.dispose);+ final server = ConversationServer();+ await _open(tester, app, swarm: await _swarm(server));+ expect(find.text('Profile'), findsOneWidget);+ expect(_text(tester, _name), 'phorom12a');+ expect(_text(tester, _username), 'owner');+ expect(find.text('in openharness'), findsOneWidget);+ });++ testWidgets('Save applies both: the account name, this Swarm\'s name and '+ 'the username', (tester) async {+ final api = NameApi();+ final app = profileApp(api);+ addTearDown(app.dispose);+ final server = ConversationServer();+ final c = await _swarm(server);+ await _open(tester, app, swarm: c);+ await tester.enterText(_name, ' Elvis ');+ await tester.enterText(_username, 'elvis');+ await tester.tap(_save);+ await tester.pumpAndSettle();+ expect(api.sent, ['Elvis']);+ expect(app.currentUser!.name, 'Elvis');+ expect(_types(server), ['member.username', 'member.name']);+ expect(_command(server.posts.last), {+ 'type': 'member.name',+ 'name': 'Elvis',+ });+ expect(c.snapshot!.people.single.username, 'elvis');+ expect(c.snapshot!.people.single.shownName, 'Elvis');+ // Saved: the sheet has closed.+ expect(find.text('Profile'), findsNothing);+ });++ testWidgets('only what changed is sent', (tester) async {+ final api = NameApi();+ final app = profileApp(api);+ addTearDown(app.dispose);+ final server = ConversationServer();+ await _open(tester, app, swarm: await _swarm(server));+ await tester.enterText(_username, 'elvis');+ await tester.tap(_save);+ await tester.pumpAndSettle();+ expect(api.sent, isEmpty);+ expect(_types(server), ['member.username']);+ });++ testWidgets('a taken username says so under it and keeps the sheet open; '+ 'Save again sends only what is left', (tester) async {+ final api = NameApi();+ final app = profileApp(api);+ addTearDown(app.dispose);+ final server = ConversationServer();+ final c = await _swarm(server);+ await _open(tester, app, swarm: c);+ server.refuse = {'code': 'USERNAME_TAKEN', 'message': 'elvis is taken.'};+ await tester.enterText(_name, 'Elvis');+ await tester.enterText(_username, 'elvis');+ await tester.tap(_save);+ await tester.pumpAndSettle();+ expect(_said(tester, 'account-profile-username-error'), 'elvis is taken.');+ expect(find.text('Profile'), findsOneWidget);+ expect(_text(tester, _username), 'elvis');+ expect(api.sent, ['Elvis']);++ server.refuse = null;+ await tester.enterText(_username, 'elvis2');+ await tester.tap(_save);+ await tester.pumpAndSettle();+ // The account name was saved already: it is not sent twice.+ expect(api.sent, ['Elvis']);+ expect(c.snapshot!.people.single.username, 'elvis2');+ expect(c.snapshot!.people.single.shownName, 'Elvis');+ expect(find.text('Profile'), findsNothing);+ });++ testWidgets('an empty name says why and sends nothing', (tester) async {+ final api = NameApi();+ final app = profileApp(api);+ addTearDown(app.dispose);+ final server = ConversationServer();+ await _open(tester, app, swarm: await _swarm(server));+ await tester.enterText(_name, ' ');+ await tester.tap(_save);+ await tester.pumpAndSettle();+ expect(+ _said(tester, 'account-profile-name-error'),+ 'Use 1 to 60 characters, with no hidden ones.',+ );+ expect(api.sent, isEmpty);+ expect(server.posts, isEmpty);+ });++ testWidgets('the backend\'s refusal of a name is said under it', (+ tester,+ ) async {+ final api = NameApi()+ ..refuse = (400, 'Use 1 to 60 characters, with no hidden ones.');+ final app = profileApp(api);+ addTearDown(app.dispose);+ final server = ConversationServer();+ await _open(tester, app, swarm: await _swarm(server));+ await tester.enterText(_name, 'Elvis');+ await tester.tap(_save);+ await tester.pumpAndSettle();+ expect(+ _said(tester, 'account-profile-name-error'),+ 'Use 1 to 60 characters, with no hidden ones.',+ );+ expect(app.currentUser!.name, 'phorom12a');+ expect(server.posts, isEmpty);+ });++ testWidgets('a Harness too old for the route says to update it', (+ tester,+ ) async {+ final api = NameApi()..refuse = (404, 'Request failed (404)');+ final app = profileApp(api);+ addTearDown(app.dispose);+ await _open(tester, app);+ await tester.enterText(_name, 'Elvis');+ await tester.tap(_save);+ await tester.pumpAndSettle();+ expect(find.text('Update Harness to change your name.'), findsOneWidget);+ expect(_text(tester, _name), 'Elvis');+ });++ testWidgets('with no Swarm open there is no username', (tester) async {+ final api = NameApi();+ final app = profileApp(api, name: null);+ addTearDown(app.dispose);+ await _open(tester, app);+ expect(_text(tester, _name), '');+ expect(_username, findsNothing);+ await tester.enterText(_name, 'Elvis');+ await tester.tap(_save);+ await tester.pumpAndSettle();+ expect(api.sent, ['Elvis']);+ expect(find.text('Profile'), findsNothing);+ });++ testWidgets('Cancel closes it and saves nothing', (tester) async {+ final api = NameApi();+ final app = profileApp(api);+ addTearDown(app.dispose);+ await _open(tester, app);+ await tester.enterText(_name, 'Elvis');+ await tester.tap(find.byKey(const ValueKey('account-profile-cancel')));+ await tester.pumpAndSettle();+ expect(find.text('Profile'), findsNothing);+ expect(api.sent, isEmpty);+ expect(app.currentUser!.name, 'phorom12a');+ });++ testWidgets('the avatar menu\'s Profile opens the sheet', (tester) async {+ final app = createApp(store: MemoryStore())+ ..currentUser = const CurrentUserProfile(+ id: 'owner',+ name: 'phorom12a',+ email: '[email protected]',+ );+ addTearDown(app.dispose);+ await mount(tester, app);+ await tester.tap(find.byKey(const ValueKey('swarm-account-button')));+ await tester.pump();+ await tester.pump();+ await tester.tap(find.byKey(const ValueKey('account-menu-profile')));+ await tester.pumpAndSettle();+ expect(find.byKey(const ValueKey('account-profile-sheet')), findsOneWidget);+ expect(_text(tester, _name), 'phorom12a');+ await tester.tap(find.byKey(const ValueKey('account-profile-cancel')));+ await tester.pumpAndSettle();+ await tester.pumpWidget(const SizedBox());+ });++ testWidgets('Settings ▸ Account shows the name with an Edit that opens the '+ 'sheet', (tester) async {+ final api = NameApi();+ final app = profileApp(api);+ addTearDown(app.dispose);+ await tester.binding.setSurfaceSize(const Size(1200, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(body: AccountSection(notifier: app)),+ ),+ );+ expect(find.text('phorom12a'), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('settings-account-edit')));+ await tester.pumpAndSettle();+ expect(find.byKey(const ValueKey('account-profile-sheet')), findsOneWidget);+ await tester.enterText(_name, 'Elvis');+ await tester.tap(_save);+ await tester.pumpAndSettle();+ expect(find.byKey(const ValueKey('account-profile-sheet')), findsNothing);+ expect(find.text('Elvis'), findsOneWidget);+ });+}diff --git a/desktop/test/screenshots/project-row-bold/project-row-bold-after-dark.png b/desktop/test/screenshots/project-row-bold/project-row-bold-after-dark.pngnew file mode 100644index 000000000..7d7d59fa7Binary files /dev/null and b/desktop/test/screenshots/project-row-bold/project-row-bold-after-dark.png differdiff --git a/desktop/test/screenshots/project-row-bold/project-row-bold-after-light.png b/desktop/test/screenshots/project-row-bold/project-row-bold-after-light.pngnew file mode 100644index 000000000..7a6c2c9f4Binary files /dev/null and b/desktop/test/screenshots/project-row-bold/project-row-bold-after-light.png differdiff --git a/desktop/test/screenshots/project-row-bold/project-row-bold-before-dark.png b/desktop/test/screenshots/project-row-bold/project-row-bold-before-dark.pngnew file mode 100644index 000000000..1f36c1f65Binary files /dev/null and b/desktop/test/screenshots/project-row-bold/project-row-bold-before-dark.png differdiff --git a/desktop/test/screenshots/project-row-bold/project-row-bold-before-light.png b/desktop/test/screenshots/project-row-bold/project-row-bold-before-light.pngnew file mode 100644index 000000000..c159ce39eBinary files /dev/null and b/desktop/test/screenshots/project-row-bold/project-row-bold-before-light.png differdiff --git a/desktop/test/super_tab_attention_test.dart b/desktop/test/super_tab_attention_test.dartindex bb2b68639..ba93c72ae 100644--- a/desktop/test/super_tab_attention_test.dart+++ b/desktop/test/super_tab_attention_test.dart@@ -171,8 +171,8 @@ void main() {}testWidgets('a tag in a task conversation counts on the project row as '- 'a task that needs the reader; the row is bold and kept by the '- 'unread filter', (tester) async {+ 'a task that needs the reader, and the unread filter keeps it; the '+ 'row is bold only for its own chat (task #2638)', (tester) async {final server = projectServer();fromLead(server, 'Please look', conversationId: 'offline');server.tag('message-1', conversationId: 'offline');@@ -183,7 +183,7 @@ void main() {expect(inRow('super-group-lead', find.text('1')), findsOneWidget);expect(rowText(tester, 'super-group-lead', 'web-project').style?.fontWeight,- FontWeight.w600,+ isNot(FontWeight.w600),);c.toggleUnreadOnly();await tester.pumpAndSettle();diff --git a/desktop/test/super_tab_chat_test.dart b/desktop/test/super_tab_chat_test.dartindex 3640ecf9f..dcf536aed 100644--- a/desktop/test/super_tab_chat_test.dart+++ b/desktop/test/super_tab_chat_test.dart@@ -369,9 +369,8 @@ void main() {});}- testWidgets('a project stays unread until its unread workgroup is visited', (- tester,- ) async {+ testWidgets('a project row is not held bold by an unread workgroup once '+ 'its chat is read (task #2638)', (tester) async {final server = ConversationServer()..append('The lead update')..append('An unread workgroup update', conversationId: 'offline');@@ -391,11 +390,12 @@ void main() {.text.style?.fontWeight;+ // Its chat is open and read; the workgroup's news is on its card.expect(c.unread(c.selected!), isFalse);- expect(projectWeight(), grid.AppFont.semibold);+ expect(projectWeight(), isNot(grid.AppFont.semibold));await tester.tap(find.byKey(const ValueKey('super-group-lead')));await tester.pumpAndSettle();- expect(projectWeight(), grid.AppFont.semibold);+ expect(projectWeight(), isNot(grid.AppFont.semibold));// Opened as the project's Tasks view opens it (task #2569).await c.select('offline');await tester.pumpAndSettle();diff --git a/desktop/test/super_tab_mark_unread_test.dart b/desktop/test/super_tab_mark_unread_test.dartnew file mode 100644index 000000000..306503b93--- /dev/null+++ b/desktop/test/super_tab_mark_unread_test.dart@@ -0,0 +1,198 @@+import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';++const _line = ValueKey('super-new-messages-line');++/// [count] messages from the Lead agent in the Lead conversation, read to+/// the end on the server.+ConversationServer _read(int count) {+ final server = ConversationServer();+ for (var i = 1; i <= count; i++) {+ server.append('Update $i');+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Lead',+ };+ }+ return server..markReadElsewhere('lead', count);+}++void main() {+ late SuperTabController c;++ Future<void> show(WidgetTester tester, ConversationServer server) async {+ await tester.binding.setSurfaceSize(const Size(1200, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ c = server.controller();+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ }++ Finder row(String id) => find.byKey(ValueKey('super-message-$id'));+ Finder more(String id) => find.descendant(+ of: row(id),+ matching: find.byKey(ValueKey('super-message-more-$id')),+ );++ Future<void> markUnread(WidgetTester tester, String id) async {+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse.addPointer(location: Offset.zero);+ await mouse.moveTo(tester.getCenter(row(id)));+ await tester.pumpAndSettle();+ await tester.tap(more(id));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Mark unread'));+ await tester.pumpAndSettle();+ await mouse.removePointer();+ await tester.pumpAndSettle();+ }++ bool leadUnread() => c.unread(c.snapshot!.conversation('lead')!);++ testWidgets('Mark unread puts the New messages line above the message and '+ 'the chat counts unread again', (tester) async {+ final server = _read(6);+ await show(tester, server);+ expect(find.byKey(_line), findsNothing);+ expect(leadUnread(), isFalse);++ await markUnread(tester, 'message-4');++ expect(server.unreadPosts, [+ {'conversationId': 'lead', 'sequence': 4},+ ]);+ expect(c.readMark('lead'), 3);+ expect(leadUnread(), isTrue);+ expect(find.byKey(_line), findsOneWidget);+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ lessThan(tester.getTopLeft(find.text('Update 4')).dy),+ );+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ greaterThan(tester.getTopLeft(find.text('Update 3')).dy),+ );+ // The menu closes after a choice.+ expect(find.text('Mark unread'), findsNothing);+ });++ testWidgets('the line goes above the message even when the reader '+ 'answered after it', (tester) async {+ final server = _read(4);+ server.append('My answer');+ server.markReadElsewhere('lead', 5);+ await show(tester, server);+ await markUnread(tester, 'message-3');+ expect(find.byKey(_line), findsOneWidget);+ expect(+ tester.getTopLeft(find.byKey(_line)).dy,+ lessThan(tester.getTopLeft(find.text('Update 3')).dy),+ );+ expect(leadUnread(), isTrue);+ });++ testWidgets('the open chat stays unread until the reader leaves it', (+ tester,+ ) async {+ final server = _read(6);+ await show(tester, server);+ await markUnread(tester, 'message-4');+ final sent = List.of(server.readMarkPosts);++ // Polls and the visible end being read do not read it again.+ await c.refresh();+ await tester.pumpAndSettle();+ c.markRead('lead');+ await tester.pumpAndSettle();+ expect(server.readMarkPosts, sent);+ expect(leadUnread(), isTrue);+ expect(find.byKey(_line), findsOneWidget);+ expect(c.readMark('lead'), 3);++ // Left and opened again: read as any chat is.+ await c.select('offline');+ await tester.pumpAndSettle();+ await c.select('lead');+ await tester.pumpAndSettle();+ c.markRead('lead');+ await tester.pumpAndSettle();+ expect(c.readMark('lead'), 6);+ expect(server.readMarkPosts.last, {+ 'conversationId': 'lead',+ 'sequence': 6,+ });+ // The view's short timers (a highlight) end before the tree goes.+ await tester.pump(const Duration(seconds: 5));+ });++ testWidgets('a mark lowered on another device is taken here', (tester) async {+ final server = _read(6);+ await show(tester, server);+ expect(c.readMark('lead'), 6);+ // Another chat is open, so nothing here reads Lead again.+ await c.select('offline');+ await tester.pumpAndSettle();++ server.markUnreadElsewhere('lead', 2);+ await c.refresh();+ await tester.pumpAndSettle();+ expect(c.readMark('lead'), 1);+ expect(leadUnread(), isTrue);++ // A read after it, here or elsewhere, wins again.+ server.markReadElsewhere('lead', 5);+ await c.refresh();+ await tester.pumpAndSettle();+ expect(c.readMark('lead'), 5);+ });++ testWidgets('a reply only in its thread offers no Mark unread', (+ tester,+ ) async {+ final server = _read(3)..threads = true;+ server.append('Root');+ server.append('In the thread only');+ server.messages.last['thread'] = 'message-4';+ server.markReadElsewhere('lead', 5);+ await show(tester, server);+ c.openThread('message-4');+ await tester.pumpAndSettle();+ final reply = find.byKey(const ValueKey('super-thread-message-message-5'));+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse.addPointer(location: Offset.zero);+ addTearDown(mouse.removePointer);+ await mouse.moveTo(tester.getCenter(reply));+ await tester.pumpAndSettle();+ await tester.tap(+ find.descendant(+ of: reply,+ matching: find.byKey(const ValueKey('super-message-more-message-5')),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.text('Copy link to message'), findsOneWidget);+ expect(find.text('Mark unread'), findsNothing);+ });+}diff --git a/desktop/test/super_tab_new_messages_test.dart b/desktop/test/super_tab_new_messages_test.dartindex 66c8e735c..eecbe94f1 100644--- a/desktop/test/super_tab_new_messages_test.dart+++ b/desktop/test/super_tab_new_messages_test.dart@@ -857,15 +857,9 @@ void main() {tester,) async {final server = _server(2);- server.append('Elsewhere', conversationId: 'offline');- server.messages.last['author'] = {- 'kind': 'agent',- 'id': 'worker',- 'name': 'Worker',- };final c = await show(tester, server);- // The sidebar lists no tasks (task #2569): the task's news makes its- // project's row bold.+ // A project's row is bold for its own chat (task #2638): its news, read+ // on another device, clears it here.final name = c.snapshot!.projects.single.name;FontWeight? weight() => tester.widget<RichText>(@@ -880,11 +874,15 @@ void main() {.text.style?.fontWeight;- await tester.tap(find.byKey(const ValueKey('super-group-lead')));+ await c.select('offline');+ await tester.pumpAndSettle();+ server.append('Elsewhere', conversationId: 'lead');+ final sequence = server.messages.last['sequence'] as int;+ await c.refresh();await tester.pumpAndSettle();expect(weight(), grid.AppFont.semibold);// Read on another device.- server.markReadElsewhere('offline', 3);+ server.markReadElsewhere('lead', sequence);await c.refresh();await tester.pumpAndSettle();expect(weight(), isNot(grid.AppFont.semibold));diff --git a/desktop/test/super_tab_project_row_bold_shots_test.dart b/desktop/test/super_tab_project_row_bold_shots_test.dartnew file mode 100644index 000000000..1f6bd0a06--- /dev/null+++ b/desktop/test/super_tab_project_row_bold_shots_test.dart@@ -0,0 +1,96 @@+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/view.dart';++import 'support/capture.dart';+import 'support/humans_fixture.dart';+import 'support/super_tab_fixture.dart';++/// Set to a folder to write the pictures of task #2638 there, in both themes:+/// # lamp, its chat read and a task under it unread, beside # pilot, whose+/// chat is unread, with # notes open (Huy, 11-04).+final shots = Platform.environment['SUPER_TAB_SIDEBAR_SHOTS'];++void main() {+ setUpAll(() => loadCaptureFonts(shots));++ for (final brightness in Brightness.values) {+ testWidgets('project rows bold for their own chat in ${brightness.name}', (+ tester,+ ) async {+ if (shots == null) return;+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ tester.view.devicePixelRatio = 2;+ tester.view.physicalSize = const Size(1600, 900);+ addTearDown(tester.view.reset);+ final server = humansSwarm();+ server.state['projects'] = [+ projectFixture('lead', 'lamp', 'lead'),+ projectFixture('pilot', 'pilot', 'pilot-lead'),+ projectFixture('notes', 'notes', 'notes-lead'),+ ];+ (server.state['conversations'] as List)+ ..add({+ ...conversationFixture('pilot-lead', 'pilot'),+ 'projectId': 'pilot',+ })+ ..add({+ ...conversationFixture('notes-lead', 'notes'),+ 'projectId': 'notes',+ });+ addNumberedWorkgroups(server, 1);+ final controller = server.controller(+ account: 'peer',+ initial: {'tabId': 'tab', 'accountId': 'peer', 'selectedId': 'lead'},+ );+ await controller.refresh();+ final picture = GlobalKey();+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: RepaintBoundary(+ key: picture,+ child: Scaffold(+ body: SuperTabView(+ controller: controller,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Studio',+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ // # lamp's chat read on screen, a person's message in a task under it+ // unread; # pilot's chat unread; # notes open, so no row is selected.+ server.append('Is the lamp wired yet?', conversationId: 'lead');+ server.append('Can you check this?', conversationId: 'g1');+ server.append('A question for everyone', conversationId: 'pilot-lead');+ await controller.refresh();+ await tester.pumpAndSettle();+ await controller.select('lead');+ await tester.pumpAndSettle();+ await controller.select('notes-lead');+ await controller.refresh();+ await tester.pumpAndSettle();+ await captureBoundary(+ tester,+ picture.currentContext!.findRenderObject()! as RenderRepaintBoundary,+ shots,+ 'project-row-bold-${Platform.environment['SHOT_LABEL'] ?? 'after'}-${brightness.name}',+ );+ await tester.pumpWidget(const SizedBox());+ await controller.flush();+ controller.dispose();+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));+ }+}diff --git a/desktop/test/super_tab_reminders_shots_test.dart b/desktop/test/super_tab_reminders_shots_test.dartnew file mode 100644index 000000000..6915eedac--- /dev/null+++ b/desktop/test/super_tab_reminders_shots_test.dart@@ -0,0 +1,132 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/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_REMIND_SHOTS'];++/// The More menu with Mark unread and Remind me, a chat marked unread, and+/// Activity's Reminders, as the PR shows them, in both appearances.+void main() {+ setUpAll(() async {+ if (shots != null) await loadPreviewFonts();+ });++ for (final brightness in Brightness.values) {+ testWidgets('screenshots for review (${brightness.name})', (tester) async {+ final picture = GlobalKey();+ final server = ConversationServer()+ ..append('Planning the reminders for Huy.')+ ..append('Draft PR is up with the plan.')+ ..append('Should a reminder clear when it is opened?')+ ..append('Yes: opening it is the answer.');+ server.messages[2]['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Avocet',+ };+ server.messages[3]['author'] = {+ 'kind': 'person',+ 'id': 'huy',+ 'name': 'Huy',+ };+ server.followedThreads = {'unread': [], 'read': [], 'more': false};+ server.markReadElsewhere('lead', 4);+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ await tester.binding.setSurfaceSize(const Size(900, 560));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ 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();++ Future<void> shot(String name) async {+ if (shots == null) return;+ await tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/remind-$name-${brightness.name}.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }++ final row = find.byKey(const ValueKey('super-message-message-3'));+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse.addPointer(location: Offset.zero);+ await mouse.moveTo(tester.getCenter(row));+ await tester.pumpAndSettle();+ await tester.tap(+ find.descendant(+ of: row,+ matching: find.byKey(const ValueKey('super-message-more-message-3')),+ ),+ );+ await tester.pumpAndSettle();+ // Pointed at, as a person opens it.+ await mouse.moveTo(tester.getCenter(find.text('Remind me')));+ await tester.pumpAndSettle();+ expect(find.text('Tomorrow at 09:00'), findsOneWidget);+ await shot('menu');++ await tester.tap(find.text('In 20 minutes'));+ await tester.pumpAndSettle();+ await tester.pump(const Duration(seconds: 3));+ await mouse.moveTo(tester.getCenter(row));+ await tester.pumpAndSettle();+ await tester.tap(+ find.descendant(+ of: row,+ matching: find.byKey(const ValueKey('super-message-more-message-3')),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.text('Mark unread'));+ await tester.pumpAndSettle();+ await mouse.removePointer();+ await tester.pumpAndSettle();+ expect(+ find.byKey(const ValueKey('super-new-messages-line')),+ findsOneWidget,+ );+ await shot('unread');++ await tester.pump(const Duration(minutes: 21));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Activity').first);+ await tester.pumpAndSettle();+ expect(find.text('Reminders'), findsOneWidget);+ await shot('activity');+ });+ }+}diff --git a/desktop/test/super_tab_reminders_test.dart b/desktop/test/super_tab_reminders_test.dartnew file mode 100644index 000000000..eee8f4b69--- /dev/null+++ b/desktop/test/super_tab_reminders_test.dart@@ -0,0 +1,265 @@+import 'package:clock/clock.dart';+import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/reminders.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';++const _question = 'Should a reminder clear when it is opened?';++/// Three messages in the Lead conversation, the last an agent's question,+/// read to the end.+ConversationServer _chat() {+ final server = ConversationServer();+ server.append('Planning the reminders');+ server.append('Draft PR is up');+ server.append(_question);+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Avocet',+ };+ return server..markReadElsewhere('lead', 3);+}++void main() {+ late SuperTabController c;+ late List<String> arrived;++ Future<void> show(WidgetTester tester, ConversationServer server) async {+ await tester.binding.setSurfaceSize(const Size(1200, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ c = server.controller();+ arrived = [];+ SuperTabReminders.of(c).onArrived = (r) => arrived.add(r.id);+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ }++ Finder row(String id) => find.byKey(ValueKey('super-message-$id'));++ /// Past every reminder set: the timer waiting for the next one ends.+ Future<void> passReminders(WidgetTester tester) async {+ await tester.pump(const Duration(days: 2));+ await tester.pumpAndSettle();+ }++ Future<void> remind(WidgetTester tester, String id, String choice) async {+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse.addPointer(location: Offset.zero);+ await mouse.moveTo(tester.getCenter(row(id)));+ await tester.pumpAndSettle();+ await tester.tap(+ find.descendant(+ of: row(id),+ matching: find.byKey(ValueKey('super-message-more-$id')),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.text('Remind me'));+ await tester.pumpAndSettle();+ await tester.tap(find.text(choice));+ await tester.pumpAndSettle();+ await mouse.removePointer();+ await tester.pumpAndSettle();+ }++ Future<void> openActivity(WidgetTester tester) async {+ await tester.tap(find.text('Activity').first);+ await tester.pumpAndSettle();+ }++ Finder reminderRow(String messageId) =>+ find.byKey(ValueKey('super-activity-row-reminder:reminder-$messageId'));++ group('Remind me', () {+ testWidgets('In 20 minutes asks for the time 20 minutes on', (+ tester,+ ) async {+ final server = _chat();+ await show(tester, server);+ final asked = clock.now();+ await remind(tester, 'message-3', 'In 20 minutes');+ expect(server.reminderWrites, hasLength(1));+ final write = server.reminderWrites.single;+ expect(write['method'], 'set');+ expect(write['conversationId'], 'lead');+ expect(write['messageId'], 'message-3');+ final at = DateTime.parse(write['at'] as String);+ expect(+ at.difference(asked).inSeconds,+ inInclusiveRange(20 * 60, 20 * 60 + 5),+ );+ // The menu closes after a choice.+ expect(find.text('In 20 minutes'), findsNothing);+ await passReminders(tester);+ });++ testWidgets('In 1 hour and Tomorrow at 09:00 are in the reader\'s time', (+ tester,+ ) async {+ final server = _chat();+ await show(tester, server);+ final asked = clock.now();+ await remind(tester, 'message-2', 'In 1 hour');+ await remind(tester, 'message-3', 'Tomorrow at 09:00');+ final [hour, tomorrow] = [+ for (final w in server.reminderWrites)+ DateTime.parse(w['at'] as String),+ ];+ expect(hour.difference(asked).inSeconds, inInclusiveRange(3600, 3605));+ expect(+ tomorrow.toLocal(),+ DateTime(asked.year, asked.month, asked.day + 1, 9),+ );+ await passReminders(tester);+ });+ });++ testWidgets('a due reminder shows once under Reminders in Activity, with one '+ 'notice, and opening it clears it', (tester) async {+ final server = _chat();+ server.remindElsewhere(+ 'message-3',+ clock.now().add(const Duration(minutes: 20)),+ );+ await show(tester, server);+ await openActivity(tester);+ expect(find.text('Reminders'), findsNothing);+ expect(reminderRow('message-3'), findsNothing);++ // Nothing polls: the list is read again when the reminder is due.+ final reads = server.reminderReads.length;+ await tester.pump(const Duration(minutes: 19));+ expect(server.reminderReads, hasLength(reads));+ await tester.pump(const Duration(minutes: 1, seconds: 1));+ await tester.pumpAndSettle();+ expect(server.reminderReads, hasLength(reads + 1));++ expect(find.text('Reminders'), findsOneWidget);+ expect(reminderRow('message-3'), findsOneWidget);+ expect(+ find.descendant(+ of: reminderRow('message-3'),+ matching: find.text('Avocet: $_question'),+ ),+ findsOneWidget,+ );+ expect(arrived, ['reminder-message-3']);++ // Read again, it is still one row and no second notice.+ await SuperTabReminders.of(c).load();+ await c.refresh();+ await tester.pumpAndSettle();+ expect(reminderRow('message-3'), findsOneWidget);+ expect(arrived, ['reminder-message-3']);++ await tester.tap(reminderRow('message-3'));+ await tester.pumpAndSettle();+ expect(server.reminderWrites.last, {+ 'method': 'clear',+ 'conversationId': 'lead',+ 'messageId': 'message-3',+ });+ expect(server.reminders, isEmpty);+ expect(c.selectedId, 'lead');+ expect(find.text(_question), findsOneWidget);+ await openActivity(tester);+ expect(reminderRow('message-3'), findsNothing);+ expect(find.text('Reminders'), findsNothing);+ });++ testWidgets('a reminder set again on the same message notifies again', (+ tester,+ ) async {+ final server = _chat();+ await show(tester, server);+ final reminders = SuperTabReminders.of(c);+ server.remindElsewhere(+ 'message-3',+ clock.now().add(const Duration(minutes: 1)),+ );+ await c.refresh();+ await tester.pump(const Duration(minutes: 1, seconds: 2));+ await tester.pumpAndSettle();+ expect(arrived, ['reminder-message-3']);+ await reminders.open(reminders.due.single);+ await tester.pumpAndSettle();++ // Snoozed again, with no time in between: one more notice when due.+ server.remindElsewhere(+ 'message-3',+ clock.now().add(const Duration(minutes: 1)),+ );+ await c.refresh();+ await tester.pump(const Duration(minutes: 1, seconds: 2));+ await tester.pumpAndSettle();+ expect(arrived, ['reminder-message-3', 'reminder-message-3']);+ });++ testWidgets('a reminder due while the timer was held (the Mac asleep) is '+ 'read at the next Swarm read', (tester) async {+ final server = _chat();+ await show(tester, server);+ server.remindElsewhere(+ 'message-2',+ clock.now().add(const Duration(minutes: 5)),+ );+ await c.refresh();+ await tester.pumpAndSettle();+ final reads = server.reminderReads.length;+ // The clock passes the time without the timer firing, as after sleep.+ await withClock(+ Clock.fixed(clock.now().add(const Duration(minutes: 6))),+ () async {+ await c.refresh();+ await tester.pumpAndSettle();+ },+ );+ expect(server.reminderReads.length, greaterThan(reads));+ expect(SuperTabReminders.of(c).due.map((r) => r.id), [+ 'reminder-message-2',+ ]);+ await tester.pump(const Duration(minutes: 6));+ await tester.pumpAndSettle();+ });++ testWidgets('a reminder set on another device wakes this one at its time', (+ tester,+ ) async {+ final server = _chat();+ await show(tester, server);+ server.remindElsewhere(+ 'message-2',+ clock.now().add(const Duration(hours: 1)),+ );+ await c.refresh();+ await tester.pumpAndSettle();+ expect(SuperTabReminders.of(c).due, isEmpty);+ await tester.pump(const Duration(hours: 1, seconds: 1));+ await tester.pumpAndSettle();+ expect(SuperTabReminders.of(c).due.map((r) => r.id), [+ 'reminder-message-2',+ ]);+ expect(arrived, ['reminder-message-2']);+ });+}diff --git a/desktop/test/super_tab_sidebar_reads_light_test.dart b/desktop/test/super_tab_sidebar_reads_light_test.dartindex 418f2f3ce..74d82be50 100644--- a/desktop/test/super_tab_sidebar_reads_light_test.dart+++ b/desktop/test/super_tab_sidebar_reads_light_test.dart@@ -99,13 +99,33 @@ void main() {},);- testWidgets('a person\'s new message in a task makes its project bold', (- tester,- ) async {+ // Huy, 11-04 (task #2638): # lamp stayed bold after he read its chat, for+ // one unread task under it. A project's row is its chat's: a task's unread+ // is on its card and in Activity (the Tasks view, #2569).+ testWidgets('the project chat read while a task under it is unread: the '+ 'project row is not bold', (tester) async {final server = humansSwarm();addNumberedWorkgroups(server, 1);final controller = await show(tester, server);+ server.append('Can you check the lamp?', conversationId: 'lead');server.append('Can you check this?', conversationId: 'g1');+ await controller.select('lead');+ await controller.refresh();+ await tester.pumpAndSettle();+ await news(tester, controller);+ expect(+ titleStyle(tester, project, 'Pilot').fontWeight,+ isNot(grid.AppFont.semibold),+ );+ await close(tester, controller);+ });++ testWidgets('a person\'s new message in the project chat makes its row '+ 'bold', (tester) async {+ final server = humansSwarm();+ addNumberedWorkgroups(server, 1);+ final controller = await show(tester, server);+ server.append('Can you check the lamp?', conversationId: 'lead');await news(tester, controller);expect(titleStyle(tester, project, 'Pilot').fontWeight,@@ -115,8 +135,8 @@ void main() {});testWidgets(- 'a mention of the reader in a task makes its project bold, though an '- 'agent wrote it',+ 'a mention of the reader in a task leaves its project regular: the tag '+ 'is the row\'s needs-you number and in Activity',(tester) async {final server = humansSwarm();addNumberedWorkgroups(server, 1);@@ -125,7 +145,7 @@ void main() {await news(tester, controller);expect(titleStyle(tester, project, 'Pilot').fontWeight,- grid.AppFont.semibold,+ isNot(grid.AppFont.semibold),);await close(tester, controller);},diff --git a/desktop/test/super_tab_sidebar_rows_test.dart b/desktop/test/super_tab_sidebar_rows_test.dartindex 577886df2..949d547f6 100644--- a/desktop/test/super_tab_sidebar_rows_test.dart+++ b/desktop/test/super_tab_sidebar_rows_test.dart@@ -167,7 +167,8 @@ void main() {?.fontWeight;testWidgets(- 'a project with an unread task shows its name in bold, with no dot',+ 'a project whose chat is unread shows its name in bold, with no dot; an '+ 'unread task under it does not (task #2638)',(tester) async {// Not "Offline editing": it waits for a person.final server = humansSwarm();@@ -179,7 +180,12 @@ void main() {await controller.select('offline');await controller.refresh();await tester.pumpAndSettle();- // Bold for what its tasks hold.+ // A task's unread is on its card and in Activity, not on the project.+ expect(weightOf(tester, project, 'Pilot'), isNot(grid.AppFont.semibold));++ server.append('A question for everyone', conversationId: 'lead');+ await controller.refresh();+ await tester.pumpAndSettle();expect(weightOf(tester, project, 'Pilot'), grid.AppFont.semibold);expect(unreadDot(project), findsNothing);await close(tester, controller);@@ -187,8 +193,8 @@ void main() {);testWidgets(- 'a screen reader hears a project with an unread task as unread, and a '- 'read one not',+ 'a screen reader hears a project whose chat is unread as unread, and one '+ 'with only an unread task not',(tester) async {final semantics = tester.ensureSemantics();final server = humansSwarm();@@ -200,6 +206,11 @@ void main() {await controller.select('offline');await controller.refresh();await tester.pumpAndSettle();+ expect(spoken(tester, project), isNot(contains('Unread messages')));++ server.append('A question for everyone', conversationId: 'lead');+ await controller.refresh();+ await tester.pumpAndSettle();expect(spoken(tester, project), contains('Unread messages'));semantics.dispose();await close(tester, controller);diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex 94a876972..95884f34f 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -3,6 +3,7 @@ import 'dart:convert';import 'dart:math';import 'dart:typed_data';+import 'package:clock/clock.dart';import 'package:cryptography/dart.dart' show DartSha256;import 'package:dio/dio.dart' show CancelToken;import 'package:harness/state/harness_attachments.dart';@@ -86,9 +87,11 @@ class SwarmPartsBackend {'otherProjectsWork','githubApp','readMarks',+ 'unreadMarks','threadMarks','chatSettings','activityDigest',+ 'remindersDigest','teamAccounts','threadSessions','sessionsFromChat',@@ -179,10 +182,17 @@ class SwarmPartsBackend {// The reader's own read marks alone, as backend readMarks.ts sends them.if ((state['readMarks'] as Map?)?[reader ?? 'owner'] case final Map marks)'readMarks': Map<String, dynamic>.from(marks),+ // The reader's marks whose last move was a Mark unread (backend+ // readMarks.ts lowerReadMark), absent when none.+ if ((state['unreadMarks'] as Map?)?[reader ?? 'owner'] case final Map marks+ when marks.isNotEmpty)+ 'unreadMarks': Map<String, dynamic>.from(marks),// Their own Activity digest and chat settings (backend activity.ts,// chatSettings.ts): every setting on every read, which the app keeps.if (state['activityDigest'] != null)'activityDigest': state['activityDigest'],+ if (state['remindersDigest'] != null)+ 'remindersDigest': state['remindersDigest'],if ((state['chatSettings'] as Map?)?[reader ?? 'owner'] case final Map setwhen set.isNotEmpty)'chatSettings': Map<String, dynamic>.from(set),@@ -687,8 +697,88 @@ class ConversationServer {reader,() => <String, dynamic>{},) as Map;- final kept = max(marks[conversationId] as int? ?? 0, sequence);- return marks[conversationId] = kept;+ final held = marks[conversationId] as int? ?? 0;+ // A mark moved forward is no longer one Mark unread left.+ if (sequence > held) _unreadMarksOf(reader).remove(conversationId);+ return marks[conversationId] = max(held, sequence);+ }++ Map _unreadMarksOf(String reader) =>+ ((state['unreadMarks'] ??= <String, dynamic>{}) as Map).putIfAbsent(+ reader,+ () => <String, dynamic>{},+ ) as Map;++ /// The reader's reminders (backend reminders.ts), as its list answers each;+ /// its read lists those due by `clock.now()` and the next time after.+ final reminders = <Map<String, dynamic>>[];++ /// Whether the server has reminders: without, each route answers 404.+ bool remindersServed = true;+ final reminderReads = <String>[];++ /// Every reminder set or cleared, in order: {method, conversationId,+ /// messageId, at}.+ final reminderWrites = <Map<String, dynamic>>[];+ int _reminderTurn = 0;++ /// [message] as a reminder due [at] lists it.+ Map<String, dynamic> remindOf(Map<String, dynamic> message, DateTime at) {+ final group = (state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((g) => g['id'] == message['conversationId']);+ final thread = message['thread'] as String?;+ return {+ 'id': 'reminder-${message['id']}',+ 'conversationId': message['conversationId'],+ 'conversationTitle': group['title'],+ 'projectName': 'Harness',+ 'messageId': message['id'],+ 'messageSequence': message['sequence'],+ 'threadId': thread != null && thread != message['id'] ? thread : null,+ 'author': message['author'],+ 'text': message['text'],+ 'dueAt': at.toUtc().toIso8601String(),+ };+ }++ /// A reminder of [messageId] the reader set on another device, due [at].+ void remindElsewhere(String messageId, DateTime at) {+ reminders.add(+ remindOf(messages.firstWhere((m) => m['id'] == messageId), at),+ );+ state['remindersDigest'] = 'r${++_reminderTurn}';+ }++ /// The Mark unread writes this device sent, in order: {conversationId,+ /// sequence} with the message's own sequence.+ final unreadPosts = <Map<String, dynamic>>[];++ /// Every Mark unread write fails, as offline.+ bool failUnread = false;++ /// [reader] marked [conversationId] unread from message [sequence] on+ /// another device, as the backend keeps it.+ void markUnreadElsewhere(+ String conversationId,+ int sequence, {+ String reader = 'owner',+ }) => _lowerReadMark(conversationId, sequence, reader);++ /// The backend's Mark unread (readMarks.ts lowerReadMark): the mark goes to+ /// just before the message, never forward.+ int _lowerReadMark(String conversationId, int sequence, String reader) {+ final marks =+ ((state['readMarks'] ??= <String, dynamic>{}) as Map).putIfAbsent(+ reader,+ () => <String, dynamic>{},+ ) as Map;+ final held = marks[conversationId] as int?;+ final target = sequence - 1;+ if (held != null && held <= target) return held;+ marks[conversationId] = target;+ _unreadMarksOf(reader)[conversationId] = target;+ return target;}/// The thread marks this device sent, in order: {conversationId, root,@@ -976,6 +1066,57 @@ class ConversationServer {if (read != null) {return _markRead(read.group(1)!, body!['sequence'] as int, reader);}+ final reminder = RegExp(+ r'/conversations/([^/]+)/messages/([^/]+)/reminder$',+ ).firstMatch(path);+ // A POST, as the daemon forwards only GET and POST: a time sets it, none+ // clears it.+ if (reminder != null && method == 'POST') {+ final conversationId = Uri.decodeComponent(reminder.group(1)!);+ final messageId = Uri.decodeComponent(reminder.group(2)!);+ final clears = body?['at'] == null;+ reminderWrites.add({+ 'method': clears ? 'clear' : 'set',+ 'conversationId': conversationId,+ 'messageId': messageId,+ if (body?['at'] case final at?) 'at': at,+ });+ if (!remindersServed) {+ throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);+ }+ final id = 'reminder-$messageId';+ final held = reminders.indexWhere((r) => r['id'] == id);+ if (clears) {+ if (held >= 0) reminders.removeAt(held);+ state['remindersDigest'] = 'r${++_reminderTurn}';+ return {'cleared': held >= 0};+ }+ final message = messages.firstWhere((m) => m['id'] == messageId);+ final row = remindOf(message, DateTime.parse(body!['at'] as String));+ if (held >= 0) {+ reminders[held] = row;+ } else {+ reminders.add(row);+ }+ state['remindersDigest'] = 'r${++_reminderTurn}';+ return {'id': id, 'dueAt': row['dueAt']};+ }+ final unread = method == 'POST'+ ? RegExp(r'/conversations/([^/]+)/unread$').firstMatch(path)+ : null;+ if (unread != null) {+ final id = Uri.decodeComponent(unread.group(1)!);+ final sequence = body!['sequence'] as int;+ unreadPosts.add({'conversationId': id, 'sequence': sequence});+ if (failUnread) {+ throw const SuperTabFailure(+ 'OFFLINE',+ 'No connection.',+ statusCode: 503,+ );+ }+ return {'sequence': _lowerReadMark(id, sequence, reader ?? 'owner')};+ }final threadRead = method == 'POST'? RegExp(r'/conversations/([^/]+)/threads/([^/]+)/read$').firstMatch(path)@@ -1613,6 +1754,28 @@ class ConversationServer {}return jsonDecode(jsonEncode(answer)) as Map<String, dynamic>;}+ if (uri.pathSegments.last == 'reminders' && method == 'GET') {+ reminderReads.add(path);+ if (!remindersServed) {+ throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);+ }+ final now = clock.now();+ DateTime due(Map r) => DateTime.parse(r['dueAt'] as String);+ final listed = [+ for (final r in reminders)+ if (!due(r).isAfter(now)) r,+ ]..sort((a, b) => due(b).compareTo(due(a)));+ final later = [+ for (final r in reminders)+ if (due(r).isAfter(now)) due(r),+ ]..sort();+ return jsonDecode(+ jsonEncode({+ 'due': listed,+ 'next': later.firstOrNull?.toUtc().toIso8601String(),+ }),+ ) as Map<String, dynamic>;+ }if (uri.pathSegments.last == 'activity') {activityReads.add(path);// Worked out when asked, as a server does: a slow answer is the onediff --git a/desktop/test/workspace_account_test.dart b/desktop/test/workspace_account_test.dartindex 1afe387b3..d22a654fb 100644--- a/desktop/test/workspace_account_test.dart+++ b/desktop/test/workspace_account_test.dart@@ -413,7 +413,8 @@ void main() {await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();await tester.pump();- expect(chosen, AccountMenuChoice.addPhone);+ // Profile, the person's own name and @username, heads the rows (#2654).+ expect(chosen, AccountMenuChoice.profile);// Up from nothing is the last row, and Down from there the first again.await _mountMenu(tester, onChoice: answer);@@ -432,7 +433,7 @@ void main() {await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();await tester.pump();- expect(chosen, AccountMenuChoice.devices);+ expect(chosen, AccountMenuChoice.addPhone);await _mountMenu(tester, onChoice: answer);await tester.tapAt(const Offset(40, 700));@@ -444,7 +445,7 @@ void main() {});testWidgets('an account with no name says its email once; Add Phone is '- 'the first row whatever the account has', (tester) async {+ 'the row after Profile whatever the account has', (tester) async {await _mountMenu(tester, name: '');expect(find.text('[email protected]'), findsOneWidget);// It was hidden once the account had a phone, which the menu learned only@@ -457,6 +458,7 @@ void main() {AccountMenuChoice? chosen;await _mountMenu(tester, onChoice: (value) => chosen = value);await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);await tester.pump();await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();diff --git a/docs/plans/2026-11-04-account-profile-name-plan.md b/docs/plans/2026-11-04-account-profile-name-plan.mdnew file mode 100644index 000000000..72b1eb0cc--- /dev/null+++ b/docs/plans/2026-11-04-account-profile-name-plan.md@@ -0,0 +1,139 @@+# Account Profile (name and @username) Implementation Plan++> Written by the Engineer of task #2654 by the project's way of working (docs/plans, test first, one pull request,+> one independent review on it). No subagent-driven-development and no execution handoff: the Engineer implements it.++**Goal:** A signed-in person changes their own account name, and their @username in the Swarm they are in, from one+Profile sheet in the avatar menu (and from Settings ▸ Account), so nobody edits the production database by hand again.++**Architecture:** The backend gets `PATCH /api/auth/me` (`{ name }`), which writes only the caller's own `User.name`+after validation and answers the same body `GET /api/auth/me` does. The CLI daemon proxies that route for Desktop like+the other account routes; the web build calls the backend directly. Desktop's new Profile sheet saves the account name+through it, and in the open Swarm saves the same name as the Swarm name (`member.name`) and the username+(`member.username`) through the existing commands and their rules (River's choice A, 2026-11-04: no user-table read+on Swarm loads). Swarm lists show the Swarm name, so they show the new name at once.++**Tech Stack:** Fastify + Prisma (MongoDB), vitest; Node CLI daemon (`cli/src/hookServer.ts`), vitest; Flutter+Desktop/web, flutter_test widget tests with a memory store and a fake sign-in.++**Spec:** task #2654 brief (conversation 7bcaebbaee8b75c294a41dcb), quoted in the pull request.++## Global Constraints++- Name: trimmed, tabs and space runs folded to one space, NFC, 1–60 characters (code points), no control, format+ (invisible, bidi), line or paragraph separator characters; empty is refused. Error: 400 `INVALID_NAME`+ "Use 1 to 60 characters, with no hidden ones."+- Only the caller's own row: no user id anywhere in the request. A Team machine sign-in is refused (403, by the+ existing team allowlist).+- `GET /api/auth/me` returns the new name on the next read; the PATCH answers `{ user, avatarUrl: null, description: null }`.+- One flat sheet titled "Profile": Name, Username (`@` prefix, "in <Swarm>"), Cancel, Save. No explanatory sentences.+ Errors in one short line under their field.+- Username row only when a Swarm is open and the reader is a member of it.+- No schema change, no new collection, no new index.+- Desktop tests: memory store and fake sign-in; never the real CLI logout.+- Swarm code stays out of `cli/src/core` (the proxy wiring line in `cli/src/core/main.ts` is account, not Swarm, code).++## Review Focus++1. A name of spaces only, or with a zero-width / bidi character → refused, nothing written (backend test).+2. A 60-character name in an emoji-heavy script → accepted; 61 → refused (counted by code points; backend test).+3. A username taken in this Swarm → the account name may already be saved; the sheet stays open, says why under+ Username, and a second Save sends only what is still different (widget test).+4. An older CLI daemon without the PATCH route (404) → the sheet says "Update Harness to change your name." and keeps+ the typed name (widget test).+5. A Swarm name clash (another member already shows that name) → the sheet says why under Name; the account name+ stays saved (widget test).++## Design++- growth: N/A because it updates one field of an existing row; nothing new is stored.+- concurrency: one `prisma.user.update` by id; last write wins, the person is the only writer of their own name.+- read cost: no new read on any hot path; Swarm loads read no user rows (choice A).+- scale: 10x people changing names is a handful of writes a day; the metric that warns first is none needed.+- compatibility: old Desktop never calls the route; new Desktop on an old daemon gets 404 and says to update Harness;+ old backend answers 404 to the web the same way.+- migration + rollback: none; rolling back removes the route, stored names stay valid.+- audience: the server takes the user from the session, never from the request.+- identity: the caller's own session; a Team session (machine owner's login on a shared Mac) is refused.+- failure: every refusal is shown in the sheet in words.+- platforms: Desktop macOS/Linux/Windows through the daemon; web direct; phone in a follow-up task.++---++### Task 1: Backend: validate and save the caller's own account name++**Files:**+- Create: `backend/src/lib/accountName.ts`, `backend/src/lib/accountName.test.ts`+- Modify: `backend/src/routes/auth.ts` (next to `GET /api/auth/me`)+- Test: `backend/src/routes/authMe.test.ts`++**Interfaces:**+- Produces: `parseAccountName(input: unknown): { ok: true; name: string } | { ok: false }` and+ `MAX_ACCOUNT_NAME_LENGTH = 60`; `PATCH /api/auth/me` body `{ name: string }` → 200 `{ user, avatarUrl, description }`,+ 400 `INVALID_NAME`, 404 `NOT_FOUND`.++- [ ] Step 1: failing tests. `accountName.test.ts`: `' Elvis '` → `Elvis`; `'Minh\t Nguyen'` → `Minh Nguyen`;+ `''`, `' '`, `42`, `null` refused; `'ab'`, `'ab'`, `'a\nb'`, `'a\u0007b'` refused; 60 `'😀'` accepted, 61+ refused. `authMe.test.ts` (real middleware and route, faked user store): PATCH as user u1 changes only u1's row+ (u2 untouched, body `id`/`email`/`role` ignored); a following GET answers the new name; `' '` → 400 `INVALID_NAME`+ and no write; no token → 401; a team session → 403 `TEAM_SESSION_LIMITED`.+- [ ] Step 2: run `npm test -- src/lib/accountName.test.ts src/routes/authMe.test.ts`; expect failures (module and route missing).+- [ ] Step 3: implement `parseAccountName` (reuse `printable` from `superTabs/profile.ts`), the route with+ `userService.update(req.user!.sub, { name })`.+- [ ] Step 4: rerun; PASS. Also `npm test -- src/lib/teamSession.test.ts` (route table pin).+- [ ] Step 5: commit tests first, then code.++### Task 2: CLI daemon: proxy `PATCH /api/auth/me`++**Files:**+- Modify: `cli/src/hookServer.ts` (handler `onAuthMeUpdate?: (body: unknown) => Promise<PairOutcome>`, route next to+ `GET /api/auth/me`, CSRF-guarded by `x-adapter-local` like the desk's ops), `cli/src/core/main.ts` (wire+ `proxyBackend('PATCH', '/api/auth/me', body)`)+- Test: `cli/src/hookServer.spec.ts`++- [ ] Step 1: failing test: without the local header → 403 and handler not called; with it → body passed through and+ the backend's answer returned; bad JSON → 400.+- [ ] Step 2: run `npx vitest run src/hookServer.spec.ts`; FAIL (404).+- [ ] Step 3: implement. Step 4: rerun; PASS. Step 5: commit test, then code.++### Task 3: Desktop: the Profile sheet++**Files:**+- Create: `desktop/lib/widgets/account_profile_sheet.dart`, `desktop/test/account_profile_sheet_test.dart`+- Modify: `desktop/lib/api/api_client.dart` (`Future<Map<String, dynamic>?> updateMe({required String name})`),+ `desktop/lib/state/app_state.dart` (`Future<String?> setAccountName(String name)`: PATCH, set `currentUser` from the+ answer, keep it in the profile cache; answers the error line or null)++**Interfaces:**+- Produces: `Future<void> showAccountProfileSheet(BuildContext context, AppNotifier app)`; keys+ `account-profile-name`, `account-profile-username`, `account-profile-save`, `account-profile-name-error`,+ `account-profile-username-error`.+- Consumes: `SuperTabController.setName`, `setUsername` (`super_tabs/profile_actions.dart`), `app.activeSwarm.superTabId`,+ `app.superTabs.peek`.++- [ ] Step 1: failing widget tests: Save with both changed sends the account PATCH, then `member.name` and+ `member.username`, closes, and the avatar menu shows the new name; a taken username (409 `USERNAME_TAKEN`) keeps the+ sheet open with the server's words under Username; `' '` shows the invalid-name line and sends nothing; 404 from+ the daemon shows "Update Harness to change your name."; no open Swarm → no Username row.+- [ ] Step 2: run `flutter test test/account_profile_sheet_test.dart`; FAIL.+- [ ] Step 3: implement on `DesktopPromptSurface` (Cancel, Save). Save sends only changed fields: account name, then+ Swarm name, then username; stops at the first refusal and shows it under its field.+- [ ] Step 4: rerun; PASS. Step 5: commit test, then code.++### Task 4: Desktop: open it from the avatar menu and Settings ▸ Account++**Files:**+- Modify: `desktop/lib/widgets/account_menu.dart` (`AccountMenuChoice.profile`, row "Profile" first),+ `desktop/lib/screens/swarm_screen.dart` (case opens the sheet), `desktop/lib/settings/sections/account_section.dart`+ (an Edit button beside the name opens the sheet)+- Test: `desktop/test/account_profile_sheet_test.dart`, `desktop/test/account_menu_version_test.dart`++- [ ] Step 1: failing tests: the avatar menu's Profile row opens the sheet; Settings ▸ Account's Edit opens it.+- [ ] Step 2: run; FAIL. Step 3: implement. Step 4: rerun with `test/settings_account_copy_test.dart`,+ `test/web_chrome_menus_test.dart`, `test/web/web_app_menu_test.dart`; PASS. Step 5: commit.++### Task 5: Evidence++- [ ] Light and dark screenshots of the sheet (golden-style screenshot test run, files attached to the PR).+- [ ] `python3 scripts/check-ui-style.py` and `flutter test test/laid_out_list_test.dart` (guard tests); `npm test` in+ backend; red/green evidence as a PR comment.diff --git a/docs/plans/2026-11-04-decisions-leaderboard-mentions-reads-plan.md b/docs/plans/2026-11-04-decisions-leaderboard-mentions-reads-plan.mdnew file mode 100644index 000000000..b400323c7--- /dev/null+++ b/docs/plans/2026-11-04-decisions-leaderboard-mentions-reads-plan.md@@ -0,0 +1,75 @@+# Decisions, leaderboard and mentions reads stop loading the whole Swarm each request: plan++> Way of working: this plan's Engineer implements it task by task, test first (test-driven-development), in one pull+> request. No subagents, no execution handoff.++**Goal:** The three reads Ken's prod scan (2026-11-04 12:00 VN, v1.3.98) found hot answer exactly as today with far fewer+Mongo reads per request: decisions reads no Swarm part at an unchanged stamp, the leaderboard reads no dormant group at an+unchanged stamp, and mentions reads its tagged messages by one plain `$in` on `_id`.++**Architecture:**+- `store.decisions` loads the Swarm in a transaction (`this.load`), so every request reads members, agents, machines,+ unfinished starts, progress and active groups (~540 ms each on prod). It moves to `this.readLoad` (the read cache), as+ `costSummary` and `projectRepository` did in #2889; `listDecisions` then reads only the quiet conversations its rows name.+- The leaderboard reads its parts through the cache already, but `recentDormantGroups` reads every dormant group of the+ kept weeks on each request (86,610 docs in 2 h on prod). It becomes a cache entry, `board:{floor}:{projects}`, of the+ projects' dormant groups since the Monday that starts the window, holding only the board's fields, patched from each change+ like the other dormant entries (cachePatch.ts). The read then keeps the exact window and the index's order.+- `listMentions` reads its messages with Prisma's `findMany({ id: { in } })`, which Prisma sends as an `$expr` OR of one+ branch per id (slow planning, up to 1,640 ms). It reads them with `readBy` and a plain `$in` on `_id`, as `taggedThreads`+ already does.++**Tech Stack:** Fastify, Prisma on MongoDB, the Swarm read cache (`cache.ts`, `cachePatch.ts`), vitest with+mongodb-memory-server.++**Spec:** Task #2674 (Ken's prod scan, via River).++## Global Constraints++- Backend only. Same answers: each read is compared with a read straight from Mongo (`readCache: null`).+- No env switch; ships on. No production access.+- Indexes unchanged: the board entry loads through the existing project index (`groupsBy 'project'`).++## Review Focus++- The board entry's patch keeps exactly what a fresh load holds: a group that goes dormant, wakes, moves project, is+ deleted or gets newer activity.+- Answer order: the board read returns groups in the index's order, as before.+- Decisions answered from cached parts still check access per reader (`actor`, `author`) on every request.++## Design++- growth: the board entry holds at most six weeks of one project set's dormant groups, board fields only; the cache's byte+ cap and max age (cache.ts) evict it. Its key changes each Monday, so the old week's entry ages out.+- concurrency: none added; cache entries load once per stamp per process (cache.ts loading map).+- read cost: at an unchanged stamp, decisions reads no part and the board no group; a change reads only the delta.+- scale: 10x groups: the board entry grows with dormant groups of the window; cache bytes (cache.ts metrics) warn first.+- compatibility: no wire or schema change.+- migration + rollback: none; rollback is the previous release.+- audience: unchanged checks per reader (actor, canReadGroup, readsRecordsIn) on every request.+- identity: reads stay the caller's own.+- failure: without stamps (Redis down) every get reads Mongo, as today.+- platforms: N/A because backend only.++## Task 1: decisions through the read cache++**Files:** `backend/src/superTabs/store.ts`; test `backend/integration/superTabRequestReads.test.ts`.+- [ ] Failing test: a second decisions read at an unchanged stamp reads part rows today; it must read none and answer as a+ direct read.+- [ ] `decisions` uses `readLoad`; `listDecisions` reads with `this.db`.++## Task 2: leaderboard's dormant groups from the read cache++**Files:** `backend/src/superTabs/leaderboard/read.ts`, `backend/src/superTabs/cachePatch.ts`,+`backend/src/superTabs/read/service.ts`; tests `backend/src/superTabs/cachePatch.test.ts`,+`backend/integration/superTabRequestReads.test.ts`.+- [ ] Failing tests: a second board read at an unchanged stamp reads dormant groups today; it must read none. After a group+ goes dormant, wakes or is deleted, the board answers as a direct read, every week and with all projects.+- [ ] `boardRule(projects, floor)` and the `board:` entry; the read keeps `lastActivityAt >= since` in index order.++## Task 3: mentions read their messages by a plain `$in`++**Files:** `backend/src/superTabs/mentions.ts`; test `backend/integration/superTabRequestReads.test.ts`.+- [ ] Failing test: the mentions read's message query is sent as an `$expr` OR today; it must be one `$in` on `_id`, one+ IXSCAN, with the same answer.+- [ ] `listMentions` reads with `readBy(tx, 'SuperTabMessage', 'id', …)`.diff --git a/docs/plans/2026-11-04-departed-checker-failure-plan.md b/docs/plans/2026-11-04-departed-checker-failure-plan.mdnew file mode 100644index 000000000..7524e77f7--- /dev/null+++ b/docs/plans/2026-11-04-departed-checker-failure-plan.md@@ -0,0 +1,56 @@+# A departed checker's failure can be cleared Implementation Plan++> **For agentic workers:** Follow the project Engineer workflow: plan first in a draft PR; implement task by task with a committed failing test before its passing code; one independent review step on the pull request.++**Goal:** A check failed by a checker who has since left the Swarm can pass again in the same attempt: a later pass by the task's PM, or by a person who owns the project or the Swarm, clears every earlier failure from checkers no longer in the Swarm. Fix to what ships ("reviewed and tested before merge": a task whose Reviewer was stopped could never pass its check).++**Architecture:** `recordCheckVerdict` (checkVerdicts.ts) takes the set of checkers whose failures this verdict clears. `work.check` (commands.ts) passes it only for a pass by someone accountable for the task: its PM (the project's current coordinator, `ledProject`; a replaced PM's removal clears the lead of the tasks it led), the project's owner or the Swarm's owner. The cleared checkers are those whose verdict names an agent or a person the Swarm no longer lists. `passedBy` and `evidence` are recomputed from the verdicts that remain, as today.++**Tech Stack:** TypeScript, Vitest (backend); the CLI's task text (Vitest spec).++**Spec:** Task #2656 (Diego, 2026-11-04; option (b) decided by the PM, River).++## Global Constraints++- A live checker's failure still stands: a later pass by anyone else, the PM and owners included, doesn't erase it.+- A departed checker's failure is never dropped by itself: only an accountable checker's pass clears it. Anyone else's pass leaves the check failed.+- A failure from before verdicts were kept names no checker, so nothing here changes it.+- A cleared failure stays on the record: a line in the task's chat names the departed checker (each verdict keeps its checker's name), its evidence's first line and who cleared it (security reviews 1 and 2).+- Someone accountable can stop a live Reviewer and then clear its failure. That gives nobody new power, since owners and the coordinator can already merge past a check, and the line in the task records it.+- The CLI names a departed checker by its last known name, not a bare id.+- Swarm code stays out of cli/src/core. The backend unit suite and the Super Tab integration suite run in PR CI.+- PR body begins `Requested by [email protected] through Harness.`++## Design++- Growth: one short name on each verdict, and one chat line per cleared failure; a cleared verdict leaves the check's list.+- Concurrency: N/A because it runs inside the existing command transaction, as every verdict does.+- Read cost: N/A because no new read; the departed test reads the state the command already holds.+- Scale: one pass looks up each of the check's verdicts in the Swarm's agents and people, a handful per check.+- Compatibility: one optional field on a verdict (`name`), which older readers ignore. Older clients read `passedBy` and `evidence` as before.+- Migration + rollback: none. A rollback leaves cleared checks passed, which is what they then were.+- Audience: the server decides who may clear: the task's PM or an owner, by the actor the command runs as.+- Identity: the actor's own key, never the machine owner's.+- Failure: a pass by someone else leaves the check failed with the departed checker's evidence, as today.+- Platforms: backend; the CLI's task text.++## Review Focus++- Who counts as accountable: the project's current coordinator, `project.ownerId`, `state.ownerId`.+- Who counts as departed: an agent no longer in `state.agents`, a person no longer in `state.people`.+- A live checker's failure is never cleared.++## Task 1: Accountable passes clear departed checkers' failures++**Files:** `backend/src/superTabs/checkVerdicts.ts`, `backend/src/superTabs/commands.ts` (`work.check`), `backend/src/superTabs/steps.test.ts`++**Interfaces:** `recordCheckVerdict(check, verdict, clears?: (by: string) => boolean)`.++- [x] Write failing tests in the steps fixture: R fails, R is removed, R2 passes: still failed. The owner passes: passed, `passedBy` and evidence from that pass. The task's PM passes: the same. A live checker's failure isn't cleared by the owner. Commit; watch them fail.+- [x] Implement; commit; watch them pass.++## Task 2: The CLI names a departed checker++**Files:** `cli/src/superTabs/agentContext.spec.ts`++- [x] Test that a departed checker's failure reads with its last known name. It already passed: the task read names stopped agents from the backend's known names.diff --git a/docs/plans/2026-11-04-machine-background-writes-plan.md b/docs/plans/2026-11-04-machine-background-writes-plan.mdnew file mode 100644index 000000000..be36e859e--- /dev/null+++ b/docs/plans/2026-11-04-machine-background-writes-plan.md@@ -0,0 +1,66 @@+# Machine background writes Implementation Plan++> Written and carried out by the task's Engineer, test first, by these project instructions (no subagent-driven+> development, no execution handoff).++**Goal:** Ken's prod scan of 11-04 found `Machine.update` by `machineId`, in background work, slow 53 times in 32+minutes (19 s total, max 723 ms). Background writers of a Machine row skip writes that change nothing and merge the+writes one connect makes into one.++**Architecture:** The background `Machine.update` calls are the adapter socket's (`backend/src/lib/adapterWs.ts`): the+upgrade and its timers run outside any request, so `lib/queryStats.ts` names them `background`. One reconnect makes up+to four updates of the same row: the team flip at the upgrade (rare), the connection facts (hostname, clientVersion,+computerId, countryCode, sessionKind, a seeded name) on every connect, the connect's `lastSeenAt` stamp at the same+moment, and the close stamp; a connected machine adds one stamp every 5 minutes. After this change a connect writes+one update holding only the facts that differ from the row read at the upgrade, plus the stamp only when the row's+stamp is due (5 minutes old or another UTC day). A new socket floors its heartbeats on the row's stamp, not on its own+start. The close stamp stays: it is the exact "offline since". The filter stays the unique `machineId` index.++**Tech Stack:** TypeScript, Fastify, `ws`, Prisma on MongoDB, Vitest.++**Spec:** the task brief (#2676) and Ken's numbers in it. No production access.++## Global Constraints++- Backend only. No env switch: ships on. No index is created; the PR says what `{planId, authMode}` matches.+- `machines.lastSeenAt` keeps its contract: lags real liveness by at most `MACHINE_PRESENCE_WRITE_MS`; close is exact.+- A failed write never advances the socket's floor, so the next heartbeat retries.+- A former team row is still set to `computer` before the socket attaches.++## Review Focus++- The connect write's diff against the upgrade's row: a fact that changed must still be written.+- Stamp floor seeded from the row: no window longer than the interval without a stamp while connected.+- Write counts per connect, heartbeat and close (test `adapterMachineWrites.test.ts`).++## Tasks++### Task 1: dailyTracking helpers++**Files:** `backend/src/lib/dailyTracking.ts`, `backend/src/lib/dailyTracking.test.ts`++**Interfaces:**+- `machineConnectChanges(row, next): MachineConnectChanges` — the fields of `next` that differ from `row`.+- `presenceStateFromRow(lastSeenAt): PresenceWriteState` — the row's stamp as a socket's write state.+- `touchMachineOnlineDay(userId, machineId, now, { isNewConnection, countryCode?, changes?, stamp? })` — one update of+ `changes` plus `lastSeenAt` unless `stamp` is false; no update when both are empty; the connect total as before.++- [ ] Failing tests: unchanged facts give no changes; a changed fact is kept; the row's stamp seeds the floor; no+ update when nothing changed and no stamp; changes and stamp go in one update.+- [ ] Implement; run `npm test -- src/lib/dailyTracking.test.ts`.++### Task 2: one write per connect in the adapter socket++**Files:** `backend/src/lib/adapterWs.ts`, `backend/src/lib/adapterMachineWrites.test.ts` (new),+`backend/src/lib/teamSessionSockets.test.ts`++- [ ] Failing tests (real dailyTracking, mocked Prisma), counting `machine.update` calls:+ - a reconnect whose facts are unchanged and whose row was stamped a minute ago writes nothing on connect;+ - a connect after 5 minutes away writes one update with the stamp; a changed version rides in it;+ - heartbeats on that socket write only when the row's stamp is 5 minutes old; close stamps once;+ - a former team row is flipped before attach and not written again on connect.+- [ ] Implement: pass the upgrade's row to `attachAdapter`, compute changes, one `touchMachinePresence('connect',+ changes)`; seed the floor from the row.+- [ ] Run `npm test -- src/lib/adapterMachineWrites.test.ts src/lib/teamSessionSockets.test.ts+ src/lib/adapterTuiPresence.test.ts src/lib/adapterShortTurns.test.ts src/lib/adapterRoutes.test.ts`, then the+ backend unit suite (`npm test`).diff --git a/docs/plans/2026-11-04-machine-liveness-apart-plan.md b/docs/plans/2026-11-04-machine-liveness-apart-plan.mdnew file mode 100644index 000000000..7bf712ce0--- /dev/null+++ b/docs/plans/2026-11-04-machine-liveness-apart-plan.md@@ -0,0 +1,84 @@+# Machine liveness apart from the machine part (backend): implementation plan++The Engineer implements this plan task by task, test first, on one branch, and opens one pull request. Nobody is asked to+choose an execution mode. Steps use checkboxes.++**Goal:** A client that asks stops receiving a whole machine part for each reading. It gets one small line saying when that+machine last reported, and the whole part only when the part's content changed. Today's clients see no change.++**Architecture:** A reading keeps writing the same row, and `changedAt` already stays put for it. A new `contentAt` column records+when a reading changed what isn't volatile. `GET changes?machines=light` sends a part that only moved by its volatile fields as a+line in `machineReadings`. `GET machine-readings` gives the whole readings on demand, for the route and the machine panel.++**Tech Stack:** TypeScript, Prisma on MongoDB, Fastify, Vitest, integration tests on `mongodb-memory-server`.++**Spec:** Ken's machine-cap plan (2026-11-04), prerequisite 3; task #2636's brief as the PM narrowed it to the backend.++## Global Constraints++- Hosts, Desktop, the phone and the route must show the same online or offline state as before.+- Today's clients get exactly what they get now, including a higher version on each reading: they drop a part unless its version is higher.+- PR body first line: `Requested by [email protected] through Harness.`+- Merges through the PM's batch.++## Why no separate storage++The first proposal kept the reading beside the part. It isn't needed. A row's `data` is only read whole, the server's decisions need+the reading, and 75% of a median part is its reading, so splitting the row would save little on the server and change every+load. What costs 397 MB an hour is sending the part to every poller, and that is decided at the feed.++## What counts as volatile++Measured on production over 40 s, of 128 parts moved: `resources` and `receivedAt` 128, `harnessUncommitted` 19, `quotas` and+`profiles` 13, `privacy` 11, `harnessProgress` 9, `harnessTokens` 5, `lent` and `lentDays` 4, `readiness` 2. None moved by time alone.++Volatile: all of those but `readiness`. Anything else in a reading (running and stopped sessions, tools, readiness, capabilities,+generation, session kind) is content, so it still goes as a whole part.++## Review Focus++- A reading that changes running sessions: a whole part, since agents' state depends on it.+- A Buddy, or a Buddy-only machine: no line, as for parts today.+- A machine whose content changed inside the cursor's overlap: a whole part, never only a line.+- A removal in the same window: a stub, never a line.+- A rolling deploy: an old pod writes a content change with no `contentAt`, so a light reader gets only a line until the next+ content change or load. No light client exists until the follow-ups ship, after this is live everywhere.++## Design++- **Growth:** one optional date on `SwarmMachine`, overwritten in place and removed with the row.+- **Concurrency:** the same version-guarded write as every reading.+- **Read cost:** the feed's rows are still read and held as today, so server reads don't fall here. The reply falls for light readers.+ The read cache's 19 MB a minute per pod stays, because the server's decisions need the reading.+- **Scale:** at 10x machines, full parts cost 100x and lines cost 100x at about 1/25 the size; `machine-readings` and first loads grow+ linearly. The metric that warns first is `GET changes` bytes in `db by shape`.+- **Compatibility:** a new optional query value and a new optional reply field. An older server rejects the unknown value, so+ clients need a fallback. Old clients keep the old cost until they update.+- **Migration + rollback:** no migration. An old row has no `contentAt`, and `changedAt` stands in. Rollback leaves an unused column.+- **Audience:** a line is built from the part the reader may already see, so it shows no more than the part did.+- **Identity:** N/A because a line names a machine and a time, as the part does.+- **Failure:** a reader with a stale line sees a machine offline, as with a late part. It says so the same way.+- **Platforms:** backend only. CLI, Desktop and the phone are the PM's follow-up tasks.++## Known limit++Bytes fall only as clients update. The cap change should wait for that, not only for this release. Nothing here lowers the server's+own reads of machines.++---++### Task 1: Content is told apart from a reading++**Files:** Modify `backend/prisma/schema.prisma`, `backend/src/superTabs/parts/{types,write,commit,load}.ts`, `backend/src/superTabs/cachePatch.ts`, `backend/src/superTabs/store.ts`.++**Interfaces:** Produces `Part.contentAt?: number`, `PartWrite.content?: true`, `machineContentChanged(before, after): boolean`.++### Task 2: The light reply and the on-demand read++**Files:** Modify `backend/src/superTabs/read/{changes,contract,service}.ts`, `backend/src/routes/superTabs.ts`. Test `backend/integration/superTabMachineLiveness.test.ts`, `backend/src/superTabs/read/changes.test.ts`.++**Interfaces:** Consumes `Part.contentAt`. Produces `changesFor(view, changed, actor, light?: { since })`, `MachineReading { key, version, receivedAt }`, `SwarmReads.machineReadings(user, tabId, asAgentId?)`.++- [x] Write the failing tests for both tasks; watch them fail; commit.+- [x] Implement both; watch them pass; commit.+- [x] Post red/green and the bytes; mark the PR ready; add one review step.diff --git a/docs/plans/2026-11-04-mark-unread-remind-me-plan.md b/docs/plans/2026-11-04-mark-unread-remind-me-plan.mdnew file mode 100644index 000000000..08eb38ea1--- /dev/null+++ b/docs/plans/2026-11-04-mark-unread-remind-me-plan.md@@ -0,0 +1,194 @@+# Mark unread and Remind me Implementation Plan++> **For agentic workers:** Follow the project Engineer workflow: plan first in a draft PR; implement task by task with a committed failing test before its passing code; one independent review step on the pull request.++**Goal:** From a message's More menu, a person can mark the chat unread from that message, or ask to be reminded of it in 20 minutes, in 1 hour or tomorrow at 09:00, when it comes back in Activity under Reminders with a notification. Strengthens "Tell the PM what you want, and your crew ships it": an agent's question is never lost, and the person comes back to it.++**Architecture:** Mark unread lowers the person's stored read mark (`SuperTabReadMark`), the one write that may move it back, and marks the row as lowered, so every device of theirs takes the lower mark instead of keeping the higher one. Reminders are a new per-person collection, `SuperTabReminder`, read by the `(tabId, personId, dueAt)` index. A digest in the person's read says when their reminders changed; the client then reads its due list and the next due time, and wakes at that time.++**Tech Stack:** TypeScript, Fastify, Prisma on MongoDB, Vitest with mongodb-memory-server; Flutter/Dart Desktop (and its web build).++**Spec:** Task #2603 in Super Tab conversation 0c18b4e9c2ee941a15db17d7 (Huy, 2026-11-04; brief from River).++## Global Constraints++- Look (ASCII mockup for Huy):++ ```+ More menu (⋯ on a message's hover bar)+ ┌──────────────────────────────┐+ │ 🔗 Copy link to message │+ │ ✉ Mark unread │+ │ ⏰ Remind me › │┌───────────────────────┐+ └──────────────────────────────┘│ In 20 minutes │+ │ In 1 hour │+ │ Tomorrow at 09:00 │+ └───────────────────────┘++ Activity+ Needs you+ ◎ Kestrel is waiting on you Open+ Reminders+ ⏰ Avocet: Should a reminder clear when opened? 10:42+ New replies+ ↩ Voice messages like Telegram 2 new+ ```++ A reminder row is bold like the other new rows, says who wrote the message and its text, and ends with the time it+ was due. Opening it opens the message in its chat (its thread for a reply only in a thread) and clears it.+- Mark unread is offered on a message in the chat's main stream. A reply that lives only in its thread is read with+ its thread's own mark; it gets Remind me only.+- The mark goes to just before the message (its sequence − 1), never forward: a chat already unread from earlier stays+ as it is.+- After Mark unread in the open chat, it stays unread with the New messages line above the message until the person+ leaves the chat; reading it again (opening it, Mark all read, Esc) works as before.+- Another device with the chat open, in view and at its end, reads it again at once: a person is looking at it.+- Remind me times are the person's local time. Setting a reminder again on the same message replaces its time.+- A due reminder shows once in Activity and fires one notification on Desktop (none on the web, as tags), and counts+ in Activity's number until it is opened.+- Tokens only, flat rows, colour never the only signal, no explanatory sentences (desktop/design/desktop-design-system.md).+- Desktop tests use a memory store and a fake sign-in. Never a test that signs the Mac out of the real CLI. No Swarm+ code in cli/src/core.+- PR body begins `Requested by [email protected] through Harness.`++## Design++- Growth: a read mark row stays one row (one more date field). A reminder row is deleted when it is opened; setting+ one again replaces it (one row per person and message); the hourly sweep deletes reminders due more than 30 days ago+ (`REMINDER_EXPIRY_MS`) by the `dueAt` index. At most `REMINDER_CAP` = 200 pending reminders per person and Swarm:+ one more is refused with `REMINDER_LIMIT`.+- Concurrency: one document per write. Mark unread is a single conditional update (`sequence > target`); a read on+ another device after it raises the mark as before. Set and clear of a reminder are an upsert and a delete by id.+- Read cost: the first load and each changes read already read the person's marks by `(tabId, personId, updatedAt)`;+ they read one more field. The reminders digest adds one indexed read to each person's read, as `activityDigest`+ does (usually an empty range): one indexed read of at most `REMINDER_CAP` ids and due times by+ `(tabId, personId, dueAt)`. The reminders list reads due rows by the same index (`dueAt <= now`) and the next one+ after now (limit 1). Each query gets a plan test (IXSCAN on its index).+- Scale: at 10x people, rows grow per person and are capped; the first warning is the reminders read's latency in the+ query stats (`integration/queryStats.test.ts` coverage) and the reminder collection's size.+- Compatibility: an older client ignores `unreadMarks` and `remindersDigest`; it keeps the higher mark, so a chat+ marked unread elsewhere stays read there until it reads past it. A new client on an older backend gets 404 for the+ new routes: Mark unread still works on that device (its own mark), Remind me says it could not be set.+- Migration + rollback: no migration. `loweredAt` is optional; rows without it read as not lowered. Rolling back+ leaves `loweredAt` and the reminders collection unread; the sweep that deletes reminders goes with it, so a rollback+ of more than a day is followed by dropping `SuperTabReminder` (documented in the PR).+- Audience: the server enforces it. A reminder is read, set and cleared only by its person, as themselves (no agent,+ no Team session); the list keeps only messages they may still read (the chat by `canReadGroup`, the message as a page+ shows it, `read/inbox.ts readable`). Mark unread checks the chat as `markRead` does.+- Identity: the person is the signed-in user (`user.sub`), never a machine owner's login.+- Failure: a refused Mark unread or Remind me shows a snackbar naming it ("Couldn't mark unread", "Couldn't set the+ reminder"); a failed reminders read shows in Activity's error line with Retry, as tags. A sweep failure is logged by+ the sweep pass, as the others.+- Platforms: backend; macOS, Linux, Windows and web through Desktop's shared Flutter code. The phone app is not+ changed.++## Review Focus++1. A mark lowered on one device is taken by another device that holds a higher one, and an older mark arriving later+ never undoes a newer read (Task 1, Task 3 tests).+2. The open chat does not mark itself read straight after Mark unread (Task 3 widget test).+3. A reminder never shows to anyone but its person, nor for a message they can no longer read (Task 2 tests).+4. A due reminder shows once and notifies once, also when two reads race (Task 4 test).+5. A reminder set on another device wakes this one at its time without polling (Task 4 test).++---++### Task 1: Backend — Mark unread++**Files:**+- Modify: `backend/prisma/schema.prisma` (`SuperTabReadMark`: `loweredAt DateTime?`)+- Modify: `backend/src/superTabs/readMarks.ts` (`lowerReadMark`, `readMarkRows`)+- Modify: `backend/src/superTabs/read/service.ts` (`markUnread`; `unreadMarks` in first load and changes)+- Modify: `backend/src/superTabs/read/contract.ts` (`Derived.unreadMarks`)+- Modify: `backend/src/routes/superTabs.ts` (`POST /api/super-tabs/:tabId/conversations/:conversationId/unread`)+- Test: `backend/integration/superTabReadMarks.test.ts`++**Interfaces:**+- Produces: `POST …/conversations/:conversationId/unread` body `{ sequence }` (the message's sequence) → `{ sequence }`+ (the mark as stored). `Derived.unreadMarks?: Record<string, number>`: marks whose last move was a Mark unread+ (`loweredAt` equals `updatedAt`), in a first load all of them, in a changes read those moved since the cursor.++- [ ] Write failing tests: Mark unread at message 41 after a read to 60 stores 40 and the owner's next changes read+ carries `unreadMarks: { web: 40 }`; at 70 after a read to 40 keeps 40; a read to 60 afterwards raises it and+ the mark is no longer in `unreadMarks`; refused for an unreadable chat, a Team session and an agent.+- [ ] Run `npx vitest run integration/superTabReadMarks.test.ts` and see them fail (404 on the route).+- [ ] Implement, then run the same file and see it pass. Commit each step.++### Task 2: Backend — Reminders++**Files:**+- Modify: `backend/prisma/schema.prisma` (`SuperTabReminder`)+- Create: `backend/src/superTabs/reminders.ts` (`setReminder`, `clearReminder`, `listReminders`, `remindersDigest`,+ `sweepReminders`, `REMINDER_CAP`, `REMINDER_EXPIRY_MS`)+- Modify: `backend/src/superTabs/parts/indexed.ts` (the reminder indexes by name, for `readBy`)+- Modify: `backend/src/superTabs/read/service.ts` (`reminders`, `setReminder`, `clearReminder`; `remindersDigest` in+ the person's read), `backend/src/superTabs/read/contract.ts`, `backend/src/superTabs/read/views.ts`+- Modify: `backend/src/superTabs/sweeps.ts` (the hourly pass runs `sweepReminders`)+- Modify: `backend/src/routes/superTabs.ts`: `GET /api/super-tabs/:tabId/reminders`,+ `POST /api/super-tabs/:tabId/conversations/:conversationId/messages/:messageId/reminder` (body `{ at }`; `at` null+ clears it: the daemon's relay and the web's transport send only GET and POST)+- Test: `backend/integration/superTabReminders.test.ts`++**Interfaces:**+- Produces: `GET …/reminders` → `{ due: ReminderItem[], next: string | null }`; `ReminderItem = { id, conversationId,+ conversationTitle, projectName, messageId, messageSequence, threadId, author: { kind, id, name }, text, dueAt }`.+ `POST …/reminder { at }` → `{ id, dueAt }`; `at` in the future and at most 30 days ahead. `POST …/reminder+ { at: null }` → `{ cleared: boolean }`. `Derived.remindersDigest?: string`.++- [ ] Write failing tests: a reminder set for +20 min is not listed before then and `next` names its time; at its time+ it is listed once (two reads give the same one row); another person, an agent and a Team session never read,+ set or clear it; a message the person can no longer read drops out; setting again replaces the time; clear+ removes it; the cap refuses the 201st; the digest moves on set and clear; the sweep deletes rows due over 30 days+ ago; plan tests read IXSCAN on `(tabId, personId, dueAt)` and `dueAt`.+- [ ] Run `npx vitest run integration/superTabReminders.test.ts` and see them fail.+- [ ] Implement, run the file and see it pass. Commit each step.++### Task 3: Desktop — Mark unread++**Files:**+- Modify: `desktop/lib/super_tabs/message_more_menu.dart` (an action may hold a submenu)+- Modify: `desktop/lib/super_tabs/message_row.dart` (`onMarkUnread`, `onRemind`; the More menu shows with them even+ without a link)+- Modify: `desktop/lib/super_tabs/controller.dart` (`markUnread`, the hold until the chat is left)+- Modify: `desktop/lib/super_tabs/read_marks.dart` (`forget(key)` so a later read is sent again)+- Modify: `desktop/lib/super_tabs/parts.dart` (`unreadMarks` lower the held mark)+- Modify: `desktop/lib/super_tabs/view.dart` (wire the row; place the New messages line again)+- Test: `desktop/test/super_tab_mark_unread_test.dart`++**Interfaces:**+- Produces: `SuperTabController.markUnread(String conversationId, SuperTabMessage message)`.++- [ ] Write failing widget test: with a chat read to its end, More → Mark unread on the third-last message shows the+ New messages line above it, the chat counts unread in the sidebar, the POST names its sequence, and the line+ stays after the next poll while the chat is open; leaving and reopening reads it. A parts test: a changes read+ with `unreadMarks` lowers a higher held mark; a later `readMarks` raise wins again.+- [ ] Run `flutter test test/super_tab_mark_unread_test.dart` and see it fail.+- [ ] Implement, run it and see it pass. Commit each step.++### Task 4: Desktop — Remind me and Activity's Reminders++**Files:**+- Create: `desktop/lib/super_tabs/reminders.dart` (`SuperTabReminder`, `SuperTabReminders`: reads on the digest, wakes+ at `next`, `onArrived` once per reminder)+- Modify: `desktop/lib/super_tabs/activity.dart` (Reminders list and count), `desktop/lib/super_tabs/activity_view.dart`+ (Reminders section), `desktop/lib/super_tabs/notifications.dart` (`superTabReminderNotice`),+ `desktop/lib/super_tabs/model.dart` (`remindersDigest`), `desktop/lib/super_tabs/view.dart` (Remind me choices;+ opening a reminder opens its message and clears it), the place tags' notices are wired (`onArrived`)+- Test: `desktop/test/super_tab_reminders_test.dart`++**Interfaces:**+- Consumes: Task 2's routes. Produces: `SuperTabReminders.of(controller)`, `set(message, DateTime at)`, `open(reminder)`.++- [ ] Write failing tests: Remind me → In 20 minutes sends the time 20 minutes on (fake clock); Tomorrow at 09:00 sends+ the next day's 09:00 local; when the fake clock reaches `next` the list is read and the row shows once under+ Reminders with its time, the notice fires once, two reads racing still show one row; opening it clears it+ and opens its chat at the message.+- [ ] Run `flutter test test/super_tab_reminders_test.dart` and see it fail.+- [ ] Implement, run it and see it pass. Commit each step.++### Task 5: Evidence++- [ ] Light and dark before/after screenshots of the More menu and Activity (golden-style shot tests, as+ `super_tab_message_link_shots_test.dart`), attached to the PR.+- [ ] Desktop guard tests (`check-ui-style`, `laid_out_list_test`), Desktop's whole unit suite once, the backend unit+ suite (`npm test`) and typecheck once; red/green evidence in a PR comment.diff --git a/docs/plans/2026-11-04-project-row-bold-own-chat-plan.md b/docs/plans/2026-11-04-project-row-bold-own-chat-plan.mdnew file mode 100644index 000000000..2863c9a95--- /dev/null+++ b/docs/plans/2026-11-04-project-row-bold-own-chat-plan.md@@ -0,0 +1,45 @@+# Project row bold for its own chat Implementation Plan++> **For agentic workers:** Follow the project Engineer workflow: plan first in a draft PR; implement test first, with the failing test committed before its code; one independent review step on the pull request.++**Goal:** A sidebar project row is bold only for an unread person message, or a tag of the reader, in the project chat itself, folded or not. An unread task under it no longer makes it bold. Strengthens "Tell the PM what you want, and your crew ships it": the project row says when the PM's chat has something for the person, and nothing else.++**Architecture:** `_ProjectReading.unread` (desktop/lib/super_tabs/project_sidebar.dart) holds every open conversation of the project with something for a person. The row's bold reads only the project chat's entry there. A task's unread stays where the Tasks view (#2569) put it: its card, Activity, and the row's needs-you number.++**Tech Stack:** Flutter/Dart Desktop, widget tests with the memory store and a fake sign-in.++**Spec:** Swarm task #2638, conversation 68db455fee2929ca3f2803b3 (Huy, 11-04). Built on main cb6bb430, with the Tasks view merged (#2883 in batch #2908).++## Global Constraints++- Only the row's bold changes. The needs-you badge, Activity and the tasks' own cards are unchanged.+- The Unread filter (`_hasUnread`) is left as it is: it still keeps a project with an unread task or a tag of the reader. The brief owns the bold rule only, and the PR says so.+- Harness Design Language: the row's existing semibold and colour; no new style.+- PR body's first line: `Requested by [email protected] through Harness.`++## Design++N/A: nothing stored, synced or exposed changes. The row reads state the client already holds.++## Review Focus++- A folded project and an unfolded one read the same rule.+- A muted project chat is still never bold.+- A screen reader hears "Unread messages" on the project row only for its own chat.++---++### Task 1: The project row's bold++**Files:**+- Modify: `desktop/lib/super_tabs/project_sidebar.dart` (`_row`)+- Test: `desktop/test/super_tab_sidebar_reads_light_test.dart`, `desktop/test/super_tab_sidebar_rows_test.dart`, `desktop/test/super_tab_attention_test.dart`++- [ ] Step 1: failing tests:+ - With the project chat read and a task under it unread, the row is not bold.+ - A person's new message in the project chat makes it bold.+ - A tag of the reader in a task leaves the row regular; the tag is still its needs-you number.+ - A screen reader hears "Unread messages" on the row only for its own chat.+- [ ] Step 2: run them and see them fail on the old rule.+- [ ] Step 3: `_row` reads `reading.unread.contains(project.leadConversationId)`.+- [ ] Step 4: run the changed tests, plus Desktop's guard tests, and expect PASS. Before and after screenshots in light and dark, offscreen.diff --git a/docs/plans/2026-11-04-refused-command-loops-plan.md b/docs/plans/2026-11-04-refused-command-loops-plan.mdnew file mode 100644index 000000000..9e9deee48--- /dev/null+++ b/docs/plans/2026-11-04-refused-command-loops-plan.md@@ -0,0 +1,92 @@+# Refused-command loops Implementation Plan++> **For agentic workers:** Follow the project Engineer workflow: plan first in a draft PR; implement task by task with a committed failing test before its passing code; one independent review step on the pull request.++**Goal:** Clients stop resending Swarm commands the backend refuses for good, back off on passing failures, and every refusal the backend logs names its Swarm, agent and client. Strengthens "Ken's router fits every agent to a machine … without choking": a host that hammers the backend with refused commands is load for nothing.++**Architecture:** One small CLI helper decides, per command, whether it may go now: never again after a permanent refusal (`AGENT_UNAVAILABLE`, `NOT_FOUND`, `BUDDY_SESSION_THREAD`, `BUDDY_MACHINE`), with doubling backoff after any other failure. The host's configuration reports and the terminal host's alerts ask it before each post, and a skill notice refused for good counts as settled. The CLI declares itself (`x-harness-client: cli/<version>`) on every backend call, and the backend's refusal log line adds the Swarm, the agent the command names or acts as, the client kind and version, and the host machine, never the command's words.++**Tech Stack:** TypeScript, Vitest (CLI and backend), Fastify route headers.++**Spec:** Task #2675 in Super Tab conversation d050ba3eefb8214257eccd07 (Ken's prod scan, 2026-11-04; River's brief).++## Where each count comes from++| Count in 32 min (Ken) | Sender | Cadence today | Why it loops |+|---|---|---|---|+| `AGENT_UNAVAILABLE agent.configuration` 615 (~19/min) | CLI host, `cli/src/superTabs/host.ts` `recordConfigurations` | every 5 s per agent | the roster still lists an agent the Swarm will not take as an actor (removed, or its contributor rejoined so it "must be shared again", backend `model.ts agent()`); the observation never lands, so every pass posts it again. ~12/min per agent: about 1.6 agents. |+| `AGENT_UNAVAILABLE agent.alert` 116 (~3.6/min) | CLI terminal host, `cli/src/superTabs/terminal.ts` `episode` | every 15 s read | a failed alert leaves its episode unalerted, so each read tries again. ~4/min per alert: about one stuck alert. |+| `BUDDY_SESSION_THREAD message.send` 125 (~3.9/min) | CLI host skill notice, `cli/src/superTabs/host.ts` `tellSkill` via `refreshSkill` | every 60 s (`SKILL_RETRY_MS`) | a Buddy session is owed a skill notice (its told record is null, `lib/swarmInstructionsSkill.ts`), posted top level as the agent; the backend refuses a session's top-level post (`commands.ts` 1150), and the refresh catch retries a minute later, for as long as the session runs. About four sessions. Some may also be session models running `post` without `--reply-to`. |+| `NOT_FOUND message.send` 316 | no code loop found | | Desktop keeps a refused send as Not sent until Retry (`controller.dart` 4799), drops queued sends for gone groups (5086); the phone's outbox removes a refused post (`swarm_outbox.dart` 281); agent `post`, dial `say` and stop notices are one-shot. Most likely agents re-running a refused `post` at a removed or unreadable group, or people sending again. The new log line names their Swarm, agent and client. |+| `BUDDY_MACHINE buddy.create` 8 | no code loop | | buttons only: Start again / Couldn't start on a Buddy machine no longer listed (`buddies.dart` 589/676, phone `swarm_buddy_chat.dart` 154/188), or older clients. |++## Global Constraints++- Permanent refusals, never retried for the same command: `AGENT_UNAVAILABLE`, `NOT_FOUND`, `BUDDY_SESSION_THREAD`, `BUDDY_MACHINE`. Anything else backs off: 5 s, doubling, at most 5 minutes; a success resets it.+- A changed command is a new command: a new configuration reading (new operation id) or a new alert episode is sent once more.+- The refusal log never carries message text, emails, tokens, conversation or recipient ids: only `code`, `type`, `tabId`, `agentId`, `asAgent`, `client`, `version`, and `machineId` for a host route.+- A declared client is believed only in its shape: `^(cli|desktop|phone|web)/[0-9A-Za-z.+-]{1,32}$`; otherwise the kind comes from the user agent (`lib/routeLatency.ts clientKind`) and the version is null.+- No env switches; no production access; Swarm code stays out of `cli/src/core`.++## Design++- Growth: the CLI keeps one entry per refused or backed-off command, dropped when its agent leaves the roster or its key changes; the backend stores nothing new.+- Concurrency: N/A, single host loop per machine; no shared state.+- Read cost: the backend log line adds no query (all fields are in the request). Queries per request unchanged; the CLI's change removes about 19 + 3.6 refused commands a minute at today's numbers, each of which cost the backend a state read and a transaction.+- Scale: at 10x agents the refused commands stay at one per stuck command instead of 12/min each; first warning is the refusal log's count per `tabId`/`agentId`.+- Compatibility: an older backend ignores the new header; an older CLI keeps looping until updated, and the log now names its version.+- Migration + rollback: none.+- Audience: the log is server-side only.+- Identity: no person ids or emails in the log.+- Failure: a refused command is logged once by the CLI as before (its message), and the backend's line says whose.+- Platforms: CLI on macOS, Linux, Windows; backend.++## Review Focus++- A refusal of one agent's configuration must not stop another agent's (Task 3 keys by operation id).+- A transient failure must still deliver eventually (Tasks 3, 4 backoff tests expect at least two tries).+- An alert refused for good must not leave its episode stuck so that the next real episode is never sent (Task 4: new episode after the screen clears).+- The log must not leak words (Task 1 test on a message.send with text and an email).+- The header must not let a client inject log content (Task 1 shape test).++---++### Task 1: Backend refusal log fields++**Files:** Create `backend/src/superTabs/refusalLog.ts`; modify `backend/src/superTabs/store.ts` (`execute` catch), `backend/src/routes/superTabs.ts` (pass the declared client); test `backend/src/superTabs/refusalLog.test.ts`.++**Interfaces:** `declaredHttpClient(headers): { kind: string; version: string | null }`; `refusalLogFields(tabId, command, code, { asAgentId?, client?, machineId? }): Record<string, unknown>`; `SuperTabStore.execute(..., client?)`.++- [x] Failing test: Swarm/agent/CLI version for a host; command's agent over the acting one; a person's message without its words; header shape.+- [x] Run red; implement; run green; `npx tsc --noEmit -p .`; commit.++### Task 2: The CLI declares itself++**Files:** modify `cli/src/gateway/accountHttp.ts`; test `cli/src/gateway/accountHttp.spec.ts`.++- [x] Failing test: the request headers carry `x-harness-client: cli/<VERSION>`. Red; add the header; green; commit.++### Task 3: Configuration reports stop on a permanent refusal++**Files:** create `cli/src/superTabs/retries.ts` (`PERMANENT_REFUSALS`, `CommandRetries`); modify `cli/src/superTabs/host.ts` `recordConfigurations`; test `cli/src/superTabs/host.spec.ts`.++**Interfaces:** `class CommandRetries { constructor(now: () => number); due(key: string): boolean; failed(key: string, error: unknown): void; sent(key: string): void; keep(keys: Iterable<string>): void }`.++- [x] Failing tests: a permanent refusal is sent once over 12 passes and a new reading once more; a 503 backs off (2–6 sends in two minutes). Red; implement; green; commit.++### Task 4: Alerts stop on a permanent refusal++**Files:** modify `cli/src/superTabs/terminal.ts` `episode`; test `cli/src/superTabs/terminal.spec.ts`.++- [x] Failing tests: a refused alert is sent once over 20 reads; a 503 backs off (2–8 sends in ten minutes). Red; implement with `CommandRetries` keyed by the episode's operation id; green; commit.++### Task 5: Skill notices stop on a permanent refusal++**Files:** modify `cli/src/superTabs/host.ts` `tellSkill`; test `cli/src/superTabs/host.spec.ts` (built-in skill text).++- [x] Failing test: a notice refused with `BUDDY_SESSION_THREAD` for one agent is tried once over five minutes of passes, and the other agents are still told. Red; on a permanent refusal `tellSkill` logs it and returns as sent (its record is kept, so nothing resends it); green; commit.++### Task 6: Whole backend suite, CLI tests of what changed, PR evidence++- [x] Backend full unit suite: in PR CI (project instructions rev 56: no local whole suite); `cd cli && npx vitest run` on the changed specs; `npm run typecheck` in both.+- [x] PR body names each sender against its count, with before/after commands per minute from the tests; red/green comment.diff --git a/docs/plans/assets/mark-unread-remind-me/remind-activity-before-dark.png b/docs/plans/assets/mark-unread-remind-me/remind-activity-before-dark.pngnew file mode 100644index 000000000..f9327cc73Binary files /dev/null and b/docs/plans/assets/mark-unread-remind-me/remind-activity-before-dark.png differdiff --git a/docs/plans/assets/mark-unread-remind-me/remind-activity-before-light.png b/docs/plans/assets/mark-unread-remind-me/remind-activity-before-light.pngnew file mode 100644index 000000000..80466c823Binary files /dev/null and b/docs/plans/assets/mark-unread-remind-me/remind-activity-before-light.png differdiff --git a/docs/plans/assets/mark-unread-remind-me/remind-activity-dark.png b/docs/plans/assets/mark-unread-remind-me/remind-activity-dark.pngnew file mode 100644index 000000000..5d6d02895Binary files /dev/null and b/docs/plans/assets/mark-unread-remind-me/remind-activity-dark.png differdiff --git a/docs/plans/assets/mark-unread-remind-me/remind-activity-light.png b/docs/plans/assets/mark-unread-remind-me/remind-activity-light.pngnew file mode 100644index 000000000..81d606c09Binary files /dev/null and b/docs/plans/assets/mark-unread-remind-me/remind-activity-light.png differdiff --git a/docs/plans/assets/mark-unread-remind-me/remind-menu-before-dark.png b/docs/plans/assets/mark-unread-remind-me/remind-menu-before-dark.pngnew file mode 100644index 000000000..0a86630aeBinary files /dev/null and b/docs/plans/assets/mark-unread-remind-me/remind-menu-before-dark.png differdiff --git a/docs/plans/assets/mark-unread-remind-me/remind-menu-before-light.png b/docs/plans/assets/mark-unread-remind-me/remind-menu-before-light.pngnew file mode 100644index 000000000..52d5d39ddBinary files /dev/null and b/docs/plans/assets/mark-unread-remind-me/remind-menu-before-light.png differdiff --git a/docs/plans/assets/mark-unread-remind-me/remind-menu-dark.png b/docs/plans/assets/mark-unread-remind-me/remind-menu-dark.pngnew file mode 100644index 000000000..68bb35010Binary files /dev/null and b/docs/plans/assets/mark-unread-remind-me/remind-menu-dark.png differdiff --git a/docs/plans/assets/mark-unread-remind-me/remind-menu-light.png b/docs/plans/assets/mark-unread-remind-me/remind-menu-light.pngnew file mode 100644index 000000000..bc2f0d3bfBinary files /dev/null and b/docs/plans/assets/mark-unread-remind-me/remind-menu-light.png differdiff --git a/docs/plans/assets/mark-unread-remind-me/remind-unread-dark.png b/docs/plans/assets/mark-unread-remind-me/remind-unread-dark.pngnew file mode 100644index 000000000..0c5f16d50Binary files /dev/null and b/docs/plans/assets/mark-unread-remind-me/remind-unread-dark.png differdiff --git a/docs/plans/assets/mark-unread-remind-me/remind-unread-light.png b/docs/plans/assets/mark-unread-remind-me/remind-unread-light.pngnew file mode 100644index 000000000..4dfe97cfcBinary files /dev/null and b/docs/plans/assets/mark-unread-remind-me/remind-unread-light.png differdiff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dartindex 7fa6d2857..01615dedd 100644--- a/mobile/lib/swarm/model.dart+++ b/mobile/lib/swarm/model.dart@@ -684,6 +684,7 @@ class SuperTabSnapshot {decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,decisionsDigest = row['decisionsDigest'] as String?,activityDigest = row['activityDigest'] as String?,+ remindersDigest = row['remindersDigest'] as String?,chatSettings = Map.unmodifiable({if (row['chatSettings'] case final Map settings)for (final MapEntry(:key, :value) in settings.entries)@@ -807,6 +808,11 @@ class SuperTabSnapshot {/// before it. Read as the desktop's model reads it; the phone shows no Activity yet.final String? activityDigest;+ /// Which reminders the reader has set and when each is due, as a digest that moves when one is set, replaced or+ /// cleared; null from a backend before reminders (superTabs/reminders.ts). Read as the desktop's is; the phone+ /// shows no reminders yet.+ final String? remindersDigest;+/// The reader's own notification setting by conversation, `all`, `mentions` or `muted` (backend chatSettings.ts)./// Read as the desktop's model reads it; the phone does not apply it yet.final Map<String, String> chatSettings;diff --git a/mobile/lib/swarm/parts.dart b/mobile/lib/swarm/parts.dartindex e29c12d95..06a186b3f 100644--- a/mobile/lib/swarm/parts.dart+++ b/mobile/lib/swarm/parts.dart@@ -65,6 +65,7 @@ class SuperTabParts {// Read marks are held apart from the other derived values (_readMarks).final derived = Map.of(superTabMap(answer['derived'] ?? const {}));final marks = derived.remove('readMarks');+ final unreadMarks = derived.remove('unreadMarks');final threadMarks = derived.remove('threadMarks');final chatSettings = derived.remove('chatSettings');final parts = SuperTabParts._(@@ -86,6 +87,8 @@ class SuperTabParts {}}parts._takeReadMarks(marks);+ // Every one is news to a device whose own mark is higher.+ parts._takeUnreadMarks(unreadMarks, all: true);parts._takeThreadMarks(threadMarks);parts._takeChatSettings(chatSettings);return parts;@@ -156,6 +159,44 @@ class SuperTabParts {return moved;}+ /// The marks a Mark unread moved back (backend readMarks.ts `unreadMarks`) since [takeLowered] last ran: the one+ /// way a mark goes down, on every device of the reader.+ final _lowered = <String, int>{};++ /// Takes the marks in [marks] that a Mark unread moved below the one held (or, [all], each one sent); whether any+ /// moved.+ bool _takeUnreadMarks(Object? marks, {required bool all}) {+ var moved = false;+ if (marks is! Map) return moved;+ for (final MapEntry(:key, :value) in marks.entries) {+ if (key is! String || value is! num) continue;+ final sequence = value.toInt();+ if (!all && (_readMarks[key] ?? 0) <= sequence) continue;+ _readMarks[key] = sequence;+ _lowered[key] = sequence;+ moved = true;+ }+ return moved;+ }++ /// This device marked [conversationId] unread back to [sequence]: the mark held goes there.+ void lowerReadMark(String conversationId, int sequence) {+ if ((_readMarks[conversationId] ?? sequence + 1) > sequence) {+ _readMarks[conversationId] = sequence;+ }+ }++ /// A Mark unread this device asked for was not kept: the mark held goes back to [sequence].+ void raiseReadMark(String conversationId, int sequence) =>+ _takeReadMarks({conversationId: sequence});++ /// The marks lowered by a Mark unread elsewhere since the last call, by conversation.+ Map<String, int> takeLowered() {+ final taken = Map.of(_lowered);+ _lowered.clear();+ return taken;+ }+/// The reader's own thread marks (backend readMarks.ts): by conversation, the newest message sequence read in each/// thread, by its root. Kept as read marks are: the higher of each, and gone with their conversation.final _threadMarks = <String, Map<String, int>>{};@@ -284,7 +325,9 @@ class SuperTabParts {}}final derived = Map.of(superTabMap(changes['derived'] ?? const {}));- final readMarksMoved = _takeReadMarks(derived.remove('readMarks'));+ final readMarksMoved =+ _takeReadMarks(derived.remove('readMarks')) |+ _takeUnreadMarks(derived.remove('unreadMarks'), all: false);// Both run: one moving never skips the other.final marksMoved =_takeThreadMarks(derived.remove('threadMarks')) |@@ -412,6 +455,9 @@ class SuperTabParts {if (_derived['decisionsDigest'] case final String digest) {state['decisionsDigest'] = digest;}+ if (_derived['remindersDigest'] case final String digest) {+ state['remindersDigest'] = digest;+ }if (_derived['activityDigest'] case final String digest) {state['activityDigest'] = digest;}