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
Activity counts only what needs you; a decision left 24 hours goes to the PM (Diego) (#2929)
0xdiego2594a268107978
diff --git a/backend/integration/overdueDecisions.test.ts b/backend/integration/overdueDecisions.test.tsnew file mode 100644index 000000000..11fcb4e73--- /dev/null+++ b/backend/integration/overdueDecisions.test.ts@@ -0,0 +1,146 @@+import { randomUUID } from 'node:crypto'+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import type { PrismaClient } from '@prisma/client'+import 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 { 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.+let replica: MongoMemoryReplSet+let db: PrismaClient+const NOW = Date.parse('2026-11-04T12:00:00Z')+const HOUR = 3_600_000, DAY = 24 * HOUR+const owner: AuthUser = { sub: '400000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const peer: AuthUser = { sub: '400000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const config = { engine: 'claude', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }++beforeAll(async () => {+ ({ replica, db } = await planDatabase('overdue_decisions_test'))+ for (const user of [owner, peer]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: 'prod' } })+ await db.machine.create({ data: { machineId: 'owner-mac', userId: owner.sub, apiKey: 'fixture-owner-mac', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+})+// Every test counts what a pass answers across the whole database, so each starts without the earlier tests' decisions.+beforeEach(async () => { await db.superTabDecision.deleteMany({}) })+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})++/** A Swarm whose PM asks peer decisions; each `ask` is stored with the given age. */+async function swarm() {+ const store = new SuperTabStore(db, () => NOW)+ const tab = (await store.create(owner, randomUUID(), 'Overdue', 'public')).id+ const 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' })+ 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 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)+ 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+ }+ /** Old data the command refuses to ask now: a recommended option past its options. */+ const askBroken = async (age: number) => {+ const id = randomUUID().replaceAll('-', '').slice(0, 24)+ await db.superTabDecision.create({ data: { id, tabId: tab, batchId: randomUUID(), projectId: 'lead', conversationId: 'lead', personId: peer.sub, askerAgentId: lead,+ question: 'Which?', options: ['A', 'B'], recommended: 9, unblocks: 'Plan', createdAt: new Date(NOW - age) } })+ return id+ }+ 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 }+}++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()+ const id = await f.ask(25 * HOUR)+ expect(await f.store.leaveOverdueDecisions(NOW)).toEqual({ answered: 1, skipped: 0, failed: 0 })+ expect(await f.row(id)).toMatchObject({ delegated: true, overdue: true, choice: 1 })+ expect(await f.notices()).toBe(1)+ })++ it('a decision asked 23 hours ago waits', async () => {+ const f = await swarm()+ const id = await f.ask(23 * HOUR)+ expect(await f.store.leaveOverdueDecisions(NOW)).toEqual({ answered: 0, skipped: 0, failed: 0 })+ expect((await f.row(id)).answeredAt).toBeNull()+ })++ it("a person's answer wins over the sweep", async () => {+ const f = await swarm()+ const id = await f.ask(25 * HOUR)+ await f.execute({ type: 'decision.answer', decisionId: id, choice: 0 }, peer)+ expect(await f.store.leaveOverdueDecisions(NOW)).toEqual({ answered: 0, skipped: 0, failed: 0 })+ const row = await f.row(id)+ expect(row.choice).toBe(0)+ expect(row.overdue).toBeNull()+ })++ it('a second pass replays nothing', async () => {+ const f = await swarm()+ await f.ask(25 * HOUR)+ expect((await f.store.leaveOverdueDecisions(NOW)).answered).toBe(1)+ expect(await f.store.leaveOverdueDecisions(NOW + HOUR)).toEqual({ answered: 0, skipped: 0, failed: 0 })+ expect(await f.notices()).toBe(1)+ })++ it('a decision older than 8 days is never taken', async () => {+ const f = await swarm()+ const ancient = await f.ask(9 * DAY)+ const week = await f.ask(7 * DAY)+ expect((await new SuperTabStore(db, () => NOW).leaveOverdueDecisions(NOW)).answered).toBe(1)+ expect((await f.row(week)).overdue).toBe(true)+ expect((await f.row(ancient)).answeredAt).toBeNull()+ expect((await f.store.leaveOverdueDecisions(NOW)).answered).toBe(0)+ expect((await f.row(ancient)).answeredAt).toBeNull()+ })++ it('a capped pass leaves the rest for the next one', async () => {+ const f = await swarm()+ const ids = [await f.ask(30 * HOUR), await f.ask(28 * HOUR), await f.ask(26 * HOUR)]+ 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)).toEqual({ answered: 1, skipped: 0, failed: 0 })+ expect((await f.row(ids[2]!)).overdue).toBe(true)+ })++ it('a decision the PM cannot take is skipped, the rest are answered', async () => {+ const f = await swarm()+ const bad = await f.askBroken(25 * HOUR)+ const good = await f.ask(26 * HOUR - 1000)+ expect(await f.store.leaveOverdueDecisions(NOW)).toEqual({ answered: 1, skipped: 1, failed: 0 })+ expect((await f.row(bad)).answeredAt).toBeNull()+ expect((await f.row(good)).overdue).toBe(true)+ })++ it('the overdue read uses decision_waiting_created', async () => {+ const f = await swarm()+ // Noise: waiting rows outside the window (older than 8 days, younger than 24 hours) and answered rows inside it.+ for (let i = 0; i < 10; i++) await f.ask(40 * DAY + i * HOUR)+ for (let i = 0; i < 5; i++) await f.ask(2 * HOUR + i)+ for (let i = 0; i < 10; i++) {+ const id = await f.ask(30 * HOUR + i * HOUR)+ await db.superTabDecision.update({ where: { id }, data: { answeredAt: new Date(NOW - HOUR), choice: 0 } })+ }+ await f.ask(25 * HOUR)+ await f.ask(24 * HOUR + 1000)+ const found: Array<unknown> = []+ const entries = await profiled(db, async () => { found.push(...await overdueDecisions(db, NOW)) })+ const read = reads(entries, 'SuperTabDecision', ['createdAt'])+ const explain = JSON.stringify(plan(read))+ expect(found).toHaveLength(2)+ expect(read, explain).toHaveLength(1)+ expect(read[0]!.planSummary, explain).toMatch(/IXSCAN \{ answeredAt: 1, createdAt: 1 \}/)+ expect(read[0]!.docsExamined, explain).toBeLessThanOrEqual(found.length + 1)+ expect(OVERDUE_DECISION_MS).toBe(DAY)+ })+})diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 0c575fd2e..35fd81e44 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1340,6 +1340,8 @@ model SuperTabDecision {note String?/// The person asked left it to the PM, who took the recommended option: never shown as their own choice.delegated Boolean?+ /// With `delegated`: the hourly sweep left it to the PM after 24 hours unanswered, not the person (overdueDecisions.ts).+ overdue Boolean?/// "routing-reflection" for a proposal of the nightly routing reflection (costs/reflection.ts): never a Buddy's to read,/// and an approved one is kept past the ledger's weeks. Absent on every other decision.kind String?@@ -1353,6 +1355,8 @@ model SuperTabDecision {@@index([tabId, projectId, createdAt])/// The decisions waiting in a conversation whose work ended (decisions.ts withdrawIn).@@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")}/// 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 d8617aef2..ea67c732c 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -429,6 +429,9 @@ export interface CommandContext {/** A Workspace removal taking the person out of this Swarm (workspaceStore.ts): it reaches a deleted Swarm too, so a restore* never brings them back (security review 2 of #2457). Set by the store alone. */workspaceLeave?: true+ /** 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/** 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@@ -2088,7 +2091,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 })+ { choice: command.choice, note: command.note ?? null, delegate: command.delegate === true, overdue: context.overdue === true })effects.decisionAnswer = answerrecordDecision(conversation(state, context.decision!.conversationId), context.decision!, context.now, answer.delegated === true)if (recipients.length) message(noticeIn, notice, recipients, null, source)diff --git a/backend/src/superTabs/decisions.test.ts b/backend/src/superTabs/decisions.test.tsindex cb669f65b..7e7ec7744 100644--- a/backend/src/superTabs/decisions.test.ts+++ b/backend/src/superTabs/decisions.test.ts@@ -3,7 +3,7 @@ import { storeOldLeads } from './leads.test-support.js'import type { Prisma } from '@prisma/client'import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'-import { checkAsker, decisionsWaiting, listDecisions, waitingInProject, withdrawIn, workEnded, workOver, type DecisionTarget } from './decisions.js'+import { checkAsker, decisionsWaiting, listDecisions, overdueNotice, delegatedNotice, answerDecision, waitingInProject, withdrawIn, workEnded, workOver, type DecisionTarget } from './decisions.js'import { buddyChatId } from './buddies.js'const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }@@ -196,6 +196,26 @@ describe('leaving a decision to the PM', () => {expect(() => s.run({ type: 'decision.answer', decisionId: 'decision-1' }, peer, { decision: open(s) })).toThrow('or leave it to the PM')expect(commandSchema.safeParse({ type: 'decision.answer', decisionId: 'decision-1', delegate: false }).success).toBe(false)})++ it('an overdue answer takes the recommended option and says it waited 24 hours', () => {+ const s = swarm()+ const answered = s.run({ type: 'decision.answer', decisionId: 'decision-1', delegate: true }, peer, { decision: open(s), overdue: true })+ expect(answered.decisionAnswer).toEqual({ id: 'decision-1', choice: 1, note: null, delegated: true, overdue: true })+ expect(answered.messages[0]!.text).toBe(overdueNotice('Product Manager'))+ })++ it('overdue without delegate is refused', () => {+ const s = swarm()+ expect(() => answerDecision(s.state, peer, open(s), { choice: 0, note: null, delegate: false, overdue: true }))+ .toThrow(expect.objectContaining({ code: 'INVALID_DECISION', status: 400 }))+ })++ it('a person\'s delegate is not overdue', () => {+ const s = swarm()+ const answered = delegate(s, peer, open(s))+ expect(answered.decisionAnswer).not.toHaveProperty('overdue')+ expect(answered.messages[0]!.text).toBe(delegatedNotice('Product Manager'))+ })})describe('listing a person\'s decisions', () => {@@ -306,6 +326,17 @@ describe('a decision whose work is over', () => {expect((await listDecisions(read, 'tab', s.state, peer, 'settled')).decisions.map(d => d.id)).toEqual(['open-task', 'done-task', 'project-chat'])})+ it('says which decisions the 24-hour sweep takes over: not a reflection, not a recommended option that does not exist', async () => {+ const s = swarm()+ const row = (id: string, extra: Record<string, unknown>) => ({ id, batchId: id, projectId: 'lead', conversationId: 'lead', assignmentId: null, personId: 'peer',+ askerAgentId: s.lead, question: id, options: ['A', 'B'], recommended: 0, unblocks: 'X', createdAt: new Date(1), answeredAt: null, choice: null,+ note: null, delegated: null, ...extra })+ const rows = [row('plain', {}), row('reflection', { kind: 'routing-reflection' }), row('out-of-range', { recommended: 9 }), row('negative', { recommended: -1 })]+ const tx = { superTabDecision: { findMany: async () => rows } } as unknown as Prisma.TransactionClient+ const listed = (await listDecisions(tx, 'tab', s.state, peer, 'open')).decisions+ expect(Object.fromEntries(listed.map(d => [d.id, d.pmTakesOver]))).toEqual({ plain: true, reflection: false, 'out-of-range': false, negative: false })+ })+it('takes no new question in finished work, where it would wait for nobody', () => {const s = swarm()const ask = () => s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer', questions: [question('Reopen it?')] }, asAgent(s.lead))diff --git a/backend/src/superTabs/decisions.ts b/backend/src/superTabs/decisions.tsindex 16fa6625f..1832c129a 100644--- a/backend/src/superTabs/decisions.ts+++ b/backend/src/superTabs/decisions.ts@@ -51,7 +51,9 @@ export interface DecisionTarget {withdrawn?: boolean}/** `delegated`: the person asked left it to the PM, who took the recommended option. */-export interface DecisionAnswer { id: string; choice: number; note: string | null; delegated?: true }+export interface DecisionAnswer { id: string; choice: number; 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 }/** 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[],@@ -107,6 +109,9 @@ export const ANSWERED_NOTICE = 'A decision asked in this conversation was answer* its coordinator (instructions.ts coordinatorNameOf). */export 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 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". */export const CLOSED_CHAT_ANSWERED_NOTICE = 'A decision you asked in a closed Chat with PM was answered. Read the answer with: harness super-tab decisions --answered'export const closedChatDelegatedNotice = (name: string) => `A decision you asked in a closed Chat with PM was left to the ${name}, who took its recommended option. `@@ -119,8 +124,9 @@ 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 }) {+ given: { choice?: number; note: string | null; delegate: boolean; overdue?: boolean }) {if ((given.choice === undefined) === !given.delegate) fail('INVALID_DECISION', 'Choose one of its options, or leave it to the PM.', 400)+ if (given.overdue && !given.delegate) fail('INVALID_DECISION', 'Only a decision left to the PM can be overdue.', 400)const group = answerable(state, actor, decision)const asked = decision!if (asked.withdrawn || workOver(state, group)) fail('DECISION_ANSWERED', NO_LONGER_WAITS)@@ -134,10 +140,11 @@ export function answerDecision(state: SuperTabState, actor: Actor, decision: Decconst lead = state.conversations.find(c => c.id === project.leadConversationId)?.leadIdconst closed = isClosedPmChat(group)const noticeIn = closed ? state.conversations.find(c => c.id === project.leadConversationId)! : group- const notice = given.delegate ? (closed ? closedChatDelegatedNotice : delegatedNotice)(coordinatorNameOf(project))+ const delegatedText = closed ? closedChatDelegatedNotice : given.overdue ? overdueNotice : delegatedNotice+ const notice = 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 } : {} }+ const answer: DecisionAnswer = { id: asked.id, choice, note: given.note, ...given.delegate ? { delegated: true as const, ...given.overdue ? { overdue: 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, choice) : nullreturn { answer, noticeIn: noticeIn.id, notice, recipients, source: { ...AGENT_ONLY, decisionId: asked.id }, line }@@ -269,7 +276,8 @@ export async function readAskedDecision(tx: Tx, tabId: string, id: string): Prom/** Conflicts with a concurrent answer of the same decision: only the first one counts. */export 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 } : {} } })+ data: { choice: answer.choice, note: answer.note, answeredAt: new Date(now), ...answer.delegated ? { delegated: true } : {},+ ...answer.overdue ? { overdue: true } : {} } })if (!taken.count) fail('DECISION_ANSWERED', 'This decision is already answered.')}@@ -382,7 +390,9 @@ 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,+ delegated: row.delegated === true, overdue: row.overdue === 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,answer: row.choice == null || row.options[row.choice] === undefined ? null : answerText(row.options[row.choice]!, row.delegated === true) }}) }}diff --git a/backend/src/superTabs/overdueDecisions.ts b/backend/src/superTabs/overdueDecisions.tsnew file mode 100644index 000000000..7bfa10f70--- /dev/null+++ b/backend/src/superTabs/overdueDecisions.ts@@ -0,0 +1,22 @@+import type { PrismaClient } from '@prisma/client'+import { REFLECTION_DECISION } from './decisions.js'++/** A decision its person leaves unanswered this long goes to the PM (spec: Diego, 2026-11-04). The clock never restarts. */+export const OVERDUE_DECISION_MS = 24 * 60 * 60_000+/** A pass reads decisions asked within this reach: older ones are never taken, so a row that keeps failing stops being retried. */+export const OVERDUE_REACH_MS = 8 * 24 * 60 * 60_000+export const OVERDUE_PER_PASS = 500+const at = (ms: number) => ({ $date: new Date(ms).toISOString() })++/**+ * The still-waiting decisions asked in `(now - 8 days, now - 24h]`, oldest first, at most `limit` a pass. One `aggregateRaw` on the+ * `decision_waiting_created` index, never a Prisma `in` (backend/AGENTS.md). `answeredAt: null` matches a missing field too, as intended.+ * No cursor is kept: a row that fails or exceeds the cap is read again by every later pass until it is 8 days old, and a person+ * answering removes it from the index range. Routing proposals (`kind`) and withdrawn decisions are never the PM's to take.+ */+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 } } },+ { $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) }))+}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex b55faaa4c..7bf2107b2 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -91,6 +91,7 @@ import { APPROVE, approvedLine, localDate, MAX_PROPOSALS, proposalQuestion, propimport { 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 { 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'@@ -1325,6 +1326,41 @@ 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.+ */+ async leaveOverdueDecisions(now: number, limit = OVERDUE_PER_PASS): Promise<{ answered: number; skipped: number; failed: number }> {+ const rows = await overdueDecisions(this.db, now, limit)+ const result = { answered: 0, skipped: 0, failed: 0 }+ const tabs = new Map<string, AuthUser['autonomousEnv'] | null>()+ const codes = new Set<string>()+ 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 }+ 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, 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 }+ 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] })+ return result+ }+async execute(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string,client?: DeclaredClient) {try {@@ -1413,7 +1449,7 @@ export class SuperTabStore {}private async executeOnce(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string,- workspaceLeave = false) {+ workspaceLeave = false, overdue = false) {const { operationId, command } = operationSchema.parse(input)const pushOrigin = await this.pushOriginFor(user, tabId, command)let ended: WorkHold[] = [], started: WorkHold[] = []@@ -1500,7 +1536,8 @@ export class SuperTabStore {return replyOf(prior)}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 } : {}) }+ const context: CommandContext = { operationId, now: this.now(), ...(leavingDeleted ? { workspaceLeave: true as const } : {}),+ ...(overdue && command.type === 'decision.answer' ? { overdue: true as const } : {}) }if (command.type === 'swarm.restore' && original.deletion && original.workspaceId) {const lost: string[] = []for (const person of original.people) if (!await hasWorkspaceAccess(tx, original, person.id)) lost.push(person.id)diff --git a/backend/src/superTabs/sweeps.ts b/backend/src/superTabs/sweeps.tsindex d86ae185e..47b172d4f 100644--- a/backend/src/superTabs/sweeps.ts+++ b/backend/src/superTabs/sweeps.ts@@ -214,10 +214,16 @@ 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>): () => void {+export function startSwarmSweeps(db: PrismaClient, everyMs = 3_600_000, finishWorkspaceRemovals?: () => Promise<number>,+ leaveOverdueDecisions?: (now: number) => Promise<unknown>): () => 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 3df5eafef..ed21d86fa 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -138,7 +138,7 @@ 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())+ stopSweeps = startSwarmSweeps(prisma, undefined, () => swarms.workspaces.finishRemovals(), 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)// Finished groups archive once GitHub says their pull requests are merged or closed; without the app, only groups thatdiff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex addc4906f..4505f1b60 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -6,7 +6,7 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts','integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabCacheDelta.test.ts', 'integration/superTabHostGroups.test.ts', 'integration/superTabMachineReports.test.ts', 'integration/superTabMachineLiveness.test.ts', 'integration/superTabHeldParts.test.ts','integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabNotAvailable.test.ts','integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabPersonalLead.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',- 'integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts',+ 'integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/overdueDecisions.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts','integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabPmSchedule.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts','integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/desktop/lib/super_tabs/activity.dart b/desktop/lib/super_tabs/activity.dartindex 281bb4aa3..27eeda698 100644--- a/desktop/lib/super_tabs/activity.dart+++ b/desktop/lib/super_tabs/activity.dart@@ -3,6 +3,7 @@ import 'dart:async';import 'package:clock/clock.dart';import 'package:flutter/widgets.dart';+import 'activity_rows.dart';import 'attention.dart';import 'controller.dart';import 'decisions.dart';@@ -11,10 +12,10 @@ import 'notifications.dart';import 'reminders.dart';/// What one row of Needs you is.-enum SuperTabNeedKind { decision, agent, mention }+enum SuperTabNeedKind { decision, agent }-/// One row of Needs you: a decision asked of the reader, an agent waiting on-/// them, or a tag of them.+/// One row of Needs you: a decision asked of the reader, or an agent waiting+/// on them.class SuperTabNeed {const SuperTabNeed({required this.kind,@@ -23,36 +24,32 @@ class SuperTabNeed {required this.conversationId,this.at,this.decision,- this.mention,- this.privateProjectName,+ this.question,});final SuperTabNeedKind kind;- /// Stable across reads: `decision:<id>`, `agent:<group>`, `mention:<id>`.+ /// Stable across reads: `decision:<id>`, `agent:<group>`.final String id;- /// What the row says: the question, `<agent> is waiting on you`, or- /// `<author> mentioned you in # <project>`; a private project carries its- /// name separately for the lock mark.+ /// What the row says: the question, or `<agent> is waiting on you`.final String title;final String conversationId;final DateTime? at;final SuperTabDecision? decision;- final SuperTabMention? mention;- /// When a mention names a private project, its lock replaces the textual #.- final String? privateProjectName;+ /// What an agent row asks: the question the task is waiting on, else the+ /// task's title. Null for a decision, which has its own.+ final String? question;}/// The reader's Activity in one Swarm: the one place for everything new for/// them (Quiet Swarm design, screens 6 and 11b). Three lists over what the/// Swarm already holds, no feed of its own:///-/// * Needs you: decisions asked of them, agents waiting on them and their-/// tags. Its length is Activity's number.-/// * Reminders: messages they asked to come back to, once due.-/// * New replies: the followed threads with replies they have not read.-/// * Done today: tasks that shipped today.+/// * Needs you: reminders they set that are due, decisions asked of them and+/// agents waiting on them. Its length is Activity's number.+/// * Mentions: the tags of them, folded by author and chat.+/// * Threads: the followed threads with replies they have not read.////// Leaving the view marks nothing read: it shows no reply or reaction row,/// and a thread is read when it is opened. One per controller.@@ -87,24 +84,15 @@ class SuperTabActivity extends ChangeNotifier {SuperTabSnapshot? get _snapshot =>controller.accessRevoked ? null : controller.snapshot;- /// Decisions asked of the reader, then agents waiting on them, then their- /// tags; each newest first.+ /// Decisions asked of the reader, then agents that asked them by name; each+ /// newest first. Tags are not here: they are the Mentions list.List<SuperTabNeed> get needsYou {final snapshot = _snapshot;if (snapshot == null) return const [];- bool isPrivateProject(String projectId) =>- snapshot.projects- .where((p) => p.id == projectId)- .firstOrNull- ?.isPrivate ==- true;final epoch = DateTime.fromMillisecondsSinceEpoch(0);- final asked = decisions.open;- final decided = {for (final d in asked) d.conversationId};- final people = {for (final p in snapshot.people) p.id: p};return [for (final d in [- ...asked,+ ...decisions.open,]..sort((a, b) => (b.createdAt ?? epoch).compareTo(a.createdAt ?? epoch)))SuperTabNeed(kind: SuperTabNeedKind.decision,@@ -114,30 +102,14 @@ class SuperTabActivity extends ChangeNotifier {at: d.createdAt,decision: d,),- for (final group in snapshot.conversations)- if (_waiting(snapshot, group, decided))- SuperTabNeed(- kind: SuperTabNeedKind.agent,- id: 'agent:${group.id}',- title:- '${_agentName(snapshot, group.assignment!['agentId'] as String)} is waiting on you',- conversationId: group.id,- ),- for (final m in [- ..._tags,- ]..sort((a, b) => (b.createdAt ?? epoch).compareTo(a.createdAt ?? epoch)))+ for (final group in _asking(snapshot))SuperTabNeed(- kind: SuperTabNeedKind.mention,- id: 'mention:${m.id}',+ kind: SuperTabNeedKind.agent,+ id: 'agent:${group.id}',title:- '${people[m.leadId]?.shownName ?? m.leadName} mentioned you in '- '${isPrivateProject(m.projectId) ? '' : '# ${m.projectName}'}',- conversationId: m.conversationId,- at: m.createdAt,- mention: m,- privateProjectName: isPrivateProject(m.projectId)- ? m.projectName- : null,+ '${_agentName(snapshot, group.assignment!['agentId'] as String)} is waiting on you',+ conversationId: group.id,+ question: _askedBy(group),),];}@@ -146,34 +118,47 @@ class SuperTabActivity extends ChangeNotifier {/// answered, past any read mark. Not `1 << 52`: a shift is 32 bits on the web.static const _unknown = 9007199254740991;- /// The tags that need the reader: not read past (the number clears by- /// reading). A tagged thread may also be in New replies; its mention remains- /// a separate Needs you item so the conversation badge represents it.+ /// The tags that are not read past (the number clears by reading). They are+ /// bold in Mentions but never counted: a tag asks for nothing.Iterable<SuperTabMention> get _tags {return mentions.waiting.where(mentionUnread);}- /// A task whose agent waits on the reader (it needs a decision, or is- /// stuck) and has not already asked it as a decision.+ /// The tasks whose agent asked the reader by name, newest chat first. Only+ /// once the decisions are loaded: that list says which of them is already+ /// a decision, and a task with one must not count twice.+ List<SuperTabConversation> _asking(SuperTabSnapshot snapshot) {+ if (!decisions.loaded) return const [];+ final decided = {for (final d in decisions.open) d.conversationId};+ return [+ for (final g in snapshot.conversations)+ if (_waiting(snapshot, g, decided)) g,+ ]..sort((a, b) => b.lastMessageSequence.compareTo(a.lastMessageSequence));+ }++ /// A task whose agent asked the reader by name and has not already asked it+ /// as a decision. A stuck task nobody was asked about stays with the PM.bool _waiting(SuperTabSnapshot snapshot,SuperTabConversation group,Set<String> decided,) {final work = group.assignment;- if (work == null ||- group.closed ||- group.isBuddyChat ||- decided.contains(group.id) ||- !superTabWorkWaits(work['status']) ||- snapshot.agent(work['agentId'] as String? ?? '') == null) {- return false;- }- // Whoever it asked, else whoever asked for the task, else the Swarm's- // owner: a task waiting on nobody named is for no other reader.- final forThem =- work['askedOf'] as String? ?? group.requesterId ?? snapshot.ownerId;- return forThem == controller.accountId;+ return work != null &&+ !group.closed &&+ !group.isBuddyChat &&+ !decided.contains(group.id) &&+ work['status'] == 'needs_human' &&+ work['askedOf'] == controller.accountId &&+ snapshot.agent(work['agentId'] as String? ?? '') != null;+ }++ /// The question a waiting task carries: its assignment's result text is the+ /// agent's ask (task_status.dart reads it the same way); the title when it+ /// has none.+ String _askedBy(SuperTabConversation group) {+ final asked = (group.assignment?['result'] as String?)?.trim();+ return asked == null || asked.isEmpty ? group.title : asked;}String _agentName(SuperTabSnapshot snapshot, String agentId) {@@ -197,42 +182,65 @@ class SuperTabActivity extends ChangeNotifier {if (attention.isNew(t)) t,];- /// Tasks that shipped today (the reader's day), newest first: no review or- /// test step, no Buddy chat.- List<SuperTabConversation> get doneToday {+ /// The Activity row's red number: what was asked of the reader and is+ /// unanswered, plus the reminders they set that are due. Tags, replies and+ /// stuck tasks nobody was asked about are in Activity but add nothing. Until+ /// the decisions are read the server's count stands in for them.+ int get count {final snapshot = _snapshot;- if (snapshot == null) return const [];+ if (snapshot == null) return 0;+ return (decisions.loaded+ ? decisions.open.length+ : snapshot.decisionsWaiting) ++ _asking(snapshot).length ++ reminders.due.length;+ }++ /// Whether the Activity row is bold: something needs the reader, or a tag+ /// or a thread they follow has news they have not read.+ bool get unread => count > 0 || _tags.isNotEmpty || attention.threadsUnread;++ /// What the reader's PM answered for them today, newest first: decisions+ /// they left to the PM, or that waited 24 hours.+ List<SuperTabDecision> get handledToday {final now = clock.now();- bool today(DateTime at) =>- at.year == now.year && at.month == now.month && at.day == now.day;return [- for (final g in snapshot.conversations)- if (g.shippedAt case final at? when today(at.toLocal()))- if (g.reviewOf == null && !g.isBuddyChat) g,- ]..sort((a, b) => b.shippedAt!.compareTo(a.shippedAt!));+ for (final d in decisions.answered)+ if (d.delegated &&+ d.answeredAt != null &&+ dayOf(d.answeredAt!.toLocal(), now) == SuperTabDay.today)+ d,+ ]..sort((a, b) => b.answeredAt!.compareTo(a.answeredAt!));}- /// The Activity row's red number: what needs the reader, and nothing else.- /// A tag counts until it is read, a decision or an agent waiting until it- /// is answered, a due reminder until it is opened. Before the tags are read the server's count stands in.- int get count {- final snapshot = _snapshot;- if (snapshot == null) return 0;- final decided = {for (final d in decisions.open) d.conversationId};- final tags = mentions.waiting.isEmpty && snapshot.mentionsWaiting > 0- ? snapshot.mentionsWaiting- : _tags.length;- return tags +- reminders.due.length +- snapshot.decisionsWaiting +- snapshot.conversations- .where((g) => _waiting(snapshot, g, decided))- .length;+ /// The tags that wait and the earlier ones (read or answered), newest first,+ /// folded by author and chat; unread ones are bold, the rest are read rows.+ List<SuperTabMentionRow> get mentionRows {+ final epoch = DateTime.fromMillisecondsSinceEpoch(0);+ final all = [...mentions.waiting, ...mentions.earlier];+ // The index breaks ties: `sort` is not stable, and equal times must keep+ // the server's order so neighbours from one author still fold.+ final order = [for (var i = 0; i < all.length; i++) i]+ ..sort((a, b) {+ final byTime = (all[b].createdAt ?? epoch).compareTo(+ all[a].createdAt ?? epoch,+ );+ return byTime != 0 ? byTime : a.compareTo(b);+ });+ return groupMentions([for (final i in order) all[i]], mentionUnread);}- /// Whether the Activity row is bold: something needs the reader, or a thread- /// they follow has replies they have not read.- bool get unread => count > 0 || attention.threadsUnread;+ /// The followed threads with news today.+ List<SuperTabFollowedThread> get threadRows => newReplies;++ /// What the listed [decided] call their PM: the coordinator of their+ /// project, or `the PMs` when they come from several.+ String coordinatorFor(Iterable<SuperTabDecision> decided) {+ final projects = {for (final d in decided) d.projectId};+ final snapshot = _snapshot;+ if (projects.length != 1 || snapshot == null) return 'the PMs';+ return snapshot.coordinatorNameOf(projects.single);+ }/// The view opened: reads what it lists now; what is new stays bold until/// [closed].diff --git a/desktop/lib/super_tabs/activity_rows.dart b/desktop/lib/super_tabs/activity_rows.dartnew file mode 100644index 000000000..4a7810bfc--- /dev/null+++ b/desktop/lib/super_tabs/activity_rows.dart@@ -0,0 +1,109 @@+import 'notifications.dart';++/// Mentions from one author in one chat or thread, folded into the row of the+/// newest: `+{more} more from {author}`.+class SuperTabMentionRow {+ const SuperTabMentionRow({+ required this.newest,+ required this.all,+ required this.unread,+ });+ final SuperTabMention newest;++ /// Every mention in the row, in the order given.+ final List<SuperTabMention> all;++ /// Whether any of them is unread.+ final bool unread;++ /// Whether any of them still waits (not read through Mark read or answered):+ /// the row can be marked read even when the reader has read past it.+ bool get unresolved => all.any((m) => m.resolvedBy == null);+ int get more => all.length - 1;+}++/// Folds neighbours with the same author, chat and thread into one row each.+/// Only neighbours: a later mention from the same author after someone else's+/// stays its own row, so the list keeps its order.+List<SuperTabMentionRow> groupMentions(+ List<SuperTabMention> mentions,+ bool Function(SuperTabMention) isUnread,+) {+ bool sameRow(SuperTabMention a, SuperTabMention b) =>+ (a.leadId ?? a.leadName) == (b.leadId ?? b.leadName) &&+ a.conversationId == b.conversationId &&+ a.threadId == b.threadId;+ final groups = <List<SuperTabMention>>[];+ for (final m in mentions) {+ if (groups.isNotEmpty && sameRow(groups.last.first, m)) {+ groups.last.add(m);+ } else {+ groups.add([m]);+ }+ }+ return [+ for (final g in groups)+ SuperTabMentionRow(+ newest: g.first,+ all: List.unmodifiable(g),+ unread: g.any(isUnread),+ ),+ ];+}++const _subjectLength = 90;++/// What a thread is about, from its root's text: the title when the root+/// carries one (`Title: ...`, up to ` — `, `. ` or the end of the line), else+/// its first line; whitespace collapsed, cut at 90 characters with `…` as the+/// 90th. A root is often a long request, so the whole text would fill the row.+String threadSubject(String rootText) {+ var subject = rootText.split('\n').first;+ final at = rootText.indexOf('Title: ');+ if (at >= 0) {+ final rest = rootText.substring(at + 'Title: '.length).split('\n').first;+ final end = [+ rest.indexOf(' — '),+ rest.indexOf('. '),+ ].where((i) => i >= 0).fold<int>(rest.length, (a, b) => a < b ? a : b);+ subject = rest.substring(0, end);+ }+ subject = subject.trim().replaceAll(RegExp(r'\s+'), ' ');+ return subject.length <= _subjectLength+ ? subject+ : '${subject.substring(0, _subjectLength - 1)}…';+}++/// How long a decision waits before the PM takes it over (the backend sweep).+const _pmTakesOver = Duration(hours: 24);++Duration _left(DateTime createdAt, DateTime now) =>+ createdAt.add(_pmTakesOver).difference(now);++/// When the PM takes the decision over: `PM in {h}h`, hours rounded up, or+/// `PM in <1h` in the last hour.+String pmIn(DateTime createdAt, DateTime now) {+ final left = _left(createdAt, now);+ if (left < const Duration(hours: 1)) return 'PM in <1h';+ return 'PM in ${(left.inMinutes / 60).ceil()}h';+}++/// Whether the PM takes the decision over in under two hours.+bool pmSoon(DateTime createdAt, DateTime now) =>+ _left(createdAt, now) < const Duration(hours: 2);++enum SuperTabDay { today, yesterday, earlier }++/// The reader's day [at] falls on, by local midnight.+SuperTabDay dayOf(DateTime at, DateTime now) {+ final day = DateTime(at.year, at.month, at.day);+ final today = DateTime(now.year, now.month, now.day);+ final days = DateTime.utc(+ today.year,+ today.month,+ today.day,+ ).difference(DateTime.utc(day.year, day.month, day.day)).inDays;+ if (days <= 0) return SuperTabDay.today;+ if (days == 1) return SuperTabDay.yesterday;+ return SuperTabDay.earlier;+}diff --git a/desktop/lib/super_tabs/activity_view.dart b/desktop/lib/super_tabs/activity_view.dartindex b20774f5f..243afb00a 100644--- a/desktop/lib/super_tabs/activity_view.dart+++ b/desktop/lib/super_tabs/activity_view.dart@@ -1,25 +1,31 @@import 'dart:async';import 'package:flutter/material.dart';+import 'package:flutter/semantics.dart' show CustomSemanticsAction;-import '../shared/theme/app_icons.dart';import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../shared/widgets/skeleton.dart';import '../widgets/desktop_chrome.dart';import '../widgets/laid_out_list.dart';import 'activity.dart';+import 'activity_rows.dart';import 'attention.dart';-import 'decisions_view.dart';+import 'avatar_art.dart';+import 'buddy_rows.dart' show SuperTabCountBadge;+import 'decisions.dart';+import 'decisions_view.dart' show quietDecisionAction;import 'machine_status.dart' show superTabAgoShort;import 'model.dart';import 'notifications.dart';import 'private_project_lock.dart';import 'reminders.dart';-import 'section_heading.dart';-/// Activity, the one place for everything new for the reader (Quiet Swarm-/// design, screens 6 and 11b): Needs you, Reminders, New replies, Done today. One line-/// to a row, bold when it is new, no filters. A click opens the thing where-/// it is; a decision opens its card to answer.+enum _Tab { needs, mentions, threads }++/// Activity, the one place for everything new for the reader, one list at a+/// time (Slack's way): Needs you, Mentions and Threads. Only Needs you has a+/// red number. A row says who said what; a click opens the thing where it is.class SuperTabActivityView extends StatefulWidget {const SuperTabActivityView({super.key,@@ -36,7 +42,7 @@ class SuperTabActivityView extends StatefulWidget {/// Opens a followed thread in its chat: chat, the thread's root message.final void Function(String conversationId, String rootId) onOpenThread;- /// Opens the chat of an agent waiting on the reader, or of a task done.+ /// Opens the chat of an agent waiting on the reader, or of a decision.final ValueChanged<String> onOpenConversation;/// Opens a due reminder's message, which clears it.@@ -48,14 +54,22 @@ class SuperTabActivityView extends StatefulWidget {}class _SuperTabActivityViewState extends State<SuperTabActivityView> {- final _marking = <String>{};- final _answering = <String>{};late SuperTabActivity _activity = widget.activity;+ _Tab _tab = _Tab.needs;++ /// The opening tab is chosen once: when the decisions are read (or failed+ /// to be), or as soon as the reader does anything here. Until then more+ /// arriving may still change it; after, it never moves under their hands.+ bool _settled = false;+ bool _mentionsUnreadOnly = false;+ bool _handledShown = false;@overridevoid initState() {super.initState();_activity.opened();+ _tab = _opening();+ _settled = _readEnough(_activity);}@override@@ -73,12 +87,30 @@ class _SuperTabActivityViewState extends State<SuperTabActivityView> {super.dispose();}- Future<void> _done(SuperTabMention mention) async {- setState(() => _marking.add(mention.id));- await _activity.mentions.done(mention);- if (mounted) setState(() => _marking.remove(mention.id));+ /// Needs you when something needs the reader, else the first tab with+ /// unread rows, else Needs you.+ _Tab _opening() {+ if (_activity.needsYou.isNotEmpty) return _Tab.needs;+ if (_activity.mentionRows.any((r) => r.unread)) return _Tab.mentions;+ if (_activity.threadRows.isNotEmpty) return _Tab.threads;+ return _Tab.needs;}+ /// The reader acted: the tab they are on stays, whatever arrives.+ void _settle() => _settled = true;++ /// Whether the opening tab can be chosen for good: the decisions and the+ /// tags have each answered or failed. Settling on the decisions alone left+ /// the view on an empty Needs you while unread tags were still on their way.+ static bool _readEnough(SuperTabActivity a) =>+ (a.decisions.loaded || a.decisions.error != null) &&+ (a.mentions.loaded || a.mentions.error != null);++ void _choose(_Tab tab) => setState(() {+ _tab = tab;+ _settle();+ });+/// Today's clock time, else how long ago: a row's one word of when.String _when(DateTime at) {final now = widget.now(), local = at.toLocal();@@ -91,117 +123,587 @@ class _SuperTabActivityViewState extends State<SuperTabActivityView> {return superTabAgoShort(now.difference(local));}- /// Starts where a row's mark does: the row's own two insets.- Widget _heading(String title) => Padding(+ SuperTabSnapshot? get _snapshot => _activity.controller.snapshot;++ bool _isPrivate(String projectId) =>+ _snapshot?.projects+ .where((p) => p.id == projectId)+ .firstOrNull+ ?.isPrivate ==+ true;++ String _oneLine(String text) => text.replaceAll(RegExp(r'\s+'), ' ').trim();++ Future<void> _confirmDecideAll(+ List<SuperTabDecision> deciding,+ String name,+ ) async {+ final confirmed = await showAppDialog<bool>(+ context: context,+ builder: (context) => AlertDialog(+ title: Text('Let $name decide all ${deciding.length}?'),+ content: Text(+ '${deciding.length} ${deciding.length == 1 ? 'decision' : 'decisions'}: '+ '$name takes each one\'s recommended option.',+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(context, false),+ child: const Text('Cancel'),+ ),+ FilledButton(+ key: const ValueKey('super-activity-decide-all-confirm'),+ onPressed: () => Navigator.pop(context, true),+ child: Text('Let $name decide'),+ ),+ ],+ ),+ );+ if (confirmed == true) {+ _settle();+ unawaited(_activity.decisions.delegateAll(deciding));+ }+ }++ // ---- Chrome: tabs and bars ----++ Widget _tabButton(_Tab tab, String key, String label, int count) {+ final selected = _tab == tab;+ final color = selected ? DesktopChrome.foreground : DesktopChrome.muted;+ return Semantics(+ selected: selected,+ button: true,+ child: InkWell(+ key: ValueKey(key),+ onTap: () => _choose(tab),+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ child: Container(+ padding: const EdgeInsets.only(bottom: grid.AppDesktop.controlGap),+ decoration: BoxDecoration(+ border: Border(+ bottom: BorderSide(+ width: 2,+ color: selected ? DesktopChrome.foreground : Colors.transparent,+ ),+ ),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ label,+ style: DesktopChrome.control(color: color)+ .copyWith(fontWeight: grid.AppFont.semibold),+ ),+ if (count > 0) ...[+ const SizedBox(width: grid.AppDesktop.controlGap - 2),+ if (tab == _Tab.needs)+ SuperTabCountBadge(count)+ else+ Text(+ '$count',+ style: DesktopChrome.metadata(color: DesktopChrome.muted)+ .copyWith(fontWeight: grid.AppFont.semibold),+ ),+ ],+ ],+ ),+ ),+ ),+ );+ }++ Widget _tabs({+ required int needs,+ required int mentions,+ required int threads,+ }) => Container(padding: const EdgeInsets.fromLTRB(- grid.AppDesktop.controlGap + grid.AppDesktop.groupGap,grid.AppDesktop.groupGap,grid.AppDesktop.groupGap,- grid.AppDesktop.menuInset,+ grid.AppDesktop.groupGap,+ 0,+ ),+ decoration: BoxDecoration(+ border: Border(bottom: BorderSide(color: grid.AppPalette.divider)),+ ),+ child: Wrap(+ spacing: grid.AppDesktop.groupGap + grid.AppDesktop.controlGap,+ children: [+ _tabButton(_Tab.needs, 'super-activity-tab-needs', 'Needs you', needs),+ _tabButton(+ _Tab.mentions,+ 'super-activity-tab-mentions',+ 'Mentions',+ mentions,+ ),+ _tabButton(+ _Tab.threads,+ 'super-activity-tab-threads',+ 'Threads',+ threads,+ ),+ ],+ ),+ );++ Widget _bar(List<Widget> children) => Container(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.groupGap,+ vertical: grid.AppDesktop.controlGap,+ ),+ decoration: BoxDecoration(+ border: Border(bottom: BorderSide(color: grid.AppPalette.divider)),+ ),+ child: Wrap(+ crossAxisAlignment: WrapCrossAlignment.center,+ runSpacing: grid.AppDesktop.controlGap,+ spacing: grid.AppDesktop.groupGap,+ children: children,),- child: SuperTabSectionHeading(title, startInset: 0, endInset: 0),);- Widget _empty(String text) => Padding(- // Under the page title's edge.+ Widget _unreadsOnly() => Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text('Unreads only', style: DesktopChrome.metadata()),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Transform.scale(+ scale: .8,+ child: Switch(+ key: const ValueKey('super-activity-unreads-only'),+ value: _mentionsUnreadOnly,+ onChanged: (on) => setState(() {+ _settle();+ _mentionsUnreadOnly = on;+ }),+ ),+ ),+ ],+ );++ Widget _markAll(VoidCallback? onPressed) => quietDecisionAction(+ key: const ValueKey('super-activity-mark-all-read'),+ label: 'Mark all read',+ onPressed: onPressed,+ );++ Widget _heading(String title) => Padding(padding: const EdgeInsets.fromLTRB(- grid.AppDesktop.panelPadding,+ grid.AppDesktop.groupGap + grid.AppDesktop.controlGap,+ grid.AppDesktop.groupGap,grid.AppDesktop.groupGap,- grid.AppDesktop.panelPadding,- grid.AppDesktop.controlGap,+ grid.AppDesktop.listRowGap,+ ),+ child: Text(+ title,+ style: DesktopChrome.metadata(color: grid.AppPalette.textFaint)+ .copyWith(fontWeight: grid.AppFont.semibold),+ ),+ );++ Widget _empty(String title, [String? more, Widget? action]) => Padding(+ padding: const EdgeInsets.all(grid.AppDesktop.groupGap * 2),+ child: Column(+ children: [+ Text(+ title,+ style: DesktopChrome.text(medium: true)+ .copyWith(fontWeight: grid.AppFont.semibold),+ ),+ if (more != null) ...[+ const SizedBox(height: grid.AppDesktop.listRowGap * 2),+ Text(+ more,+ textAlign: TextAlign.center,+ style: DesktopChrome.control(color: DesktopChrome.muted),+ ),+ ],+ ?action,+ ],),- child: Text(text, style: DesktopChrome.metadata()),);+ /// Day headings between runs of rows already in newest-first order.+ List<Widget> _byDay<T>(+ List<T> items,+ DateTime? Function(T) at,+ Widget Function(T) row,+ ) {+ final now = widget.now();+ final out = <Widget>[];+ SuperTabDay? last;+ for (final item in items) {+ final when = at(item);+ // A row with no date belongs to the day it follows.+ final day = when == null+ ? (last ?? SuperTabDay.today)+ : dayOf(when.toLocal(), now);+ if (day != last) {+ last = day;+ out.add(+ _heading(switch (day) {+ SuperTabDay.today => 'Today',+ SuperTabDay.yesterday => 'Yesterday',+ SuperTabDay.earlier => 'Earlier',+ }),+ );+ }+ out.add(row(item));+ }+ return out;+ }++ // ---- Needs you ----++ List<Widget> _needsYou() {+ final a = _activity;+ // Until the decisions are read the list is not known: neither "nothing"+ // nor a count. A failed read says so above, with Retry.+ if (!a.decisions.loaded) {+ return a.decisions.error != null+ ? const []+ : [+ SkeletonList(+ key: const ValueKey('super-activity-skeleton'),+ rows: 3,+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.controlGap,+ ),+ itemBuilder: (context, _) => const SkeletonListTile(+ leading: 32,+ leadingRadius: 8,+ padding: EdgeInsets.all(grid.AppDesktop.controlGap),+ ),+ ),+ ];+ }+ final needs = a.needsYou;+ final due = a.reminders.due;+ final decided = [+ for (final n in needs)+ if (n.decision != null) n,+ ];+ // Only these can be left to the PM, and only these the bar speaks of.+ final delegatable = [+ for (final n in decided)+ if (n.decision!.canDelegate) n.decision!,+ ];+ final bar = delegatable.isEmpty+ ? null+ : () {+ final name = a.coordinatorFor(delegatable);+ final busy = delegatable.any(+ (d) => a.decisions.answering.contains(d.id),+ );+ return _bar([+ Text(+ name == 'the PMs'+ ? '$name take over anything you leave for 24 hours'+ : '$name takes over anything you leave for 24 hours',+ style: DesktopChrome.metadata(),+ ),+ FilledButton(+ key: const ValueKey('super-activity-decide-all'),+ onPressed: busy+ ? null+ : () => unawaited(_confirmDecideAll(delegatable, name)),+ child: Text('Let $name decide for all'),+ ),+ ]);+ }();+ if (needs.isEmpty && due.isEmpty) {+ final handled = a.handledToday;+ final name = a.coordinatorFor(handled);+ return [+ _empty(+ 'Nothing needs you',+ handled.isEmpty+ ? null+ : '$name handled ${handled.length} for you today',+ handled.isEmpty+ ? null+ : quietDecisionAction(+ key: const ValueKey('super-activity-handled'),+ label: 'See what',+ onPressed: () =>+ setState(() => _handledShown = !_handledShown),+ ),+ ),+ if (_handledShown && handled.isNotEmpty)+ for (final d in handled) _handledRow(d),+ ];+ }+ return [+ ?bar,+ // A reminder the reader set is theirs to answer: it leads, above the+ // decisions, and is not left to the PM.+ for (final reminder in due) _reminder(reminder),+ // An agent waiting has no time of its own: it leads, above the days.+ for (final n in needs)+ if (n.decision == null) _need(n),+ ..._byDay<SuperTabNeed>(decided, (n) => n.at, _need),+ ];+ }++ Widget _handledRow(SuperTabDecision d) {+ final choice = d.choice;+ return Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.groupGap * 2,+ vertical: grid.AppDesktop.listRowGap,+ ),+ child: Row(+ children: [+ Expanded(+ child: Text(+ d.question,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(),+ ),+ ),+ const SizedBox(width: grid.AppDesktop.groupGap),+ if (choice != null && choice >= 0 && choice < d.options.length)+ Text(d.options[choice], style: DesktopChrome.metadata()),+ ],+ ),+ );+ }+Widget _need(SuperTabNeed need) {final decision = need.decision;- final mention = need.mention;- final open = decision != null && _answering.contains(decision.id);- final row = _Row(+ if (decision == null) {+ final project = _snapshot?.projectFor(need.conversationId);+ return _ActivityRow(+ key: ValueKey('super-activity-row-${need.id}'),+ unread: true,+ avatarName: need.title,+ who: need.title,+ where: project?.name,+ privateWhere: project?.isPrivate == true,+ trailing: 'Open',+ preview: _oneLine(need.question ?? ''),+ onTap: () => widget.onOpenConversation(need.conversationId),+ );+ }+ final now = widget.now(), created = decision.createdAt;+ // The sweep takes only what it can answer, and only within its window.+ final pmComing =+ decision.pmTakesOver &&+ created != null &&+ now.difference(created) < const Duration(days: 8);+ return _ActivityRow(key: ValueKey('super-activity-row-${need.id}'),- // The design's @: the icon set has none, and it adds none.- glyph: need.kind == SuperTabNeedKind.mention ? '@' : null,- mark: need.kind == SuperTabNeedKind.mention ? null : AppIcons.circleDot,- title: need.title,- privateProjectName: need.privateProjectName,unread: true,- trailing: switch (need.kind) {- SuperTabNeedKind.decision => 'Answer',- SuperTabNeedKind.agent => 'Open',- SuperTabNeedKind.mention => need.at == null ? '' : _when(need.at!),- },- hoverAction: mention != null && mention.resolvedBy == null- ? (- label: 'Mark done',- busy: _marking.contains(mention.id),- run: () => unawaited(_done(mention)),- )- : null,- onTap: () {- if (decision != null) {- setState(() {- if (!_answering.remove(decision.id)) _answering.add(decision.id);- });- } else if (mention != null) {- widget.onOpenMention(mention);- } else {- widget.onOpenConversation(need.conversationId);- }- },- );- if (!open) return row;- return Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- row,- SuperTabDecisionCard(- decisions: _activity.decisions,- decision: decision,- ),- ],+ avatarName: decision.askerName,+ who: decision.askerName,+ where: decision.projectName,+ privateWhere: _isPrivate(decision.projectId),+ trailing: pmComing+ ? pmIn(created, now)+ : created == null+ ? ''+ : _when(created),+ trailingWarn: pmComing && pmSoon(created, now),+ preview: decision.question,+ previewStrong: true,+ previewLines: 2,+ extra: _options(decision),+ onTap: () => widget.onOpenConversation(decision.conversationId),);}Widget _reminder(SuperTabReminder reminder) {- final text = reminder.text.replaceAll(RegExp(r'\s+'), ' ').trim();- return _Row(+ final project = _snapshot?.projectFor(reminder.conversationId);+ final name = reminder.authorName?.trim() ?? '';+ final who = name.isEmpty ? 'Reminder' : name;+ final text = _oneLine(reminder.text);+ return _ActivityRow(key: ValueKey('super-activity-row-reminder:${reminder.id}'),- mark: AppIcons.clock,- title: [- if (reminder.authorName case final name? when name.isNotEmpty) name,- text.isEmpty ? reminder.conversationTitle : text,- ].join(': '),unread: true,+ avatarName: who,+ who: who,+ where: project?.name,+ privateWhere: project?.isPrivate == true,trailing: _when(reminder.dueAt),+ preview: text.isEmpty ? reminder.conversationTitle : text,onTap: () => widget.onOpenReminder?.call(reminder),);}- Widget _thread(SuperTabFollowedThread thread) {- final text = thread.rootText.replaceAll(RegExp(r'\s+'), ' ').trim();- return _Row(- key: ValueKey('super-activity-row-thread:${thread.key}'),- mark: AppIcons.reply,- title: text.isEmpty ? 'Thread' : text,- unread: true,- trailing: '${_activity.attention.newCount(thread)} new',- hoverAction: (- label: 'Unfollow',- busy: _activity.attention.following.contains(thread.key),- run: () => unawaited(_activity.attention.setFollow(thread, false)),+ Widget _options(SuperTabDecision decision) {+ final decisions = _activity.decisions;+ final busy = decisions.answering.contains(decision.id);+ return Padding(+ padding: const EdgeInsets.only(top: grid.AppDesktop.controlGap),+ child: Wrap(+ spacing: grid.AppDesktop.controlGap,+ runSpacing: grid.AppDesktop.controlGap,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ for (final (index, option) in decision.options.indexed)+ _option(decision, index, option, busy),+ if (decisions.failedToSend(decision))+ Text(SuperTabDecisions.sendFailed, style: DesktopChrome.metadata()),+ if (decisions.failedToSend(decision))+ quietDecisionAction(+ key: ValueKey('super-activity-retry:${decision.id}'),+ label: 'Retry',+ onPressed: busy+ ? null+ : () => unawaited(decisions.retry(decision)),+ ),+ ],),- onTap: () => widget.onOpenThread(thread.conversationId, thread.rootId),);}- Widget _finished(SuperTabConversation group) => _Row(- key: ValueKey('super-activity-row-done:${group.id}'),- mark: AppIcons.check,- title: group.title,- unread: false,- trailing: _when(group.shippedAt!),- onTap: () => widget.onOpenConversation(group.id),- );+ Widget _option(+ SuperTabDecision decision,+ int index,+ String option,+ bool busy,+ ) {+ final recommended = index == decision.recommended;+ final onPressed = busy+ ? null+ : () {+ _settle();+ unawaited(_activity.decisions.answer(decision, index));+ };+ final label = Text(+ recommended ? '$option · Recommended' : option,+ overflow: TextOverflow.ellipsis,+ );+ final key = ValueKey('super-activity-option:${decision.id}:$index');+ return ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 320),+ child: recommended+ ? FilledButton.tonal(key: key, onPressed: onPressed, child: label)+ : OutlinedButton(key: key, onPressed: onPressed, child: label),+ );+ }++ // ---- Mentions ----++ List<Widget> _mentions() {+ final a = _activity;+ final all = a.mentionRows;+ final rows = _mentionsUnreadOnly+ ? [+ for (final r in all)+ if (r.unread) r,+ ]+ : all;+ // Every one still waiting, read past or not: Mark read answers them all.+ final waiting = [+ for (final r in rows)+ for (final m in r.all)+ if (m.resolvedBy == null) m,+ ];+ final people = {+ for (final p in _snapshot?.people ?? const <SuperTabPerson>[]) p.id: p,+ };+ String author(SuperTabMention m) =>+ people[m.leadId]?.shownName ?? m.leadName;+ void markRead(List<SuperTabMention> mentions) {+ _settle();+ unawaited(a.mentions.doneAll(mentions));+ }++ return [+ _bar([+ _unreadsOnly(),+ _markAll(waiting.isEmpty ? null : () => markRead(waiting)),+ ]),+ if (rows.isEmpty)+ _empty(_mentionsUnreadOnly ? 'No unread mentions' : 'No mentions')+ else+ ..._byDay<SuperTabMentionRow>(rows, (r) => r.newest.createdAt, (row) {+ final m = row.newest;+ final name = author(m);+ return _ActivityRow(+ key: ValueKey('super-activity-row-mention:${m.id}'),+ unread: row.unread,+ avatarName: name,+ who: name,+ where: m.projectName,+ privateWhere: _isPrivate(m.projectId),+ trailing: m.createdAt == null ? '' : _when(m.createdAt!),+ preview: _oneLine(m.text),+ more: row.more > 0 ? '+${row.more} more from $name' : null,+ actions: row.unresolved+ ? [(label: 'Mark read', run: () => markRead(row.all))]+ : const [],+ onTap: () => widget.onOpenMention(m),+ );+ }),+ ];+ }++ // ---- Threads ----++ /// Every thread listed is unread (Activity lists today's new replies), so+ /// there is no Unreads only here.+ List<Widget> _threads() {+ final a = _activity;+ final rows = a.threadRows;+ return [+ _bar([+ _markAll(+ rows.isEmpty+ ? null+ : () {+ _settle();+ a.attention.markAllRead(rows);+ },+ ),+ ]),+ if (rows.isEmpty)+ _empty('No threads with new replies')+ else+ ..._byDay<SuperTabFollowedThread>(rows, (t) => t.lastReplyAt, (t) {+ // The data holds the root and the newest reply's author, not the+ // reply's text: the preview is the root, said by the root's author.+ final author = t.rootAuthor['name'] as String? ?? '';+ final replier = t.lastReplier?['name'] as String? ?? '';+ final project = _snapshot?.projectFor(t.conversationId);+ final subject = threadSubject(t.rootText);+ final root = _oneLine(t.rootText);+ return _ActivityRow(+ key: ValueKey('super-activity-row-thread:${t.key}'),+ unread: a.attention.isNew(t),+ avatarName: author.isEmpty ? subject : author,+ who: subject.isEmpty ? 'Thread' : subject,+ where: project?.name,+ privateWhere: project?.isPrivate == true,+ forThread: true,+ repliedBy: replier.isEmpty ? null : replier,+ trailing: '${a.attention.newCount(t)} new',+ preview: author.isEmpty ? root : '$author: $root',+ previewLead: author.isEmpty ? null : author.length + 1,+ actions: [+ (+ label: 'Mark read',+ run: () {+ _settle();+ a.attention.markRead(t);+ },+ ),+ (+ label: 'Unfollow',+ run: () {+ _settle();+ unawaited(a.attention.setFollow(t, false));+ },+ ),+ ],+ onTap: () => widget.onOpenThread(t.conversationId, t.rootId),+ );+ }),+ ];+ }@overrideWidget build(BuildContext context) => ListenableBuilder(@@ -210,106 +712,221 @@ class _SuperTabActivityViewState extends State<SuperTabActivityView> {builder: (context, _) {grid.AppTheme.watch(context);final a = _activity;- final needs = a.needsYou;- final reminders = a.reminders.due;- final replies = a.newReplies;- final done = a.doneToday;+ if (!_settled) {+ _tab = _opening();+ _settled = _readEnough(a);+ }final error =a.mentions.error ??a.decisions.error ??a.reminders.error ??a.attention.error;- return LaidOutListView(- key: const ValueKey('super-activity-list'),- padding: const EdgeInsets.only(bottom: grid.AppDesktop.groupGap),+ final body = switch (_tab) {+ _Tab.needs => _needsYou(),+ _Tab.mentions => _mentions(),+ _Tab.threads => _threads(),+ };+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,children: [- if (error != null)- Padding(- padding: const EdgeInsets.fromLTRB(- grid.AppDesktop.groupGap,- grid.AppDesktop.controlGap,- grid.AppDesktop.groupGap,- 0,- ),- child: Row(- children: [- Expanded(child: Text(error, style: DesktopChrome.control())),- TextButton(- onPressed: () {- unawaited(a.mentions.load());- unawaited(a.decisions.load());- unawaited(a.attention.load());- unawaited(a.reminders.load());- },- child: const Text('Retry'),+ _tabs(+ needs: a.count,+ mentions: a.mentionRows.where((r) => r.unread).length,+ threads: a.threadRows.length,+ ),+ Expanded(+ child: LaidOutListView(+ key: const ValueKey('super-activity-list'),+ padding: const EdgeInsets.only(bottom: grid.AppDesktop.groupGap),+ children: [+ if (error != null)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.groupGap,+ 0,+ ),+ child: Row(+ children: [+ Expanded(+ child: Text(error, style: DesktopChrome.control()),+ ),+ TextButton(+ onPressed: () {+ unawaited(a.mentions.load());+ unawaited(a.decisions.load());+ unawaited(a.attention.load());+ unawaited(a.reminders.load());+ },+ child: const Text('Retry'),+ ),+ ],+ ),),- ],- ),+ ...body,+ ],),- if (needs.isEmpty &&- reminders.isEmpty &&- replies.isEmpty &&- done.isEmpty)- _empty("You're all caught up."),- if (needs.isNotEmpty) ...[- _heading('Needs you'),- for (final need in needs) _need(need),- ],- if (reminders.isNotEmpty) ...[- _heading('Reminders'),- for (final reminder in reminders) _reminder(reminder),- ],- if (replies.isNotEmpty) ...[- _heading('New replies'),- for (final thread in replies) _thread(thread),- ],- if (done.isNotEmpty) ...[- _heading('Done today'),- for (final group in done) _finished(group),- ],+ ),],);},);}-/// One line: a mark, the name, and one word or time at the end. Bold when it-/// is new; a hover action (Mark done) takes the place of the time.-class _Row extends StatefulWidget {- const _Row({+/// One row, Slack's way: an unread dot, an avatar, who and where and when,+/// then a preview and whatever hangs under it. Hover actions float at the+/// right, over the time.+class _ActivityRow extends StatefulWidget {+ const _ActivityRow({super.key,- this.mark,- this.glyph,- required this.title,- this.privateProjectName,required this.unread,+ required this.avatarName,+ required this.who,+ this.where,+ this.privateWhere = false,+ this.forThread = false,+ this.repliedBy,required this.trailing,+ this.trailingWarn = false,+ this.preview,+ this.previewStrong = false,+ this.previewLines = 1,+ this.previewLead,+ this.more,+ this.extra,+ this.actions = const [],required this.onTap,- this.hoverAction,});- final IconData? mark;- final String? glyph;- final String title;- final String? privateProjectName;final bool unread;- final String trailing;+ final String avatarName, who, trailing;+ final String? where;++ /// The project is private: its lock stands for the #.+ final bool privateWhere;++ /// A thread's meta reads `{repliedBy} replied · # project` (or the project+ /// alone with no replier) in place of `in # project`.+ final bool forThread;+ final String? repliedBy;+ final bool trailingWarn;+ final String? preview;+ final bool previewStrong;+ final int previewLines;++ /// How many leading characters of [preview] are a name, shown stronger.+ final int? previewLead;++ final String? more;+ final Widget? extra;+ final List<({String label, VoidCallback run})> actions;final VoidCallback onTap;- final ({String label, bool busy, VoidCallback run})? hoverAction;@override- State<_Row> createState() => _RowState();+ State<_ActivityRow> createState() => _ActivityRowState();}-class _RowState extends State<_Row> {+class _ActivityRowState extends State<_ActivityRow> {bool _hovered = false;+ /// The row has keyboard focus, on it or on one of its actions: they show+ /// for someone who cannot hover.+ bool _focused = false;++ bool get _hasProject => widget.where?.isNotEmpty ?? false;++ String get _lead => !widget.forThread+ ? 'in'+ : widget.repliedBy == null+ ? ''+ : '${widget.repliedBy} replied';++ /// Whether the row has meta to show: a project, or who replied.+ bool get _hasWhere => _hasProject || (widget.forThread && _lead.isNotEmpty);++ Widget _where() {+ final style = DesktopChrome.metadata();+ final where = widget.where;+ final lead = _lead;+ final join = lead.isEmpty ? '' : (widget.forThread ? ' · ' : ' ');+ if (where == null || where.isEmpty) {+ return Text(+ lead,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: style,+ );+ }+ if (!widget.privateWhere) {+ return Text(+ '$lead$join# $where',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: style,+ );+ }+ return Text.rich(+ TextSpan(+ children: [+ TextSpan(text: '$lead$join'),+ WidgetSpan(+ alignment: PlaceholderAlignment.middle,+ child: PrivateProjectLock(size: 12, color: style.color),+ ),+ TextSpan(text: ' $where'),+ ],+ ),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: style,+ );+ }++ Widget _preview() {+ final text = widget.preview;+ if (text == null) return const SizedBox.shrink();+ final strong = widget.previewStrong;+ final base = DesktopChrome.control(+ color: strong+ ? DesktopChrome.foreground+ : widget.unread+ ? DesktopChrome.muted+ : grid.AppPalette.textFaint,+ ).copyWith(fontWeight: strong ? grid.AppFont.semibold : null);+ final lead = widget.previewLead;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ const SizedBox(height: 1),+ Text.rich(+ TextSpan(+ style: base,+ children: [+ if (lead != null) ...[+ TextSpan(+ text: text.substring(0, lead),+ style: TextStyle(color: DesktopChrome.foreground),+ ),+ TextSpan(text: text.substring(lead)),+ ] else+ TextSpan(text: text),+ ],+ ),+ maxLines: widget.previewLines,+ overflow: TextOverflow.ellipsis,+ ),+ ],+ );+ }+@overrideWidget build(BuildContext context) {- final action = widget.hoverAction;- final bold = widget.unread;- final style = DesktopChrome.control(- color: bold ? null : DesktopChrome.muted,- ).copyWith(fontWeight: bold ? grid.AppFont.semibold : null);+ final unread = widget.unread;+ final whoStyle = DesktopChrome.control(+ color: unread ? DesktopChrome.foreground : DesktopChrome.muted,+ ).copyWith(fontWeight: unread ? grid.AppFont.semibold : null);+ final actions = widget.actions;return Padding(padding: const EdgeInsets.symmetric(horizontal: grid.AppDesktop.controlGap,@@ -318,78 +935,179 @@ class _RowState extends State<_Row> {child: MouseRegion(onEnter: (_) => setState(() => _hovered = true),onExit: (_) => setState(() => _hovered = false),- child: Material(- color: Colors.transparent,- borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),- clipBehavior: Clip.antiAlias,- child: InkWell(- onTap: widget.onTap,- hoverColor: grid.AppSurface.hoverFill,- focusColor: grid.AppSurface.hoverFill,- child: Semantics(- label: bold ? 'New' : null,- child: Padding(- padding: const EdgeInsets.symmetric(- horizontal: grid.AppDesktop.groupGap,- vertical: grid.AppDesktop.controlGap,+ // Focus on the row or on any action in it: the actions stay while+ // someone tabs to them.+ child: Focus(+ canRequestFocus: false,+ skipTraversal: true,+ onFocusChange: (focused) => setState(() => _focused = focused),+ child: Stack(+ children: [+ Material(+ color: Colors.transparent,+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: widget.onTap,+ hoverColor: grid.AppSurface.hoverFill,+ focusColor: grid.AppSurface.hoverFill,+ child: Semantics(+ label: unread ? 'New' : null,+ // The hover actions, for a screen reader that cannot hover.+ customSemanticsActions: {+ for (final action in actions)+ CustomSemanticsAction(label: action.label): action.run,+ },+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.controlGap,+ vertical: grid.AppDesktop.controlGap,+ ),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SizedBox(+ width: grid.AppDesktop.controlGap,+ child: unread+ ? Column(+ mainAxisAlignment: MainAxisAlignment.start,+ crossAxisAlignment:+ CrossAxisAlignment.start,+ children: [+ const SizedBox(height: 13),+ DecoratedBox(+ key: const ValueKey(+ 'super-activity-dot',+ ),+ decoration: BoxDecoration(+ color: DesktopChrome.accent,+ shape: BoxShape.circle,+ ),+ child: const SizedBox.square(+ dimension: 7,+ ),+ ),+ ],+ )+ : null,+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ SuperTabAvatarFace(+ identity: widget.avatarName,+ name: widget.avatarName,+ size: 32,+ radius: 8,+ ),+ const SizedBox(width: grid.AppDesktop.controlGap + 4),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ // The name and channel share what the time+ // leaves: loose Flexibles beside a Spacer left+ // the time floating mid-row (review shots).+ Expanded(+ child: Row(+ children: [+ Flexible(+ flex: 3,+ child: Text(+ widget.who,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: whoStyle,+ ),+ ),+ if (_hasWhere) ...[+ const SizedBox(width: 6),+ Flexible(flex: 2, child: _where()),+ ],+ ],+ ),+ ),+ const SizedBox(+ width: grid.AppDesktop.controlGap,+ ),+ Text(+ widget.trailing,+ maxLines: 1,+ style: DesktopChrome.metadata(+ color: widget.trailingWarn+ ? grid.AppPalette.warn+ : grid.AppPalette.textFaint,+ ),+ ),+ ],+ ),+ _preview(),+ if (widget.more != null) ...[+ const SizedBox(height: 3),+ Text(+ widget.more!,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(+ color: DesktopChrome.accent,+ ),+ ),+ ],+ ?widget.extra,+ ],+ ),+ ),+ ],+ ),+ ),+ ),),- child: Row(- children: [- // Every row has the slot, so every title starts in one column.- SizedBox(- width: 20,- child: Align(- alignment: Alignment.centerLeft,- child: widget.mark == null- ? Text(widget.glyph ?? '', style: style)- : Icon(- widget.mark,- size: AppIcons.inlineSize,- color: style.color,- ),+ ),+ if ((_hovered || _focused) && actions.isNotEmpty)+ Positioned(+ right: grid.AppDesktop.controlGap,+ top: 4,+ child: DecoratedBox(+ decoration: BoxDecoration(+ color: grid.AppDesktop.surface,+ borderRadius: BorderRadius.circular(+ DesktopChrome.rowRadius,),+ border: Border.all(color: DesktopChrome.rim),),- Expanded(- child: widget.privateProjectName == null- ? Text(- widget.title,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: style,- )- : Text.rich(- TextSpan(+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ for (final action in actions)+ InkWell(+ onTap: action.run,+ borderRadius: BorderRadius.circular(+ DesktopChrome.rowRadius,+ ),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.controlGap,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,children: [- TextSpan(text: widget.title),- WidgetSpan(- alignment: PlaceholderAlignment.middle,- child: PrivateProjectLock(- size: 14,- color: style.color,+ const SizedBox(height: 3),+ Text(+ action.label,+ style: DesktopChrome.metadata(+ color: DesktopChrome.foreground,),),- TextSpan(- text: ' ${widget.privateProjectName}',- ),+ const SizedBox(height: 3),],),- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: style,),+ ),+ ],),- const SizedBox(width: grid.AppDesktop.groupGap),- if (action != null && _hovered)- GestureDetector(- onTap: action.busy ? null : action.run,- child: Text(action.label, style: style),- )- else- Text(widget.trailing, style: DesktopChrome.metadata()),- ],+ ),),- ),- ),+ ],),),),diff --git a/desktop/lib/super_tabs/attention.dart b/desktop/lib/super_tabs/attention.dartindex 91b84d745..63fdef865 100644--- a/desktop/lib/super_tabs/attention.dart+++ b/desktop/lib/super_tabs/attention.dart@@ -247,6 +247,36 @@ class SuperTabAttention extends ChangeNotifier {];}+ /// Marks [thread] read through its newest reply, as opening it does, so it+ /// stops showing as new before the next read says so.+ void markRead(SuperTabFollowedThread thread) {+ _markRead(thread);+ notifyListeners();+ }++ /// [markRead] for each of [threads], telling listeners once.+ void markAllRead(Iterable<SuperTabFollowedThread> threads) {+ threads.forEach(_markRead);+ notifyListeners();+ }++ void _markRead(SuperTabFollowedThread thread) {+ controller.markThreadRead(+ thread.conversationId,+ thread.rootId,+ thread.lastReplySequence,+ );+ // Moved to read now; the next read of the server agrees.+ if (unread.any((t) => t.key == thread.key)) {+ unread = [+ for (final t in unread)+ if (t.key != thread.key) t,+ ];+ read = [thread, ...read];+ }+ _newThisVisit.remove(thread.key);+ }+/// The Threads view opened: reads now, and what is new stays new until/// [closed].void opened() {diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex dd4588078..ef251b74b 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -43,6 +43,27 @@ String superTabOperationId() {).join();}+/// Runs [task] for each of [items], two at a time, and returns the results in+/// order. Every Swarm command rewrites the whole Swarm row, so twenty at once+/// hit SWARM_BUSY (503); two keep a batch moving without that.+Future<List<R>> superTabTwoAtATime<T, R>(+ Iterable<T> items,+ Future<R> Function(T item) task,+) async {+ final queue = items.toList();+ final results = List<R?>.filled(queue.length, null);+ var next = 0;+ Future<void> worker() async {+ while (next < queue.length) {+ final at = next++;+ results[at] = await task(queue[at]);+ }+ }++ await Future.wait([worker(), worker()]);+ return [for (final r in results) r as R];+}+/// The id the backend gives the message a person sends with receipt/// [operationId]: `stableId(state.id, actorKey(actor), operationId)`, the/// first 24 hex of sha256 over the JSON of those parts (backenddiff --git a/desktop/lib/super_tabs/decisions.dart b/desktop/lib/super_tabs/decisions.dartindex 44463fe30..b5643ddb1 100644--- a/desktop/lib/super_tabs/decisions.dart+++ b/desktop/lib/super_tabs/decisions.dart@@ -24,8 +24,11 @@ class SuperTabDecision {unblocks = row['unblocks'] as String? ?? '',choice = (row['choice'] as num?)?.toInt(),delegated = row['delegated'] == true,+ overdue = row['overdue'] == true,+ pmTakesOver = row['pmTakesOver'] == true,note = row['note'] as String?,- createdAt = DateTime.tryParse(row['createdAt'] as String? ?? '');+ createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),+ answeredAt = DateTime.tryParse(row['answeredAt'] as String? ?? '');final String id, batchId, projectId, projectName, conversationId;final String conversationTitle, askerName, question, unblocks;final List<String> options;@@ -46,8 +49,20 @@ class SuperTabDecision {/// The reader left it to the PM, who took the recommended option.final bool delegated;++ /// The PM answered it because it waited 24 hours, not because the reader+ /// chose Let PM decide.+ final bool overdue;++ /// Whether the 24-hour sweep will take it over (the backend says: not a+ /// reflection, and the recommended option exists). Only then does its row say+ /// `PM in ...`.+ final bool pmTakesOver;final String? note;final DateTime? createdAt;++ /// When it was answered; null while it is open.+ final DateTime? answeredAt;}/// The reader's decisions in one Swarm: open and answered, read from the@@ -68,6 +83,10 @@ class SuperTabDecisions extends ChangeNotifier {final SuperTabController controller;List<SuperTabDecision> open = const [], answered = const [];++ /// Whether [open] was read since the Swarm was opened or its audience last+ /// changed. Before that, the server's count is all there is.+ bool loaded = false;String? error;/// Decisions being answered: their buttons wait for the backend.@@ -135,6 +154,7 @@ class SuperTabDecisions extends ChangeNotifier {if (epoch != null && epoch != _epoch) {// Who may read what changed: nothing read before shows until read again// (review of #1820), even while the count stays.+ if (_epoch != null) loaded = false;if (_epoch != null && (open.isNotEmpty || answered.isNotEmpty)) {open = answered = const [];notifyListeners();@@ -206,6 +226,7 @@ class SuperTabDecisions extends ChangeNotifier {if (epoch != _epoch) return;open = nextOpen;answered = nextAnswered;+ loaded = true;_openComplete = openComplete;// The lists are the newest of each (the backend caps them): what is// set aside is forgotten only once it is known answered or gone.@@ -243,9 +264,35 @@ class SuperTabDecisions extends ChangeNotifier {Future<bool> delegate(SuperTabDecision decision) =>_answer(decision, {'delegate': true});+ /// Let PM decide for every one of [decisions] it can (those with a+ /// recommended option) that are not being answered, two at a time and read+ /// back once; how many the backend took. A failed one stays on its card for+ /// [retry].+ Future<int> delegateAll(List<SuperTabDecision> decisions) async {+ final sent = await superTabTwoAtATime([+ for (final d in decisions)+ if (d.canDelegate && !answering.contains(d.id)) d,+ ], (d) => _send(d, {'delegate': true}));+ await load();+ unawaited(controller.refresh());+ return sent.where((ok) => ok).length;+ }+Future<bool> _answer(SuperTabDecision decision,Map<String, dynamic> answer,+ ) async {+ if (!await _send(decision, answer)) return false;+ await load();+ unawaited(controller.refresh());+ return true;+ }++ /// Sends one answer and keeps what it needs to be sent again; the callers+ /// read the decisions back, once for all they sent.+ Future<bool> _send(+ SuperTabDecision decision,+ Map<String, dynamic> answer,) async {answering.add(decision.id);notifyListeners();@@ -263,6 +310,7 @@ class SuperTabDecisions extends ChangeNotifier {},);_failed.remove(decision.id);+ return true;} catch (_) {// Said on the card that sent it ([failedToSend]), wherever it shows._failed[decision.id] = answer;@@ -271,8 +319,5 @@ class SuperTabDecisions extends ChangeNotifier {answering.remove(decision.id);notifyListeners();}- await load();- unawaited(controller.refresh());- return true;}}diff --git a/desktop/lib/super_tabs/notifications.dart b/desktop/lib/super_tabs/notifications.dartindex 2521fc32e..3897d543e 100644--- a/desktop/lib/super_tabs/notifications.dart+++ b/desktop/lib/super_tabs/notifications.dart@@ -133,6 +133,9 @@ class SuperTabMentions extends ChangeNotifier {int? _epoch;// Null until the first read: tags waiting then are not news.Set<String>? _seen;++ /// Whether the tags have been read once, so an empty list means none.+ bool get loaded => _seen != null;Future<void>? _loading;// Something changed while a read was under way: read once more after it.bool _dirty = false;@@ -289,6 +292,36 @@ class SuperTabMentions extends ChangeNotifier {/// The reader is finished with [mention]. Any reader of the Swarm may, read/// only included, so this does not wait behind the composer's pending send.Future<bool> done(SuperTabMention mention) async {+ if (!await _markDone(mention)) {+ error = 'Could not mark it read. Try again.';+ notifyListeners();+ return false;+ }+ await load();+ unawaited(controller.refresh());+ return true;+ }++ /// Marks every unresolved one of [mentions] read, two at a time and read+ /// back once; how many the backend took. One that failed does not stop the+ /// rest.+ Future<int> doneAll(List<SuperTabMention> mentions) async {+ final sent = await superTabTwoAtATime([+ for (final m in mentions)+ if (m.resolvedBy == null) m,+ ], _markDone);+ final marked = sent.where((ok) => ok).length;+ await load();+ unawaited(controller.refresh());+ // After the read, which clears the error of an earlier one.+ if (marked < sent.length) {+ error = 'Could not mark some as read. Try again.';+ notifyListeners();+ }+ return marked;+ }++ Future<bool> _markDone(SuperTabMention mention) async {try {await controller.request('POST',@@ -298,14 +331,10 @@ class SuperTabMentions extends ChangeNotifier {'command': {'type': 'mention.done', 'mentionId': mention.id},},);+ return true;} catch (_) {- error = 'Could not mark it done. Try again.';- notifyListeners();return false;}- await load();- unawaited(controller.refresh());- return true;}}diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dartindex 009ef97b1..fd6fbbcae 100644--- a/desktop/lib/super_tabs/project_sidebar.dart+++ b/desktop/lib/super_tabs/project_sidebar.dart@@ -670,10 +670,7 @@ class ProjectSidebar extends StatelessWidget {onTap: onNotifications,selected: notificationsSelected,unread: activity?.unread ?? false,- badge:- activity?.count ??- (snapshot?.mentionsWaiting ?? 0) +- (snapshot?.decisionsWaiting ?? 0),+ badge: activity?.count ?? snapshot?.decisionsWaiting ?? 0,),// One Buddy for the whole Swarm, under Activity (Quiet Swarm, screen 1).if (controller.oneBuddy) ?_swarmBuddyRow(),diff --git a/desktop/test/super_tab_activity_lists_test.dart b/desktop/test/super_tab_activity_lists_test.dartindex 4388f18a9..425aa0d3b 100644--- a/desktop/test/super_tab_activity_lists_test.dart+++ b/desktop/test/super_tab_activity_lists_test.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:clock/clock.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/super_tabs/activity.dart';@@ -34,13 +36,13 @@ Map<String, dynamic> _group(ConversationServer server, String id) =>.cast<Map<String, dynamic>>().firstWhere((g) => g['id'] == id);-/// The task in `offline` waiting on its requester, the default reader.-void wait(ConversationServer server, {String requester = 'owner'}) {- _group(server, 'offline')['requesterId'] = requester;+/// The task in `offline` whose agent asked [askedOf], the default reader, by name.+void wait(ConversationServer server, {String askedOf = 'owner'}) {_group(server, 'offline')['assignment'] = {'id': 'a1','agentId': 'kestrel','status': 'needs_human',+ 'askedOf': askedOf,};}@@ -91,8 +93,8 @@ final _evening = DateTime(2026, 11, 2, 20, 30);void main() {group('Needs you', () {- test('lists the decisions asked of the reader, the agents waiting on them '- 'and their tags, in that order, and counts each', () async {+ test('lists the decisions asked of the reader and the agents waiting on '+ 'them, in that order, and counts each; a tag is not listed', () async {final server = swarm()..followedThreads = null;server.ask(['Ship it?']);wait(server);@@ -100,21 +102,13 @@ void main() {final activity = await load(server);expect([for (final n in activity.needsYou) n.kind],- [- SuperTabNeedKind.decision,- SuperTabNeedKind.agent,- SuperTabNeedKind.mention,- ],+ [SuperTabNeedKind.decision, SuperTabNeedKind.agent],);expect([for (final n in activity.needsYou) n.title],- [- 'Ship it?',- 'Kestrel is waiting on you',- 'Wren mentioned you in # web-project',- ],+ ['Ship it?', 'Kestrel is waiting on you'],);- expect(activity.count, 3);+ expect(activity.count, 2);});test(@@ -165,50 +159,46 @@ void main() {return server;}- test('a task waiting on nobody named is for its requester alone', () async {+ test('a task waiting on nobody named is for no one, not its requester '+ 'or the owner', () async {final server = twoPeople();- wait(server, requester: 'peer');- final other = await load(server);- expect(other.needsYou, isEmpty);- expect(other.count, 0);- expect(other.unread, isFalse);- final requester = await load(server, account: 'peer');- expect(- [for (final n in requester.needsYou) n.kind],- [SuperTabNeedKind.agent],- );- expect(requester.count, 1);+ wait(server);+ _group(server, 'offline')+ ..['requesterId'] = 'peer'+ ..['assignment'].remove('askedOf');+ for (final account in ['owner', 'peer']) {+ final activity = await load(server, account: account);+ expect(activity.needsYou, isEmpty);+ expect(activity.count, 0);+ expect(activity.unread, isFalse);+ }});test('a task asked of one person is for that person alone', () async {final server = twoPeople();- wait(server, requester: 'owner');- _group(server, 'offline')['assignment']['askedOf'] = 'peer';+ wait(server, askedOf: 'peer');expect((await load(server)).count, 0);expect((await load(server, account: 'peer')).count, 1);});- test(- 'a tag in a thread the reader does not follow is still Needs you',- () async {- final server = swarm();- server.tag('message-2', threadId: 'message-1', messageSequence: 2);- server.followedThreads = {'unread': [], 'read': [], 'more': false};- final activity = await load(server);- expect(- [for (final n in activity.needsYou) n.kind],- [SuperTabNeedKind.mention],- );- expect(activity.count, 1);- expect(activity.newReplies, isEmpty);- },- );+ test('a tag in a thread the reader does not follow is a mention, not Needs you', () async {+ final server = swarm();+ server.tag('message-2', threadId: 'message-1', messageSequence: 2);+ server.followedThreads = {'unread': [], 'read': [], 'more': false};+ final activity = await load(server);+ expect(activity.needsYou, isEmpty);+ expect(activity.count, 0);+ expect(activity.mentionRows, hasLength(1));+ expect(activity.unread, isTrue);+ expect(activity.newReplies, isEmpty);+ });});group('the number', () {- test('counts only Needs you: new replies, done work and replies to the '- 'reader add nothing', () async {+ test('counts only Needs you: tags, new replies, done work and replies to '+ 'the reader add nothing', () async {final server = swarm();+ server.ask(['Ship it?']);server.tag('message-1');server.followedThreads = {'unread': [unreadThread('message-1')],@@ -241,7 +231,6 @@ void main() {final activity = await load(server);expect(activity.count, 1);expect(activity.newReplies, hasLength(1));- expect(activity.doneToday, hasLength(1));});});@@ -277,7 +266,7 @@ void main() {}test(- 'a tag counts until its chat is read past it, then it leaves Needs you',+ 'a tag is bold until its chat is read past it; it never counts',() async {final server = swarm()..followedThreads = null;server.tag('message-1', messageSequence: 5);@@ -285,17 +274,15 @@ void main() {'owner': {'lead': 4},};final activity = await load(server);- expect(activity.count, 1);- expect(- [for (final n in activity.needsYou) n.kind],- [SuperTabNeedKind.mention],- );+ expect(activity.count, 0);+ expect(activity.needsYou, isEmpty);+ expect(activity.unread, isTrue);server.state['readMarks'] = {'owner': {'lead': 5},};await reload(activity, server);expect(activity.count, 0);- expect(activity.needsYou, isEmpty);+ expect(activity.unread, isFalse);},);@@ -326,29 +313,25 @@ void main() {expect(activity.needsYou, isEmpty);});- test(- 'a tag in a thread-only reply is Needs you and a new reply',- () async {- final server = swarm();- server.tag(- 'message-2',- conversationId: 'offline',- threadId: 'message-1',- messageSequence: 2,- );- server.followedThreads = {- 'unread': [unreadThread('message-1')],- 'read': [],- 'more': false,- };- final activity = await load(server);- expect(activity.needsYou, hasLength(1));- expect(activity.needsYou.single.kind, SuperTabNeedKind.mention);- expect(activity.needsYou.single.conversationId, 'offline');- expect(activity.count, 1);- expect(activity.newReplies.map((t) => t.rootId), ['message-1']);- },- );+ test('a tag in a thread-only reply is a mention and a new reply, not Needs you', () async {+ final server = swarm();+ server.tag(+ 'message-2',+ conversationId: 'offline',+ threadId: 'message-1',+ messageSequence: 2,+ );+ server.followedThreads = {+ 'unread': [unreadThread('message-1')],+ 'read': [],+ 'more': false,+ };+ final activity = await load(server);+ expect(activity.needsYou, isEmpty);+ expect(activity.mentionRows.single.newest.conversationId, 'offline');+ expect(activity.count, 0);+ expect(activity.newReplies.map((t) => t.rootId), ['message-1']);+ });});group('New replies', () {@@ -370,57 +353,68 @@ void main() {);});- group('Done today', () {- test(- 'lists what shipped today, newest first, not yesterday, not a step',- () async {- final server = swarm()..followedThreads = null;- finish(server, DateTime(2026, 11, 2, 8, 8));- (server.state['conversations'] as List).addAll(<Map<String, dynamic>>[- {- ...conversationFixture('later', 'Commits read Harness'),- 'projectId': 'lead',- 'assignment': {'id': 'a2', 'agentId': 'kestrel', 'status': 'done'},- 'shippedAt': DateTime(2026, 11, 2, 8, 28).millisecondsSinceEpoch,- },- {- ...conversationFixture('yesterday', 'Shipped yesterday'),- 'projectId': 'lead',- 'assignment': {'id': 'a3', 'agentId': 'kestrel', 'status': 'done'},- 'shippedAt': DateTime(2026, 11, 1, 23, 50).millisecondsSinceEpoch,- },- {- ...conversationFixture('review', 'Review: Windows credential fix'),- 'projectId': 'lead',- 'reviewOf': 'offline',- 'assignment': {'id': 'a4', 'agentId': 'kestrel', 'status': 'done'},- 'shippedAt': DateTime(2026, 11, 2, 9).millisecondsSinceEpoch,- },- ]);- await withClock(Clock.fixed(_evening), () async {- final activity = await load(server);- expect(- [for (final g in activity.doneToday) g.title],- ['Commits read Harness', 'Windows credential fix'],- );- });- },- );+ group('batch actions', () {+ test('mark all read keeps going past a failure', () async {+ final server = swarm()+ ..tag('message-1')+ ..tag('message-2')+ ..tag('message-3');+ var done = 0;+ server.unknownCommand = (command) =>+ command['type'] == 'mention.done' && ++done == 2;+ final activity = await load(server);+ final mentions = activity.mentions;+ final reads = server.mentionReads;+ final posts = server.posts.length;- test(- 'is empty from a server that does not say when work shipped',- () async {- final server = swarm()..followedThreads = null;- _group(server, 'offline')['assignment'] = {- 'id': 'a1',- 'agentId': 'kestrel',- 'status': 'done',- };- await withClock(Clock.fixed(_evening), () async {- expect((await load(server)).doneToday, isEmpty);- });- },- );+ final marked = await mentions.doneAll(mentions.waiting);++ expect(marked, 2);+ expect(server.posts.length - posts, 3);+ expect(mentions.error, 'Could not mark some as read. Try again.');+ // The one read after: waiting and earlier are two lists.+ expect(server.mentionReads - reads, 2);+ expect(mentions.waiting.length, 1);+ });++ test('mark all read sends two at a time, never more', () async {+ final server = swarm();+ for (var i = 1; i <= 5; i++) {+ server.tag('message-$i');+ }+ final activity = await load(server);+ final before = server.posts.length;+ final hold = server.holdCommands = Completer<void>();++ final marked = activity.mentions.doneAll(activity.mentions.waiting);+ await pumpEventQueue();+ expect(server.posts.length - before, 2);++ hold.complete();+ expect(await marked, 5);+ expect(server.posts.length - before, 5);+ });++ test('mark read moves the thread mark to its newest reply', () async {+ final server = swarm();+ server.followedThreads = {+ 'unread': [unreadThread('message-1')],+ 'read': [],+ 'more': false,+ };+ final activity = await load(server);+ final attention = activity.attention;+ final thread = attention.unread.single;+ expect(attention.isNew(thread), isTrue);++ attention.markRead(thread);++ expect(+ activity.controller.threadReadMark(thread.rootId),+ thread.lastReplySequence,+ );+ expect(attention.isNew(thread), isFalse);+ });});group('leaving', () {diff --git a/desktop/test/super_tab_activity_rows_test.dart b/desktop/test/super_tab_activity_rows_test.dartnew file mode 100644index 000000000..0b6067161--- /dev/null+++ b/desktop/test/super_tab_activity_rows_test.dart@@ -0,0 +1,88 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/activity_rows.dart';+import 'package:harness/super_tabs/notifications.dart';++SuperTabMention mention(+ String id,+ String author, {+ String conversationId = 'c1',+ String? threadId,+ String? resolvedBy,+}) => SuperTabMention.fromJson({+ 'id': id,+ 'conversationId': conversationId,+ 'messageId': 'm-$id',+ 'leadName': author,+ 'threadId': ?threadId,+ 'resolvedBy': ?resolvedBy,+});++void main() {+ test('a row is unresolved while any of its mentions still waits', () {+ final rows = groupMentions([+ mention('1', 'dee', resolvedBy: 'done'),+ mention('2', 'dee'),+ mention('3', 'Plover', resolvedBy: 'reply'),+ ], (_) => false);+ expect([for (final r in rows) r.unresolved], [true, false]);+ });++ test('neighbours from one author in one chat fold', () {+ final rows = groupMentions([+ mention('1', 'dee'),+ mention('2', 'dee'),+ mention('3', 'dee'),+ mention('4', 'Plover'),+ mention('5', 'Plover'),+ mention('6', 'dee', conversationId: 'c2'),+ ], (m) => m.id == '5');+ expect([for (final r in rows) r.newest.leadName], ['dee', 'Plover', 'dee']);+ expect([for (final r in rows) r.all.length], [3, 2, 1]);+ expect([for (final r in rows) r.more], [2, 1, 0]);+ expect([for (final r in rows) r.unread], [false, true, false]);+ });++ test('a Title: line gives the subject', () {+ expect(+ threadSubject(+ 'Please send this to the openharness PM as a proposal (priority '+ 'normal). Title: Swarm: a member cannot close a lost or stopped task '+ '— details',+ ),+ 'Swarm: a member cannot close a lost or stopped task',+ );+ });++ test('without a Title: the first line is the subject, whitespace folded', () {+ expect(threadSubject('Ship it\n second line'), 'Ship it');+ });++ test('a long first line is cut at 90', () {+ expect(threadSubject('a' * 120), '${'a' * 89}…');+ });++ group('the PM takes over 24 hours after the ask', () {+ final now = DateTime(2026, 11, 4, 12);+ DateTime ago(Duration d) => now.subtract(d);++ test('pm in rounds up and says <1h in the last hour', () {+ expect(+ pmIn(ago(const Duration(hours: 18, minutes: 30)), now),+ 'PM in 6h',+ );+ expect(+ pmIn(ago(const Duration(hours: 23, minutes: 30)), now),+ 'PM in <1h',+ );+ expect(pmSoon(ago(const Duration(hours: 23, minutes: 30)), now), isTrue);+ expect(pmSoon(ago(const Duration(hours: 21)), now), isFalse);+ });+ });++ test('days split at local midnight', () {+ final now = DateTime(2026, 11, 4, 12);+ expect(dayOf(DateTime(2026, 11, 4, 0, 1), now), SuperTabDay.today);+ expect(dayOf(DateTime(2026, 11, 3, 23, 59), now), SuperTabDay.yesterday);+ expect(dayOf(DateTime(2026, 11, 1, 12), now), SuperTabDay.earlier);+ });+}diff --git a/desktop/test/super_tab_activity_test.dart b/desktop/test/super_tab_activity_test.dartindex d52908571..301ae4ae1 100644--- a/desktop/test/super_tab_activity_test.dart+++ b/desktop/test/super_tab_activity_test.dart@@ -1,5 +1,6 @@import 'dart:async';+import 'package:clock/clock.dart';import 'package:fake_async/fake_async.dart';import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';@@ -17,6 +18,7 @@ import 'package:harness/widgets/desktop_chrome.dart';import 'super_tab_attention_test.dart'showclose,+ conversation,fromLead,inRow,openHere,@@ -560,7 +562,8 @@ void main() {await pumpSidebar(tester, c, brightness: brightness);expect(find.text('Notifications'), findsNothing);expect(inRow('super-activity', find.text('Activity')), findsOneWidget);- expect(inRow('super-activity', find.text('1')), findsOneWidget);+ // A tag is no longer counted: Activity shows no number for it.+ expect(inRow('super-activity', find.text('1')), findsNothing);expect(find.byKey(const ValueKey('super-muted-lead')), findsOneWidget);expect(inRow('super-group-lead', find.byType(SuperTabCountBadge)),@@ -688,4 +691,113 @@ void main() {c.dispose();});});++ group('Needs you counts what was asked of the reader', () {+ ConversationServer withAgent() {+ final server = projectServer();+ server.state['agents'] = [+ {+ 'id': 'kestrel',+ 'projectId': 'lead',+ 'name': 'Builder',+ 'displayName': 'Kestrel',+ 'machineId': 'host',+ 'harnessId': 'session',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'codex'},+ },+ ];+ conversation(server, 'offline')['agentIds'] = ['kestrel'];+ return server;+ }++ void assign(+ ConversationServer server,+ String status, {+ String? askedOf,+ String? requesterId,+ }) {+ final group = conversation(server, 'offline');+ if (requesterId != null) group['requesterId'] = requesterId;+ group['assignment'] = {+ 'id': 'a1',+ 'agentId': 'kestrel',+ 'status': status,+ 'askedOf': ?askedOf,+ };+ }++ Future<SuperTabActivity> activityOf(ConversationServer server) async {+ final c = await open(server);+ return SuperTabActivity.of(c);+ }++ test('tags do not count', () async {+ final server = withAgent();+ for (var i = 1; i <= 4; i++) {+ server.tag('message-$i', messageSequence: i);+ }+ final activity = await activityOf(server);+ await activity.mentions.load();+ await activity.decisions.load();+ expect(activity.count, 0);+ expect(activity.unread, isTrue);+ });++ test('a stuck task nobody was asked about does not count', () async {+ final server = withAgent();+ assign(server, 'blocked', requesterId: 'owner');+ final activity = await activityOf(server);+ await activity.decisions.load();+ expect(activity.count, 0);+ expect(activity.needsYou, isEmpty);+ });++ test('an agent that asked the reader by name counts once, before and '+ 'after the decisions load', () async {+ final server = withAgent();+ server.ask(['Ship it?'], conversationId: 'offline');+ assign(server, 'needs_human', askedOf: 'owner');+ final hold = server.holdDecisions = Completer<void>();+ final activity = await activityOf(server);+ // Not loaded yet: the server's number stands in and the task waits for+ // the list that tells it is the same ask.+ expect(activity.count, 1);+ hold.complete();+ await settle();+ await activity.decisions.load();+ expect(activity.count, 1);+ });++ testWidgets('the sidebar fallback counts decisions only', (tester) async {+ final server = withAgent();+ server.state['mentionsWaiting'] = 4;+ server.state['decisionsWaiting'] = 2;+ server.failDecisions = true;+ final c = await openHere(server);+ await pumpSidebar(tester, c);+ expect(inRow('super-activity', find.text('2')), findsOneWidget);+ await close(tester, c);+ });++ test('handled today lists the PM\'s answers of today', () async {+ final now = DateTime(2026, 11, 4, 12);+ final server = withAgent();+ server.ask(['Today?', 'Yesterday?']);+ String at(DateTime t) => t.toUtc().toIso8601String();+ server.decisions[0]+ ..['answeredAt'] = at(DateTime(2026, 11, 4, 9))+ ..['choice'] = 0+ ..['delegated'] = true;+ server.decisions[1]+ ..['answeredAt'] = at(DateTime(2026, 11, 3, 9))+ ..['choice'] = 0+ ..['delegated'] = true;+ await withClock(Clock.fixed(now), () async {+ final activity = await activityOf(server);+ await activity.decisions.load();+ expect([for (final d in activity.handledToday) d.question], ['Today?']);+ });+ });+ });}diff --git a/desktop/test/super_tab_activity_view_test.dart b/desktop/test/super_tab_activity_view_test.dartindex a509c28ab..ddd2ddcc7 100644--- a/desktop/test/super_tab_activity_view_test.dart+++ b/desktop/test/super_tab_activity_view_test.dart@@ -1,14 +1,18 @@+import 'dart:async';+import 'package:clock/clock.dart';import 'package:flutter/gestures.dart';import 'package:flutter/material.dart';+import 'package:flutter/semantics.dart';+import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/shared/theme/app_icons.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/super_tabs/activity.dart';import 'package:harness/super_tabs/activity_view.dart';+import 'package:harness/super_tabs/buddy_rows.dart' show SuperTabCountBadge;-import 'super_tab_activity_lists_test.dart'- show finish, load, swarm, unreadThread;+import 'super_tab_activity_lists_test.dart' show load, swarm, unreadThread;import 'support/super_tab_fixture.dart';final _now = DateTime(2026, 11, 2, 20, 30);@@ -18,13 +22,27 @@ Future<SuperTabActivity> loaded(ConversationServer server,) async => (await tester.runAsync(() => load(server)))!;-class _Opened {+/// The Swarm read, but not its decisions: a server holding them keeps them so.+Future<SuperTabActivity> _unread(+ WidgetTester tester,+ ConversationServer server,+) async => (await tester.runAsync(() async {+ final c = server.controller(account: 'owner');+ addTearDown(() async {+ await c.flush();+ c.dispose();+ });+ await c.refresh();+ return SuperTabActivity.of(c);+}))!;++class Opened {final mentions = <String>[];final threads = <(String, String)>[];final conversations = <String>[];}-Future<_Opened> show(+Future<Opened> show(WidgetTester tester,SuperTabActivity activity, {double width = 900,@@ -32,7 +50,9 @@ Future<_Opened> show(}) async {await tester.binding.setSurfaceSize(Size(width, 900));addTearDown(() => tester.binding.setSurfaceSize(null));- final opened = _Opened();+ final opened = Opened();+ // A fresh view each time: a tab chosen before does not carry over.+ await tester.pumpWidget(const SizedBox());await tester.pumpWidget(MaterialApp(theme: grid.buildAppTheme(brightness: brightness),@@ -52,11 +72,60 @@ Future<_Opened> show(return opened;}-/// Everything the Activity screen draws: a decision, an agent waiting, a tag,-/// a thread with new replies and two tasks done today.-ConversationServer full() {- final server = swarm();- server.ask(['W1 ships alone or waits?']);+Finder _key(String key) => find.byKey(ValueKey(key));++/// A tab's words as one string: its name, then its count.+String _tab(WidgetTester tester, String key) => [+ for (final w in tester.widgetList<Text>(+ find.descendant(of: _key(key), matching: find.byType(Text)),+ ))+ w.data ?? '',+].join(' ');++String _utc(DateTime at) => at.toUtc().toIso8601String();++/// Taps something that sends to the server, and lets the send finish.+Future<void> _tapSending(WidgetTester tester, Finder finder) async {+ await tester.runAsync(() async {+ await tester.tap(finder);+ await Future<void>.delayed(const Duration(milliseconds: 80));+ });+ await tester.pumpAndSettle();+}++Future<void> _hover(WidgetTester tester, Finder row) async {+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ addTearDown(mouse.removePointer);+ await mouse.moveTo(tester.getCenter(row));+ await tester.pumpAndSettle();+}++/// [n] unread tags from as many people, newest last (so newest first on+/// screen is the last one).+void _tags(ConversationServer server, int n, {String? at}) {+ for (var i = 0; i < n; i++) {+ server.tag(+ 'message-${i + 1}',+ leadId: 'person-$i',+ text: 'Tag number $i',+ createdAt: at ?? _utc(_now),+ );+ server.mentions.last['leadName'] = 'Person $i';+ }+}++/// A followed thread with three new replies, rooted in `offline`.+void _thread(ConversationServer server) {+ server.followedThreads = {+ 'unread': [unreadThread('message-1', text: 'Windows credential fix')],+ 'read': [],+ 'more': false,+ };+}++/// An agent, Nico, whose task `waiting` asks the reader by name; [result] is+/// the question it asked.+void _agentWaiting(ConversationServer server, {String? result}) {server.state['agents'] = [...(server.state['agents'] as List),{@@ -74,261 +143,877 @@ ConversationServer full() {...conversationFixture('waiting', 'Mac fix'),'projectId': 'lead','agentIds': ['nico'],- 'assignment': {'id': 'a9', 'agentId': 'nico', 'status': 'needs_human'},+ 'assignment': {+ 'id': 'a9',+ 'agentId': 'nico',+ 'status': 'needs_human',+ 'askedOf': 'owner',+ 'result': ?result,+ },});- server.tag('message-1', createdAt: '2026-11-02T13:09:00Z');- server.followedThreads = {- 'unread': [unreadThread('message-1', text: 'Windows credential fix')],- 'read': [],- 'more': false,- };- finish(- server,- DateTime(2026, 11, 2, 8, 8),- title: 'Closed agents leave the list',- );- return server;+}++/// Presses Tab until [wanted] shows, as someone without a mouse would.+Future<void> _tabUntil(WidgetTester tester, Finder wanted) async {+ for (var i = 0; i < 20 && wanted.evaluate().isEmpty; i++) {+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);+ await tester.pump();+ }}void main() {- testWidgets('has the three sections in order, and no filter', (tester) async {+ testWidgets(+ 'opens on Needs you when something needs the reader, else on the tab '+ 'with unread rows',+ (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final needing = swarm()..followedThreads = null;+ needing.ask(['Ship it?']);+ _tags(needing, 1);+ await show(tester, await loaded(tester, needing));+ expect(find.text('Ship it?'), findsOneWidget);+ expect(find.text('Tag number 0'), findsNothing);+ });+ await withClock(Clock.fixed(_now), () async {+ final mentions = swarm()..followedThreads = null;+ _tags(mentions, 1);+ await show(tester, await loaded(tester, mentions));+ expect(find.text('Tag number 0'), findsOneWidget);+ expect(_key('super-activity-decide-all'), findsNothing);+ });+ await withClock(Clock.fixed(_now), () async {+ final threads = swarm();+ _thread(threads);+ await show(tester, await loaded(tester, threads));+ expect(find.text('Windows credential fix'), findsOneWidget);+ expect(+ _key('super-activity-row-thread:offline/message-1'),+ findsOneWidget,+ );+ });+ await withClock(Clock.fixed(_now), () async {+ final quiet = swarm()..followedThreads = null;+ await show(tester, await loaded(tester, quiet));+ expect(find.text('Nothing needs you'), findsOneWidget);+ });+ },+ );++ testWidgets(+ 'decisions read before the tags still open on the tab with unread rows',+ (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ _tags(server, 1);+ final tags = server.holdMentions = Completer<void>();+ // The Swarm and its decisions are read; the tags are not yet.+ final activity = (await tester.runAsync(() async {+ final c = server.controller(account: 'owner');+ addTearDown(() async {+ await c.flush();+ c.dispose();+ });+ await c.refresh();+ final a = SuperTabActivity.of(c);+ await a.decisions.load();+ return a;+ }))!;+ expect(activity.mentions.loaded, isFalse);+ await show(tester, activity);+ tags.complete();+ await tester.runAsync(() => activity.mentions.load());+ await tester.pumpAndSettle();+ expect(find.text('Tag number 0'), findsOneWidget);+ expect(find.text('Nothing needs you'), findsNothing);+ });+ },+ );++ testWidgets(+ 'the Needs you tab shows the count in red and the others in grey',+ (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm();+ _thread(server);+ server.ask(['One?', 'Two?']);+ _tags(server, 4);+ await show(tester, await loaded(tester, server));+ expect(_tab(tester, 'super-activity-tab-needs'), 'Needs you 2');+ expect(_tab(tester, 'super-activity-tab-mentions'), 'Mentions 4');+ expect(_tab(tester, 'super-activity-tab-threads'), 'Threads 1');+ expect(+ find.descendant(+ of: _key('super-activity-tab-needs'),+ matching: find.byType(SuperTabCountBadge),+ ),+ findsOneWidget,+ );+ for (final grey in ['mentions', 'threads']) {+ expect(+ find.descendant(+ of: _key('super-activity-tab-$grey'),+ matching: find.byType(SuperTabCountBadge),+ ),+ findsNothing,+ );+ }+ });+ },+ );++ testWidgets('a decision row answers from its options', (tester) async {await withClock(Clock.fixed(_now), () async {- final activity = await loaded(tester, full());- await show(tester, activity);- double top(String text) => tester.getTopLeft(find.text(text)).dy;- expect(top('Needs you'), lessThan(top('New replies')));- expect(top('New replies'), lessThan(top('Done today')));- for (final filter in [- 'All',- 'Decisions',- 'Mentions',- 'Replies',- 'Reactions',- ]) {- expect(find.text(filter), findsNothing, reason: filter);+ final server = swarm()..followedThreads = null;+ server.ask(['W1 ships alone or waits?']);+ await show(tester, await loaded(tester, server));+ expect(find.text('Wren'), findsOneWidget);+ expect(find.text('in # web-project'), findsOneWidget);+ expect(find.text('W1 ships alone or waits?'), findsOneWidget);+ expect(+ find.descendant(+ of: _key('super-activity-option:decision-1:0'),+ matching: find.textContaining('Recommended'),+ ),+ findsOneWidget,+ );+ await _tapSending(tester, _key('super-activity-option:decision-1:1'));+ expect(server.posts, hasLength(1));+ expect(server.posts.single['command'], {+ 'type': 'decision.answer',+ 'decisionId': 'decision-1',+ 'choice': 1,+ });+ });+ });++ testWidgets('a decision row says when the PM takes over', (tester) async {+ final server = swarm()..followedThreads = null;+ server.ask(['Soon?']);+ server.decisions.single['createdAt'] = _utc(+ _now.subtract(const Duration(hours: 18, minutes: 30)),+ );+ await withClock(Clock.fixed(_now), () async {+ await show(tester, await loaded(tester, server));+ expect(find.text('PM in 6h'), findsOneWidget);+ });+ });++ testWidgets('let PM decide for all asks first', (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ server.ask(['One?', 'Two?']);+ await show(tester, await loaded(tester, server));+ expect(+ find.text('Product Manager takes over anything you leave for 24 hours'),+ findsOneWidget,+ );+ await tester.tap(_key('super-activity-decide-all'));+ await tester.pumpAndSettle();+ expect(find.text('Let Product Manager decide all 2?'), findsOneWidget);+ expect(find.textContaining('2 decisions'), findsOneWidget);+ expect(+ find.textContaining("Product Manager takes each one's recommended"),+ findsOneWidget,+ );+ await tester.tap(find.text('Cancel'));+ await tester.pumpAndSettle();+ expect(server.posts, isEmpty);+ await tester.tap(_key('super-activity-decide-all'));+ await tester.pumpAndSettle();+ await _tapSending(tester, _key('super-activity-decide-all-confirm'));+ expect(+ {for (final post in server.posts) post['command']['decisionId']},+ {'decision-1', 'decision-2'},+ );+ expect(server.posts, hasLength(2));+ for (final post in server.posts) {+ expect(post['command']['type'], 'decision.answer');+ expect(post['command']['delegate'], true);}- expect(find.text("You're all caught up."), findsNothing);});});- testWidgets('draws each row as one line with its word or time', (+ testWidgets('a due reminder shows in Needs you and is not left to the PM', (tester,) async {await withClock(Clock.fixed(_now), () async {- final activity = await loaded(tester, full());- await show(tester, activity);- expect(find.text('W1 ships alone or waits?'), findsOneWidget);- expect(find.text('Answer'), findsOneWidget);- expect(find.text('Nico is waiting on you'), findsOneWidget);- expect(find.text('Open'), findsOneWidget);- expect(find.text('Wren mentioned you in # web-project'), findsOneWidget);- expect(find.text('Windows credential fix'), findsOneWidget);- expect(find.text('3 new'), findsOneWidget);- expect(find.text('Closed agents leave the list'), findsOneWidget);- expect(find.text('8:08 AM'), findsOneWidget);+ final server = swarm()..followedThreads = null;+ server.ask(['Takeable?']);+ server.reminders.add({+ 'id': 'reminder-message-1',+ 'conversationId': 'lead',+ 'conversationTitle': 'Lead',+ 'messageId': 'message-1',+ 'messageSequence': 1,+ 'threadId': null,+ 'author': {'name': 'Avocet'},+ 'text': 'Send the release notes',+ 'dueAt': _utc(_now.subtract(const Duration(minutes: 5))),+ });+ server.state['remindersDigest'] = 'r1';+ await show(tester, await loaded(tester, server));+ final reminder = _key('super-activity-row-reminder:reminder-message-1');+ final decision = find.text('Takeable?');+ expect(reminder, findsOneWidget);+ expect(+ tester.getTopLeft(reminder).dy,+ lessThan(tester.getTopLeft(decision).dy),+ );+ expect(_tab(tester, 'super-activity-tab-needs'), contains('2'));+ await tester.tap(_key('super-activity-decide-all'));+ await tester.pumpAndSettle();+ expect(find.text('Let Product Manager decide all 1?'), findsOneWidget);+ expect(find.textContaining('1 decision:'), findsOneWidget);});});- testWidgets('a private project mention uses the lock channel mark', (+ testWidgets('mentions fold and show who said what', (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ for (var i = 0; i < 3; i++) {+ server.tag(+ 'message-${i + 1}',+ leadId: 'dee',+ text: 'Check number $i',+ createdAt: _utc(_now.subtract(Duration(minutes: 10 - i))),+ );+ server.mentions.last['leadName'] = 'dee';+ }+ await show(tester, await loaded(tester, server));+ expect(+ find.byWidgetPredicate(+ (w) =>+ w.key is ValueKey<String> &&+ (w.key! as ValueKey<String>).value.startsWith(+ 'super-activity-row-mention:',+ ),+ ),+ findsOneWidget,+ );+ expect(find.text('dee'), findsOneWidget);+ expect(find.text('Check number 2'), findsOneWidget);+ expect(find.text('+2 more from dee'), findsOneWidget);+ });+ });++ testWidgets('mark read on a folded row marks all of it', (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ for (var i = 0; i < 3; i++) {+ server.tag('message-${i + 1}', leadId: 'dee', text: 'Check $i');+ server.mentions.last['leadName'] = 'dee';+ }+ await show(tester, await loaded(tester, server));+ final row = find.byWidgetPredicate(+ (w) =>+ w.key is ValueKey<String> &&+ (w.key! as ValueKey<String>).value.startsWith(+ 'super-activity-row-mention:',+ ),+ );+ expect(find.text('Mark read'), findsNothing);+ await _hover(tester, row);+ await _tapSending(tester, find.text('Mark read'));+ expect(+ [for (final post in server.posts) post['command']['type']],+ ['mention.done', 'mention.done', 'mention.done'],+ );+ expect(server.posts, hasLength(3));+ });+ });++ testWidgets('mark all read marks only the mentions listed', (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ server.ask(['Still open?']);+ _tags(server, 2);+ await show(tester, await loaded(tester, server));+ await tester.tap(_key('super-activity-tab-mentions'));+ await tester.pumpAndSettle();+ await _tapSending(tester, _key('super-activity-mark-all-read'));+ expect(+ [for (final post in server.posts) post['command']['type']],+ ['mention.done', 'mention.done'],+ );+ expect(server.decisions.single['answeredAt'], isNull);+ });+ });++ testWidgets('unreads only hides read rows', (tester) async {+ final server = swarm()..followedThreads = null;+ server.tag('message-1', messageSequence: 1, leadId: 'a', text: 'Old news');+ server.tag('message-2', messageSequence: 9, leadId: 'b', text: 'New news');+ server.state['readMarks'] = {+ 'owner': {'lead': 4},+ };+ await withClock(Clock.fixed(_now), () async {+ await show(tester, await loaded(tester, server));+ final read = _key('super-activity-row-mention:mention-1');+ final unread = _key('super-activity-row-mention:mention-2');+ expect(read, findsOneWidget);+ expect(unread, findsOneWidget);+ expect(+ (tester.widget<Text>(find.text('New news')).textSpan! as TextSpan)+ .style+ ?.color,+ isNot(+ (tester.widget<Text>(find.text('Old news')).textSpan! as TextSpan)+ .style+ ?.color,+ ),+ );+ await tester.tap(_key('super-activity-unreads-only'));+ await tester.pumpAndSettle();+ expect(read, findsNothing);+ expect(unread, findsOneWidget);+ });+ });++ testWidgets('a thread row shows its subject, root and who replied', (tester,) async {+ final server = swarm();+ server.followedThreads = {+ 'unread': [+ {+ ...unreadThread(+ 'message-1',+ text: 'Please file this. Title: Dial fix — long details follow',+ ),+ 'lastReplier': {'kind': 'agent', 'id': 'river', 'name': 'River'},+ },+ ],+ 'read': [],+ 'more': false,+ };await withClock(Clock.fixed(_now), () async {- final server = full();- (server.state['projects'] as List).first['visibility'] = 'private';- final activity = await loaded(tester, server);- await show(tester, activity);+ await show(tester, await loaded(tester, server));+ final row = _key('super-activity-row-thread:offline/message-1');+ expect(+ find.descendant(of: row, matching: find.text('Dial fix')),+ findsOneWidget,+ );+ // The data has no reply text: the preview is the root, said by its+ // author (Lead), never by the replier.+ expect(+ find.descendant(+ of: row,+ matching: find.textContaining(+ 'Lead: Please file this. Title: Dial fix',+ ),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(of: row, matching: find.textContaining('River:')),+ findsNothing,+ );+ expect(+ find.descendant(+ of: row,+ matching: find.text('River replied · # web-project'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(of: row, matching: find.text('3 new')),+ findsOneWidget,+ );+ });+ });- final row = find.byKey(- const ValueKey('super-activity-row-mention:mention-1'),+ testWidgets('a thread with no replier names only its project, a private '+ 'one with the lock', (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm();+ _thread(server);+ (server.followedThreads!['unread'] as List).single['lastReplier'] = null;+ await show(tester, await loaded(tester, server));+ final row = _key('super-activity-row-thread:offline/message-1');+ expect(+ find.descendant(of: row, matching: find.text('# web-project')),+ findsOneWidget,);- final need = activity.needsYou.singleWhere(- (need) => need.id == 'mention:mention-1',+ expect(+ find.descendant(of: row, matching: find.textContaining('replied')),+ findsNothing,);- expect(need.title, 'Wren mentioned you in ');- expect(need.privateProjectName, 'web-project');++ final priv = swarm();+ _thread(priv);+ (priv.state['projects'] as List).first['visibility'] = 'private';+ await show(tester, await loaded(tester, priv));expect(find.descendant(of: row, matching: find.byIcon(AppIcons.lock)),findsOneWidget,);+ expect(find.textContaining('# web-project'), findsNothing);});});- for (final width in [900.0, 360.0]) {- testWidgets('every row stays one line at $width px with long names', (- tester,- ) async {- await withClock(Clock.fixed(_now), () async {- final server = full();- final long = 'A very long name that cannot fit on one line ' * 4;- server.ask([long]);- (server.state['conversations'] as List)- .cast<Map<String, dynamic>>()- .firstWhere((g) => g['id'] == 'offline')['title'] =- long;- server.followedThreads = {- 'unread': [unreadThread('message-1', text: long)],- 'read': [],- 'more': false,- };- final activity = await loaded(tester, server);- await show(tester, activity, width: width);- final rows = find.byWidgetPredicate(- (w) =>- w.key is ValueKey<String> &&- (w.key! as ValueKey<String>).value.startsWith(- 'super-activity-row-',- ),- );- expect(rows, findsNWidgets(6));- final heights = {- for (final row in rows.evaluate())- tester.getSize(find.byWidget(row.widget)).height,- };- expect(- heights,- hasLength(1),- reason: 'all rows are one height: $heights',- );- expect(heights.single, lessThan(48));- expect(tester.takeException(), isNull);- });+ testWidgets('hover shows mark read on a thread', (tester) async {+ final server = swarm();+ _thread(server);+ final activity = await loaded(tester, server);+ final opened = await show(tester, activity);+ final row = _key('super-activity-row-thread:offline/message-1');+ expect(find.text('Mark read'), findsNothing);+ expect(find.text('Unfollow'), findsNothing);+ await _hover(tester, row);+ expect(find.text('Unfollow'), findsOneWidget);+ final thread = activity.threadRows.single;+ await _tapSending(tester, find.text('Mark read'));+ expect(activity.attention.isNew(thread), isFalse);+ expect(opened.threads, isEmpty);+ });++ testWidgets('a thread can be unfollowed from its row', (tester) async {+ final server = swarm();+ _thread(server);+ await show(tester, await loaded(tester, server));+ await _hover(tester, _key('super-activity-row-thread:offline/message-1'));+ await _tapSending(tester, find.text('Unfollow'));+ expect(server.followPosts.single['follow'], false);+ expect(server.followPosts.single['root'], 'message-1');+ });++ testWidgets('nothing needs you says what the PM handled', (tester) async {+ final server = swarm()..followedThreads = null;+ server.ask(['Today?', 'Also today?']);+ for (final d in ['decision-1', 'decision-2']) {+ server.answerDecision(d, 0, delegated: true);+ }+ for (final d in server.decisions) {+ d['answeredAt'] = _utc(DateTime(2026, 11, 2, 9));+ }+ await withClock(Clock.fixed(_now), () async {+ await show(tester, await loaded(tester, server));+ expect(find.text('Nothing needs you'), findsOneWidget);+ expect(+ find.text('Product Manager handled 2 for you today'),+ findsOneWidget,+ );+ expect(find.text('Today?'), findsNothing);+ await tester.tap(_key('super-activity-handled'));+ await tester.pumpAndSettle();+ expect(find.text('Today?'), findsOneWidget);+ expect(find.text('Also today?'), findsOneWidget);+ expect(find.text('Behind a flag'), findsNWidgets(2));});- }+ });- testWidgets(- 'a decision row opens its card to answer, a second tap folds it',- (tester) async {- final activity = await loaded(tester, full());- await show(tester, activity);- expect(find.text('Behind a flag'), findsNothing);- await tester.tap(- find.byKey(const ValueKey('super-activity-row-decision:decision-1')),+ testWidgets('an agent row asks its question, sits above the days and has '+ 'no time', (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ server.ask(['Ship it?']);+ _agentWaiting(server, result: 'Merge or rebase the Mac fix?');+ await show(tester, await loaded(tester, server));+ final row = _key('super-activity-row-agent:waiting');+ expect(+ find.descendant(+ of: row,+ matching: find.text('Merge or rebase the Mac fix?'),+ ),+ findsOneWidget,);+ expect(+ find.descendant(of: row, matching: find.text('in # web-project')),+ findsOneWidget,+ );+ expect(+ tester.getTopLeft(row).dy,+ lessThan(tester.getTopLeft(find.text('Earlier')).dy),+ );+ });+ // No result text: the task's title stands in.+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ server.ask(['Ship it?']);+ _agentWaiting(server);+ await show(tester, await loaded(tester, server));+ expect(+ find.descendant(+ of: _key('super-activity-row-agent:waiting'),+ matching: find.text('Mac fix'),+ ),+ findsOneWidget,+ );+ });+ });++ testWidgets('PM in shows only for what the PM can take, and the bar counts '+ 'only those', (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ server.ask(['Takeable?']);+ server.ask(['No recommendation?'], recommended: -1);+ for (final d in server.decisions) {+ d['createdAt'] = _utc(_now.subtract(const Duration(hours: 18)));+ }+ await show(tester, await loaded(tester, server));+ expect(find.text('PM in 6h'), findsOneWidget);+ await tester.tap(_key('super-activity-decide-all'));await tester.pumpAndSettle();- expect(find.textContaining('Behind a flag'), findsOneWidget);- await tester.tap(- find.byKey(const ValueKey('super-activity-row-decision:decision-1')),+ expect(find.text('Let Product Manager decide all 1?'), findsOneWidget);+ expect(find.textContaining('1 decision:'), findsOneWidget);+ });+ // Asked more than 8 days ago: the sweep no longer reaches it.+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ server.ask(['Ancient?']);+ server.decisions.single['createdAt'] = _utc(+ _now.subtract(const Duration(days: 9)),+ );+ await show(tester, await loaded(tester, server));+ expect(find.textContaining('PM in'), findsNothing);+ });+ // Nothing the PM can take: no bar, no button.+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ server.ask(['Unsure?'], recommended: -1);+ await show(tester, await loaded(tester, server));+ expect(_key('super-activity-decide-all'), findsNothing);+ expect(find.textContaining('takes over'), findsNothing);+ });+ });++ testWidgets('decisions of several projects are left to the PMs', (+ tester,+ ) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ server.ask(['One?']);+ server.ask(['Two?'], projectId: 'other');+ await show(tester, await loaded(tester, server));+ expect(+ find.text('the PMs take over anything you leave for 24 hours'),+ findsOneWidget,+ );+ expect(find.text('Let the PMs decide for all'), findsOneWidget);+ });+ });++ testWidgets('decide all waits while a listed decision is being answered', (+ tester,+ ) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ server.ask(['One?', 'Two?']);+ await show(tester, await loaded(tester, server));+ final hold = server.holdCommands = Completer<void>();+ await tester.runAsync(+ () => tester.tap(_key('super-activity-option:decision-1:1')),+ );+ await tester.pump();+ expect(+ tester+ .widget<FilledButton>(_key('super-activity-decide-all'))+ .onPressed,+ isNull,);+ await tester.runAsync(() async {+ hold.complete();+ await Future<void>.delayed(const Duration(milliseconds: 80));+ });await tester.pumpAndSettle();- expect(find.textContaining('Behind a flag'), findsNothing);- },- );+ });+ });- testWidgets('every title starts in one column, and a heading starts where '- 'its rows do', (tester) async {+ testWidgets('Needs you waits in a skeleton while the decisions are read', (+ tester,+ ) async {await withClock(Clock.fixed(_now), () async {- final activity = await loaded(tester, full());+ final server = swarm()..followedThreads = null;+ server.ask(['Late?']);+ final hold = server.holdDecisions = Completer<void>();+ await show(tester, await _unread(tester, server));+ expect(_key('super-activity-skeleton'), findsOneWidget);+ expect(find.text('Nothing needs you'), findsNothing);+ await tester.runAsync(() async {+ hold.complete();+ await Future<void>.delayed(const Duration(milliseconds: 80));+ });+ await tester.pumpAndSettle();+ expect(_key('super-activity-skeleton'), findsNothing);+ expect(find.text('Late?'), findsOneWidget);+ });+ });++ testWidgets('a failed decisions read says so with Retry, not "Nothing '+ 'needs you"', (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ server.ask(['Late?']);+ server.failDecisions = true;+ await show(tester, await loaded(tester, server));+ expect(find.text('Could not load decisions. Try again.'), findsOneWidget);+ expect(find.text('Nothing needs you'), findsNothing);+ expect(_key('super-activity-skeleton'), findsNothing);+ server.failDecisions = false;+ await _tapSending(tester, find.text('Retry'));+ expect(find.text('Late?'), findsOneWidget);+ });+ });++ testWidgets('doing something before the decisions load keeps the tab', (+ tester,+ ) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ _tags(server, 1);+ server.holdDecisions = Completer<void>();+ final activity = await _unread(tester, server);+ await tester.runAsync(activity.mentions.load);await show(tester, activity);- double left(Finder f) => tester.getTopLeft(f).dx;- final titles = {- left(find.text('W1 ships alone or waits?')),- left(find.text('Nico is waiting on you')),- left(find.text('Wren mentioned you in # web-project')),- left(find.text('Windows credential fix')),- left(find.text('Closed agents leave the list')),- };- expect(titles, hasLength(1), reason: 'title columns: $titles');- // The mark column starts where the headings do.- final marks = {- left(find.byIcon(AppIcons.circleDot).first),- left(find.text('@')),- left(find.byIcon(AppIcons.reply)),- left(find.byIcon(AppIcons.check).first),+ expect(_key('super-activity-unreads-only'), findsOneWidget);+ await _tapSending(tester, _key('super-activity-mark-all-read'));+ // Everything is read now; the reader is still where they chose to act.+ expect(_key('super-activity-unreads-only'), findsOneWidget);+ });+ });++ testWidgets('decisions failing to load and Mark all read do not switch the '+ 'tab', (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ _tags(server, 2);+ server.failDecisions = true;+ await show(tester, await loaded(tester, server));+ expect(_key('super-activity-unreads-only'), findsOneWidget);+ await _tapSending(tester, _key('super-activity-mark-all-read'));+ expect(_key('super-activity-unreads-only'), findsOneWidget);+ });+ });++ testWidgets('keyboard focus on a row shows its actions and offers them to '+ 'a screen reader', (tester) async {+ final handle = tester.ensureSemantics();+ await withClock(Clock.fixed(_now), () async {+ final server = swarm();+ _thread(server);+ await show(tester, await loaded(tester, server));+ expect(find.text('Mark read'), findsNothing);+ await _tabUntil(tester, find.text('Mark read'));+ expect(find.text('Mark read'), findsOneWidget);+ expect(find.text('Unfollow'), findsOneWidget);+ final labels = <String>{};+ void collect(SemanticsNode node) {+ for (final id+ in node.getSemanticsData().customSemanticsActionIds ??+ const <int>[]) {+ labels.add(CustomSemanticsAction.getAction(id)!.label!);+ }+ node.visitChildren((child) {+ collect(child);+ return true;+ });+ }++ collect(tester.getSemantics(find.text('Windows credential fix')));+ var node = tester.getSemantics(find.text('Windows credential fix'));+ while (labels.isEmpty && node.parent != null) {+ node = node.parent!;+ collect(node);+ }+ expect(labels, {'Mark read', 'Unfollow'});+ });+ handle.dispose();+ });++ testWidgets('Mentions lists read and answered ones; Mark read reaches any '+ 'that still waits', (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ server.tag('message-1', messageSequence: 9, leadId: 'a', text: 'New');+ server.tag('message-2', messageSequence: 1, leadId: 'b', text: 'Seen');+ server.tag('message-3', messageSequence: 2, leadId: 'c', text: 'Done');+ server.mentions.last+ ..['resolvedAt'] = _utc(_now)+ ..['resolvedBy'] = 'done';+ server.state['readMarks'] = {+ 'owner': {'lead': 4},};- expect(marks, hasLength(1), reason: 'mark columns: $marks');- for (final heading in ['Needs you', 'New replies', 'Done today']) {- expect(left(find.text(heading)), marks.single, reason: heading);+ await show(tester, await loaded(tester, server));+ for (final id in ['mention-1', 'mention-2', 'mention-3']) {+ expect(_key('super-activity-row-mention:$id'), findsOneWidget);}+ await _hover(tester, _key('super-activity-row-mention:mention-3'));+ expect(find.text('Mark read'), findsNothing);+ await _hover(tester, _key('super-activity-row-mention:mention-2'));+ expect(find.text('Mark read'), findsOneWidget);+ await _tapSending(tester, _key('super-activity-mark-all-read'));+ expect(+ {+ for (final post in server.posts)+ '${post['command']['type']}:${post['command']['mentionId']}',+ },+ {'mention.done:mention-1', 'mention.done:mention-2'},+ );+ });+ });++ testWidgets('Threads has no Unreads only', (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm();+ _thread(server);+ _tags(server, 1);+ await show(tester, await loaded(tester, server));+ await tester.tap(_key('super-activity-tab-threads'));+ await tester.pumpAndSettle();+ expect(_key('super-activity-unreads-only'), findsNothing);+ expect(_key('super-activity-mark-all-read'), findsOneWidget);+ await tester.tap(_key('super-activity-tab-mentions'));+ await tester.pumpAndSettle();+ expect(_key('super-activity-unreads-only'), findsOneWidget);+ });+ });++ testWidgets('rows are split by day', (tester) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ server.tag(+ 'message-2',+ leadId: 'b',+ text: 'Stale',+ createdAt: _utc(_now.subtract(const Duration(days: 2))),+ );+ server.tag(+ 'message-1',+ leadId: 'a',+ text: 'Fresh',+ createdAt: _utc(_now),+ );+ await show(tester, await loaded(tester, server));+ expect(find.text('Today'), findsOneWidget);+ expect(find.text('Earlier'), findsOneWidget);+ expect(find.text('Yesterday'), findsNothing);+ expect(+ tester.getTopLeft(find.text('Today')).dy,+ lessThan(tester.getTopLeft(find.text('Earlier')).dy),+ );});});- testWidgets('a New replies row offers Unfollow on hover, nothing at rest', (+ testWidgets('a private project mention uses the lock channel mark', (tester,) async {- final server = full();- final activity = await loaded(tester, server);- await show(tester, activity);- final row = find.byKey(- const ValueKey('super-activity-row-thread:offline/message-1'),- );- expect(find.text('Unfollow'), findsNothing);- final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);- addTearDown(mouse.removePointer);- await mouse.moveTo(tester.getCenter(row));- await tester.pumpAndSettle();- expect(find.text('Unfollow'), findsOneWidget);- await tester.runAsync(() async {- await tester.tap(find.text('Unfollow'));- await Future<void>.delayed(const Duration(milliseconds: 50));+ await withClock(Clock.fixed(_now), () async {+ final server = swarm()..followedThreads = null;+ (server.state['projects'] as List).first['visibility'] = 'private';+ _tags(server, 1);+ await show(tester, await loaded(tester, server));+ expect(+ find.descendant(+ of: _key('super-activity-row-mention:mention-1'),+ matching: find.byIcon(AppIcons.lock),+ ),+ findsOneWidget,+ );+ expect(find.textContaining('# web-project'), findsNothing);});- await tester.pumpAndSettle();- expect(server.followPosts.single['follow'], false);- expect(server.followPosts.single['root'], 'message-1');});- testWidgets('a row opens where it is: agent, tag, thread and done task', (+ for (final width in [900.0, 360.0]) {+ testWidgets('every row keeps to its lines at $width px with long names', (+ tester,+ ) async {+ await withClock(Clock.fixed(_now), () async {+ final server = swarm();+ final long = 'A very long name that cannot fit on one line ' * 4;+ server.ask([long]);+ _tags(server, 2);+ for (final m in server.mentions) {+ m['leadName'] = long;+ m['text'] = long;+ }+ server.followedThreads = {+ 'unread': [+ {+ ...unreadThread('message-1', text: long),+ 'lastReplier': {'kind': 'agent', 'id': 'r', 'name': long},+ },+ unreadThread('message-2', text: long),+ ],+ 'read': [],+ 'more': false,+ };+ final activity = await loaded(tester, server);+ await show(tester, activity, width: width);+ double height(String prefix) {+ final rows = find.byWidgetPredicate(+ (w) =>+ w.key is ValueKey<String> &&+ (w.key! as ValueKey<String>).value.startsWith(prefix),+ );+ expect(rows, findsWidgets, reason: prefix);+ final heights = {+ for (final row in rows.evaluate())+ tester.getSize(find.byWidget(row.widget)).height,+ };+ expect(heights, hasLength(1), reason: '$prefix: $heights');+ return heights.single;+ }++ expect(height('super-activity-row-decision:'), lessThan(170));+ expect(tester.takeException(), isNull);+ await tester.tap(_key('super-activity-tab-mentions'));+ await tester.pumpAndSettle();+ expect(height('super-activity-row-mention:'), lessThan(70));+ expect(tester.takeException(), isNull);+ await tester.tap(_key('super-activity-tab-threads'));+ await tester.pumpAndSettle();+ expect(height('super-activity-row-thread:'), lessThan(70));+ expect(tester.takeException(), isNull);+ });+ });+ }++ testWidgets('a row opens where it is: agent, tag, thread and decision', (tester,) async {await withClock(Clock.fixed(_now), () async {- final activity = await loaded(tester, full());- final opened = await show(tester, activity);+ final server = swarm();+ _thread(server);+ server.ask(['Ship it?'], conversationId: 'lead');+ _agentWaiting(server);+ _tags(server, 1);+ final opened = await show(tester, await loaded(tester, server));+ expect(find.text('Nico is waiting on you'), findsOneWidget);await tester.tap(find.text('Nico is waiting on you'));- await tester.tap(find.text('Wren mentioned you in # web-project'));+ await tester.tap(find.text('Ship it?'));+ expect(opened.conversations, ['waiting', 'lead']);+ await tester.tap(_key('super-activity-tab-mentions'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Tag number 0'));+ expect(opened.mentions, ['mention-1']);+ await tester.tap(_key('super-activity-tab-threads'));+ await tester.pumpAndSettle();await tester.tap(find.text('Windows credential fix'));- await tester.tap(find.text('Closed agents leave the list'));- expect(opened.conversations, ['waiting', 'offline']);- expect(opened.mentions, hasLength(1));expect(opened.threads, [('offline', 'message-1')]);});});- testWidgets('a tag read past leaves the list, one not read is bold', (- tester,- ) async {- final server = swarm()..followedThreads = null;- server.tag('message-1', messageSequence: 1);- server.tag('message-2', messageSequence: 9);- server.state['readMarks'] = {- 'owner': {'lead': 4},- };- final activity = await loaded(tester, server);- await show(tester, activity);- final unread = find.byKey(- const ValueKey('super-activity-row-mention:mention-2'),- );- expect(- find.byKey(const ValueKey('super-activity-row-mention:mention-1')),- findsNothing,- );- expect(unread, findsOneWidget);- final title = find.descendant(- of: unread,- matching: find.textContaining('mentioned you'),- );- expect(tester.widget<Text>(title).style?.fontWeight, FontWeight.w600);- });-for (final brightness in Brightness.values) {- testWidgets(- 'says you are all caught up when nothing is new ($brightness)',- (tester) async {- final server = swarm()..followedThreads = null;- final activity = await loaded(tester, server);- await show(tester, activity, brightness: brightness);- expect(find.text("You're all caught up."), findsOneWidget);- for (final heading in ['Needs you', 'New replies', 'Done today']) {- expect(find.text(heading), findsNothing, reason: heading);- }- },- );+ testWidgets('says nothing needs you when nothing is new ($brightness)', (+ tester,+ ) async {+ final server = swarm()..followedThreads = null;+ final activity = await loaded(tester, server);+ await show(tester, activity, brightness: brightness);+ expect(find.text('Nothing needs you'), findsOneWidget);+ expect(_key('super-activity-decide-all'), findsNothing);+ });}testWidgets('leaving the view marks nothing read', (tester) async {- final server = full();+ final server = swarm();+ _tags(server, 1);final activity = await loaded(tester, server);await show(tester, activity);await tester.pumpWidget(const SizedBox());await tester.pump();expect(server.activityReadPosts, isEmpty);+ expect(server.posts, isEmpty);});}diff --git a/desktop/test/super_tab_attention_test.dart b/desktop/test/super_tab_attention_test.dartindex ba93c72ae..129f702f0 100644--- a/desktop/test/super_tab_attention_test.dart+++ b/desktop/test/super_tab_attention_test.dart@@ -212,8 +212,8 @@ void main() {await close(tester, c);});- testWidgets('a tag in an unread New replies thread also counts on the '- 'project row and in Needs you', (tester) async {+ testWidgets('a tag in an unread New replies thread counts on the '+ 'project row, not in Needs you', (tester) async {final server = projectServer();server.followedThreads = {'unread': [unreadThread('message-1', 2, conversationId: 'lead')],@@ -228,16 +228,15 @@ void main() {expect(attention.mentionsIn('lead'), 1);expect(attention.mentionsIn('offline'), 0);expect(activity.newReplies, hasLength(1));- expect(- activity.needsYou.where((need) => need.conversationId == 'lead'),- hasLength(1),- );+ // A tag asks for nothing: Activity's number and Needs you leave it out.+ expect(activity.needsYou, isEmpty);+ expect(activity.count, 0);expect(inRow('super-group-lead', find.text('1')), findsOneWidget);await close(tester, c);});- testWidgets('the project badge explains its count and clears with '- 'Needs you', (tester) async {+ testWidgets('the project badge explains its count and clears as the tag '+ 'is read and the decision answered', (tester) async {final server = projectServer();server.followedThreads = {'unread': [],@@ -255,7 +254,11 @@ void main() {find.descendant(of: projectBadge, matching: find.text('2')),findsOneWidget,);- expect(attention.mentionsIn('lead'), activity.needsYou.length);+ // The project row counts the tag and the decision; Activity's number+ // only the decision.+ expect(attention.mentionsIn('lead'), 2);+ expect(activity.needsYou, hasLength(1));+ expect(activity.count, 1);final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);await mouse.addPointer(location: tester.getCenter(projectBadge));await mouse.moveTo(tester.getCenter(projectBadge));@@ -286,7 +289,7 @@ void main() {await pumpSidebar(tester, c, attention);expect(attention.threadMentions, 1);expect(attention.mentionsIn('lead'), 1);- expect(activity.needsYou, hasLength(1));+ expect(activity.needsYou, isEmpty);expect(inRow('super-group-lead', find.text('1')), findsOneWidget);c.markThreadRead('lead', 'message-1', 2);await tester.pumpAndSettle();diff --git a/desktop/test/super_tab_buddies_test.dart b/desktop/test/super_tab_buddies_test.dartindex 7c6c56d8c..1f31d4503 100644--- a/desktop/test/super_tab_buddies_test.dart+++ b/desktop/test/super_tab_buddies_test.dart@@ -1547,6 +1547,12 @@ void main() {await tester.tap(find.byKey(const ValueKey('super-activity')));await tester.pumpAndSettle();+ // Tags live in the Mentions tab, not in Needs you.+ await tester.tap(+ find.byKey(const ValueKey('super-activity-tab-mentions')),+ );+ await tester.pumpAndSettle();+expect(find.textContaining('Chat with PM'), findsNothing);await tester.tap(find.byKey(const ValueKey('super-activity-row-mention:mention-1')),diff --git a/desktop/test/super_tab_decisions_test.dart b/desktop/test/super_tab_decisions_test.dartindex e39aace8c..09bb2080d 100644--- a/desktop/test/super_tab_decisions_test.dart+++ b/desktop/test/super_tab_decisions_test.dart@@ -91,6 +91,8 @@ Future<SuperTabController> showView(Finder notificationsEntry() => find.byKey(const ValueKey('super-activity'));Finder option(String id, int index) =>find.byKey(ValueKey('super-decision-$id-$index'));+Finder activityOption(String id, int index) =>+ find.byKey(ValueKey('super-activity-option:$id:$index'));Finder letPmDecide(String id) =>find.byKey(ValueKey('super-decision-$id-delegate'));Finder notNow(String id) => find.byKey(ValueKey('super-decision-$id-later'));@@ -139,6 +141,86 @@ void main() {);});+ test('delegate all sends one answer per decision and reads once', () async {+ final server = swarm()+ ..ask(['Ship how?', 'Name it?'])+ ..ask(['Which day?'], recommended: -1);+ final controller = server.controller(account: 'peer');+ addTearDown(controller.dispose);+ final decisions = SuperTabDecisions.of(controller);+ await controller.refresh();+ await decisions.load();+ final before = (server.posts.length, server.decisionReads);++ final done = await decisions.delegateAll(decisions.open);++ expect(done, 2);+ expect(+ [for (final post in server.posts.skip(before.$1)) post['command']],+ [+ {+ 'type': 'decision.answer',+ 'decisionId': 'decision-2',+ 'delegate': true,+ },+ {+ 'type': 'decision.answer',+ 'decisionId': 'decision-1',+ 'delegate': true,+ },+ ],+ );+ // One open list and one settled list, once.+ expect(server.decisionReads - before.$2, 2);+ expect(decisions.open.single.question, 'Which day?');+ });++ test('delegate all sends two at a time, never more', () async {+ final server = swarm()..ask(['a?', 'b?', 'c?', 'd?', 'e?']);+ final controller = server.controller(account: 'peer');+ addTearDown(controller.dispose);+ final decisions = SuperTabDecisions.of(controller);+ await controller.refresh();+ await decisions.load();+ final before = server.posts.length;+ // Held answers stay in flight: what has been sent is what is in flight.+ final hold = server.holdCommands = Completer<void>();++ final done = decisions.delegateAll(decisions.open);+ await pumpEventQueue();+ expect(server.posts.length - before, 2);++ hold.complete();+ expect(await done, 5);+ expect(server.posts.length - before, 5);+ });++ test('delegate all leaves out what is being answered', () async {+ final server = swarm()..ask(['a?', 'b?']);+ final controller = server.controller(account: 'peer');+ addTearDown(controller.dispose);+ final decisions = SuperTabDecisions.of(controller);+ await controller.refresh();+ await decisions.load();+ final before = server.posts.length;+ final hold = server.holdCommands = Completer<void>();+ final listed = decisions.open;++ final first = decisions.answer(listed.first, 1);+ await pumpEventQueue();+ final all = decisions.delegateAll(listed);+ await pumpEventQueue();+ hold.complete();+ await first;++ expect(await all, 1);+ final delegated = [+ for (final post in server.posts.skip(before))+ if (post['command']['delegate'] == true) post['command']['decisionId'],+ ];+ expect(delegated, [listed.last.id]);+ });+group('reading the reader\'s decisions', () {test('a Swarm change that leaves the waiting count alone reads no decisions',@@ -227,7 +309,7 @@ void main() {group('the Decisions list', () {testWidgets(- 'lists each question as one row, opens its card with the recommendation, and answers with one tap',+ 'lists each question as one row with its options and the recommendation, and answers with one tap',(tester) async {final server = swarm()..ask(['Ship how?', 'Name it?']);await showView(tester, server);@@ -238,17 +320,9 @@ void main() {await tester.tap(notificationsEntry());await tester.pumpAndSettle();expect(find.text('Needs you'), findsOneWidget);- expect(find.text('Answer'), findsNWidgets(2));- expect(find.text('Behind a flag · Recommended'), findsNothing);-- await tester.tap(- find.byKey(const ValueKey('super-activity-row-decision:decision-2')),- );- await tester.pumpAndSettle();- expect(find.text('Behind a flag · Recommended'), findsOneWidget);- expect(find.text('Unblocks: The release'), findsOneWidget);+ expect(find.text('Behind a flag · Recommended'), findsNWidgets(2));- await tester.tap(option('decision-2', 1));+ await tester.tap(activityOption('decision-2', 1));await tester.pumpAndSettle();expect(server.posts.last['command'], {@@ -312,7 +386,7 @@ void main() {await showView(tester, swarm());await tester.tap(notificationsEntry());await tester.pumpAndSettle();- expect(find.text("You're all caught up."), findsOneWidget);+ expect(find.text('Nothing needs you'), findsOneWidget);});});@@ -610,18 +684,14 @@ void main() {await showView(tester, server);await tester.tap(notificationsEntry());await tester.pumpAndSettle();- await tester.tap(- find.byKey(const ValueKey('super-activity-row-decision:decision-1')),- );- await tester.pumpAndSettle();server.refuse = {'code': 'DECISION_ANSWERED', 'message': 'Answered.'};- await tester.tap(option('decision-1', 1));+ await tester.tap(activityOption('decision-1', 1));await tester.pumpAndSettle();expect(find.text(SuperTabDecisions.sendFailed), findsOneWidget);expect(- find.byKey(const ValueKey('super-decision-decision-1-retry')),+ find.byKey(const ValueKey('super-activity-retry:decision-1')),findsOneWidget,);},diff --git a/desktop/test/super_tab_mentions_test.dart b/desktop/test/super_tab_mentions_test.dartindex 9bb698274..4e74c72b2 100644--- a/desktop/test/super_tab_mentions_test.dart+++ b/desktop/test/super_tab_mentions_test.dart@@ -576,51 +576,77 @@ void main() {});group('notifications view', () {- testWidgets('the entry counts what waits; the view lists only that', (- tester,- ) async {- final server = ConversationServer()- ..append('Earlier ask')- ..append('Ship it?')- ..tag('message-1', text: 'Earlier ask', createdAt: minutesAgo(90))- ..tag('message-2', text: 'Ship it?', createdAt: minutesAgo(3));- server.mentions[0]- ..['resolvedAt'] = minutesAgo(80)- ..['resolvedBy'] = 'reply';- server.state['mentionsWaiting'] = 1;- await showView(tester, server);- expect(- find.descendant(of: notificationsEntry(), matching: find.text('1')),- findsOneWidget,- );- await tester.tap(notificationsEntry());- await tester.pumpAndSettle();- final waiting = find.byKey(- const ValueKey('super-activity-row-mention:mention-2'),- );- expect(waiting, findsOneWidget);- expect(- find.descendant(- of: waiting,- matching: find.text('Wren mentioned you in # web-project'),- ),- findsOneWidget,- );- expect(- find.byKey(const ValueKey('super-activity-row-mention:mention-1')),- findsNothing,- );- });+ testWidgets(+ 'the entry counts no tag; the Mentions tab bolds what waits and '+ 'Unreads only lists only that',+ (tester) async {+ final server = ConversationServer()+ ..append('Earlier ask')+ ..append('Ship it?')+ ..tag('message-1', text: 'Earlier ask', createdAt: minutesAgo(90))+ ..tag('message-2', text: 'Ship it?', createdAt: minutesAgo(3));+ server.mentions[0]+ ..['resolvedAt'] = minutesAgo(80)+ ..['resolvedBy'] = 'reply';+ server.state['mentionsWaiting'] = 1;+ await showView(tester, server);+ // A tag asks for nothing: the Activity row carries no number for it.+ expect(+ find.descendant(of: notificationsEntry(), matching: find.text('1')),+ findsNothing,+ );+ await tester.tap(notificationsEntry());+ await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const ValueKey('super-activity-tab-mentions')),+ );+ await tester.pumpAndSettle();+ final waiting = find.byKey(+ const ValueKey('super-activity-row-mention:mention-2'),+ );+ expect(waiting, findsOneWidget);+ expect(+ find.descendant(of: waiting, matching: find.text('Wren')),+ findsOneWidget,+ );+ expect(+ find.descendant(of: waiting, matching: find.text('Ship it?')),+ findsOneWidget,+ );+ // Neighbours from one author fold into the newest, the answered one+ // behind it; Unreads only keeps the row because one of them waits.+ expect(+ find.descendant(+ of: waiting,+ matching: find.text('+1 more from Wren'),+ ),+ findsOneWidget,+ );+ expect(+ find.byKey(const ValueKey('super-activity-row-mention:mention-1')),+ findsNothing,+ );+ await tester.tap(+ find.byKey(const ValueKey('super-activity-unreads-only')),+ );+ await tester.pumpAndSettle();+ expect(waiting, findsOneWidget);+ },+ );- testWidgets('Mark done, offered where the time is on hover, clears the tag '- 'and the count', (tester) async {+ testWidgets('Mark read, offered where the time is on hover, clears the '+ 'tag', (tester) async {final server = ConversationServer()..append('Ship it?')..tag('message-1', text: 'Ship it?', createdAt: minutesAgo(3));await showView(tester, server);await tester.tap(notificationsEntry());await tester.pumpAndSettle();- expect(find.text('Mark done'), findsNothing);+ await tester.tap(+ find.byKey(const ValueKey('super-activity-tab-mentions')),+ );+ await tester.pumpAndSettle();+ expect(find.text('Mark read'), findsNothing);final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);addTearDown(mouse.removePointer);await mouse.moveTo(@@ -629,16 +655,36 @@ void main() {),);await tester.pumpAndSettle();- await tester.tap(find.text('Mark done'));+ await tester.tap(find.text('Mark read'));await tester.pumpAndSettle();+ // It stays listed as a read row, with nothing left to mark.expect(find.byKey(const ValueKey('super-activity-row-mention:mention-1')),- findsNothing,+ findsOneWidget,);expect(find.descendant(of: notificationsEntry(), matching: find.text('1')),findsNothing,);+ await mouse.moveTo(+ tester.getCenter(+ find.byKey(const ValueKey('super-activity-row-mention:mention-1')),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.text('Mark read'), findsNothing);+ expect(+ find.byKey(const ValueKey('super-activity-unreads-only')),+ findsOneWidget,+ );+ await tester.tap(+ find.byKey(const ValueKey('super-activity-unreads-only')),+ );+ await tester.pumpAndSettle();+ expect(+ find.byKey(const ValueKey('super-activity-row-mention:mention-1')),+ findsNothing,+ );});// A task with no worker is a quiet conversation: the state does not hold it until it is asked for (Dee, 2026-10-29).@@ -736,6 +782,10 @@ void main() {server.tag('message-150', conversationId: 'group', text: 'Note 150');await tester.tap(notificationsEntry());await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const ValueKey('super-activity-tab-mentions')),+ );+ await tester.pumpAndSettle();await tester.tap(find.byKey(const ValueKey('super-activity-row-mention:mention-1')),);@@ -772,6 +822,10 @@ void main() {server.tag('message-120', conversationId: 'group', text: 'Note 120');await tester.tap(notificationsEntry());await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const ValueKey('super-activity-tab-mentions')),+ );+ await tester.pumpAndSettle();await tester.tap(find.byKey(const ValueKey('super-activity-row-mention:mention-1')),);@@ -809,6 +863,10 @@ void main() {server.tag('message-650', conversationId: 'group', text: 'Note 650');await tester.tap(notificationsEntry());await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const ValueKey('super-activity-tab-mentions')),+ );+ await tester.pumpAndSettle();await tester.tap(find.byKey(const ValueKey('super-activity-row-mention:mention-1')),);@@ -850,6 +908,10 @@ void main() {server.tag('message-650', conversationId: 'group', text: 'Note 650');await tester.tap(notificationsEntry());await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const ValueKey('super-activity-tab-mentions')),+ );+ await tester.pumpAndSettle();// A background poll is reading the rows held when the tag opens.final held = server.holdReads = Completer<void>();final poll = c.loadMessages('group');diff --git a/desktop/test/super_tab_quiet_polish_test.dart b/desktop/test/super_tab_quiet_polish_test.dartindex 568455a6d..6302afbc4 100644--- a/desktop/test/super_tab_quiet_polish_test.dart+++ b/desktop/test/super_tab_quiet_polish_test.dart@@ -4,7 +4,7 @@ import 'package:harness/shared/theme/app_icons.dart';import 'package:harness/super_tabs/buddy_rows.dart';import 'super_tab_activity_lists_test.dart'- show finish, swarm, unreadThread, wait;+ show swarm, unreadThread, wait;import 'super_tab_mentions_test.dart' show showView;import 'support/super_tab_fixture.dart';@@ -56,8 +56,11 @@ void main() {testWidgets("a project's red number ends where Activity's does", (tester,) async {+ // Activity's number is what was asked of the reader: a decision. The+ // project row counts it with the tag, and both numbers end at one edge.final server = swarm()..followedThreads = null;server.tag('message-1');+ server.ask(['Ship it?'], conversationId: 'lead');await showView(tester, server);final activity = find.descendant(of: _key('super-activity'),@@ -173,21 +176,30 @@ void main() {'read': [],'more': false,};- finish(server, DateTime.now());await showView(tester, server);await tester.tap(_key('super-activity'));await tester.pumpAndSettle();for (final glyph in ['↳', '✓', '◐']) {expect(find.text(glyph), findsNothing);}- expect(find.byIcon(AppIcons.check), findsOneWidget);- expect(find.byIcon(AppIcons.reply), findsOneWidget);+ // A thread row says who replied in words, not with a reply mark.+ expect(find.textContaining('Lead replied'), findsOneWidget);+ expect(find.byIcon(AppIcons.reply), findsNothing);});testWidgets("today's time reads as the chat's", (tester) async {final server = swarm()..followedThreads = null;final now = DateTime.now();- finish(server, DateTime(now.year, now.month, now.day, 20, 8));+ server.tag(+ 'message-1',+ createdAt: DateTime(+ now.year,+ now.month,+ now.day,+ 20,+ 8,+ ).toUtc().toIso8601String(),+ );await showView(tester, server);await tester.tap(_key('super-activity'));await tester.pumpAndSettle();@@ -199,17 +211,22 @@ void main() {) async {final server = swarm();server.followedThreads = {- 'unread': [unreadThread('message-1')],+ 'unread': [+ {+ ...unreadThread('message-1'),+ 'lastReplyAt': DateTime.now().toUtc().toIso8601String(),+ },+ unreadThread('message-2', text: 'Older root'),+ ],'read': [],'more': false,};- finish(server, DateTime.now());await showView(tester, server);await tester.tap(_key('super-activity'));await tester.pumpAndSettle();double y(String text) => tester.getCenter(find.text(text)).dy;- final under = y('Root text') - y('New replies');- final over = y('Done today') - y('Root text');+ final under = y('Older root') - y('Earlier');+ final over = y('Earlier') - y('Lead: Root text');expect(under, lessThan(over));});});diff --git a/desktop/test/super_tab_reminders_shots_test.dart b/desktop/test/super_tab_reminders_shots_test.dartindex 6915eedac..ceb9c730c 100644--- a/desktop/test/super_tab_reminders_shots_test.dart+++ b/desktop/test/super_tab_reminders_shots_test.dart@@ -15,7 +15,7 @@ import 'support/super_tab_fixture.dart';final shots = Platform.environment['SUPER_TAB_REMIND_SHOTS'];/// The More menu with Mark unread and Remind me, a chat marked unread, and-/// Activity's Reminders, as the PR shows them, in both appearances.+/// a due reminder in Activity's Needs you, as the PR shows them, in both appearances.void main() {setUpAll(() async {if (shots != null) await loadPreviewFonts();@@ -125,7 +125,12 @@ void main() {await tester.pumpAndSettle();await tester.tap(find.text('Activity').first);await tester.pumpAndSettle();- expect(find.text('Reminders'), findsOneWidget);+ expect(+ find.byKey(+ const ValueKey('super-activity-row-reminder:reminder-message-3'),+ ),+ findsOneWidget,+ );await shot('activity');});}diff --git a/desktop/test/super_tab_reminders_test.dart b/desktop/test/super_tab_reminders_test.dartindex eee8f4b69..033128125 100644--- a/desktop/test/super_tab_reminders_test.dart+++ b/desktop/test/super_tab_reminders_test.dart@@ -135,7 +135,7 @@ void main() {});});- testWidgets('a due reminder shows once under Reminders in Activity, with one '+ testWidgets("a due reminder shows once in Activity's Needs you, with one "'notice, and opening it clears it', (tester) async {final server = _chat();server.remindElsewhere(@@ -144,7 +144,6 @@ void main() {);await show(tester, server);await openActivity(tester);- expect(find.text('Reminders'), findsNothing);expect(reminderRow('message-3'), findsNothing);// Nothing polls: the list is read again when the reminder is due.@@ -155,12 +154,18 @@ void main() {await tester.pumpAndSettle();expect(server.reminderReads, hasLength(reads + 1));- expect(find.text('Reminders'), findsOneWidget);expect(reminderRow('message-3'), findsOneWidget);expect(find.descendant(of: reminderRow('message-3'),- matching: find.text('Avocet: $_question'),+ matching: find.text(_question),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: reminderRow('message-3'),+ matching: find.text('Avocet'),),findsOneWidget,);@@ -185,7 +190,6 @@ void main() {expect(find.text(_question), findsOneWidget);await openActivity(tester);expect(reminderRow('message-3'), findsNothing);- expect(find.text('Reminders'), findsNothing);});testWidgets('a reminder set again on the same message notifies again', (diff --git a/desktop/test/super_tab_sidebar_cleanup_test.dart b/desktop/test/super_tab_sidebar_cleanup_test.dartindex 7f4809012..3d18d7a7c 100644--- a/desktop/test/super_tab_sidebar_cleanup_test.dart+++ b/desktop/test/super_tab_sidebar_cleanup_test.dart@@ -47,7 +47,10 @@ Future<SuperTabController> showSwarm(WidgetTester tester) async {final app = createApp(connected: true);addTearDown(app.dispose);final server = ConversationServer();+ // Two tags wait and one decision is asked: the Activity row counts only the+ // decision.server.state['mentionsWaiting'] = 2;+ server.ask(['Ship it?']);server.state['decisionsWaiting'] = 1;final c = server.controller();await c.refresh();@@ -83,10 +86,10 @@ void main() {// Dock. The rest moved// into Manage, at the foot (Quiet Swarm, screen 1).for (final platform in [TargetPlatform.macOS, TargetPlatform.linux]) {- testWidgets('the top reads Activity with its count, and Manage is at the '- 'foot', (tester) async {+ testWidgets('the top reads Activity with its count of asks, and Manage is '+ 'at the foot', (tester) async {final c = await showSwarm(tester);- expect(topRows(tester), ['Activity3']);+ expect(topRows(tester), ['Activity1']);expect(tester.getTopLeft(find.byKey(const ValueKey('super-manage'))).dy,greaterThan(tester.getTopLeft(find.text('Projects')).dy),diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex 95884f34f..a62dba0fe 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -2014,6 +2014,8 @@ class ConversationServer {'question': question,'options': ['Behind a flag', 'To everyone'],'recommended': recommended,+ // As the backend says it: a recommended option that exists.+ 'pmTakesOver': recommended >= 0 && recommended < 2,'unblocks': 'The release','createdAt': '2026-10-27T05:00:00Z','answeredAt': null,diff --git a/desktop/test/swarm_projects_test.dart b/desktop/test/swarm_projects_test.dartindex 97e7e36fd..e837b6d5d 100644--- a/desktop/test/swarm_projects_test.dart+++ b/desktop/test/swarm_projects_test.dart@@ -194,8 +194,14 @@ void main() {];final group = (server.state['conversations'] as List)[1] as Map;group['agentIds'] = ['worker'];- group['assignment'] = {'status': 'needs_human', 'agentId': 'worker'};+ group['assignment'] = {+ 'status': 'needs_human',+ 'agentId': 'worker',+ // Activity holds a waiting task only when it asked the reader by name.+ 'askedOf': 'owner',+ };await mount(tester, c);+ await SuperTabActivity.of(c).decisions.load();expect(find.byKey(const ValueKey('super-group-offline')), findsNothing);expect(find.descendant(diff --git a/docs/plans/2026-11-04-activity-needs-you-plan.md b/docs/plans/2026-11-04-activity-needs-you-plan.mdnew file mode 100644index 000000000..680a84bca--- /dev/null+++ b/docs/plans/2026-11-04-activity-needs-you-plan.md@@ -0,0 +1,258 @@+# Activity shows only what needs you: Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Activity's number counts only what the reader must decide; decisions left 24 hours go to the PM; Let PM decide+for all; Mark read for mentions and threads; a tabbed, Slack-like view.++**Architecture:** The backend gains one hourly sweep that answers overdue decisions through the existing+`decision.answer` delegate path, marked `overdue`. Everything else is Desktop: the count rule in `activity.dart`, pure row+helpers in a new `activity_rows.dart`, batch actions on the existing decision/mention/thread controllers, and a rewritten+`activity_view.dart`.++**Tech Stack:** TypeScript, Prisma on MongoDB, vitest (backend); Flutter/Dart, flutter_test (Desktop).++**Spec:** `docs/specs/2026-11-04-activity-needs-you.md`++## Global Constraints++- Overdue means `createdAt + 24h` has passed: `OVERDUE_DECISION_MS = 24 * 60 * 60_000`. The clock never restarts.+- Every hourly pass reads waiting decisions with `createdAt` in `(now - 8d, now - 24h]`, at most 500, oldest first+ (changed after review: no in-memory cursor, so capped or failed rows are retried).+- Sweep operation id: `overdue-decision-<decisionId>` (operation ids allow only `[A-Za-z0-9_-]`).+- Overdue notice, exact: `A decision asked in this conversation waited 24 hours, so it was left to the ${name}, who took its recommended option. `+- Failure log, exact: `[swarm-sweeps] overdue decisions failed`, at error level, every failed pass.+- New index: `@@index([answeredAt, createdAt], map: "decision_waiting_created")` on `SuperTabDecision`. Query it with `aggregateRaw` `$match`,+ never a Prisma `in` (backend/AGENTS.md rule 3).+- Desktop copy, exact: tabs `Needs you`, `Mentions`, `Threads`; `Unreads only`; `Mark read`; `Mark all read`;+ `Let {name} decide for all`; dialog title `Let {name} decide all {n}?`; confirm `Let {name} decide`; bar+ `{name} takes over anything you leave for 24 hours`; empty `Nothing needs you`; `{name} handled {n} for you today`;+ `See what`; `PM in {h}h`, `PM in <1h`; `+{n} more from {author}`; `{n} new`; day labels `Today`, `Yesterday`, `Earlier`.+ `{name}` is the coordinator name when all listed decisions share a project, else `the PMs`.+- Thread subjects are cut to 90 characters with `…`.+- Commit or push only when Diego asks; stage only this branch's files.+- Gates: backend `npm test` for touched specs plus the new integration test; Desktop `flutter analyze` and the touched+ test files; record them in the PR. Measure `SuperTabDecision` on the read-only production DB before and after+ (backend/AGENTS.md rule 5): Diego runs it.++## Review Focus++- A person answers a decision in the same second the sweep delegates it: exactly one answer is stored, and the sweep+ gets `DECISION_ANSWERED` and moves on (Task 2 test `a person's answer wins over the sweep`).+- A decision whose recommended option is out of range (old data) must not stop the pass: it is skipped and counted as+ failed in the pass result (Task 2 test `a decision the PM cannot take is skipped, the rest are answered`).+- The worker was down for two days, or a pass hit the 500 cap: every pass reads the whole 8-day window, so nothing is+ dropped (Task 2 tests `a decision older than 8 days is never taken`, `a capped pass leaves the rest for the next one`).+- Mark all read while one `mention.done` fails: the others are marked, the error line shows, one read follows+ (Task 4 test `mark all read keeps going past a failure`).+- A thread root with no `Title:` and no newline, longer than 90 characters, is cut with an ellipsis+ (Task 3 test `a long first line is cut at 90`).++---++### Task 1: Overdue answers are recorded and worded as such (backend)++**Files:**+- Modify: `backend/prisma/schema.prisma` (model `SuperTabDecision`: field `overdue Boolean?` with a `///` line, and the+ `decision_waiting_created` index on `[answeredAt, createdAt]` with a `///` line naming the sweep)+- Modify: `backend/src/superTabs/decisions.ts` (`DecisionAnswer`, `answerDecision`, `recordAnswer`, `listDecisions`, a new+ `overdueNotice`)+- Modify: `backend/src/superTabs/commands.ts:2041` (`case 'decision.answer'`: pass `overdue: context.overdue === true`)+- Test: `backend/src/superTabs/decisions.test.ts`++**Interfaces:**+- Produces: `answerDecision(state, actor, decision, given: { choice?: number; note: string | null; delegate: boolean; overdue?: boolean })`.+ With `overdue`, `delegate` must be true, else `INVALID_DECISION`. `DecisionAnswer` gains `overdue?: true`.+- Produces: `overdueNotice(name: string): string` (exact copy in Global Constraints).+- Produces: the command context field `overdue?: boolean` that `applyCommand` reads for `decision.answer` (set only by+ the store in Task 2, never by a client; it is not in the command schema).+- Produces: `listDecisions` rows gain `overdue: boolean`.++- [ ] **Step 1: Write the failing tests** in `decisions.test.ts`, using the file's `swarm()` fixture:+ - `an overdue answer takes the recommended option and says it waited 24 hours`: `applyCommand` of `decision.answer`+ `{ delegate: true }` with context `{ overdue: true }` → `effects.decisionAnswer` equals+ `{ id, choice: recommended, note: null, delegated: true, overdue: true }`, and the notice message text equals+ `overdueNotice('Product Manager')`.+ - `overdue without delegate is refused`: `answerDecision(..., { choice: 0, note: null, delegate: false, overdue: true })`+ throws `INVALID_DECISION`.+ - `a person's delegate is not overdue`: `{ delegate: true }` without context → no `overdue` key, notice is+ `delegatedNotice('Product Manager')`.+- [ ] **Step 2: Run** `cd backend && npx vitest run src/superTabs/decisions.test.ts`. Expected: the three new tests FAIL.+- [ ] **Step 3: Implement.** `overdue` picks `overdueNotice` in place of `delegatedNotice` (the closed-chat variant keeps+ `closedChatDelegatedNotice`); `recordAnswer` writes `overdue: true` beside `delegated`; `listDecisions` maps+ `overdue: row.overdue === true`; the schema field and index as listed.+- [ ] **Step 4: Run** the same command. Expected: PASS. Also `npm run typecheck`.+- [ ] **Step 5: Commit** (when Diego asks): `git add backend/prisma/schema.prisma backend/src/superTabs/decisions.ts backend/src/superTabs/commands.ts backend/src/superTabs/decisions.test.ts`,+ message `Swarm: record a decision left to the PM after 24 hours as overdue`.++### Task 2: The hourly sweep answers overdue decisions (backend)++**Files:**+- Create: `backend/src/superTabs/overdueDecisions.ts`+- Modify: `backend/src/superTabs/store.ts` (new public method)+- Modify: `backend/src/superTabs/sweeps.ts` (`startSwarmSweeps` takes the callback and logs its result)+- Modify: `backend/src/worker.ts:136` (pass `now => swarms.leaveOverdueDecisions(now)`)+- Test: `backend/integration/overdueDecisions.test.ts` (MongoDB replica via `planDatabase`, as `swarmSweepPlans.test.ts`)++**Interfaces:**+- Consumes: Task 1's context `overdue` and `answerDecision` behaviour.+- Produces: `export const OVERDUE_DECISION_MS: number` and+ `export async function overdueDecisions(db: PrismaClient, now: number, since: number): Promise<Array<{ tabId: string; id: string; personId: string }>>`+ in `overdueDecisions.ts`: one `aggregateRaw` on `SuperTabDecision` with+ `$match: { createdAt: { $gt: since, $lte: now - OVERDUE_DECISION_MS }, answeredAt: null, withdrawn: { $ne: true }, kind: { $exists: false } }`,+ projecting `_id`, `tabId`, `personId`; capped at 500 per pass, oldest first.+- Produces: `SuperTabStore.leaveOverdueDecisions(now: number): Promise<{ answered: number; skipped: number; failed: number }>`.+ It keeps `private overdueSince?: number` (unset → `now - 8 * DAY`, then `now - 26 * HOUR`). For each row it reads the+ person's email from the Swarm's people (skipped when they left), builds+ `AuthUser { sub: personId, email, autonomousEnv: <the store's env as other internal callers use>, role: 'user' }` and runs+ the same pipeline as `execute` with `{ operationId: 'overdue-decision:' + id, command: { type: 'decision.answer', decisionId: id, delegate: true } }`+ and the internal context `overdue: true` threaded into `executeOnce`'s command context. `DECISION_ANSWERED` and+ `INVALID_DECISION` count as `skipped`, any other error as `failed` (logged with the error code, no ids).+- Produces: `startSwarmSweeps(db, everyMs?, finishWorkspaceRemovals?, leaveOverdueDecisions?: (now: number) => Promise<unknown>)`.+ Its result appears as `overdue` in the `[swarm-sweeps] done` log; a throw logs `[swarm-sweeps] overdue decisions failed`+ at error level.++- [ ] **Step 1: Write the failing integration tests** in `overdueDecisions.test.ts` (fresh replica, never `DATABASE_URL`):+ - `a decision asked 25 hours ago is left to the PM`: seed a Swarm through the store with an agent asking a person+ (`work.status` with `ask`), set its `createdAt` to `NOW - 25h`, run `leaveOverdueDecisions(NOW)` → result+ `{ answered: 1, skipped: 0, failed: 0 }`; the row has `delegated: true, overdue: true, choice: recommended`; the+ conversation has the overdue notice.+ - `a decision asked 23 hours ago waits`: `answered: 0`, row still waiting.+ - `a person's answer wins over the sweep`: answer it as the person first, then sweep → `skipped: 1`, `choice` is the+ person's, no `overdue`.+ - `a second pass replays nothing`: sweep twice → second `{ answered: 0 }`, one notice.+ - `the first pass reaches back 8 days`: a decision at `NOW - 7d` is answered on a new store's first pass; on that+ store's next pass one at `NOW - 3d` (seeded after) is not.+ - `a decision the PM cannot take is skipped, the rest are answered`: one row with `recommended: 9` and 2 options, one+ valid → `{ answered: 1, skipped: 1 }`.+ - `the overdue read uses decision_waiting_created`: `profiled(db, () => overdueDecisions(db, NOW))` →+ `plan(reads(entries, 'SuperTabDecision', ['createdAt']))` shows `IXSCAN { createdAt: 1 }` and `docsExamined` ≤ the+ rows in the window + 1, with 10 decisions outside the window seeded.+- [ ] **Step 2: Run** `cd backend && npx vitest run integration/overdueDecisions.test.ts`. Expected: FAIL (module missing).+- [ ] **Step 3: Implement** `overdueDecisions.ts`, the store method, the sweeps parameter and the worker wiring per+ Interfaces.+- [ ] **Step 4: Run** the integration test, `npx vitest run src/superTabs/sweeps.test.ts` if it exists, and+ `npm run typecheck`. Expected: PASS.+- [ ] **Step 5: Commit** (when Diego asks): message `Swarm: leave a decision unanswered for 24 hours to the PM`.++### Task 3: Count rule and row helpers (Desktop)++**Files:**+- Modify: `desktop/lib/super_tabs/activity.dart` (`count`, `needsYou`, `unread`, new getters)+- Modify: `desktop/lib/super_tabs/project_sidebar.dart:1027` (fallback badge)+- Modify: `desktop/lib/super_tabs/decisions.dart` (`SuperTabDecision.overdue`, `answeredAt`)+- Create: `desktop/lib/super_tabs/activity_rows.dart`+- Test: `desktop/test/super_tab_activity_test.dart`, create `desktop/test/super_tab_activity_rows_test.dart`++**Interfaces:**+- Produces in `activity.dart`:+ - `int get count`: open decisions (the loaded `decisions.open` once loaded, else `snapshot.decisionsWaiting`) + groups+ where `work['status'] == 'needs_human'`, `work['askedOf'] == controller.accountId`, not closed, not a Buddy chat, and+ no loaded open decision in that conversation. No tags, no `blocked`, no requester or owner fallback.+ - `List<SuperTabNeed> get needsYou`: the same items, decisions then tasks, newest first (no mentions).+ - `bool get unread => count > 0 || _tags.isNotEmpty || attention.threadsUnread`.+ - `List<SuperTabDecision> get handledToday`: `decisions.answered` with `delegated` and `answeredAt` today, newest first.+ - `List<SuperTabMentionRow> get mentionRows` (via `groupMentions`), `List<SuperTabFollowedThread> get threadRows`+ (today's `newReplies`).+ - `String coordinatorFor(Iterable<SuperTabDecision>)`: the project's coordinator name when one project, else `the PMs`.+- Produces in `activity_rows.dart` (pure, no controller):+ - `class SuperTabMentionRow { final SuperTabMention newest; final List<SuperTabMention> all; final bool unread; int get more => all.length - 1; }`+ - `List<SuperTabMentionRow> groupMentions(List<SuperTabMention> mentions, bool Function(SuperTabMention) isUnread)`:+ folds neighbours with the same `leadId ?? leadName`, `conversationId` and `threadId`; `unread` if any member is.+ - `String threadSubject(String rootText)` (spec rule, 90-character cut).+ - `String pmIn(DateTime createdAt, DateTime now)`: `PM in {h}h` (hours to `createdAt + 24h` rounded up) or `PM in <1h`.+ - `bool pmSoon(DateTime createdAt, DateTime now)`: under 2 hours left.+ - `enum SuperTabDay { today, yesterday, earlier }` and `SuperTabDay dayOf(DateTime at, DateTime now)` (local time).+- `SuperTabDecision` gains `final bool overdue` (`row['overdue'] == true`) and `final DateTime? answeredAt` if absent.++- [ ] **Step 1: Write the failing tests.**+ - `super_tab_activity_test.dart`:+ - `tags do not count`: 4 waiting mentions, 0 decisions → `count == 0`, `unread == true`.+ - `a stuck task nobody was asked about does not count`: `blocked` group with `requesterId` = reader → `count == 0`.+ - `an agent that asked the reader by name counts once`: `needs_human`, `askedOf` = reader, an open decision in that+ conversation → `count == 1` both before and after `decisions.load()` (the double count fix).+ - `the sidebar fallback counts decisions only`: `snapshot.mentionsWaiting = 4, decisionsWaiting = 2` → the+ Activity row's badge reads `2`.+ - `handled today lists the PM's answers of today`: two delegated answered decisions (today, yesterday) → one row.+ - `super_tab_activity_rows_test.dart`:+ - `neighbours from one author in one chat fold`: dee×3 in `c1`, Plover×2, dee×1 in `c2` → rows `[dee(3), Plover(2), dee(1)]`, `more` `[2, 1, 0]`.+ - `a Title: line gives the subject`: `'Please send this to the openharness PM as a proposal (priority normal). Title: Swarm: a member cannot close a lost or stopped task — details'` → `'Swarm: a member cannot close a lost or stopped task'`.+ - `a long first line is cut at 90`: 120 `a`s → 89 `a`s + `…`.+ - `pm in rounds up and says <1h in the last hour`: asked 18.5h ago → `PM in 6h`; asked 23.5h ago → `PM in <1h`, `pmSoon` true; asked 21h ago → `pmSoon` false.+ - `days split at local midnight`: today 00:01 → today; yesterday 23:59 → yesterday; 3 days ago → earlier.+- [ ] **Step 2: Run** `cd desktop && flutter test test/super_tab_activity_test.dart test/super_tab_activity_rows_test.dart`.+ Expected: FAIL.+- [ ] **Step 3: Implement** per Interfaces. Remove the requester/owner fallback from `_waiting`; build `decided` only from+ the loaded list.+- [ ] **Step 4: Run** the same tests and `flutter analyze`. Expected: PASS, no issues.+- [ ] **Step 5: Commit** (when Diego asks): message `Desktop: Activity counts only what needs you`.++### Task 4: Batch actions (Desktop)++**Files:**+- Modify: `desktop/lib/super_tabs/decisions.dart` (`delegateAll`)+- Modify: `desktop/lib/super_tabs/notifications.dart` (`doneAll`)+- Modify: `desktop/lib/super_tabs/attention.dart` (`markRead`, `markAllRead`)+- Test: `desktop/test/super_tab_decisions_test.dart`, `desktop/test/super_tab_activity_lists_test.dart`++**Interfaces:**+- Produces: `Future<int> SuperTabDecisions.delegateAll(List<SuperTabDecision> decisions)`: sends `decision.answer`+ `{delegate: true}` for each `canDelegate` one, all at once, keeps each failure in `_failed` as `_answer` does, then one+ `load()` and one `controller.refresh()`; returns how many succeeded.+- Produces: `Future<int> SuperTabMentions.doneAll(List<SuperTabMention> mentions)`: `mention.done` for each unresolved one,+ all at once, then one `load()`; sets `error = 'Could not mark some as read. Try again.'` if any failed; returns how many+ succeeded. `done()` keeps its behaviour; its error text becomes `'Could not mark it read. Try again.'`.+- Produces: `void SuperTabAttention.markRead(SuperTabFollowedThread t)` →+ `controller.markThreadRead(t.conversationId, t.rootId, t.lastReplySequence)`; `void markAllRead(Iterable<SuperTabFollowedThread>)`.++- [ ] **Step 1: Write the failing tests** with the files' existing fake request recorders:+ - `delegate all sends one answer per decision and reads once`: 3 decisions (one without `recommended`) → 2 POSTs with+ `delegate: true`, 1 GET pair after, returns 2.+ - `mark all read keeps going past a failure`: 3 mentions, the 2nd POST throws → 3 POSTs, `error` set, one load, returns 2.+ - `mark read moves the thread mark to its newest reply`: after `markRead(t)` the controller's thread mark for+ `t.rootId` is `t.lastReplySequence` and `attention.isNew(t)` is false.+- [ ] **Step 2: Run** `flutter test test/super_tab_decisions_test.dart test/super_tab_activity_lists_test.dart`. Expected: FAIL.+- [ ] **Step 3: Implement** per Interfaces.+- [ ] **Step 4: Run** the same tests. Expected: PASS.+- [ ] **Step 5: Commit** (when Diego asks): message `Desktop: let the PM decide for all, and mark mentions and threads read`.++### Task 5: The tabbed Activity view (Desktop)++**Files:**+- Modify: `desktop/lib/super_tabs/activity_view.dart` (rewrite of the list; keep `SuperTabActivityView`'s constructor)+- Test: `desktop/test/super_tab_activity_view_test.dart`++**Interfaces:**+- Consumes: Task 3 getters and helpers, Task 4 batch actions, the existing decision answer/delegate calls,+ `superTabAgoShort`, `DesktopChrome`, `grid.AppDesktop` spacing and `AppIcons`.+- Produces: keys used by tests: `super-activity-tab-needs`, `super-activity-tab-mentions`, `super-activity-tab-threads`,+ `super-activity-decide-all`, `super-activity-decide-all-confirm`, `super-activity-mark-all-read`,+ `super-activity-unreads-only`, `super-activity-row-mention:<newest id>`, `super-activity-row-thread:<key>`,+ `super-activity-row-decision:<id>`, `super-activity-option:<decisionId>:<index>`, `super-activity-handled`.++- [ ] **Step 1: Write the failing widget tests:**+ - `opens on Needs you when something needs the reader, else on the tab with unread rows`.+ - `the Needs you tab shows the count in red and the others in grey`: tab texts `Needs you 2`, `Mentions 4`, `Threads 1`.+ - `a decision row answers from its options`: tap `super-activity-option:<id>:1` → one `decision.answer` `{choice: 1}`.+ - `a decision row says when the PM takes over`: asked 18.5h before `now` → text `PM in 6h`.+ - `let PM decide for all asks first`: tap decide-all → dialog `Let Product Manager decide all 2?`; Cancel sends nothing;+ confirm sends 2 delegated answers.+ - `mentions fold and show who said what`: dee×3 → one row with `dee`, the newest text, `+2 more from dee`.+ - `mark read on a folded row marks all of it`: hover dee's folded row, tap `Mark read` → 3 `mention.done`.+ - `mark all read marks only the mentions listed`: tap mark-all-read on Mentions → `mention.done` for each unread one, no+ `decision.answer`.+ - `unreads only hides read rows`: an answered mention disappears when the switch is on.+ - `a thread row shows its subject and latest reply`: root with `Title: X — y`, last replier River → `X`, `River: …`, `1 new`.+ - `hover shows mark read on a thread`: hover then tap `Mark read` → `attention.isNew` false, no navigation. The second hover action is `Unfollow`.+ - `nothing needs you says what the PM handled`: no open decisions, 2 handled today → `Nothing needs you`,+ `Product Manager handled 2 for you today`; `See what` lists both with their chosen option.+ - `rows are split by day`: mentions today and 2 days ago → `Today` and `Earlier` headings.+- [ ] **Step 2: Run** `flutter test test/super_tab_activity_view_test.dart`. Expected: FAIL.+- [ ] **Step 3: Implement** the view: a tab row (selected tab underlined), a bar per tab (decide-all on Needs you, Mark all+ read and Unreads only on the other two), day headings, the row widget (dot, avatar initial, name, `in # project` or the+ lock, time or `PM in`, preview, hover actions), the confirmation via the app's existing dialog helper, and the empty+ state. Remove the Done today section and its `_finished` row. Match the mockup `desktop/mockup/activity-slack.html`.+- [ ] **Step 4: Run** the view tests, `flutter test test/super_tab_activity_test.dart test/super_tab_activity_lists_test.dart`+ and `flutter analyze`. Expected: PASS. Then a manual look on macOS (`bash scripts/build-macos-debug.sh`) with screenshots+ of the three tabs for the PR.+- [ ] **Step 5: Commit** (when Diego asks): message `Desktop: a tabbed Activity, one list at a time`.diff --git a/docs/specs/2026-11-04-activity-needs-you.md b/docs/specs/2026-11-04-activity-needs-you.mdnew file mode 100644index 000000000..ce5ea6074--- /dev/null+++ b/docs/specs/2026-11-04-activity-needs-you.md@@ -0,0 +1,147 @@+# Activity shows only what needs you (Diego, 2026-11-04)++Mockups: `desktop/mockup/activity-slack.html` (chosen layout) and `desktop/mockup/activity-needs-you.html` (the rules), in the+main checkout's gitignored mockup folder.++## What Diego asked++- The red number on Activity is too high (11 on 2026-11-04), and most of what it counts does not need him. It should count+ only what he must decide himself.+- Anything he leaves untouched for a day goes to the PM, who handles it.+- A **Let PM decide for all** button.+- **Mark read** for Mentions and for thread replies.+- A calmer view, organised the way Slack's Activity is: one list at a time, each row saying who said what.++Choices Diego made: count decisions and agents that asked him by name; tags leave the number. An agent waiting on him that+is left for a day is answered by the PM.++## How it works today (main 4f5f7425c)++- The number is `SuperTabActivity.count` (`desktop/lib/super_tabs/activity.dart:225`): open tags + `decisionsWaiting` ++ tasks with status `needs_human`/`blocked` whose `askedOf ?? requesterId ?? ownerId` is the reader. A stuck task nobody+ was asked about counts for its requester or the Swarm owner.+- The sidebar falls back to `mentionsWaiting + decisionsWaiting` before Activity loads (`project_sidebar.dart:1027`).+- The `decided` set that keeps a task with an open decision from counting twice is built from the decisions **loaded on+ the client**, while the decision part of the number is the server's count. Until Activity is opened once, such a task+ counts twice.+- An agent asks a person by name only through `work.status` with `ask` (`backend/src/superTabs/commands.ts:3312-3333`),+ which writes a decision and sets `askedOf`. So "an agent asked you by name" is a decision, except when the asker already+ has `MAX_OPEN_DECISIONS` (20) open for that person: then `askedOf` is set and the decision is not written.+- A `needs_human` or `blocked` status already reaches the task's lead (`commands.ts:3357`). The PM hears about a stuck task+ at once; only the person's number also counted it.+- **Let PM decide** exists for one decision at a time: `decision.answer` with `delegate: true` takes the recommended+ option, which every decision must have (`decisions.ts:63`, `:121`). Nothing delegates on its own, and nothing records+ when a person set a decision aside (Not now is local to Desktop: `controller.decisionsAside`).+- The view stacks Needs you, New replies and Done today on one page. Every mention row reads "X mentioned you in+ # project", every row is bold, and a thread row's title is the root message's whole text.++## Behaviour++### The number (Desktop)++The Activity number counts only **Needs you**:++- every open decision asked of the reader;+- every task whose agent waits on the reader by name (`assignment.askedOf` is the reader, status `needs_human`) and that+ has no open decision of the reader's.++Tags, thread replies and stuck tasks nobody was asked about are not counted. A stuck task with no `askedOf` stays with the+PM, who was told when it got stuck; it no longer falls to the requester or the Swarm owner in Activity.++The decision part is the server's `decisionsWaiting` until the reader's decisions are loaded, then the loaded list. The+`decided` set is only applied to the loaded list, so a task with an open decision never counts twice.++The Activity row is bold when the number is above zero or a tag or followed thread is unread. With nothing counted it shows+no number. The sidebar's fallback before Activity loads is `decisionsWaiting` alone.++### A decision left for 24 hours goes to the PM (backend)++A decision still unanswered **24 hours after it was asked** (`createdAt + 24h`) is left to the PM: answered with its+recommended option and recorded as `delegated: true, overdue: true`. The clock does not restart. Not now and Hide stay+local to Desktop, as today.++- The sweep runs hourly in the worker. Each pass reads the waiting decisions asked between 8 days and 24 hours ago, at most+ 500, oldest first, so a row that failed or did not fit is tried again next hour until it is 8 days old. Each answer goes through `decision.answer` as the asked person, with+ `operationId = overdue-decision-<id>`. A repeated pass or a person answering at the same moment replays or gets+ `DECISION_ANSWERED`, never a second answer.+- Withdrawn decisions, decisions whose work is over and routing reflections (which expire on their own after 7 days) are+ skipped.+- The notice in the conversation says: "A decision asked in this conversation waited 24 hours, so it was left to the+ {PM name}, who took its recommended option." The PM's line in the person's Buddy chat is the one a delegated answer+ writes today. The leaderboard gives the person no credit, as for any delegated answer (`recordDecision`).+- A pass with any failure logs `[swarm-sweeps] overdue decisions failed` at error level with the count and error codes,+ every time; the decisions stay waiting and the next pass retries. A person no longer in the Swarm or Workspace is skipped.++A task waiting on the reader by name with no decision (the 20-decision cap) is not delegated: it has no recommended option.+It stays in Needs you, and its row's Open takes the reader to the task. That case is rare.++### Let PM decide for all (Desktop)++The Needs you tab shows a bar above its list: "{PM name} takes over anything you leave for 24 hours" and a button **Let+{PM name} decide for all**. The name is the coordinator's when every listed decision is in one project, else "the PMs".+The button is shown while at least one listed decision can be delegated.++Pressing it opens a confirmation: "Let {PM name} decide all {n}?", naming how many decisions it answers ("{PM name} takes+each one's recommended option"), with Cancel and **Let {PM name} decide**. Confirming sends one `decision.answer` with+`delegate: true` per decision, then reads the lists once. Tasks without a decision and tags are not included. A decision+that fails keeps its card's existing failure line and Retry.++### Mark read (Desktop)++- **Mentions:** hovering a row shows **Mark read**, which is today's `mention.done` (it replaces the Mark done label). The+ bar above the list has **Mark all read**, which sends `mention.done` for every unread mention listed, then reads once.+- **Threads:** hovering a row shows **Mark read**, which moves that thread's read mark to its newest reply+ (`controller.markThreadRead(conversationId, rootId, lastReplySequence)`). **Mark all read** does it for every listed+ thread. Unfollow moves to the row's second hover action.++Neither opens anything. Mark all read never touches decisions.++### The view (Desktop)++Activity has three tabs, one list on screen at a time: **Needs you** (red count), **Mentions** and **Threads** (grey+counts of unread rows). It opens on Needs you when it has something, else on the tab with unread rows, else Needs you.+The tab is kept while the view is open, and not saved.++- **Rows** carry an avatar (the author's initial and colour), the author's name, "in # {project}" (the lock mark for a+ private project), the time at the end, and a one-line preview under them. An unread row has a blue dot at its start; a+ read row is not bold and its preview is fainter.+- **Days** split each list into Today, Yesterday and Earlier.+- **Needs you rows** show the question as the preview and its options as buttons under it, the recommended one marked; a+ tap answers. Its end shows "PM in {h}h": hours until `createdAt + 24h`, rounded up, "PM in <1h" in the last hour and+ amber under 2 hours. A task row reads "{agent} is waiting on you" with its question as the preview, and Open.+- **Mentions** lists unread mentions, then recently answered ones (`mentions.earlier`). Mentions from the same author in+ the same conversation and thread that follow each other in the list fold into one row: the newest preview and+ "+{n} more from {author}". Mark read on a folded row marks all of them. An **Unreads only** switch hides read rows.+- **Threads** lists followed threads with unread replies (`attention.shown` where `isNew`). A row's title is the thread's+ subject; its preview is "{last replier}: {last reply text}" (falling back to the root author and text), then "# {project}";+ its end shows "{n} new". **Unreads only** applies here too.+- **Thread subject:** if the root text has a `Title: ` the subject is what follows it up to " — ", ". " or the line's end;+ otherwise the root's first line. Cut to 90 characters with an ellipsis.+- **Empty Needs you:** "Nothing needs you", and when the PM answered any of the reader's decisions today, "{PM name}+ handled {n} for you today" with **See what**, which lists them with the option chosen. Done today is removed; shipped+ tasks remain in their chats and the Tasks view.++### Out of scope++The menu bar list, the phone, the dial and their badges keep their counts. Reactions, saved views and a dense layout are+not added. No change to how tags are made, resolved or expired.++## Design++- **Growth:** one optional field (`overdue`) on existing `SuperTabDecision` rows; nothing new is stored per read. Decisions+ are removed as today.+- **Concurrency:** the sweep answers through `decision.answer`, whose `recordAnswer` updates only waiting rows; a racing+ answer wins once. The receipt id makes a repeated pass a replay.+- **Read cost:** the hourly query reads only waiting decisions asked in the last 8 days, through a new+ `[answeredAt, createdAt]` index (`decision_waiting_created`); answered rows are never examined. Desktop reads no new list.+- **Scale:** at 10x waiting decisions the read grows linearly (capped at 500 a pass); the warning metric is the pass's `overdue` count and+ duration in the `[swarm-sweeps] done` log.+- **Compatibility:** older Desktops ignore `overdue` and show "PM decided"; the new Desktop treats a missing `overdue` as+ false. Older backends have no sweep; the new Desktop still works and only its "PM in" hint is never honoured.+- **Migration + rollback:** `overdue` is optional (no migration). The index is added by the backend release's schema step;+ rollback drops it (`db.SuperTabDecision.dropIndex('decision_waiting_created')`) and reverts the release.+- **Audience:** the sweep acts as the asked person and through the same `answerable` check; Desktop changes only presentation.+- **Identity:** the answer is recorded as the PM's choice (`delegated`), never the person's own, and earns them no credit.+- **Failure:** a failed pass logs every time and retries next hour; a failed send from the button keeps the card's failure+ line and Retry.+- **Platforms:** backend; Desktop on macOS, Linux, Windows and web (the same Flutter screen). Phone and dial unchanged.