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-06 k1150: #3321 #3330 #3333 #3315 (#3339)
0xken15342edb2d7933
diff --git a/backend/integration/overdueDecisions.test.ts b/backend/integration/overdueDecisions.test.tsindex 11fcb4e73..2df5ad767 100644--- a/backend/integration/overdueDecisions.test.ts+++ b/backend/integration/overdueDecisions.test.ts@@ -6,7 +6,7 @@ import type { AuthUser } from '../src/lib/ssoAuth.js'import { SuperTabStore } from '../src/superTabs/store.js'import type { Command } from '../src/superTabs/commands.js'import { overdueNotice } from '../src/superTabs/decisions.js'-import { OVERDUE_DECISION_MS, overdueDecisions } from '../src/superTabs/overdueDecisions.js'+import { OVERDUE_DECISION_MS, overdueDecisions, dueDefaultDecisions } from '../src/superTabs/overdueDecisions.js'import { planDatabase, plan, profiled, reads } from './plans.test-support.js'// A decision its person leaves for 24 hours goes to the PM (spec: Diego, 2026-11-04). A fresh loopback replica set; never DATABASE_URL.@@ -31,17 +31,17 @@ afterAll(async () => {})/** A Swarm whose PM asks peer decisions; each `ask` is stored with the given age. */-async function swarm() {+async function swarm(role: 'collaborator' | 'viewer' = 'collaborator') {const store = new SuperTabStore(db, () => NOW)const tab = (await store.create(owner, randomUUID(), 'Overdue', 'public')).idconst execute = (command: Command, user = owner, asAgentId?: string) => store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId)- const invitation = await execute({ type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })+ const invitation = await execute({ type: 'invite.create', email: peer.email, role, conversationId: 'lead' })await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, peer)const lead = String((await execute({ type: 'agent.add', conversationId: 'lead', machineId: 'owner-mac', harnessId: randomUUID(), name: 'PM', configuration: config, lead: true })).result.agentId)/** Asks peer one question, then dates it `age` ago. */- const ask = async (age: number) => {+ const ask = async (age: number, defaultAt?: string) => {const before = new Set((await db.superTabDecision.findMany({ where: { tabId: tab }, select: { id: true } })).map(d => d.id))- await execute({ type: 'decision.ask', conversationId: 'lead', personId: peer.sub, questions: [{ question: `Which week ${randomUUID()}?`, options: ['This week', 'Next week'], recommended: 1, unblocks: 'The plan' }] }, owner, lead)+ await new SuperTabStore(db, () => NOW - age).execute(owner, tab, { operationId: randomUUID(), command: { type: 'decision.ask', conversationId: 'lead', personId: peer.sub, questions: [{ question: `Which week ${randomUUID()}?`, options: ['This week', 'Next week'], recommended: 1, unblocks: 'The plan', ...defaultAt ? { defaultAt } : {} }] } }, lead)const row = (await db.superTabDecision.findMany({ where: { tabId: tab } })).find(d => !before.has(d.id))!await db.superTabDecision.update({ where: { id: row.id }, data: { createdAt: new Date(NOW - age) } })return row.id@@ -56,9 +56,133 @@ async function swarm() {const row = (id: string) => db.superTabDecision.findUniqueOrThrow({ where: { id } })// The notice is the agents' line (AGENT_ONLY): the PM reads it, a person does not.const notices = async () => (await store.messages(owner, tab, 'lead', {}, lead)).messages.filter(m => m.text.startsWith(overdueNotice('Product Manager'))).length- return { store, tab, execute, ask, askBroken, row, notices }+ return { store, tab, lead, execute, ask, askBroken, row, notices }}+describe('explicit deadline persistence', () => {+ it('stores, reads and deduplicates the normalized deadline while a changed deadline is a new decision', async () => {+ const f = await swarm()+ const question = { question: 'Ship today?', options: ['Yes', 'Tomorrow'], recommended: 0, unblocks: 'Release', defaultAt: '2026-11-04T13:00:00Z' }+ const ask = async (defaultAt: string) => {+ return f.execute({ type: 'decision.ask', conversationId: 'lead', personId: peer.sub, questions: [{ ...question, defaultAt }] } as Command, owner, f.lead)+ }+ const first = await ask(question.defaultAt)+ const id = String((first.result.decisionIds as string[])[0])+ expect(await f.row(id)).toMatchObject({ defaultAt: new Date('2026-11-04T13:00:00Z') })+ expect((await ask('2026-11-04T14:00:00+01:00')).result.decisionIds).toEqual([id])+ const changed = await ask('2026-11-04T14:00:00Z')+ expect(changed.result.decisionIds).not.toEqual([id])+ const list = await f.store.decisions(peer, f.tab, 'open')+ expect(list.decisions.find(d => d.id === id)).toMatchObject({ defaultAt: new Date('2026-11-04T13:00:00Z'), defaulted: false })+ })+})++describe('timed recommendation defaults', () => {+ const at = (delta: number) => new Date(NOW + delta).toISOString()++ it('waits before the deadline, then applies its recommendation at the exact time and tells the asker once', async () => {+ const f = await swarm()+ const id = await f.ask(HOUR, at(0))+ expect(await new SuperTabStore(db, () => NOW - 1).leaveOverdueDecisions(NOW - 1)).toEqual({ answered: 0, skipped: 0, failed: 0 })+ expect(await f.store.leaveOverdueDecisions(NOW)).toEqual({ answered: 1, skipped: 0, failed: 0 })+ expect(await f.row(id)).toMatchObject({ choice: 1, delegated: true, defaulted: true, overdue: null, answeredAt: new Date(NOW) })+ const notices = (await f.store.messages(owner, f.tab, 'lead', {}, f.lead)).messages.filter(m => (m.source as { decisionId?: string })?.decisionId === id)+ expect(notices).toHaveLength(1)+ expect(notices[0]).toMatchObject({ recipientIds: [f.lead], source: { kind: 'agent-only' } })+ expect(notices[0]!.text).toMatch(/default.*time|deadline/i)+ expect(notices[0]!.text).not.toContain('Next week')+ const settled = await f.store.decisions(peer, f.tab, 'settled')+ expect(settled.decisions.find(d => d.id === id)).toMatchObject({ defaulted: true, answer: 'Default applied: Next week' })+ expect((await f.store.decisions(peer, f.tab, 'answered')).decisions).toHaveLength(0)+ expect(await f.store.leaveOverdueDecisions(NOW)).toEqual({ answered: 0, skipped: 0, failed: 0 })+ })++ it('does not take a future deadline at the legacy 24-hour age and does take a long-lived question due today', async () => {+ const f = await swarm()+ const future = await f.ask(25 * HOUR, at(HOUR))+ const ancient = await f.ask(40 * DAY, at(0))+ expect(await f.store.leaveOverdueDecisions(NOW)).toEqual({ answered: 1, skipped: 0, failed: 0 })+ expect((await f.row(future)).answeredAt).toBeNull()+ expect((await f.row(ancient)).defaulted).toBe(true)+ })++ it('keeps a person’s prior answer and makes concurrent sweep/answer attempts single-winner', async () => {+ const f = await swarm()+ const answered = await f.ask(HOUR, at(0))+ await f.execute({ type: 'decision.answer', decisionId: answered, choice: 0 }, peer)+ const racing = await f.ask(HOUR, at(0))+ await Promise.allSettled([f.store.leaveOverdueDecisions(NOW), f.store.leaveOverdueDecisions(NOW), f.execute({ type: 'decision.answer', decisionId: racing, choice: 0 }, peer)])+ expect(await f.row(answered)).toMatchObject({ choice: 0, defaulted: null })+ const row = await f.row(racing)+ expect(row.answeredAt).toEqual(new Date(NOW))+ expect([0, 1]).toContain(row.choice)+ const notices = (await f.store.messages(owner, f.tab, 'lead', {}, f.lead)).messages.filter(m => (m.source as { decisionId?: string })?.decisionId === racing)+ expect(notices).toHaveLength(1)+ })++ it('caps explicit defaults per pass and excludes withdrawn or reflection decisions', async () => {+ const f = await swarm()+ const withdrawn = await f.ask(HOUR, at(0)), reflection = await f.ask(HOUR, at(0))+ await db.superTabDecision.update({ where: { id: withdrawn }, data: { withdrawn: true } })+ await db.superTabDecision.update({ where: { id: reflection }, data: { kind: 'routing-reflection' } })+ const ids = [await f.ask(HOUR, at(-2)), await f.ask(HOUR, at(-1)), await f.ask(HOUR, at(0))]+ expect(await f.store.leaveOverdueDecisions(NOW, 2)).toEqual({ answered: 2, skipped: 0, failed: 0 })+ expect((await f.row(ids[2]!)).answeredAt).toBeNull()+ expect((await f.store.leaveOverdueDecisions(NOW, 2)).answered).toBe(1)+ for (const id of [withdrawn, reflection]) expect((await f.row(id)).answeredAt).toBeNull()+ })++ it('withdraws permanently unavailable due rows so they cannot starve fresh or legacy questions', async () => {+ const f = await swarm()+ const gone = [await f.ask(HOUR, at(-3)), await f.ask(HOUR, at(-2))]+ for (const id of gone) await db.superTabDecision.update({ where: { id }, data: { personId: '400000000000000000000099' } })+ const due = await f.ask(HOUR, at(0)), legacy = await f.ask(25 * HOUR)+ // A small cap models a full queue of permanently unanswerable rows. Legacy work gets its share immediately.+ await f.store.leaveOverdueDecisions(NOW, 2)+ expect((await f.row(legacy)).overdue).toBe(true)+ for (let i = 0; i < 2; i++) await f.store.leaveOverdueDecisions(NOW, 2)+ for (const id of gone) expect(await f.row(id)).toMatchObject({ withdrawn: true, answeredAt: new Date(NOW), choice: null })+ expect((await f.row(due)).defaulted).toBe(true)+ })++ it('withdraws a removed member’s due default even while their user still exists', async () => {+ const f = await swarm()+ const id = await f.ask(HOUR, at(0))+ await f.execute({ type: 'member.remove', userId: peer.sub })+ expect(await db.user.findUnique({ where: { id: peer.sub } })).not.toBeNull()+ expect(await f.store.leaveOverdueDecisions(NOW)).toEqual({ answered: 0, skipped: 1, failed: 0 })+ expect(await f.row(id)).toMatchObject({ withdrawn: true, answeredAt: new Date(NOW), choice: null, defaulted: null })+ expect(await f.store.leaveOverdueDecisions(NOW)).toEqual({ answered: 0, skipped: 0, failed: 0 })+ })++ it('keeps decision defaults available to viewers, who may answer their own questions', async () => {+ const f = await swarm('viewer')+ const id = await f.ask(HOUR, at(0))+ expect(await f.store.leaveOverdueDecisions(NOW)).toEqual({ answered: 1, skipped: 0, failed: 0 })+ expect(await f.row(id)).toMatchObject({ choice: 1, defaulted: true, withdrawn: null })+ })++ it('uses the deadline index without scanning future, legacy or answered noise', async () => {+ const f = await swarm()+ for (let i = 0; i < 10; i++) await f.ask(HOUR, at(HOUR + i))+ for (let i = 0; i < 5; i++) await f.ask(25 * HOUR)+ const done = await f.ask(HOUR, at(-1))+ await f.execute({ type: 'decision.answer', decisionId: done, choice: 0 }, peer)+ await f.ask(40 * DAY, at(0))+ const found: unknown[] = []+ const start = performance.now()+ const entries = await profiled(db, async () => { found.push(...await dueDefaultDecisions(db, NOW)) })+ const elapsedMs = performance.now() - start+ const read = reads(entries, 'SuperTabDecision', ['defaultAt'])+ const explain = JSON.stringify(plan(read))+ expect(found).toHaveLength(1)+ expect(read, explain).toHaveLength(1)+ expect(read[0]!.planSummary, explain).toMatch(/IXSCAN \{ answeredAt: 1, defaultAt: 1 \}/)+ expect(read[0]!.docsExamined, explain).toBeLessThanOrEqual(found.length + 1)+ console.info('deadline query evidence', { elapsedMs, returned: found.length, examined: read[0]!.docsExamined, plan: read[0]!.planSummary })+ })+})+describe('decisions left to the PM after 24 hours', () => {it('a decision asked 25 hours ago is left to the PM', async () => {const f = await swarm()diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex f50b29bc8..7d5adda42 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1350,6 +1350,7 @@ model SuperTabSweepCursor {/// A question to one person, with options and a recommendation (backend/src/superTabs/decisions.ts). Kept out of the tab/// state, as mentions are: an asking agent and the asked person read it, and the person answers it once.+/// writeDecisions removes answered rows older than LEDGER_WEEKS on the next ask; Swarm purge removes all its rows.model SuperTabDecision {id String @id @map("_id")tabId String@@ -1364,6 +1365,10 @@ model SuperTabDecision {question Stringoptions String[]recommended Int+ /// Optional recommendation deadline; absent on legacy questions, which keep their 24-hour fallback.+ defaultAt DateTime?+ /// The server applied the recommendation at defaultAt; never a person’s choice or a legacy overdue answer.+ defaulted Boolean?unblocks StringcreatedAt DateTimeansweredAt DateTime?@@ -1388,6 +1393,8 @@ model SuperTabDecision {@@index([tabId, conversationId])/// The hourly overdue sweep reads only the waiting decisions of the last 8 days through it (superTabs/overdueDecisions.ts).@@index([answeredAt, createdAt], map: "decision_waiting_created")+ /// Explicit deadlines use their own range so long-lived questions are not missed by the legacy creation window.+ @@index([answeredAt, defaultAt], map: "decision_waiting_default")}/// One uploaded file, which one message of the actor that uploaded it can send once.diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 905850a31..5de2a8731 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -32,7 +32,7 @@ import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'import { agentsNamedIn, checkMentions, MAX_MENTIONS, namedIn, saysName, textTags, withTags, type MentionTarget } from './mentions.js'import { CREW_NEED_KIND, crewNeedPlace, crewNeedText, routedLine, routesToPm, type CrewNeed } from './crewNeeds.js'import { checkReason, heldReason, missingReason } from './heldReason.js'-import { answerDecision, askDecisions, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'+import { answerDecision, askDecisions, checkDecisionDeadline, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'import { leadOf, TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, toLead, type TerminalRequest, workedAgain } from './terminal.js'import { BACK_WITH_YOU, pickUp, reopenHanded } from './handed.js'import { changesRequested, engineerAnswered, leadNoticeRows, loseTasks, recordTaskState, renewLease, renewOwnTask, restartQuietTime, revisionReady, toldEngineer, waitingForReview } from './liveness.js'@@ -546,6 +546,8 @@ export interface CommandContext {/** For `decision.answer`: the hourly sweep leaves a decision unanswered for 24 hours to the PM (overdueDecisions.ts). Set by the* store alone; a client cannot send it. */overdue?: boolean+ /** Server-only timed recommendation application; a client cannot send it. */+ defaulted?: boolean/** For a restore: the people no longer in the Swarm's Workspace, read by the store. They do not come back with it. */workspaceLost?: string[]/** The machines of this Swarm's pending cleanups whose machine account is deleted, read by the store: no host will ever@@ -2640,13 +2642,13 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,case 'decision.ask': {const group = open(state, command.conversationId)const drafts = askDecisions(state, group, command.personId, command.questions,- { operationId, askerAgentId: checkAsker(state, actor, group), assignmentId: null })+ { now: context.now, operationId, askerAgentId: checkAsker(state, actor, group), assignmentId: null })// People talk only to the PM (anh Dee, 11-05; crewNeeds.ts): another agent's questions are the PM's crew needs, one// each, checked as a decision would be and opened for nobody.const pmInstead = routesToPm(state, actor, group)if (pmInstead) {command.questions.forEach((q, i) => crewNeed(group, pmInstead, { personIds: [command.personId], conversationId: group.id,- question: q.question, options: q.options, recommended: q.recommended }, q.question, stableId(operationId, 'crew-need', String(i))))+ question: q.question, options: q.options, recommended: q.recommended, ...q.defaultAt ? { defaultAt: q.defaultAt } : {} }, q.question, stableId(operationId, 'crew-need', String(i))))result.decisionIds = []break}@@ -2656,7 +2658,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,}case 'decision.answer': {const { answer, noticeIn, notice, recipients, source, line } = answerDecision(state, actor, context.decision,- { choice: command.choice, note: command.note ?? null, delegate: command.delegate === true, overdue: context.overdue === true })+ { choice: command.choice, note: command.note ?? null, delegate: command.delegate === true, overdue: context.overdue === true, defaulted: context.defaulted === true, now: context.now })effects.decisionAnswer = answerrecordDecision(conversation(state, context.decision!.conversationId), context.decision!, context.now, answer.delegated === true)if (recipients.length) message(noticeIn, notice, recipients, null, source)@@ -4143,13 +4145,14 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (command.status !== 'needs_human' || !command.result || actor.kind !== 'agent') {fail('INVALID_DECISION', 'An agent asks a person for a decision only when its work needs a human, with the question as its result.', 400)}+ checkDecisionDeadline(command.ask, context.now)// For the PM to ask: the person must be in the Swarm, as a decision's would.if (pmInstead) person(state, command.ask.personId)}if (command.ask && !pmInstead && command.result && actor.kind === 'agent') {const { personId, ...choices } = command.askconst drafts = askDecisions(state, group, personId, [{ question: command.result, ...choices }],- { operationId, askerAgentId: actor.agentId, assignmentId: assignment.id })+ { now: context.now, operationId, askerAgentId: actor.agentId, assignmentId: assignment.id })// At the cap the status still counts, reaches the Lead and renews the lease; only the question waits (review of #1859).if (context.openDecisions == null) {effects.decisions = drafts@@ -4206,7 +4209,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,: effects.result.notAsked ? `\n\n${effects.result.notAsked}` : `\n\nAsked ${askedName}.`// A needs_human for the PM is its crew need: on this row when the row reaches the PM, else on a row of its own there.const need = pmInstead ? { personIds: command.ask ? [command.ask.personId] : [], conversationId: group.id,- ...command.result ? { question: command.result } : {}, ...command.ask ? { options: command.ask.options, recommended: command.ask.recommended } : {} } : null+ ...command.result ? { question: command.result } : {}, ...command.ask ? { options: command.ask.options, recommended: command.ask.recommended, ...command.ask.defaultAt ? { defaultAt: command.ask.defaultAt } : {} } : {} } : nullconst onRow = need && pmInstead && actor.kind === 'agent' && recipients.includes(pmInstead)? { crewNeed: { agentId: actor.agentId, ...need, messageId: operationId } } : {}// The status set, on the row: a Done waits for the coordinator's next digest, what needs someone does not (store.ts writeMessages).diff --git a/backend/src/superTabs/crewNeeds.ts b/backend/src/superTabs/crewNeeds.tsindex 1b627dbf2..aed365181 100644--- a/backend/src/superTabs/crewNeeds.ts+++ b/backend/src/superTabs/crewNeeds.ts@@ -26,6 +26,7 @@ export interface CrewNeed {question?: stringoptions?: string[]recommended?: number+ defaultAt?: string}/** The crew need a stored message's source carries, in either shape, or null. */diff --git a/backend/src/superTabs/decisionSweep.test.ts b/backend/src/superTabs/decisionSweep.test.tsnew file mode 100644index 000000000..e60d0b4bd--- /dev/null+++ b/backend/src/superTabs/decisionSweep.test.ts@@ -0,0 +1,50 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { startDecisionSweep } from './decisionSweep.js'+import { logger } from '../utils/logger.js'++afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })++describe('decision deadline schedule', () => {+ it('runs immediately and each minute, and stops future passes', async () => {+ vi.useFakeTimers()+ const times: number[] = []+ const stop = startDecisionSweep(async now => { times.push(now) })+ await vi.advanceTimersByTimeAsync(0)+ expect(times).toHaveLength(1)+ await vi.advanceTimersByTimeAsync(59_999)+ expect(times).toHaveLength(1)+ await vi.advanceTimersByTimeAsync(1)+ expect(times).toHaveLength(2)+ expect(times[1]! - times[0]!).toBe(60_000)+ stop()+ await vi.advanceTimersByTimeAsync(120_000)+ expect(times).toHaveLength(2)+ })++ it('does not overlap a slow pass, and resumes once it finishes', async () => {+ vi.useFakeTimers()+ let finish!: () => void+ let count = 0+ const waiting = new Promise<void>(resolve => { finish = resolve })+ const stop = startDecisionSweep(async () => { count++; if (count === 1) await waiting })+ await vi.advanceTimersByTimeAsync(180_000)+ expect(count).toBe(1)+ finish()+ await vi.advanceTimersByTimeAsync(60_000)+ expect(count).toBe(2)+ stop()+ })++ it('reports a failed pass without content and tries again on the next minute', async () => {+ vi.useFakeTimers()+ const errors = vi.spyOn(logger, 'error').mockImplementation(() => {})+ let count = 0+ const stop = startDecisionSweep(async () => { if (++count === 1) throw new Error('private option text') })+ await vi.advanceTimersByTimeAsync(0)+ expect(errors).toHaveBeenCalledOnce()+ expect(JSON.stringify(errors.mock.calls)).not.toContain('private option text')+ await vi.advanceTimersByTimeAsync(60_000)+ expect(count).toBe(2)+ stop()+ })+})diff --git a/backend/src/superTabs/decisionSweep.ts b/backend/src/superTabs/decisionSweep.tsnew file mode 100644index 000000000..f0da6e6ee--- /dev/null+++ b/backend/src/superTabs/decisionSweep.ts@@ -0,0 +1,22 @@+import { logger } from '../utils/logger.js'++/** Decision deadlines must not wait behind hourly maintenance. The singleton worker owns this timer and its cleanup. */+export function startDecisionSweep(apply: (now: number) => Promise<unknown>, everyMs = 60_000): () => void {+ let running = false, stopped = false+ const run = async () => {+ if (running || stopped) return+ running = true+ try {+ await apply(Date.now())+ } catch {+ // Errors may contain option text or database details. Say what remains waiting without logging their content.+ logger.error('[swarm-decisions] default pass failed; unanswered decisions remain waiting and retry next minute')+ } finally {+ running = false+ }+ }+ void run()+ const timer = setInterval(() => { void run() }, everyMs)+ timer.unref()+ return () => { stopped = true; clearInterval(timer) }+}diff --git a/backend/src/superTabs/decisions.test.ts b/backend/src/superTabs/decisions.test.tsindex 37611615e..381970423 100644--- a/backend/src/superTabs/decisions.test.ts+++ b/backend/src/superTabs/decisions.test.ts@@ -60,7 +60,7 @@ describe('asking a person for decisions', () => {// Someone who cannot read the conversation is named by username, never email (task #2954).const group = s.state.conversations.find(c => c.id === s.group)!const narrowed = { ...group, audience: { people: [{ id: 'owner', generation: s.state.people[0]!.generation }] } }- expect(() => askDecisions(s.state, narrowed, 'peer', [question('Ship how?')], { operationId: 'op', askerAgentId: s.lead, assignmentId: null }))+ expect(() => askDecisions(s.state, narrowed, 'peer', [question('Ship how?')], { now: 1000, operationId: 'op', askerAgentId: s.lead, assignmentId: null })).toThrow(/^peer cannot read this conversation\.$/)expect(commandSchema.safeParse({ type: 'decision.ask', conversationId: s.group, personId: 'peer',questions: [{ ...question('One option only'), options: ['Yes'] }] }).success).toBe(false)@@ -102,6 +102,59 @@ describe('asking a person for decisions', () => {})})+describe('explicit decision deadlines', () => {+ const defaultAt = '2026-11-06T04:00:00.000Z'+ it('carries a decision deadline beside its recommended option', () => {+ const s = swarm()+ const asked = s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer',+ questions: [{ ...question('Ship when?'), defaultAt }] } as Command, asAgent(s.lead))+ expect(asked.decisions?.[0]).toMatchObject({ defaultAt, recommended: 0 })+ })++ it('carries a needs-human deadline when there is no PM to route through', () => {+ const s = swarm()+ s.state.conversations.find(c => c.id === 'lead')!.leadId = null+ const asked = s.run({ type: 'work.status', conversationId: s.group, assignmentId: s.assignmentId, status: 'needs_human', hold: HOLD,+ result: 'Ship when?', ask: { personId: 'peer', options: ['Today', 'Tomorrow'], recommended: 1, unblocks: 'Release', defaultAt } } as Command, asAgent(s.worker))+ expect(asked.decisions?.[0]).toMatchObject({ defaultAt, recommended: 1 })+ })++ it('keeps the deadline when a worker question becomes the PM’s crew need', () => {+ const s = swarm()+ const asked = s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer',+ questions: [{ ...question('Ship when?'), defaultAt }] } as Command, asAgent(s.worker))+ expect(asked.decisions ?? []).toEqual([])+ expect(asked.messages[0]?.source?.crewNeed).toMatchObject({ defaultAt, recommended: 0 })+ const needs = s.run({ type: 'work.status', conversationId: s.group, assignmentId: s.assignmentId, status: 'needs_human', hold: HOLD,+ result: 'Ship when?', ask: { personId: 'peer', options: ['Today', 'Tomorrow'], recommended: 1, unblocks: 'Release', defaultAt } } as Command, asAgent(s.worker))+ expect(needs.messages.find(m => m.source?.crewNeed)?.source?.crewNeed).toMatchObject({ defaultAt, recommended: 1 })+ })++ it('requires 15 minutes for a person to see the ask, including needs-human and PM-routed asks', () => {+ const at = (ms: number) => new Date(ms).toISOString()+ for (const delta of [-1, 0, 15 * 60_000 - 1]) {+ const s = swarm()+ expect(() => s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer', questions: [{ ...question('Ship when?'), defaultAt: at(1000 + delta) }] }, asAgent(s.lead)))+ .toThrow(expect.objectContaining({ code: 'INVALID_DECISION' }))+ expect(() => s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer', questions: [{ ...question('Ship when?'), defaultAt: at(1000 + delta) }] }, asAgent(s.worker)))+ .toThrow(expect.objectContaining({ code: 'INVALID_DECISION' }))+ expect(() => s.run({ type: 'work.status', conversationId: s.group, assignmentId: s.assignmentId, status: 'needs_human', hold: HOLD, result: 'Ship when?',+ ask: { personId: 'peer', options: ['Today', 'Tomorrow'], recommended: 0, unblocks: 'Release', defaultAt: at(1000 + delta) } }, asAgent(s.worker)))+ .toThrow(expect.objectContaining({ code: 'INVALID_DECISION' }))+ }+ const s = swarm()+ expect(() => s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer', questions: [{ ...question('Ship when?'), defaultAt: at(1000 + 15 * 60_000) }] }, asAgent(s.lead))).not.toThrow()+ })++ it('refuses an invalid deadline and keeps deadline-free legacy callers valid', () => {+ const s = swarm()+ const send = (at?: string) => ({ type: 'decision.ask', conversationId: s.group, personId: 'peer',+ questions: [{ ...question('Ship when?'), ...at ? { defaultAt: at } : {} }] })+ expect(commandSchema.safeParse(send('tomorrow')).success).toBe(false)+ expect(commandSchema.safeParse(send()).success).toBe(true)+ })+})+describe('answering a decision', () => {const open = (s: ReturnType<typeof swarm>, overrides: Partial<DecisionTarget> = {}): DecisionTarget => ({ id: 'decision-1', personId: 'peer',conversationId: s.group, projectId: 'lead', askerAgentId: s.worker, question: 'Ship how?', options: ['Behind a flag', 'To everyone'], recommended: 0,@@ -225,6 +278,20 @@ describe('leaving a decision to the PM', () => {expect(answered.messages[0]!.text).toBe(overdueNotice('Product Manager'))})+ it('takes a timed default only at its trusted deadline, and never accepts the marker from a client', () => {+ const s = swarm()+ const decision = open(s, { defaultAt: 1000 })+ const command = { type: 'decision.answer', decisionId: 'decision-1', delegate: true } as const+ expect(() => s.run(command, peer, { decision, defaulted: true, now: 999 } as Partial<CommandContext>)).toThrow(/default.*time|deadline/i)+ expect(() => s.run(command, peer, { decision: open(s), defaulted: true, now: 1000 } as Partial<CommandContext>)).toThrow(/default.*time|deadline/i)+ expect(() => s.run(command, peer, { decision: open(s, { defaultAt: 1000, kind: 'routing-reflection' }), defaulted: true, now: 1000 } as Partial<CommandContext>)).toThrow(/default|reflection/i)+ expect(commandSchema.safeParse({ ...command, defaulted: true }).success).toBe(false)+ const taken = s.run(command, peer, { decision, defaulted: true, now: 1000 } as Partial<CommandContext>)+ expect(taken.decisionAnswer).toMatchObject({ delegated: true, defaulted: true, choice: 1 })+ expect(taken.messages[0]!.text).toMatch(/default.*time|deadline/i)+ expect(taken.messages[1]!.text).toBe('Default applied: To everyone — Ship how?')+ })+it('overdue without delegate is refused', () => {const s = swarm()expect(() => answerDecision(s.state, peer, open(s), { choice: 0, note: null, delegate: false, overdue: true }))diff --git a/backend/src/superTabs/decisions.ts b/backend/src/superTabs/decisions.tsindex 165fb1fcb..ff30b601a 100644--- a/backend/src/superTabs/decisions.ts+++ b/backend/src/superTabs/decisions.ts@@ -26,10 +26,19 @@ export const MAX_OPEN_DECISIONS = 20const line = (max: number) => z.string().trim().min(1).max(max)/** What a question offers besides itself: 2–5 distinct options, the index of the recommended one, and what an answer unblocks. */export const decisionChoices = z.object({ options: z.array(line(200)).min(2).max(5).refine(o => new Set(o).size === o.length, 'Give distinct options.'),- recommended: z.number().int().min(0), unblocks: line(300) }).strict()+ recommended: z.number().int().min(0), unblocks: line(300),+ defaultAt: z.string().datetime({ offset: true }).transform(value => new Date(value).toISOString()).optional() }).strict()export const decisionQuestion = decisionChoices.extend({ question: line(1000) }).strict()type Question = z.infer<typeof decisionQuestion>+/** Give a person time to see the question before its recommendation can apply automatically. */+export const MIN_DEFAULT_DELAY_MS = 15 * 60_000+export function checkDecisionDeadline(question: { defaultAt?: string }, now: number): void {+ if (question.defaultAt && Date.parse(question.defaultAt) < now + MIN_DEFAULT_DELAY_MS) {+ fail('INVALID_DECISION', 'Set the default time at least 15 minutes ahead so the person can answer.', 400)+ }+}+/** The kind of a decision the nightly routing reflection asks (costs/reflection.ts): about the project's routing, so its* owner's Buddy never reads it, and an approved one stays until routing applies it (review of #2276). */export const REFLECTION_DECISION = 'routing-reflection'@@ -46,6 +55,7 @@ export interface DecisionTarget {id: string; personId: string; conversationId: string; projectId: string; askerAgentId: string; question: string; options: string[]/** The option Let PM decide takes; a row whose index is not one of its options has none. */recommended: number; answeredAt: number | null+ defaultAt?: number | null/** When it was asked, and the task whose needs_human asked it: the leaderboard credits the answer (leaderboard/record.ts). */createdAt: number; assignmentId: string | nullkind?: string | null@@ -56,15 +66,16 @@ export interface DecisionTarget {/** `choice` null with a `note`: the person typed their own answer instead of choosing an option (task #2996). */export interface DecisionAnswer { id: string; choice: number | null; note: string | null; delegated?: true/** Left to the PM by the hourly sweep after 24 hours unanswered, not by the person (overdueDecisions.ts). */- overdue?: true }+ overdue?: true; defaulted?: true }/** Questions for one person in one conversation they read, from `asker`. One batch: one id ties them, no ping per question. */export function askDecisions(state: SuperTabState, group: Conversation, personId: string, questions: Question[],- from: { operationId: string; askerAgentId: string; assignmentId: string | null; kind?: typeof REFLECTION_DECISION }): DecisionDraft[] {+ from: { now: number; operationId: string; askerAgentId: string; assignmentId: string | null; kind?: typeof REFLECTION_DECISION }): DecisionDraft[] {const asked = state.people.find(p => p.id === personId) ?? fail('INVALID_PERSON', 'Ask a person in this Swarm.', 400)if (!canReadGroup(state, { kind: 'person', userId: asked.id, email: asked.email }, group)) {fail('INVALID_PERSON', `${usernameOf(state, asked.id)} cannot read this conversation.`, 400)}+ for (const q of questions) checkDecisionDeadline(q, from.now)for (const q of questions) if (q.recommended >= q.options.length) fail('INVALID_DECISION', 'A question must recommend one of its options.', 400)// It would wait for nobody: none waits where the work is over (workOver).if (workOver(state, group)) fail('WORK_FINISHED', 'This work is finished, so a decision asked here would not wait. Ask in the project chat, or reopen the task first.', 400)@@ -113,6 +124,7 @@ export const ANSWERED_NOTICE = 'A decision asked in this conversation was answerexport const delegatedNotice = (name: string) => `A decision asked in this conversation was left to the ${name}, who took its recommended option. `+ 'Read it with: harness super-tab decisions --answered'/** The notice for a decision left to the PM by the sweep, not the person: it says why, so nobody reads it as their choice. */+export const defaultedNotice = 'A decision you asked reached its default time. The server applied its recommended option. Read it with: harness super-tab decisions --answered'export const overdueNotice = (name: string) => `A decision asked in this conversation waited 24 hours, so it was left to the ${name}, who took its recommended option. `+ 'Read it with: harness super-tab decisions --answered'/** The notices for a decision asked in a closed Chat with PM, told in the project chat instead: never "in this conversation". */@@ -128,7 +140,7 @@ const answerText = (option: string, delegated: boolean) => delegated ? `PM decid* for the asking agent and the Lead, in the conversation it was asked in or, for a closed Chat with PM nobody reads, in* the project chat (`noticeIn`); and for a delegated one, the Lead's line in the person's Buddy chat. */export function answerDecision(state: SuperTabState, actor: Actor, decision: DecisionTarget | undefined,- given: { choice?: number; note: string | null; delegate: boolean; overdue?: boolean }) {+ given: { choice?: number; note: string | null; delegate: boolean; overdue?: boolean; defaulted?: boolean; now?: number }) {if (given.choice !== undefined ? given.delegate : !given.delegate && given.note === null) {fail('INVALID_DECISION', 'Choose one of its options, type an answer, or leave it to the PM.', 400)}@@ -140,6 +152,10 @@ export function answerDecision(state: SuperTabState, actor: Actor, decision: Decif (given.delegate && !(asked.recommended >= 0 && asked.recommended < asked.options.length)) {fail('INVALID_DECISION', 'This decision has no recommended option to leave to the PM.', 400)}+ if (given.defaulted && (!given.delegate || asked.kind === REFLECTION_DECISION || asked.defaultAt == null || given.now == null || asked.defaultAt > given.now)) {+ fail('INVALID_DECISION', 'This decision has not reached its default time.', 400)+ }+ if (given.overdue && asked.defaultAt != null) fail('INVALID_DECISION', 'This decision uses its explicit default time.', 400)const choice = given.delegate ? asked.recommended : given.choice ?? nullif (choice !== null && choice >= asked.options.length) fail('INVALID_DECISION', 'Choose one of its options.', 400)const project = groupProject(state, group)@@ -147,25 +163,25 @@ export function answerDecision(state: SuperTabState, actor: Actor, decision: Decconst closed = isClosedPmChat(group)const noticeIn = closed ? state.conversations.find(c => c.id === project.leadConversationId)! : groupconst delegatedText = closed ? closedChatDelegatedNotice : given.overdue ? overdueNotice : delegatedNotice- const notice = given.delegate ? delegatedText(coordinatorNameOf(project))+ const notice = given.defaulted ? defaultedNotice : given.delegate ? delegatedText(coordinatorNameOf(project)): closed ? CLOSED_CHAT_ANSWERED_NOTICE : ANSWERED_NOTICEconst recipients = [...new Set([asked.askerAgentId, ...lead ? [lead] : []])].filter(id => noticeIn.agentIds.includes(id))- const answer: DecisionAnswer = { id: asked.id, choice, note: given.note, ...given.delegate ? { delegated: true as const, ...given.overdue ? { overdue: true as const } : {} } : {} }+ const answer: DecisionAnswer = { id: asked.id, choice, note: given.note, ...given.delegate ? { delegated: true as const, ...given.overdue ? { overdue: true as const } : {}, ...given.defaulted ? { defaulted: true as const } : {} } : {} }// A routing reflection's never reaches the Buddy chat: the person's Buddy reads it (review of #2276).- const line = given.delegate && lead && asked.kind !== REFLECTION_DECISION ? delegatedLine(state, project.id, lead, asked, asked.recommended) : null+ const line = given.delegate && lead && asked.kind !== REFLECTION_DECISION ? delegatedLine(state, project.id, lead, asked, asked.recommended, given.defaulted) : nullreturn { answer, noticeIn: noticeIn.id, notice, recipients, source: { ...AGENT_ONLY, decisionId: asked.id }, line }}/** The Lead's one line saying what it chose, in the person's own Buddy chat of that project: only they and their Buddy read* it, and they were asked the question. Opened for the line when they have none (buddies.ts openBuddyChat), so it never* drops: Buddies replaced Chat with PM (Ken, 10-29). */-function delegatedLine(state: SuperTabState, projectId: string, leadId: string, asked: DecisionTarget, choice: number) {+function delegatedLine(state: SuperTabState, projectId: string, leadId: string, asked: DecisionTarget, choice: number, defaulted = false) {const lead = state.agents.find(a => a.id === leadId)if (!lead) return nullconst to = person(state, asked.personId)const author: Author = { kind: 'agent', id: lead.id, name: lead.name, displayName: agentDisplayName(state.agents, lead.id), membershipGeneration: lead.membershipGeneration }const question = asked.question.replace(/\s+/g, ' ')- const text = `${answerText(asked.options[choice]!, true)} — ${question}`+ const text = `${defaulted ? `Default applied: ${asked.options[choice]!}` : answerText(asked.options[choice]!, true)} — ${question}`// In their one Buddy chat, marked with its project (Dee, 10-31), and in their older chat there for older apps.return [{ conversationId: openSwarmBuddyChat(state, to).id, author, text, source: { kind: 'decision-delegated', decisionId: asked.id, projectId }, buddyProject: projectId },{ conversationId: openBuddyChat(state, projectId, to).id, author, text, source: { kind: 'decision-delegated', decisionId: asked.id } }]@@ -213,8 +229,8 @@ export function workEnded(before: SuperTabState, after: SuperTabState): string[]/** What makes an ask a repeat: the same asker, task, person, conversation, question, options, recommendation and what it* unblocks. Another asker, another task or other options with the same text is a decision of its own (review of #1753). */-const repeatKey = (d: Pick<DecisionDraft, 'askerAgentId' | 'assignmentId' | 'personId' | 'conversationId' | 'question' | 'options' | 'recommended' | 'unblocks'>) =>- JSON.stringify([d.askerAgentId, d.assignmentId ?? null, d.personId, d.conversationId, d.question, d.options, d.recommended, d.unblocks])+const repeatKey = (d: Pick<DecisionDraft, 'askerAgentId' | 'assignmentId' | 'personId' | 'conversationId' | 'question' | 'options' | 'recommended' | 'unblocks'> & { defaultAt?: string | Date | null }) =>+ JSON.stringify([d.askerAgentId, d.assignmentId ?? null, d.personId, d.conversationId, d.question, d.options, d.recommended, d.unblocks, d.defaultAt ? new Date(d.defaultAt).toISOString() : null])/** Writes the questions asked and returns the decision each one is: an open decision that this ask exactly repeats is that* decision again, not a second one. New ones beyond MAX_OPEN_DECISIONS from this asker to this person are refused, and@@ -233,7 +249,7 @@ export async function writeDecisions(tx: Tx, tabId: string, drafts: DecisionDrafif (asked + fresh.length > MAX_OPEN_DECISIONS) {fail('DECISIONS_FULL', `${asked} decisions you asked this person are still open, and at most ${MAX_OPEN_DECISIONS} can be. Wait for answers before asking more.`)}- await tx.superTabDecision.createMany({ data: fresh.map(d => ({ ...d, tabId, createdAt: new Date(now) })) })+ await tx.superTabDecision.createMany({ data: fresh.map(d => ({ ...d, defaultAt: d.defaultAt ? new Date(d.defaultAt) : undefined, tabId, createdAt: new Date(now) })) })await tx.superTabDecision.deleteMany({ where: { tabId, answeredAt: { lt: new Date(now - LEDGER_WEEKS * WEEK_MS) } } })}return drafts.map(d => held.get(repeatKey(d)) ?? d.id)@@ -274,8 +290,8 @@ export async function expireReflections(tx: Tx, tabId: string, projectId: stringexport async function readAskedDecision(tx: Tx, tabId: string, id: string): Promise<DecisionTarget | undefined> {const row = await tx.superTabDecision.findFirst({ where: { id, tabId },select: { id: true, personId: true, conversationId: true, projectId: true, askerAgentId: true, question: true, options: true, recommended: true,- answeredAt: true, createdAt: true, assignmentId: true, kind: true, withdrawn: true } })- return row ? { ...row, answeredAt: row.answeredAt?.getTime() ?? null, createdAt: row.createdAt.getTime(), assignmentId: row.assignmentId ?? null,+ answeredAt: true, defaultAt: true, createdAt: true, assignmentId: true, kind: true, withdrawn: true } })+ return row ? { ...row, answeredAt: row.answeredAt?.getTime() ?? null, defaultAt: row.defaultAt?.getTime() ?? null, createdAt: row.createdAt.getTime(), assignmentId: row.assignmentId ?? null,withdrawn: row.withdrawn === true } : undefined}@@ -283,7 +299,7 @@ export async function readAskedDecision(tx: Tx, tabId: string, id: string): Promexport async function recordAnswer(tx: Tx, tabId: string, answer: DecisionAnswer, now: number): Promise<void> {const taken = await tx.superTabDecision.updateMany({ where: { id: answer.id, tabId, ...waiting },data: { choice: answer.choice, note: answer.note, answeredAt: new Date(now), ...answer.delegated ? { delegated: true } : {},- ...answer.overdue ? { overdue: true } : {} } })+ ...answer.overdue ? { overdue: true } : {}, ...answer.defaulted ? { defaulted: true } : {} } })if (!taken.count) fail('DECISION_ANSWERED', 'This decision is already answered.')}@@ -398,11 +414,11 @@ export async function listDecisions(tx: Tx, tabId: string, state: SuperTabState,askerAgentId: row.askerAgentId, askerName: asker?.displayName ?? asker?.name ?? 'Agent',question: row.question, options: row.options, recommended: row.recommended, unblocks: row.unblocks,createdAt: row.createdAt, answeredAt: row.answeredAt ?? null, choice: row.choice ?? null, note: row.note ?? null,- delegated: row.delegated === true, overdue: row.overdue === true,+ delegated: row.delegated === true, overdue: row.overdue === true, defaultAt: row.defaultAt ?? null, defaulted: row.defaulted === true,// What the 24-hour sweep can take: the sweep skips a reflection and a recommended option that is not one of the options.pmTakesOver: row.kind !== REFLECTION_DECISION && row.recommended >= 0 && row.recommended < row.options.length,// A typed answer (no option) reads as its words.answer: row.choice == null ? (row.answeredAt ? row.note ?? null : null)- : row.options[row.choice] === undefined ? null : answerText(row.options[row.choice]!, row.delegated === true) }+ : row.options[row.choice] === undefined ? null : row.defaulted ? `Default applied: ${row.options[row.choice]!}` : answerText(row.options[row.choice]!, row.delegated === true) }}) }}diff --git a/backend/src/superTabs/overdueDecisions.ts b/backend/src/superTabs/overdueDecisions.tsindex 7bfa10f70..4e519843b 100644--- a/backend/src/superTabs/overdueDecisions.ts+++ b/backend/src/superTabs/overdueDecisions.ts@@ -16,7 +16,16 @@ const at = (ms: number) => ({ $date: new Date(ms).toISOString() })*/export async function overdueDecisions(db: PrismaClient, now: number, limit = OVERDUE_PER_PASS): Promise<Array<{ tabId: string; id: string; personId: string }>> {const rows = await db.superTabDecision.aggregateRaw({ pipeline: [- { $match: { answeredAt: null, createdAt: { $gt: at(now - OVERDUE_REACH_MS), $lte: at(now - OVERDUE_DECISION_MS) }, withdrawn: { $ne: true }, kind: { $ne: REFLECTION_DECISION } } },+ { $match: { answeredAt: null, defaultAt: null, createdAt: { $gt: at(now - OVERDUE_REACH_MS), $lte: at(now - OVERDUE_DECISION_MS) }, withdrawn: { $ne: true }, kind: { $ne: REFLECTION_DECISION } } },{ $sort: { createdAt: 1 } }, { $limit: limit }, { $project: { _id: 1, tabId: 1, personId: 1 } }] }) as unknown as Array<Record<string, unknown>>return rows.map(row => ({ tabId: String(row.tabId), id: String(row._id), personId: String(row.personId) }))}++/** Explicit deadlines have no creation-age reach: a question scheduled weeks ago is still due today. The range excludes+ * missing/null deadlines and answered rows. IDs only, through decision_waiting_default; withdrawn/reflection rows stay closed. */+export async function dueDefaultDecisions(db: PrismaClient, now: number, limit = OVERDUE_PER_PASS): Promise<Array<{ tabId: string; id: string; personId: string }>> {+ const rows = await db.superTabDecision.aggregateRaw({ pipeline: [+ { $match: { answeredAt: null, defaultAt: { $lte: at(now) }, withdrawn: { $ne: true }, kind: { $ne: REFLECTION_DECISION } } },+ { $sort: { defaultAt: 1 } }, { $limit: limit }, { $project: { _id: 1, tabId: 1, personId: 1 } }] }) as unknown as Array<Record<string, unknown>>+ return rows.map(row => ({ tabId: String(row.tabId), id: String(row._id), personId: String(row.personId) }))+}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 5c31c656b..067b79236 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -121,7 +121,7 @@ import { MAX_PROPOSALS, proposalQuestion, proposalTitle, REASK_DAYS, reflectionMimport { readEvidence, recordEvidence } from './evidence/store.js'import { closeAssignment, closeUnassignedStart, LIST_SIZE, newestConversations, newestDecisions, readDecision, recentDecisions, recordAttempts, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'import { answeredAgents, dropHeldTags, listMentions, markDone, mentionsWaiting, openTags, readMention, resolveByAnswer, resolveByReply, resolveWhenWorked, writeMentions } from './mentions.js'-import { OVERDUE_PER_PASS, overdueDecisions } from './overdueDecisions.js'+import { OVERDUE_PER_PASS, overdueDecisions, dueDefaultDecisions } from './overdueDecisions.js'import { answerable, askDecisions, MAX_OPEN_DECISIONS, REFLECTION_DECISION, reflectionDecisions, expireReflections, fullFor, listDecisions, type DecisionList, readAskedDecision, recordAnswer, repeatOf, waitingConversations, waitingFor, waitingInProject, withdrawIn, workEnded, workOver, writeDecisions } from './decisions.js'import { CATCH_UP_SCAN, catchUpSummary, type CatchUp } from './catchUp.js'import { recordMessageRead, type MessageReadKey } from './messageReadStats.js'@@ -1472,38 +1472,48 @@ export class SuperTabStore {})}- /**- * Leaves to the PM every decision asked at least 24 hours ago that its person still has not answered (spec: Diego,- * 2026-11-04, a decision left a day goes to the PM). Runs as the person through the same pipeline as their own delegate, with- * the store-only `overdue` context, so a person answering in the same second wins (DECISION_ANSWERED) and a repeat replays.- * Every pass reads the waiting decisions asked 24 hours to 8 days ago, 500 at most, oldest first. No cursor: a row that failed or- * missed the cap is read again next pass until it is 8 days old, and a person answering takes it out of the index range.- */+ /** Applies explicit due recommendations first, then legacy 24-hour defaults, at most 500 per pass. Each answer uses+ * the same access-checked transaction and conditional write as a person's answer. Explicit deadlines have no age cutoff;+ * legacy retries keep their 8-day reach. Failed rows remain waiting and the next minute retries them. */async leaveOverdueDecisions(now: number, limit = OVERDUE_PER_PASS): Promise<{ answered: number; skipped: number; failed: number }> {- const rows = await overdueDecisions(this.db, now, limit)+ // Reserve legacy capacity even when the explicit queue is full; let explicit work use any unused share.+ const legacyWaiting = await overdueDecisions(this.db, now, limit)+ const reserved = Math.min(legacyWaiting.length, Math.max(1, Math.floor(limit / 2)))+ const due = reserved < limit ? await dueDefaultDecisions(this.db, now, limit - reserved) : []+ const legacy = legacyWaiting.slice(0, limit - due.length)+ const rows = [...due.map(row => ({ ...row, defaulted: true })), ...legacy.map(row => ({ ...row, defaulted: false }))]const result = { answered: 0, skipped: 0, failed: 0 }const tabs = new Map<string, AuthUser['autonomousEnv'] | null>()const codes = new Set<string>()+ const withdrawDefault = async (row: typeof rows[number]) => {+ if (!row.defaulted) return+ // A person can answer meanwhile; never overwrite that answer. Closed rows leave the next indexed due range.+ await this.db.superTabDecision.updateMany({ where: { id: row.id, tabId: row.tabId,+ OR: [{ answeredAt: null }, { answeredAt: { isSet: false } }] }, data: { answeredAt: new Date(now), withdrawn: true } })+ }for (const row of rows) {try {if (!tabs.has(row.tabId)) tabs.set(row.tabId, (await this.db.superTab.findUnique({ where: { id: row.tabId }, select: { autonomousEnv: true } }))?.autonomousEnv as AuthUser['autonomousEnv'] | undefined ?? null)const autonomousEnv = tabs.get(row.tabId)const person = await this.db.user.findUnique({ where: { id: row.personId }, select: { email: true } })- if (!autonomousEnv || !person) { result.skipped++; continue }+ if (!autonomousEnv || !person) { await withdrawDefault(row); result.skipped++; continue }const user: AuthUser = { sub: row.personId, email: person.email, autonomousEnv, role: 'user' }- await this.executeOnce(user, row.tabId, { operationId: `overdue-decision-${row.id}`, command: { type: 'decision.answer', decisionId: row.id, delegate: true } },- undefined, undefined, false, { overdue: true })+ await this.executeOnce(user, row.tabId, { operationId: `${row.defaulted ? 'default' : 'overdue'}-decision-${row.id}`, command: { type: 'decision.answer', decisionId: row.id, delegate: true } },+ undefined, undefined, false, row.defaulted ? { defaulted: true } : { overdue: true })result.answered++} catch (error) {const code = error instanceof SuperTabError ? error.code : 'unknown'// Answered meanwhile, a recommendation out of range, or the person or Swarm gone: nothing for the sweep to do.- if (code === 'DECISION_ANSWERED' || code === 'INVALID_DECISION' || code === 'NOT_FOUND' || code === 'WORKSPACE_ACCESS_REVOKED') { result.skipped++; continue }+ if (code === 'DECISION_ANSWERED' || code === 'INVALID_DECISION' || code === 'NOT_FOUND' || code === 'WORKSPACE_ACCESS_REVOKED' || code === 'FORBIDDEN' || code === 'READ_ONLY') {+ try { await withdrawDefault(row) } catch { result.failed++; codes.add('DEFAULT_WITHDRAW_FAILED'); continue }+ result.skipped++; continue+ }result.failed++codes.add(code)}}// One loud line a pass (backend/AGENTS.md rule 4): codes only, never ids or emails.- if (result.failed > 0) logger.error('[swarm-sweeps] overdue decisions failed: they stay waiting and every pass tries them again until answered or 8 days old', { failed: result.failed, codes: [...codes] })+ if (result.failed > 0) logger.error('[swarm-sweeps] overdue decisions failed: they stay waiting and every pass tries them again until answered (legacy questions stop at 8 days old)', { failed: result.failed, codes: [...codes] })return result}@@ -1698,10 +1708,10 @@ export class SuperTabStore {}}- /** [only]: what the store alone may give a command: `overdue` for decision.answer (leaveOverdueDecisions), `movedTo` for+ /** [only]: what the store alone may give a command: `overdue`/`defaulted` for decision.answer (leaveOverdueDecisions), `movedTo` for* machine.moved (computerSignedIn). */private async executeOnce(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string,- workspaceLeave = false, only: { overdue?: boolean; movedTo?: { machineId: string; ownerId: string }; asProjectPm?: string } = {}) {+ workspaceLeave = false, only: { overdue?: boolean; defaulted?: boolean; movedTo?: { machineId: string; ownerId: string }; asProjectPm?: string } = {}) {const { operationId, command } = operationSchema.parse(input)const [pushOrigin, repositoryReach, pullRequestFiles, pullRequestMerges] = await Promise.all([this.pushOriginFor(user, tabId, command),this.repositoryReachFor(user, tabId, command), this.pullRequestFilesFor(user, tabId, command), this.pullRequestMergesFor(user, tabId, command)])@@ -1810,7 +1820,8 @@ export class SuperTabStore {}if (command.type !== 'invite.accept' && command.type !== 'agent.sessionClosed' && command.type !== 'machine.cleaned') author(original, actor)const context: CommandContext = { operationId, now: this.now(), ...(leavingDeleted ? { workspaceLeave: true as const } : {}),- ...(only.overdue && command.type === 'decision.answer' ? { overdue: true as const } : {}) }+ ...(only.overdue && command.type === 'decision.answer' ? { overdue: true as const } : {}),+ ...(only.defaulted && command.type === 'decision.answer' ? { defaulted: true as const } : {}) }if (command.type === 'machine.moved' && only.movedTo && actor.kind === 'person') {context.computerMove = await this.computerMove(tx, original, actor.userId, command.machineId, only.movedTo)}@@ -4906,7 +4917,7 @@ export class SuperTabStore {if (!fresh.length) return 'empty'await this.save(tx, loaded, state, clock.next(), [{ kind: 'head', key: 'head' }])await writeDecisions(tx, tabId, askDecisions(state, chat, project.ownerId, fresh.map(proposalQuestion),- { operationId: id, askerAgentId: lead.id, assignmentId: null, kind: REFLECTION_DECISION }), now)+ { now, operationId: id, askerAgentId: lead.id, assignmentId: null, kind: REFLECTION_DECISION }), now)return 'posted'})}diff --git a/backend/src/superTabs/sweeps.ts b/backend/src/superTabs/sweeps.tsindex 47b172d4f..d86ae185e 100644--- a/backend/src/superTabs/sweeps.ts+++ b/backend/src/superTabs/sweeps.ts@@ -214,16 +214,10 @@ export async function sweepSwarms(db: PrismaClient, now = Date.now()) {/** Runs the sweeps every hour in the singleton worker. `finishWorkspaceRemovals` finishes Workspace removals whose Swarm removals* did not all run (workspaceStore.ts SwarmWorkspaces.finishRemovals); it needs the store, so the worker passes it in. */-export function startSwarmSweeps(db: PrismaClient, everyMs = 3_600_000, finishWorkspaceRemovals?: () => Promise<number>,- leaveOverdueDecisions?: (now: number) => Promise<unknown>): () => void {+export function startSwarmSweeps(db: PrismaClient, everyMs = 3_600_000, finishWorkspaceRemovals?: () => Promise<number>): () => void {// The worker names indexes as servers do: listed before each pass, so a pass after the schema push names them.const run = () => void listNamedIndexes(db).catch(error => logger.warn('[swarm-sweeps] listing indexes failed', { error: error instanceof Error ? error.message : String(error) })).then(() => sweepSwarms(db)).then(async result => ({ ...result, workspaceRemovalsPending: await finishWorkspaceRemovals?.() }))- // A decision left 24 hours goes to the PM (spec: Diego, 2026-11-04). Its failure is loud and never stops the rest of the pass.- .then(async result => ({ ...result, overdue: await leaveOverdueDecisions?.(Date.now()).catch(error => {- logger.error('[swarm-sweeps] overdue decisions failed', { error: error instanceof Error ? error.message : String(error) })- return { failed: true as const }- }) })).then(result => logger.info('[swarm-sweeps] done', result)).catch(error => logger.warn('[swarm-sweeps] failed', { error: error instanceof Error ? error.message : String(error) }))run()diff --git a/backend/src/worker.ts b/backend/src/worker.tsindex 4f37b5671..f0bf2f98f 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -18,6 +18,7 @@ import { startQueryStats } from './lib/queryStats.js'import { startRetryStats } from './superTabs/retryStats.js'import { releaseSchema } from './lib/db/schemaRelease.js'import { startSwarmSweeps } from './superTabs/sweeps.js'+import { startDecisionSweep } from './superTabs/decisionSweep.js'import { requeueCompactedAgents } from './superTabs/agentTombstones.js'import { startLegacyDrop } from './superTabs/migration/dropLegacyJob.js'import { startInstructionsRebase } from './superTabs/migration/rebase.js'@@ -81,6 +82,7 @@ async function start(): Promise<void> {await reconcileCommunityLikeCounts()let stopSweeps = (): void => {}+ let stopDecisionSweep = (): void => {}let stopLegacyDrop = (): void => {}let stopInstructionsRebase = (): void => {}let stopArchive = (): void => {}@@ -106,6 +108,7 @@ async function start(): Promise<void> {machineBillingWorkerService.stop()productUsagePeopleRollupService.stop()stopSweeps()+ stopDecisionSweep()stopLegacyDrop()stopInstructionsRebase()stopArchive()@@ -161,7 +164,8 @@ async function start(): Promise<void> {// A failure leaves them compacted, as before, and never stops the worker starting.await requeueCompactedAgents(prisma, Date.now()).then(queued => logger.info('[swarm-sweeps] queued compacted agent tombstones for purge', { queued }),error => logger.warn('[swarm-sweeps] queuing compacted agent tombstones failed', { error: error instanceof Error ? error.message : String(error) }))- stopSweeps = startSwarmSweeps(prisma, undefined, () => swarms.workspaces.finishRemovals(), now => swarms.leaveOverdueDecisions(now))+ stopSweeps = startSwarmSweeps(prisma, undefined, () => swarms.workspaces.finishRemovals())+ stopDecisionSweep = startDecisionSweep(now => swarms.leaveOverdueDecisions(now))// The dead old state of migrated Swarms goes by itself, a few at a time (superTabs/migration/dropLegacyJob.ts).stopLegacyDrop = startLegacyDrop(prisma)// Every project's instructions move onto the new base once, by themselves (superTabs/migration/rebase.ts, task #3600).diff --git a/desktop/lib/super_tabs/agent_details.dart b/desktop/lib/super_tabs/agent_details.dartindex 71c7f46cc..809483230 100644--- a/desktop/lib/super_tabs/agent_details.dart+++ b/desktop/lib/super_tabs/agent_details.dart@@ -22,6 +22,30 @@ import 'model.dart';import 'profile_sheet.dart';import 'pull_requests.dart';+/// The task [agent] holds now. A task the Swarm lost is that task's history: it names the agent's state only when the+/// agent holds nothing else (Gray, 2026-11-06: Lamp read "Lost" on an old task while working on another).+SuperTabConversation? _currentTask(+ SuperTabController controller,+ SuperTabAgent agent,+) {+ final open = [+ for (final g+ in controller.snapshot?.conversations ?? const <SuperTabConversation>[])+ if (!g.closed &&+ g.assignment?['agentId'] == agent.id &&+ // Never a task the viewer may not read (review of #2281).+ superTabGroupReadable(controller, g) &&+ !const {+ 'done',+ 'stopped',+ 'cancelled',+ }.contains(g.assignment?['status']))+ g,+ ];+ return open.where((g) => g.assignment?['status'] != 'lost').firstOrNull ??+ open.firstOrNull;+}+/// Facts already observed by the Swarm or the agent's machine. Unknown facts/// stay absent; an idle or working claim needs actual work or native activity.class SuperTabAgentInfo {@@ -43,20 +67,7 @@ class SuperTabAgentInfo {?.agents.where((a) => a.id == agent.harnessId).firstOrNull,- controller.snapshot?.conversations- .where(- (g) =>- !g.closed &&- g.assignment?['agentId'] == agent.id &&- // Never a task the viewer may not read (review of #2281).- superTabGroupReadable(controller, g) &&- !const {- 'done',- 'stopped',- 'cancelled',- }.contains(g.assignment?['status']),- )- .firstOrNull,+ _currentTask(controller, agent),);SuperTabAgentInfo._(diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 16ccd3611..2213a822e 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -463,6 +463,20 @@ class SuperTabController extends ChangeNotifier {return _uploadErrors[conversationId];}+ /// Takes the last action's refusal for a caller that says it in its own place, the instructions panel's Save (task+ /// #3652): no composer says it after. An action whose answer was lost keeps it, since every composer waits on it+ /// with Retry.+ String? takeOperationError() {+ final failure = operationError;+ if (failure == null || _pending != null) return failure;+ operationError = null;+ operationErrorCode = null;+ _operationErrorFor = null;+ _operationErrorRoot = null;+ _changed();+ return failure;+ }+/// The thread the last failed reply was going to: the thread of the message/// it answers, or that message itself, as the backend files a reply. Null/// when the failure was not a reply.@@ -2256,10 +2270,12 @@ class SuperTabController extends ChangeNotifier {bool hasNewer(String id) => _newer.contains(id);/// Brings [id]'s newest messages: when more are waiting than reads- /// brought, the latest page replaces what is held; otherwise what came- /// after it is read. Its own read: one already under way may have asked- /// for less (the rows held below a reader scrolled up).- Future<void> showLatest(String id) async {+ /// brought, or [replace] asks it, the latest page replaces what is held;+ /// otherwise what came after it is read. Its own read: one already under+ /// way may have asked for less (the rows held below a reader scrolled up).+ /// [replace] is Jump to latest from far up (task #3630): the rows read back+ /// go, and earlier history is read again from the latest page.+ Future<void> showLatest(String id, {bool replace = false}) async {_readingBack.remove(id);for (var under = _reading[(id, false)];@@ -2269,7 +2285,7 @@ class SuperTabController extends ChangeNotifier {await under;}if (_disposed) return;- if (_newer.contains(id)) _latestWanted.add(id);+ if (replace || _newer.contains(id)) _latestWanted.add(id);await _readMessages(id);}diff --git a/desktop/lib/super_tabs/instructions_panel.dart b/desktop/lib/super_tabs/instructions_panel.dartindex 027cccd6a..294616e0d 100644--- a/desktop/lib/super_tabs/instructions_panel.dart+++ b/desktop/lib/super_tabs/instructions_panel.dart@@ -246,9 +246,11 @@ class _InstructionsPanelState extends State<_InstructionsPanel> {return;}final stale = c.operationErrorCode == 'INSTRUCTIONS_STALE';+ // The panel says why itself; the chat's Reply boxes do not (task #3652).+ final why = c.takeOperationError();setState(() {_saving = false;- if (!stale) _saveError = c.operationError;+ if (!stale) _saveError = why;});// The refusal's text does not reach this client (decision 3): read the revision it missed.if (stale) await _read();@@ -355,9 +357,10 @@ class _InstructionsPanelState extends State<_InstructionsPanel> {'noteId': note.id,});if (!mounted) return;+ final why = result == null ? c.takeOperationError() : null;setState(() {_removing.remove(note.id);- if (result == null) _saveError = c.operationError;+ if (result == null) _saveError = why;});// The notes' revision moved with the command: the Swarm read's move reads them (never touching the draft).if (result != null) _onSwarm();diff --git a/desktop/lib/super_tabs/pulse_strip.dart b/desktop/lib/super_tabs/pulse_strip.dartindex c7cbfbaaa..4237a5f55 100644--- a/desktop/lib/super_tabs/pulse_strip.dart+++ b/desktop/lib/super_tabs/pulse_strip.dart@@ -335,16 +335,19 @@ class _SuperTabPulseStripState extends State<SuperTabPulseStrip>if (widget.pulse.asks.list.isEmpty) _none('No asks waiting'),];- /// The task [agentId] works on in this project, while the Swarm holds it.- SuperTabConversation? _taskOf(String agentId) => _snapshot.conversations- .where(- (g) =>- g.projectId == widget.projectId &&- g.assignment?['agentId'] == agentId &&- !g.closed &&- !superTabTaskShipped(g),- )- .firstOrNull;+ /// The task [agentId] works on in this project, while the Swarm holds it. A lost one counts only when it holds+ /// nothing else (#3649): an old lost task is that task's history, not the agent's work.+ SuperTabConversation? _taskOf(String agentId) {+ final held = _snapshot.conversations.where(+ (g) =>+ g.projectId == widget.projectId &&+ g.assignment?['agentId'] == agentId &&+ !g.closed &&+ !superTabTaskShipped(g),+ );+ return held.where((g) => g.assignment?['status'] != 'lost').firstOrNull ??+ held.firstOrNull;+ }List<Widget> _agentRows() => [for (final id in widget.pulse.working.agentIds)diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 475427956..9df80e20e 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -1038,13 +1038,13 @@ class _SuperTabViewState extends State<SuperTabView>void _jumpToLatest() {final id = c.selectedId;_focus.requestFocus();- if (!c.hasNewer(id)) {- if (_farFromEnd(id)) _restartAtEnd(id);- return _followEnd(id);- }- // More are waiting than were read: the latest page first, then its end.+ final far = _farFromEnd(id);+ if (!c.hasNewer(id) && !far) return _followEnd(id);+ // More are waiting than were read, or the reader is far up: the latest+ // page replaces the rows read back, then its end shows. The rows on screen+ // stay until it lands, so the list is never empty (task #3630).unawaited(- c.showLatest(id).then((_) {+ c.showLatest(id, replace: far).then((_) {if (!mounted || c.selectedId != id) return;_restartAtEnd(id);_followEnd(id);diff --git a/desktop/test/super_tab_agent_line_test.dart b/desktop/test/super_tab_agent_line_test.dartindex 4efa8368c..2bf2821ee 100644--- a/desktop/test/super_tab_agent_line_test.dart+++ b/desktop/test/super_tab_agent_line_test.dart@@ -9,6 +9,9 @@ import 'package:harness/super_tabs/agent_details.dart';import 'package:harness/super_tabs/roster.dart';import 'package:harness/super_tabs/agent_line.dart';+import 'dart:io';++import 'support/capture.dart';import 'support/super_tab_fixture.dart';import 'support/super_tab_members.dart';@@ -80,6 +83,7 @@ Future<ConversationServer> _swarm(List<Map<String, dynamic>> tasks = const [],List<Map<String, dynamic>> starts = const [],String account = 'owner',+ Brightness brightness = Brightness.dark,}) async {final server = ConversationServer();if (account != 'owner') {@@ -102,7 +106,7 @@ Future<ConversationServer> _swarm(addTearDown(() => tester.binding.setSurfaceSize(null));await tester.pumpWidget(MaterialApp(- theme: grid.buildAppTheme(brightness: Brightness.dark),+ theme: grid.buildAppTheme(brightness: brightness),home: Scaffold(body: SuperTabRoster(controller: c,@@ -131,6 +135,8 @@ Finder _line(String id, String text) => find.ancestor();void main() {+ final captureDir = Platform.environment['HARNESS_AGENT_LINE_CAPTURE_DIR'];+ setUpAll(() => loadCaptureFonts(captureDir));group('an agent row', () {testWidgets('says in one line its state, its machine, and its model and effort',@@ -175,6 +181,95 @@ void main() {expect(line(null), 'Assigned · Mac Studio · Opus · high');});+ test(+ 'reads the current task, never an older lost one (task #3649)',+ () async {+ // Gray, 2026-11-06: Lamp showed "Lost" on an old task while the Swarm had it working on another.+ Map<String, dynamic> task(String id, String title, String status) => {+ ...conversationFixture(id, title),+ 'leadId': 'Lead',+ 'agentIds': ['Lead', 'Lamp'],+ 'assignment': {'id': 'as-$id', 'agentId': 'Lamp', 'status': status},+ };+ final server = ConversationServer();+ server.state['machines'] = [_machine('m1', 'Mac Studio')];+ server.state['agents'] = [_agent('Lamp', 'm1')];+ // The lost one comes first, as an older task does in the Swarm's list.+ (server.state['conversations'] as List)+ ..add(task('old', 'First customers', 'lost'))+ ..add(task('now', 'Move the guide link', 'working'));+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ final info = SuperTabAgentInfo(+ c,+ null,+ c.snapshot!.agent('Lamp')!,+ activity: HarnessActivity.working,+ );+ expect(+ superTabAgentGlance(info).line,+ 'Working · Mac Studio · Opus · high',+ );+ expect(info.status, 'Working on "Move the guide link"');+ // With no other task, the lost one is still the agent's state.+ server.state['conversations'] = [+ ...(server.state['conversations'] as List).where(+ (g) => g['id'] != 'now',+ ),+ ];+ await c.refresh();+ expect(+ superTabAgentGlance(+ SuperTabAgentInfo(c, null, c.snapshot!.agent('Lamp')!),+ ).label,+ 'Lost',+ );+ },+ );++ for (final brightness in Brightness.values)+ testWidgets(+ 'the row of an agent with a lost older task shows the current one (${brightness.name})',+ (tester) async {+ Map<String, dynamic> task(String id, String title, String status) => {+ ...conversationFixture(id, title),+ 'leadId': 'Lead',+ 'agentIds': ['Lead', 'Lamp'],+ 'assignment': {'id': 'as-$id', 'agentId': 'Lamp', 'status': status},+ };+ await _swarm(+ tester,+ brightness: brightness,+ agents: [_agent('Lamp', 'm1')],+ tasks: [+ task('old', 'First customers: run 1', 'lost'),+ task('now', 'Mobile: move the app guide link', 'working'),+ ],+ );+ expect(+ _line('Lamp', 'Assigned · Mac Studio · Opus · high'),+ findsOneWidget,+ );+ final tip = tester+ .widgetList<Tooltip>(+ find.ancestor(of: _row('Lamp'), matching: find.byType(Tooltip)),+ )+ .single+ .message!;+ expect(+ tip,+ contains('Assigned to "Mobile: move the app guide link"'),+ );+ expect(tip, isNot(contains('Lost')));+ await captureWindow(+ tester,+ captureDir,+ 'agent-lost-older-task-${brightness.name}',+ );+ },+ );+testWidgets('names each state in a word: waiting, lost, down, kept (closed), limited, stuck, in review',(tester) async {diff --git a/desktop/test/super_tab_big_chat_jump_test.dart b/desktop/test/super_tab_big_chat_jump_test.dartindex 06caeeedc..d68a2b2a8 100644--- a/desktop/test/super_tab_big_chat_jump_test.dart+++ b/desktop/test/super_tab_big_chat_jump_test.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;@@ -218,4 +220,80 @@ void main() {await tester.pumpWidget(const SizedBox());await c.flush();}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));+ testWidgets('Jump to latest from far up drops the rows read back and holds '+ 'the newest page, with older history still there to read (#3630)', (+ tester,+ ) async {+ final c = await show(tester, chat(1500));+ await scrollFarUp(tester, 15);+ expect(c.messages('lead').length, 1500);++ await tester.tap(find.byKey(jump));+ for (var frame = 0; frame < 30; frame++) {+ await tester.pump(const Duration(milliseconds: 16));+ expect(visibleRows(tester), greaterThan(0), reason: 'frame $frame');+ }+ await tester.pumpAndSettle();++ expect(find.text(text(1500)), findsOneWidget);+ expect(chatScroll(tester).position.extentAfter, lessThan(40));+ expect(c.messages('lead').length, lessThanOrEqualTo(100));+ expect(c.messages('lead').last.text, text(1500));+ expect(c.hasOlder('lead'), isTrue);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));++ testWidgets('while the newest page is on its way, the rows read back stay '+ 'on screen (#3630)', (tester) async {+ final server = chat(1500);+ final c = await show(tester, server);+ await scrollFarUp(tester, 15);+ final latest = <String>[];+ server.onRead = (path) {+ if (!path.contains('before=') && !path.contains('after=')) {+ latest.add(path);+ }+ };+ server.holdReads = Completer<void>();++ await tester.tap(find.byKey(jump));+ for (var frame = 0; frame < 30; frame++) {+ await tester.pump(const Duration(milliseconds: 16));+ expect(visibleRows(tester), greaterThan(0), reason: 'frame $frame');+ }+ final hold = server.holdReads!;+ server.holdReads = null;+ hold.complete();+ for (var frame = 0; frame < 30; frame++) {+ await tester.pump(const Duration(milliseconds: 16));+ expect(visibleRows(tester), greaterThan(0), reason: 'after, $frame');+ }+ await tester.pumpAndSettle();+ // The server tells of a read once it answers it.+ expect(latest, isNotEmpty, reason: 'the latest page is asked for');+ expect(find.text(text(1500)), findsOneWidget);+ expect(c.messages('lead').length, lessThanOrEqualTo(100));+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));++ testWidgets('Jump to latest from near the end reads nothing (#3630)', (+ tester,+ ) async {+ final server = chat(400);+ final c = await show(tester, server);+ final scroll = chatScroll(tester);+ scroll.jumpTo(scroll.position.maxScrollExtent - 1500);+ await tester.pumpAndSettle();+ final reads = <String>[];+ server.onRead = reads.add;+ expect(find.byKey(jump), findsOneWidget);+ await tester.tap(find.byKey(jump));+ await tester.pumpAndSettle();+ expect(reads, isEmpty);+ expect(chatScroll(tester).position.extentAfter, lessThan(40));+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));}diff --git a/desktop/test/super_tab_instructions_error_shots_test.dart b/desktop/test/super_tab_instructions_error_shots_test.dartnew file mode 100644index 000000000..c36cd38f2--- /dev/null+++ b/desktop/test/super_tab_instructions_error_shots_test.dart@@ -0,0 +1,116 @@+// Task #3652 (Hoai, 11-06): a refused instructions save, for the PR's pictures, light and dark: the panel saying+// why, then the chat after it closes with no error in its Reply box. Writes nothing unless HARNESS_SUPER_TAB_CAPTURE+// names a folder.+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shared/widgets/app_menu.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/capture.dart';+import 'support/super_tab_fixture.dart';++final shots = Platform.environment['HARNESS_SUPER_TAB_CAPTURE'];++void main() {+ setUpAll(() => loadCaptureFonts(shots));++ for (final brightness in Brightness.values) {+ testWidgets('a refused instructions save 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(2400, 1600);+ addTearDown(tester.view.reset);++ final server = ConversationServer();+ server.state['projects'] = [+ {+ ...projectFixture('lead', 'Pilot', 'lead'),+ 'coordinatorName': 'Product Manager',+ 'instructionsRevision': 3,+ },+ ];+ (server.state['people'] as List).add({+ 'id': 'peer',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ server.instructions['lead'] = {+ 'projectId': 'lead',+ 'revision': 3,+ 'hash': 'hash-lead-3',+ 'text': '## Roles\n\n### PM\n- Talks with people in the project chat.\n',+ 'template': false,+ 'coordinatorName': 'Product Manager',+ 'notesRevision': 0,+ 'notes': <dynamic>[],+ };+ server.append('Morning. The release is out.');+ final c = server.controller(account: 'peer');+ await c.refresh();+ addTearDown(() async {+ await tester.pumpWidget(const SizedBox());+ c.dispose();+ });+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Test Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.byTooltip('Project options'));+ await tester.pumpAndSettle();+ await tester.tap(find.widgetWithText(AppMenuItem, 'Instructions'));+ await tester.pumpAndSettle();+ await tester.enterText(+ find.byKey(const ValueKey('super-instructions-editor')),+ '## Roles\n\n### PM\n- Talks with people in the project chat.\n'+ '- A long new rule.\n',+ );+ await tester.enterText(+ find.byKey(const ValueKey('super-instructions-summary')),+ 'A new rule',+ );+ await tester.pump();+ server.refuse = {+ 'code': 'INSTRUCTIONS_BUDGET',+ 'message': 'Not saved: Core over budget.',+ };+ server.refuseStatus = 400;+ await tester.tap(find.byKey(const ValueKey('super-instructions-save')));+ await tester.pumpAndSettle();+ server.refuse = null;+ await captureWindow(+ tester,+ shots,+ 'instructions-refused-${brightness.name}',+ );++ await tester.tap(find.byTooltip('Close'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Discard'));+ await tester.pumpAndSettle();+ await captureWindow(+ tester,+ shots,+ 'instructions-refused-closed-${brightness.name}',+ );+ });+ }+}diff --git a/desktop/test/super_tab_instructions_test.dart b/desktop/test/super_tab_instructions_test.dartindex 371ae2bb9..9f76d8eb4 100644--- a/desktop/test/super_tab_instructions_test.dart+++ b/desktop/test/super_tab_instructions_test.dart@@ -353,6 +353,43 @@ void main() {expect(unconfirmed, findsNothing);});+ testWidgets(+ 'a refused save says why only in the panel, and no Reply box keeps it '+ 'after the panel closes (task #3652)',+ (tester) async {+ final (server, controller) = await mount(tester, account: 'peer');+ await openInstructions(tester);+ await tester.enterText(find.byKey(_editor), 'Draft line');+ await tester.enterText(find.byKey(_summary), 'Mine');+ await tester.pump();+ const why = 'Not saved: Core over budget.';+ server.refuse = {'code': 'INSTRUCTIONS_BUDGET', 'message': why};+ server.refuseStatus = 400;+ await tester.tap(find.byKey(_save));+ await tester.pumpAndSettle();+ server.refuse = null;++ final inPanel = find.descendant(+ of: find.byType(SuperTabDetailDialog),+ matching: find.textContaining('Core over budget'),+ );+ expect(inPanel, findsOneWidget);+ // Only there: not in the chat's Reply box behind it.+ expect(find.textContaining('Core over budget'), findsOneWidget);+ expect(controller.composerError('lead'), isNull);+ expect(controller.threadComposerError('lead', 'message-1'), isNull);++ await tester.tap(find.byTooltip('Close'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Discard'));+ await tester.pumpAndSettle();+ expect(find.byType(SuperTabDetailDialog), findsNothing);+ expect(find.textContaining('Core over budget'), findsNothing);+ expect(controller.composerError('lead'), isNull);+ expect(controller.threadComposerError('lead', 'message-1'), isNull);+ },+ );+testWidgets('closing with unsaved changes asks first', (tester) async {await mount(tester, account: 'peer');await openInstructions(tester);@@ -658,6 +695,33 @@ void main() {expect(editorText(tester), 'Draft stays');});+ testWidgets(+ 'a refused note delete says why only in the panel (task #3652)',+ (tester) async {+ final (server, controller) = await mount(tester, account: 'peer');+ server.instructions['lead']!['notes'] = [+ note('n1', 'Keep it short', 'owner', const Duration(hours: 1)),+ ];+ await openInstructions(tester);+ await tester.ensureVisible(+ find.byKey(const ValueKey('super-note-delete-n1')),+ );+ await tester.pumpAndSettle();+ server.refuse = {'code': 'FORBIDDEN', 'message': 'Not removed: no access.'};+ await tester.tap(find.byKey(const ValueKey('super-note-delete-n1')));+ await tester.pumpAndSettle();+ server.refuse = null;+ expect(+ find.descendant(+ of: find.byType(SuperTabDetailDialog),+ matching: find.textContaining('Not removed'),+ ),+ findsOneWidget,+ );+ expect(find.textContaining('Not removed'), findsOneWidget);+ expect(controller.composerError('lead'), isNull);+ },+ );testWidgets('a viewer has no Delete', (tester) async {final (viewerServer, _) = await mount(tester, account: 'viewer');viewerServer.instructions['lead']!['notes'] = [diff --git a/desktop/test/super_tab_pulse_test.dart b/desktop/test/super_tab_pulse_test.dartindex e2410ed56..3cca2f16d 100644--- a/desktop/test/super_tab_pulse_test.dart+++ b/desktop/test/super_tab_pulse_test.dart@@ -11,7 +11,7 @@ import 'package:harness/super_tabs/parts.dart';import 'package:harness/super_tabs/pulse.dart';import 'package:harness/super_tabs/tasks_view.dart';-import 'super_tab_tasks_view_test.dart' show tasksServer;+import 'super_tab_tasks_view_test.dart' show taskFixture, tasksServer;import 'support/memory_key_value_store.dart';import 'support/super_tab_fixture.dart';@@ -450,6 +450,25 @@ void main() {await closePulse(tester, c);});+ testWidgets(+ 'working: an agent with a lost older task opens its current one (#3649)',+ (tester) async {+ final server = pulseServer(pulseFixture());+ // The lost task comes first in the Swarm's list, as an older one does.+ (server.state['conversations'] as List).insert(+ 1,+ taskFixture('old-lost', 'First customers', 5, status: 'lost'),+ );+ final (c, opened) = await showPulse(tester, server);+ await tester.tap(segment('working'));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-pulse-agent-finch')));+ await tester.pumpAndSettle();+ expect(opened.tasks, ['tag']);+ await closePulse(tester, c);+ },+ );+testWidgets('next up: the tasks by title and number', (tester) async {final (c, opened) = await showPulse(tester, pulseServer(pulseFixture()));await tester.tap(segment('nextUp'));diff --git a/docs/plans/2026-11-06-decision-defaults-plan.md b/docs/plans/2026-11-06-decision-defaults-plan.mdnew file mode 100644index 000000000..fbfe14f84--- /dev/null+++ b/docs/plans/2026-11-06-decision-defaults-plan.md@@ -0,0 +1,87 @@+# Decision deadlines implementation plan++> Implement task by task in this session, test first, followed by one independent review.++**Goal:** Apply an unanswered decision's recommended option at its declared deadline and tell its asker once.++**Architecture:** Extend each decision question/needs-human ask with optional ISO `defaultAt`. Persist it on the existing decision row, select due rows through an answeredAt/defaultAt index, and use the existing transactional decision-answer pipeline with a server-only default-applied marker. Keep the legacy 24-hour fallback for questions without a deadline, and run the decision sweep separately every minute rather than behind hourly maintenance.++**Tech Stack:** Existing TypeScript, Zod, Prisma/MongoDB, Vitest and singleton worker timers.++**Spec:** Task #3599, inventory Table A #8; Dee's 11-06 checkable-rules-as-code decision. Existing decisions-in-one-place privacy and answer concurrency contracts remain in force.++## Global Constraints++- No new refusal/execution authority: applying an option records a decision; it does not execute the work it describes.+- One explicit deadline per question, alongside its recommendation, at least 15 minutes after the trusted ask time. Older clients may omit it and retain the 24-hour fallback.+- An answer already committed by a person wins; a repeated sweep creates no second answer/notice.+- Worker questions still route through the PM; their deadline survives in the crew need.+- Notices carry no question/option text, matching existing decision privacy. The authorized decisions list supplies the chosen option and distinguishes automatic defaults from a person's choice.+- Test first, commit failing tests before implementation, push each task. Affected local checks only; full backend unit/integration suites in ready PR CI.+- No real CLI sign-out, production write, process-by-name stop or cli/src/core change. Temp files only in mktemp directories.++## Design++- **Growth:** Two optional fields on existing decision rows (`defaultAt`, `defaulted`), no collection. Existing answered-decision retention removes them with their row. New index holds two scalar dates per row; no text or array fanout.+- **Concurrency:** Due selection is advisory; the answer transaction rereads the row, checks the deadline against its trusted clock, and conditional answer write makes person/sweep races single-winner. Stable operation ID makes retries idempotent.+- **Read cost:** Two bounded index queries (at most 500 candidate IDs each) and at most 500 attempted answers per pass; no full history/collection scans. Due rows carry only IDs/person IDs. A minute sweep has overlap protection and cleanup.+- **Scale:** 10x decisions retain the same per-pass cap and indexed range. Plan test records IXSCAN and examined/returned counts; measure loopback latency. Production read-only environment is absent on this Team machine, so collection count/size/growth evidence is unavailable; no attempt to use another account's credentials.+- **Compatibility:** Optional server fields, additive API only. Keep overdue's existing 24-hour meaning; a separate `defaulted` flag identifies timed defaults. Old clients ignore the deadline fields and still see an agent decision rather than their own choice.+- **Migration/rollback:** Schema release adds a non-TTL index and optional fields. No backfill, no rewrite of old deadlines. Rollback backend ignores new fields; do not deploy new callers until backend supports them. Release owner deploys schema during the authorized window; Engineer performs no production writes.+- **Audience/identity:** Existing answerable/access/work-finished checks remain. Default uses server-only context; a caller cannot claim it. Cross-account text remains data, with no new execution path.+- **Failure/platforms:** Existing loud per-pass errors; no overlapping passes. Explicit defaults are due on the first minute pass at/after deadline; old fallback remains hourly-or-better. Common server behavior for every client.++## Review Focus++- A future explicit deadline must prevent the legacy 24-hour sweep from answering early (Task 2).+- A long-lived question whose deadline is today must not be missed by the createdAt reach (Task 2).+- A person's answer racing the sweep must produce exactly one answer and notice (Task 2).+- A worker's PM-routed question must keep the recommended deadline (Task 1).+- A slow/failed sweep must not overlap itself or block hourly maintenance (Task 3).++### Task 1: Carry and store explicit deadlines++**Files:** `backend/src/superTabs/decisions.ts`, `decisions.test.ts`, `commands.ts`, `crewNeeds.ts`; `backend/prisma/schema.prisma`.+**Interfaces:** `decisionChoices.defaultAt?: string` (ISO), `DecisionDraft.defaultAt?: string`, `DecisionTarget.defaultAt?: number|null`; persisted `SuperTabDecision.defaultAt?: DateTime` and `defaulted?: Boolean`.++- [x] Commit tests: decision.ask and needs-human preserve deadline, malformed time rejected, PM routing retains it, repeats with the same time reuse while a changed time is distinct.+- [x] Run affected decision tests and verify missing schema/field behavior fails.+- [x] Extend choices, row writes/reads/list and crew-need metadata; include normalized deadline in repeat identity. Add optional schema fields/index; generate local Prisma client.+- [x] Run decision/crew-need unit tests, typecheck and focused persistence integration; commit and push.++### Task 2: Apply due defaults once++**Files:** `backend/src/superTabs/overdueDecisions.ts`, `decisions.ts`, `commands.ts`, `store.ts`; `backend/integration/overdueDecisions.test.ts`.+**Interfaces:** `dueDefaultDecisions(db, now, limit)` returns IDs only; existing `leaveOverdueDecisions` processes explicit due defaults before legacy fallback. Server-only context `defaulted` becomes `DecisionAnswer.defaulted` and a dedicated notice.++- [x] Commit failing tests: before deadline stays open; exact deadline takes recommendation and tells asker; answered decision untouched; repeated/concurrent sweeps once; later deadline defeats old 24h fallback; long-lived question due today works; ended/private/withdrawn/reflection protections remain; query uses intended index with bounded examined rows.+- [x] Run focused integration file and observe missing timed behavior.+- [x] Add indexed query and transactional deadline validation, recording `defaulted` without mislabeling as person/24-hour choice. Reuse idempotent answer/notice path.+- [x] Run affected unit/integration tests, query-plan evidence and typecheck; commit and push.++### Task 3: Schedule defaults independently++**Files:** `backend/src/superTabs/overdueDecisions.ts`, new `decisionSweep.test.ts`, `backend/src/worker.ts`, `sweeps.ts`.+**Interfaces:** `startDecisionSweep(run, everyMs=60_000): stop`; singleton worker starts/stops it alongside hourly maintenance.++- [x] Commit timer tests with fake clock: immediate pass, one-minute pass, no overlap, failure recovers visibly, stop removes future wakes.+- [x] Run new test and observe missing scheduler.+- [x] Separate decision schedule from hourly maintenance, wire worker shutdown and preserve loud failure reporting.+- [x] Run affected scheduler/decision tests, focused integrations/typecheck, record timing/red-green evidence, mark ready and request one independent review.++## Evidence++- Task 1: `2a25b628e` produced three failures / 27 passes in decisions.test.ts because defaultAt was not accepted; persistence regression `4464f0bfd` also failed on the unsupported field. `2ea902402` passes 38 decision/crew-need tests and the focused storage/list/repeat integration test. Offset-equivalent times share a decision; a changed deadline creates another.+- Task 2: `83f0854f9` produced four failures / one pass in timed integration cases (deadline ignored, future deadline answered early, no due cap/query); `8161cdb57` fails trusted-clock enforcement. `11011f0f5` passes the deadline behavior and existing 24-hour cases. A follow-up removed a redundant date-type filter that Prisma’s profile reader could not decode; the date comparison already uses MongoDB date type bracketing. The intended deadline index returns one due row and examines at most two documents amid future, legacy and answered noise.+- Task 3: `8927710b4` cannot load the absent scheduler. `b9545b2e7` passes immediate/minute/stop, non-overlap and loud failure recovery tests. Decision work no longer waits behind hourly maintenance.+- Final affected local checks: 469 unit tests across decisionSweep, decisions, crewNeeds and commands, plus backend typecheck. Full backend unit and four integration shards are ready PR CI’s responsibility. The focused deadline integration file covers normalized persistence, exact deadline, future and long-lived questions, person/concurrent answers, replay, cap, withdrawal/reflection exclusions and both query plans.+- No production read/write was attempted. The required read-only environment file is absent on this Team machine. Collection count, index size and daily growth therefore remain a release-owner measurement, with bounded loopback query-plan evidence as the local substitute.+- Release: add the non-TTL decision_waiting_default index through the normal schema step, deploy backend before new callers; no backfill. Each pass attempts at most 500 questions, reserving half for legacy questions when both queues are full and reusing unused capacity. Permanently unavailable explicit defaults are withdrawn conditionally, never overwriting a person’s answer; transient failures retry without an age cutoff. A sustained transient failure backlog can delay later explicit questions and is visible in worker failure counts. Minute precision means the first pass at/after deadline; a slow active pass postpones the next one. Rollback ignores the additive fields and leaves the index harmlessly unused.++## Independent-review corrections++- Both reviewers found that an immediate or past deadline gave a person no response time. `44c7ffa35` fails the new lower-bound unit test (one failure / 31 passes). The common check now requires 15 minutes from the trusted ask clock, including worker questions routed through the PM and needs-human asks; exactly 15 minutes passes. The integration fixture asks at its actual historical creation time so due tests model a valid previously asked question.+- SecAlder found permanent rows could occupy the entire due queue indefinitely. The same test-first commit fails a bounded stuck-row integration test: legacy work gets no share. Missing people/tabs and permanent access/decision refusals now conditionally withdraw only unanswered explicit rows. Legacy work reserves half the pass; either queue reuses unused capacity. The existing legacy-cap test caught an initial underfill and is preserved.+- Final review-fix checks: 470 affected unit tests in four files, clean backend typecheck, and all 15 focused deadline integration tests pass. The stuck-row test proves legacy work proceeds immediately and fresh timed work is reached after the unavailable prefix drains. Existing query plans remain green.+- Explicit deadlines farther than 24 hours remain intentional; the task asks to honor the stated time rather than replace it with the old fallback. No maximum or new person-approval authority is introduced. A default records the recommendation with automatic attribution; it does not execute protected work.+- Follow-up on SecAlder's remaining access case: `b9ebd5809` fails the real-store removed-member regression (one failure / one viewer pass). The user still exists, but its membership is gone. Permanent FORBIDDEN/READ_ONLY failures now retire only still-unanswered explicit defaults. Viewers deliberately may answer decisions (commands.ts bypasses write access for decision.answer), so the viewer regression preserves successful automatic answers. All 17 focused integrations and backend typecheck pass after this fix.diff --git a/docs/plans/2026-11-06-jump-to-latest-drops-held-plan.md b/docs/plans/2026-11-06-jump-to-latest-drops-held-plan.mdnew file mode 100644index 000000000..058d4c413--- /dev/null+++ b/docs/plans/2026-11-06-jump-to-latest-drops-held-plan.md@@ -0,0 +1,45 @@+# Jump to latest drops the held older window — plan (task #3630)++**Goal:** In a very large chat (the openharness project chat: 4,819 messages, 2,720 of them thread replies), Jump to+latest from far up always lands on the newest messages with nothing missing and never an empty list (Huy, 11-05 and+11-06).++**Architecture:** Today, Jump to latest from far up with nothing newer waiting keeps every row read on the way up+(here, the whole history) and rebuilds the list around its newest 40 rows (#3049). The held rows stay until a later+poll cuts them. The fix follows the brief: from far up, Jump to latest always asks the controller for the latest page,+which replaces what is held (the existing latest read, `_latestWanted`). The rows on screen stay until that page+lands, so the list is never empty, and then the list restarts at its newest rows as before. A jump from near the end is+unchanged: no read, no rebuilt rows.++**Tech Stack:** Flutter 3.47 (Desktop), `flutter_test` widget tests with `ConversationServer` (memory store, fake+sign-in).++**Spec:** River's brief on task #3630 (conversation 1bcd2e7b75220952e3c693b2).++This plan is written and carried out by its Engineer, test first; there is no execution handoff.++## Global Constraints++- Owns `desktop/lib/super_tabs/`. No backend or CLI change.+- Desktop tests use a memory store and a fake sign-in; none runs the real CLI.+- The real project chat replayed headless stays local and is never committed.++## Review Focus++- The list shows rows in every frame between the press and the newest page landing.+- Nothing newer than the newest held is missed: the latest page is read whole.+- Jump to latest from near the end reads nothing and rebuilds nothing.++## Tasks++### 1. From far up, Jump to latest replaces the held window with the latest page++Files: `desktop/lib/super_tabs/controller.dart`, `desktop/lib/super_tabs/view.dart`,+`desktop/test/super_tab_big_chat_jump_test.dart`.+Interfaces: `SuperTabController.showLatest(id, {bool replace = false})`.++- [x] Failing test: a 1,500-message chat scrolled to its start; Jump to latest shows the newest message, every frame+ shows rows, and afterwards the chat holds one page (100), not 1,500, with older history still readable.+- [x] Failing test: the same with the server slow to answer: rows stay on screen while the page is on its way.+- [x] Test (guard): Jump to latest from near the end reads no messages.+- [x] Code: `showLatest(replace: true)` asks for the latest page whole; the view calls it when far from the end.