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
Decisions: the catch-up card's counts open them; finished work's stop waiting (Dee) (#2454)
0xken15d4a36c774e62
diff --git a/backend/integration/superTabHotReads.test.ts b/backend/integration/superTabHotReads.test.tsindex de77983c4..5eecf41c5 100644--- a/backend/integration/superTabHotReads.test.ts+++ b/backend/integration/superTabHotReads.test.ts@@ -10,7 +10,6 @@ import type { AuthUser } from '../src/lib/ssoAuth.js'import { SuperTabStore } from '../src/superTabs/store.js'import { listGroupIndexes } from '../src/superTabs/parts/indexed.js'import { migrateSwarm } from '../src/superTabs/migration/migrate.js'-import { waitingIn } from '../src/superTabs/decisions.js'import { HostReads } from '../src/superTabs/read/host.js'import { machineSwarms, swarmsIn } from '../src/superTabs/swarmRows.js'import { SwarmReads } from '../src/superTabs/read/service.js'@@ -250,6 +249,9 @@ describe('hot reads read only what they return (roadmap 2.7)', () => {// Another Swarm with running work: a read not bounded by its Swarm reads that one's rows too.await scene()s = await scene()+ // One decision waiting in the work ended last, which that end closes (decisions.ts withdrawIn).+ await db.superTabDecision.create({ data: { id: `${s.tabId}-web`, tabId: s.tabId, batchId: 'w', projectId: 'lead', conversationId: s.web,+ personId: owner.sub, askerAgentId: s.lead, question: 'Ship?', options: ['A', 'B'], recommended: 0, unblocks: 'Work', createdAt: new Date(MIGRATED) } })const hosts = new HostReads(store, { now: () => clock })clock = Date.now()entries = await profiled(async () => {@@ -257,7 +259,6 @@ describe('hot reads read only what they return (roadmap 2.7)', () => {clock = Date.now()await hosts.changes(owner, s.machineId, { cursor: first.cursor })await store.deliveries(owner, s.tabId, s.lead)- await db.$transaction(tx => waitingIn(tx, s.tabId, s.web))// Last: ending the running work releases its run record and open deliveries.const work = ((await db.swarmGroup.findFirst({ where: { tabId: s.tabId, key: s.web } }))!.data as { assignment: { id: string } }).assignment.idawait store.execute(owner, s.tabId, { operationId: randomUUID(),@@ -296,10 +297,12 @@ describe('hot reads read only what they return (roadmap 2.7)', () => {for (const row of rows) expect(row.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(row.nreturned!)})- it('whether a decision waits in a conversation reads only that conversation\'s decisions', () => {+ it('ending work closes its waiting decisions reading only that conversation\'s, never the Swarm\'s others', async () => {const rows = reads(entries, 'SuperTabDecision', ['tabId', 'conversationId'], ['personId'])- expect(rows).toHaveLength(1)- expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(rows[0]!.nreturned!)+ expect(rows.length, JSON.stringify(entries.filter(e => e.ns.endsWith('.SuperTabDecision')))).toBeGreaterThan(0)+ // The other quiet conversations hold waiting decisions too: only the one in this work is examined.+ for (const row of rows) expect(row.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(1)+ expect(await db.superTabDecision.findUnique({ where: { id: `${s.tabId}-web` } })).toMatchObject({ withdrawn: true })})it('no read of these scans a whole collection', () => {diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.tsindex a9f43c211..1a1a6df54 100644--- a/backend/integration/superTabRead.test.ts+++ b/backend/integration/superTabRead.test.ts@@ -812,13 +812,13 @@ describe('decisions asked of one person (v2)', () => {expect((await decisions(s.tabId, peer, 'answered')).map(d => d.id)).toEqual([mine])})- it('takes an answer in a conversation that went quiet and was archived, counts it on a fresh first load, and tells both agents', async () => {+ it('takes an answer in a conversation that went quiet with its task still waiting, counts it on a fresh first load, and tells both agents', async () => {const s = await scene()clock = Date.now()const assignmentId = (await get(`/api/super-tabs/${s.tabId}/parts`, owner)).body.data.groups.find((g: { key: string }) => g.key === s.web).data.assignment.idawait post(s.tabId, { type: 'work.status', conversationId: s.web, assignmentId, status: 'needs_human', result: 'Ship to everyone?',ask: { personId: peer.sub, options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'Turning it on' } }, owner, s.worker)- await writeGroup(s.tabId, s.web, Date.now(), group => { group.assignment = { ...group.assignment!, status: 'done' }; group.archived = true; group.dormant = true })+ await writeGroup(s.tabId, s.web, Date.now(), group => { group.dormant = true })const first = (await get(`/api/super-tabs/${s.tabId}/parts`, peer)).body.dataexpect(first.groups.map((g: { key: string }) => g.key)).not.toContain(s.web)expect(first.derived.decisionsWaiting).toBe(1)@@ -830,6 +830,90 @@ describe('decisions asked of one person (v2)', () => {expect((await get(`/api/super-tabs/${s.tabId}/parts`, peer)).body.data.derived.decisionsWaiting).toBe(0)})+ // Dee, 10-31: "4 decisions wait for you", two asked in tasks already done and merged.+ it('stops waiting once its task is cancelled: closed as withdrawn, listed nowhere, answered by nobody; the project chat\'s still waits', async () => {+ const s = await scene()+ clock = Date.now()+ const ask = async (conversationId: string, text: string) => ((await post(s.tabId, { type: 'decision.ask', conversationId, personId: peer.sub,+ questions: [question(text)] }, owner, s.lead)).body.data.result.decisionIds as string[])[0]!+ const waiting = async () => (await get(`/api/super-tabs/${s.tabId}/parts`, peer)).body.data.derived.decisionsWaiting+ const inWork = await ask(s.web, 'Ship how?')+ const inChat = await ask('lead', 'Name it?')+ expect(await waiting()).toBe(2)+ const assignmentId = (await get(`/api/super-tabs/${s.tabId}/parts`, owner)).body.data.groups.find((g: { key: string }) => g.key === s.web).data.assignment.id+ const cancelled = await post(s.tabId, { type: 'work.cancel', conversationId: s.web, assignmentId, reason: 'Not needed' })+ expect(cancelled.status, JSON.stringify(cancelled.body)).toBe(200)+ expect(await waiting()).toBe(1)+ expect((await decisions(s.tabId, peer)).map(d => d.id)).toEqual([inChat])+ expect(await decisions(s.tabId, peer, 'answered')).toEqual([])+ expect(await decisions(s.tabId, peer, 'settled')).toEqual([])+ expect((await decisions(s.tabId, owner, 'open', s.lead)).map(d => d.id)).toEqual([inChat])+ expect(await decisions(s.tabId, owner, 'answered', s.lead)).toEqual([])+ expect(await db.superTabDecision.findUnique({ where: { id: inWork } })).toMatchObject({ withdrawn: true, choice: null, answeredAt: expect.any(Date) })+ expect(await db.superTabDecision.findUnique({ where: { id: inChat } })).toMatchObject({ answeredAt: null })+ expect((await post(s.tabId, { type: 'decision.answer', decisionId: inWork, choice: 0 }, peer)).body.error?.code).toBe('DECISION_ANSWERED')+ // The catch-up card of that conversation counts none.+ expect((await get(`/api/super-tabs/${s.tabId}/conversations/${s.web}/catch-up?after=0`, peer)).body.data.decisions).toBe(0)+ })++ it('stops waiting once its group is archived by hand, and only there', async () => {+ const s = await scene()+ clock = Date.now()+ const other = String((await post(s.tabId, { type: 'conversation.create', title: 'Search', brief: 'Find things.', checks: [] })).body.data.result.conversationId)+ const ask = async (conversationId: string, text: string) => ((await post(s.tabId, { type: 'decision.ask', conversationId, personId: peer.sub,+ questions: [question(text)] }, owner, s.lead)).body.data.result.decisionIds as string[])[0]!+ const archivedOne = await ask(other, 'Index what?')+ const kept = await ask(s.web, 'Ship how?')+ const archived = await post(s.tabId, { type: 'conversation.archive', conversationId: other, archived: true })+ expect(archived.status, JSON.stringify(archived.body)).toBe(200)+ expect((await decisions(s.tabId, peer)).map(d => d.id)).toEqual([kept])+ expect(await db.superTabDecision.findUnique({ where: { id: archivedOne } })).toMatchObject({ withdrawn: true })+ // Taken out of the archive, it stays closed.+ await post(s.tabId, { type: 'conversation.archive', conversationId: other, archived: false })+ expect((await decisions(s.tabId, peer)).map(d => d.id)).toEqual([kept])+ })++ it('keeps a withdrawn decision closed when its task is reopened, and asks the same question again as a new one', async () => {+ const s = await scene()+ clock = Date.now()+ const ask = async () => ((await post(s.tabId, { type: 'decision.ask', conversationId: s.web, personId: peer.sub,+ questions: [question('Ship how?')] }, owner, s.lead)).body.data.result.decisionIds as string[])[0]!+ const first = await ask()+ const assignmentId = (await get(`/api/super-tabs/${s.tabId}/parts`, owner)).body.data.groups.find((g: { key: string }) => g.key === s.web).data.assignment.id+ expect((await post(s.tabId, { type: 'work.cancel', conversationId: s.web, assignmentId, reason: 'Not needed' })).status).toBe(200)+ const reopened = await post(s.tabId, { type: 'work.assign', conversationId: s.web, agentId: s.worker })+ expect(reopened.status, JSON.stringify(reopened.body)).toBe(200)+ // Open work again, but the old decision does not come back.+ expect(await decisions(s.tabId, peer)).toEqual([])+ expect((await get(`/api/super-tabs/${s.tabId}/parts`, peer)).body.data.derived.decisionsWaiting).toBe(0)+ const again = await ask()+ expect(again).not.toBe(first)+ expect((await decisions(s.tabId, peer)).map(d => d.id)).toEqual([again])+ expect(await db.superTabDecision.findUnique({ where: { id: first } })).toMatchObject({ withdrawn: true, choice: null })+ expect((await post(s.tabId, { type: 'decision.answer', decisionId: again, choice: 1 }, peer)).status).toBe(200)+ })++ it('stops counting one in work that ended before decisions closed (no command closed it): not counted, listed, in catch-up or answerable', async () => {+ const s = await scene()+ clock = Date.now()+ const ask = async (conversationId: string, text: string) => ((await post(s.tabId, { type: 'decision.ask', conversationId, personId: peer.sub,+ questions: [question(text)] }, owner, s.lead)).body.data.result.decisionIds as string[])[0]!+ const stale = await ask(s.web, 'Ship how?')+ const inChat = await ask('lead', 'Name it?')+ // As stored by an older server: done, archived and quiet, its decision still open.+ await writeGroup(s.tabId, s.web, Date.now(), group => { group.assignment = { ...group.assignment!, status: 'done' }; group.archived = true; group.dormant = true })+ // A project chat holding a finished assignment is no work group: its decisions still wait.+ await writeGroup(s.tabId, 'lead', Date.now(), group => { group.assignment = { ...(group.assignment ?? { id: 'x', agentId: s.lead, configuration: {} as never,+ execution: { machineId: 'host', harnessId: 'h', machineOwnerId: owner.sub }, result: null }), status: 'cancelled' } })+ const first = (await get(`/api/super-tabs/${s.tabId}/parts`, peer)).body.data+ expect(first.groups.map((g: { key: string }) => g.key)).not.toContain(s.web)+ expect(first.derived.decisionsWaiting).toBe(1)+ expect((await decisions(s.tabId, peer)).map(d => d.id)).toEqual([inChat])+ expect((await get(`/api/super-tabs/${s.tabId}/conversations/${s.web}/catch-up?after=0`, peer)).body.data.decisions).toBe(0)+ expect((await post(s.tabId, { type: 'decision.answer', decisionId: stale, choice: 0 }, peer)).body.error?.code).toBe('DECISION_ANSWERED')+ expect(await db.superTabDecision.findUnique({ where: { id: stale } })).toMatchObject({ answeredAt: null })+ })+it('reads only the conversations its decisions are in: a quiet one the reader still reads, not one they left, and no other quiet history', async () => {const s = await scene()clock = Date.now()@@ -837,8 +921,8 @@ describe('decisions asked of one person (v2)', () => {questions: [question(text)] }, owner, s.lead)).body.data.result.decisionIds as string[]const [kept] = await ask(s.web, 'Ship how?')await askedBefore(s.tabId, s.privateId, s.lead, ['Keep it?'])- // Both go quiet; the peer then leaves the private one.- await writeGroup(s.tabId, s.web, Date.now(), group => { group.archived = true; group.dormant = true })+ // Both go quiet, the work still open; the peer then leaves the private one.+ await writeGroup(s.tabId, s.web, Date.now(), group => { group.dormant = true })await writeGroup(s.tabId, s.privateId, Date.now(), group => { group.dormant = true; group.audience = { people: [] } })const read: string[] = []const counted = new SuperTabStore(db.$extends({ query: { swarmGroup: { async findMany({ args, query }) {@@ -908,9 +992,9 @@ describe('decisions asked of one person (v2)', () => {it('counts every open decision the reader can open, past 200, reading only which ones and where', async () => {const s = await scene()clock = Date.now()- // 150 in finished work gone quiet, which the peer still reads; then 100 newer in a conversation they have left, quiet too:+ // 150 in open work gone quiet, which the peer still reads; then 100 newer in a conversation they have left, quiet too:// both are read for their access fields alone, and the left one is filtered on those.- await writeGroup(s.tabId, s.web, Date.now(), group => { group.archived = true; group.dormant = true })+ await writeGroup(s.tabId, s.web, Date.now(), group => { group.dormant = true })await writeGroup(s.tabId, s.privateId, Date.now(), group => { group.audience = { people: [] }; group.dormant = true })const asked = (conversationId: string, n: number, from: number) => Array.from({ length: n }, (_, i) => ({ id: `${conversationId}-${i}`,tabId: s.tabId, batchId: `${conversationId}-batch`, projectId: 'lead', conversationId, assignmentId: null, personId: peer.sub,@@ -938,8 +1022,10 @@ describe('decisions asked of one person (v2)', () => {expect(reads[0]).not.toHaveProperty('take')expect(whole).toEqual([])expect(quiet.map(row => row.key).sort()).toEqual([s.web, s.privateId].sort())- for (const row of quiet) expect(['id', 'kind', 'projectId', 'audience']).toEqual(expect.arrayContaining(Object.keys(row.data)))- expect(quiet.find(row => row.key === s.privateId)!.data).toEqual({ id: s.privateId, projectId: 'lead', audience: { people: [] } })+ // And whether its work is over (decisions.ts workOver): its archived mark and its task's status alone.+ for (const row of quiet) expect(['id', 'kind', 'projectId', 'audience', 'archived', 'assignment']).toEqual(expect.arrayContaining(Object.keys(row.data)))+ expect(quiet.find(row => row.key === s.web)!.data.assignment).toEqual({ status: 'working' })+ expect(quiet.find(row => row.key === s.privateId)!.data).toEqual({ id: s.privateId, projectId: 'lead', audience: { people: [] }, archived: false })})it('keeps one answer when two arrive at once, returns the same receipt for a retried answer, and refuses a person removed from the Swarm', async () => {@@ -1059,7 +1145,12 @@ describe('decisions asked of one person (v2)', () => {it('counts an open decision in a quiet conversation on a change read, which loads only some conversations', async () => {const s = await scene()clock = Date.now()- expect((await post(s.tabId, { type: 'decision.ask', conversationId: s.done, personId: peer.sub, questions: [question('Reopen it?')] }, owner, s.lead)).status).toBe(200)+ expect((await post(s.tabId, { type: 'decision.ask', conversationId: s.web, personId: peer.sub, questions: [question('Ship how?')] }, owner, s.lead)).status).toBe(200)+ await writeGroup(s.tabId, s.web, Date.now(), group => { group.dormant = true })+ // Finished work takes no new decision: it would wait for nobody (Dee, 10-31).+ const late = await post(s.tabId, { type: 'decision.ask', conversationId: s.done, personId: peer.sub, questions: [question('Reopen it?')] }, owner, s.lead)+ expect(late.status).toBe(400)+ expect(late.body.error?.code).toBe('WORK_FINISHED')const first = (await get(`/api/super-tabs/${s.tabId}/parts`, peer)).body.dataclock = Date.now()expect((await get(`/api/super-tabs/${s.tabId}/changes?cursor=${first.cursor}`, peer)).body.data.derived.decisionsWaiting).toBe(1)diff --git a/backend/integration/superTabTidy.test.ts b/backend/integration/superTabTidy.test.tsindex 803031fa1..5b2579502 100644--- a/backend/integration/superTabTidy.test.ts+++ b/backend/integration/superTabTidy.test.ts@@ -240,13 +240,16 @@ describe('a finished group', () => {}})- it('stays open while a person\'s decision asked there waits', async () => {+ // Dee, 10-31: a decision asked in finished work waits no more, so it no longer holds the group open.+ it('archives finished work with a person\'s decision still open there, closing it as withdrawn', async () => {const f = await swarm()- await db.superTabDecision.create({ data: { id: randomUUID(), tabId: f.tab, batchId: 'b', conversationId: f.group, projectId: 'p', personId: owner.sub,+ const id = randomUUID()+ await db.superTabDecision.create({ data: { id, tabId: f.tab, batchId: 'b', conversationId: f.group, projectId: 'p', personId: owner.sub,askerAgentId: f.lead, assignmentId: null, question: 'Ship it?', options: ['Yes', 'No'], recommended: 0, unblocks: 'Release', createdAt: new Date(f.clock.now) } })f.clock.now += 40 * MINUTEawait archiveFinishedGroups(db, f.timed, github({}), f.clock.now)- expect(await archived(f)).toBe(false)+ expect(await archived(f)).toBe(true)+ expect(await db.superTabDecision.findUnique({ where: { id } })).toMatchObject({ withdrawn: true, choice: null, answeredAt: new Date(f.clock.now) })})it('stays open once the owner turned tidying off, and never archives the Lead conversation', async () => {@@ -342,7 +345,8 @@ describe('a review nobody reviews', () => {it('stays open when a Ready for review with a new pull request commits during its close, so the work keeps a review', async () => {const f = await waiting()let during: (() => Promise<unknown>) | null = () => f.ready('Ready: yes, revision fff. https://github.com/example/parser/pull/11')- const hooked = db.$extends({ query: { superTabDecision: { async findFirst({ args, query }) {+ // Paused at the close's first write, which closes the decisions still waiting there.+ const hooked = db.$extends({ query: { superTabDecision: { async updateMany({ args, query }) {if (during && (args.where as { conversationId?: string } | undefined)?.conversationId === f.review.key) { const run = during; during = null; await run() }return query(args)} } } })diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 299cb43e5..2f5e24aad 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1290,11 +1290,15 @@ model SuperTabDecision {/// "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?+ /// Closed unanswered because the work it was asked about is over: its task done or cancelled, or its group archived+ /// (decisions.ts withdrawIn; Dee, 10-31). Set with answeredAt and no choice, so it waits no more, is in no list and goes+ /// with the answered ones after the ledger's weeks. Absent on every other decision.+ withdrawn Boolean?@@index([tabId, personId, createdAt])@@index([tabId, askerAgentId, createdAt])@@index([tabId, projectId, createdAt])- /// Whether a decision waits in a conversation (decisions.ts waitingIn).+ /// The decisions waiting in a conversation whose work ended (decisions.ts withdrawIn).@@index([tabId, conversationId])}diff --git a/backend/src/superTabs/decisions.test.ts b/backend/src/superTabs/decisions.test.tsindex 9b2a9630a..cb669f65b 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, listDecisions, waitingInProject, type DecisionTarget } from './decisions.js'+import { checkAsker, decisionsWaiting, listDecisions, 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]' }@@ -237,3 +237,98 @@ describe('the decisions waiting in a project', () => {select: { conversationId: true, personId: true } }])})})++// Dee, 10-31: "4 decisions wait for you", two of them asked in tasks already done and merged.+describe('a decision whose work is over', () => {+ const at = (s: ReturnType<typeof swarm>, id: string) => s.state.conversations.find(c => c.id === id)!+ const ended = (s: ReturnType<typeof swarm>, change: (state: ReturnType<typeof swarm>['state']) => void) => {+ const before = structuredClone(s.state), after = structuredClone(s.state)+ change(after)+ return workEnded(before, after)+ }++ it('is over once its work group\'s task is done or cancelled, or the group archived; not while its task is open or reopened', () => {+ const s = swarm()+ const group = at(s, s.group)+ expect(workOver(s.state, group)).toBe(false)+ for (const status of ['done', 'cancelled'] as const) expect(workOver(s.state, { ...group, assignment: { ...group.assignment!, status } })).toBe(true)+ for (const status of ['working', 'needs_human', 'blocked', 'review', 'stopped', 'lost'] as const) {+ expect(workOver(s.state, { ...group, assignment: { ...group.assignment!, status } })).toBe(false)+ }+ expect(workOver(s.state, { ...group, archived: true })).toBe(true)+ expect(workOver(s.state, { ...group, assignment: null })).toBe(false)+ })++ it('is never over in a project chat, a Buddy chat or a closed Chat with PM, whatever they hold', () => {+ const s = swarm()+ const finished = { archived: true, assignment: { ...at(s, s.group).assignment!, status: 'cancelled' as const } }+ expect(workOver(s.state, { ...at(s, 'lead'), ...finished })).toBe(false)+ expect(workOver(s.state, { ...at(s, s.group), ...finished, kind: 'buddy' })).toBe(false)+ expect(workOver(s.state, { ...at(s, s.group), ...finished, audience: { people: [] } })).toBe(false)+ })++ it('names the conversations a write ended, once: not those already over, nor one reopened', () => {+ const s = swarm()+ expect(ended(s, state => { state.conversations.find(c => c.id === s.group)!.assignment!.status = 'done' })).toEqual([s.group])+ expect(ended(s, state => { state.conversations.find(c => c.id === s.group)!.archived = true })).toEqual([s.group])+ expect(ended(s, state => { state.conversations.find(c => c.id === s.group)!.assignment!.status = 'review' })).toEqual([])+ s.run({ type: 'work.cancel', conversationId: s.group, assignmentId: s.assignmentId, reason: 'Not needed' })+ expect(ended(s, state => { state.conversations.find(c => c.id === s.group)!.archived = true })).toEqual([])+ expect(ended(s, state => { state.conversations.find(c => c.id === s.group)!.assignment = null })).toEqual([])+ })++ it('closes those still waiting there as withdrawn, never a routing reflection\'s, and only in the conversations named', async () => {+ const calls: unknown[] = []+ const tx = { superTabDecision: { updateMany: async (args: unknown) => { calls.push(args); return { count: 2 } } } } as unknown as Prisma.TransactionClient+ expect(await withdrawIn(tx, 'tab', [], 5)).toBe(0)+ expect(calls).toEqual([])+ expect(await withdrawIn(tx, 'tab', ['g1', 'g1'], 5)).toBe(2)+ expect(calls).toEqual([{ where: { tabId: 'tab', conversationId: 'g1', AND: [+ { OR: [{ answeredAt: null }, { answeredAt: { isSet: false } }] },+ { OR: [{ kind: { isSet: false } }, { kind: null }, { kind: { not: 'routing-reflection' } }] }] },+ data: { answeredAt: new Date(5), withdrawn: true } }])+ })++ it('leaves the open list and the count, closed or not yet, while one in an open task stays', async () => {+ const s = swarm()+ const other = s.run({ type: 'conversation.create', title: 'Search', brief: 'Find things.', checks: [] }).result.conversationId as string+ at(s, other).assignment = { ...at(s, s.group).assignment!, id: 'old', status: 'done' }+ const row = (id: string, conversationId: string) => ({ id, batchId: id, projectId: 'lead', conversationId, 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 })+ const rows = [row('open-task', s.group), row('done-task', other), row('project-chat', 'lead')]+ const tx = { superTabDecision: { findMany: async () => rows } } as unknown as Prisma.TransactionClient+ expect((await listDecisions(tx, 'tab', s.state, peer, 'open')).decisions.map(d => d.id)).toEqual(['open-task', 'project-chat'])+ expect((await decisionsWaiting(tx, 'tab', s.state, peer)).count).toBe(2)+ // Its answered history stays: a decision answered before the work ended is still listed as answered.+ const answered = rows.map(r => ({ ...r, answeredAt: new Date(2), choice: 0 }))+ const read = { superTabDecision: { findMany: async () => answered } } as unknown as Prisma.TransactionClient+ expect((await listDecisions(read, 'tab', s.state, peer, 'settled')).decisions.map(d => d.id)).toEqual(['open-task', 'done-task', 'project-chat'])+ })++ 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))+ expect(ask().decisions).toHaveLength(1)+ s.run({ type: 'work.cancel', conversationId: s.group, assignmentId: s.assignmentId, reason: 'Not needed' })+ expect(ask).toThrow(expect.objectContaining({ code: 'WORK_FINISHED' }))+ // Anyone who may not ask there is refused as before, never told the work is finished.+ expect(() => s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer', questions: [question('Reopen it?')] }, owner))+ .toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))+ // The project chat always takes one.+ expect(s.run({ type: 'decision.ask', conversationId: 'lead', personId: 'peer', questions: [question('Reopen it?')] }, asAgent(s.lead)).decisions).toHaveLength(1)+ })++ it('takes no answer, closed or not yet, with the code an answered one gets', () => {+ const s = swarm()+ const decision: DecisionTarget = { id: 'decision-1', personId: 'peer', conversationId: s.group, projectId: 'lead', askerAgentId: s.worker,+ question: 'Ship how?', options: ['A', 'B'], recommended: 0, answeredAt: null, createdAt: 0, assignmentId: null }+ const answer = (d: DecisionTarget) => () => s.run({ type: 'decision.answer', decisionId: d.id, choice: 0 }, peer, { decision: d })+ expect(answer({ ...decision, answeredAt: 5, withdrawn: true })).toThrow(expect.objectContaining({ code: 'DECISION_ANSWERED', message: expect.stringContaining('no longer waits') }))+ s.run({ type: 'work.cancel', conversationId: s.group, assignmentId: s.assignmentId, reason: 'Not needed' })+ expect(answer(decision)).toThrow(expect.objectContaining({ code: 'DECISION_ANSWERED', message: expect.stringContaining('no longer waits') }))+ // Anyone but the person asked is told it does not exist, as before: never that its work is finished.+ expect(() => s.run({ type: 'decision.answer', decisionId: decision.id, choice: 0 }, owner, { decision }))+ .toThrow(expect.objectContaining({ code: 'NOT_FOUND' }))+ })+})diff --git a/backend/src/superTabs/decisions.ts b/backend/src/superTabs/decisions.tsindex 32d72f132..ef1e530d3 100644--- a/backend/src/superTabs/decisions.ts+++ b/backend/src/superTabs/decisions.ts@@ -9,7 +9,7 @@ import type { Prisma } from '@prisma/client'import { z } from 'zod'import { agentDisplayName } from './agentNames.js'import { AGENT_ONLY, fail, isLeads, person, stableId, type Actor, type Author, type Conversation, type SuperTabState } from './model.js'-import { agentProjectId, canReadGroup, groupProject, isClosedPmChat, ledProject, projectAgent, projectOf, readsRecordsIn } from './projects.js'+import { agentProjectId, canReadGroup, groupProject, isClosedPmChat, ledProject, projectAgent, projectOf, projectsOf, readsRecordsIn } from './projects.js'import { LEDGER_WEEKS } from './leaderboard/record.js'import { coordinatorNameOf } from './instructions.js'import { WEEK_MS } from './leaderboard/week.js'@@ -47,6 +47,8 @@ export interface DecisionTarget {/** When it was asked, and the task whose needs_human asked it: the leaderboard credits the answer (leaderboard/record.ts). */createdAt: number; assignmentId: string | nullkind?: string | null+ /** Closed unanswered once its work was over (withdrawIn). */+ 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 }@@ -59,6 +61,8 @@ export function askDecisions(state: SuperTabState, group: Conversation, personIdfail('INVALID_PERSON', `${asked.email} cannot read this conversation.`, 400)}for (const q of questions) if (q.recommended >= q.options.length) fail('INVALID_DECISION', 'A question must recommend one of its options.', 400)+ // It would wait for nobody: none waits where the work is over (workOver).+ if (workOver(state, group)) fail('WORK_FINISHED', 'This work is finished, so a decision asked here would not wait. Ask in the project chat, or reopen the task first.', 400)const projectId = groupProject(state, group).idreturn questions.map((q, index) => ({ ...q, id: stableId(from.operationId, 'decision', String(index)), batchId: from.operationId,conversationId: group.id, projectId, personId, askerAgentId: from.askerAgentId, assignmentId: from.assignmentId, ...from.kind ? { kind: from.kind } : {} }))@@ -73,6 +77,19 @@ export function checkAsker(state: SuperTabState, actor: Actor, group: Conversatireturn actor.agentId}+/** Whether the work a decision was asked about is over, so it waits no more (Dee, 10-31: decisions of tasks already done and+ * merged still said they waited): a work group whose task is done or cancelled, or which is archived. Never a project chat,+ * a Buddy chat or a closed Chat with PM, which hold no task of their own (tidy.ts archivable leaves them out alike). A+ * deleted group is none: the reads find no conversation for its decisions. Reads only what an access check of a quiet+ * conversation brings (ACCESS_FIELDS). */+export function workOver(state: SuperTabState, group: Pick<Conversation, 'id' | 'kind' | 'audience' | 'archived' | 'assignment'>): boolean {+ if (group.kind || group.audience || projectsOf(state).some(p => p.leadConversationId === group.id)) return false+ return group.archived === true || ['done', 'cancelled'].includes(group.assignment?.status ?? '')+}++/** The answer a decision whose work is over gets: the code an answered one gets, which a client already takes as gone. */+const NO_LONGER_WAITS = 'This decision no longer waits: its work is finished.'+/** The conversation a decision was asked in, while the person asked is still in the Swarm and still reads it, or read it* before it closed as a Chat with PM: checked on every answer and on every retry of one (review of #1753). Anyone else is* told it does not exist. */@@ -106,6 +123,7 @@ export function answerDecision(state: SuperTabState, actor: Actor, decision: Decif ((given.choice === undefined) === !given.delegate) fail('INVALID_DECISION', 'Choose one of its options, or leave it to the PM.', 400)const group = answerable(state, actor, decision)const asked = decision!+ if (asked.withdrawn || workOver(state, group)) fail('DECISION_ANSWERED', NO_LONGER_WAITS)if (asked.answeredAt !== null) fail('DECISION_ANSWERED', 'This decision is already answered.')if (given.delegate && !(asked.recommended >= 0 && asked.recommended < asked.options.length)) {fail('INVALID_DECISION', 'This decision has no recommended option to leave to the PM.', 400)@@ -143,16 +161,31 @@ function delegatedLine(state: SuperTabState, projectId: string, leadId: string,/** Mongo omits unset fields, so `answeredAt: null` alone would miss a row written without it. */const waiting: Prisma.SuperTabDecisionWhereInput = { OR: [{ answeredAt: null }, { answeredAt: { isSet: false } }] }-/** Whether a person's decision asked in this conversation still waits: a group that has one is never archived by itself. */-export async function waitingIn(tx: Tx, tabId: string, conversationId: string): Promise<boolean> {- return !!await tx.superTabDecision.findFirst({ where: { tabId, conversationId, ...waiting }, select: { id: true } })-}-/** How many decisions asked of `personId` in this conversation still wait for them (catchUp.ts). */export async function waitingFor(tx: Tx, tabId: string, conversationId: string, personId: string): Promise<number> {return tx.superTabDecision.count({ where: { tabId, conversationId, personId, ...waiting } })}+/** Closes the decisions still waiting in these conversations, whose work is over (workOver), as withdrawn: answered at+ * [now] with no choice, so none waits, none is listed, none can be answered and a new ask of the same question is a new+ * decision. Never a routing reflection's, which expires on its own (expireReflections). Run in the transaction that ends+ * the work (store.ts), so a concurrent answer conflicts with it and only one of them counts. The number closed. */+export async function withdrawIn(tx: Tx, tabId: string, conversationIds: readonly string[], now: number): Promise<number> {+ let closed = 0+ // One by one through the conversation index: a command ends one conversation's work, rarely a few (hotFilters.test.ts).+ for (const conversationId of new Set(conversationIds)) {+ closed += (await tx.superTabDecision.updateMany({ where: { tabId, conversationId, AND: [waiting, notReflection] },+ data: { answeredAt: new Date(now), withdrawn: true } })).count+ }+ return closed+}++/** The conversations whose work this write ended (workOver in [after], not in [before]): their waiting decisions close. */+export function workEnded(before: SuperTabState, after: SuperTabState): string[] {+ const was = new Map(before.conversations.map(c => [c.id, c]))+ return after.conversations.filter(c => workOver(after, c) && !(was.has(c.id) && workOver(before, was.get(c.id)!))).map(c => c.id)+}+/** What makes an ask a repeat: the same asker, task, person, conversation, question, options, recommendation and what it* unblocks. Another asker, another task or other options with the same text is a decision of its own (review of #1753). */const repeatKey = (d: Pick<DecisionDraft, 'askerAgentId' | 'assignmentId' | 'personId' | 'conversationId' | 'question' | 'options' | 'recommended' | 'unblocks'>) =>@@ -216,8 +249,9 @@ export async function expireReflections(tx: Tx, tabId: string, projectId: stringexport async function readAskedDecision(tx: Tx, tabId: string, id: string): Promise<DecisionTarget | undefined> {const row = await tx.superTabDecision.findFirst({ where: { id, tabId },select: { id: true, personId: true, conversationId: true, projectId: true, askerAgentId: true, question: true, options: true, recommended: true,- answeredAt: true, createdAt: true, assignmentId: true, kind: true } })- return row ? { ...row, answeredAt: row.answeredAt?.getTime() ?? null, createdAt: row.createdAt.getTime(), assignmentId: row.assignmentId ?? null } : undefined+ answeredAt: true, createdAt: true, assignmentId: true, kind: true, withdrawn: true } })+ return row ? { ...row, answeredAt: row.answeredAt?.getTime() ?? null, createdAt: row.createdAt.getTime(), assignmentId: row.assignmentId ?? null,+ withdrawn: row.withdrawn === true } : undefined}/** Conflicts with a concurrent answer of the same decision: only the first one counts. */@@ -242,8 +276,8 @@ function readerWhere(state: SuperTabState, actor: Actor): Prisma.SuperTabDecisioreturn { OR: [{ askerAgentId: actor.agentId }, ...led ? [{ projectId: led.id }] : []] }}-/** What an access check reads of a conversation (projects.ts canReadGroup). */-const ACCESS_FIELDS = ['id', 'kind', 'projectId', 'audience'] as const+/** What an access check reads of a conversation (projects.ts canReadGroup), and whether its work is over (workOver). */+const ACCESS_FIELDS = ['id', 'kind', 'projectId', 'audience', 'archived', 'assignment.status'] as const/** The conversations [ids] names: those the read loaded, and the rest (quiet, archived, or left out of a light read) read* here, so a decision in one still counts. With [only], the rest bring only those fields. A deleted conversation is none. */@@ -269,6 +303,8 @@ const readableIn = (state: SuperTabState, actor: Actor, groups: Map<string, Conv/** Answered by the person themself: as `waiting`, a row written before `delegated` has no such field. */const yours: Prisma.SuperTabDecisionWhereInput = { OR: [{ delegated: { isSet: false } }, { delegated: null }, { delegated: false }] }+/** Answered by someone: not closed unanswered (withdrawIn), which every row from before `withdrawn` was not. */+const notWithdrawn: Prisma.SuperTabDecisionWhereInput = { OR: [{ withdrawn: { isSet: false } }, { withdrawn: null }, { withdrawn: false }] }/** Which decisions a list holds: those still open, or those answered. `settled` is every answered one, those left to the* PM included; `answered` is what an older Desktop reads and labels each "You chose", so for a person it leaves out those@@ -279,14 +315,15 @@ const LIST_PAGE = 200/** ponytail: the newest LIST_PAGE per list; `more` says when there are others. Page it if a reader ever has more. */async function readable(tx: Tx, tabId: string, state: SuperTabState, actor: Actor, list: DecisionList) {const which = list === 'open' ? [waiting] : list === 'answered' && actor.kind === 'person'- ? [{ answeredAt: { not: null } }, yours] : [{ answeredAt: { not: null } }]+ ? [{ answeredAt: { not: null } }, yours, notWithdrawn] : [{ answeredAt: { not: null } }, notWithdrawn]const read = await tx.superTabDecision.findMany({ where: { tabId, AND: [readerWhere(state, actor), ...which] },orderBy: { createdAt: 'desc' }, take: LIST_PAGE + 1 })const rows = read.slice(0, LIST_PAGE)const groups = await conversationsOf(tx, tabId, state, rows.map(r => r.conversationId))return { more: read.length > LIST_PAGE, rows: rows.flatMap(row => {const group = readableIn(state, actor, groups, row.conversationId)- return group ? [{ row, group }] : []+ // An open one whose work is over waits no more, closed or not yet (one from before withdrawIn).+ return group && !(list === 'open' && workOver(state, group)) ? [{ row, group }] : []}) }}@@ -314,7 +351,10 @@ export async function decisionsWaiting(tx: Tx, tabId: string, state: SuperTabStaactor: Extract<Actor, { kind: 'person' }>): Promise<{ count: number; digest: string }> {const rows = await tx.superTabDecision.findMany({ where: { tabId, AND: [readerWhere(state, actor), waiting] }, select: { id: true, conversationId: true } })const groups = await conversationsOf(tx, tabId, state, rows.map(r => r.conversationId), ACCESS_FIELDS)- const ids = rows.filter(row => readableIn(state, actor, groups, row.conversationId)).map(row => row.id).sort()+ const ids = rows.filter(row => {+ const group = readableIn(state, actor, groups, row.conversationId)+ return group && !workOver(state, group)+ }).map(row => row.id).sort()return { count: ids.length, digest: createHash('sha256').update(ids.join('\n')).digest('base64url').slice(0, 16) }}diff --git a/backend/src/superTabs/digest.test.ts b/backend/src/superTabs/digest.test.tsindex d90177b60..8ff05a314 100644--- a/backend/src/superTabs/digest.test.ts+++ b/backend/src/superTabs/digest.test.ts@@ -83,6 +83,14 @@ describe('a project\'s morning digest', () => {expect(decisionLines(state, lampOS(state), [])).toEqual([])})+ it('leaves out decisions in work that is over: its task done or cancelled, or archived (Dee, 10-31)', () => {+ const state = fixture()+ const group = state.conversations.find(c => c.id === 'g7')!+ group.assignment = { ...group.assignment!, status: 'done' }+ expect(decisionLines(state, lampOS(state), [{ conversationId: 'g7', personId: 'owner', count: 1 }, { conversationId: 'g3', personId: 'ann', count: 1 }]))+ .toEqual(['- #3 Lexer: 1 for [email protected]'])+ })+it('puts the decisions waiting in the Lead\'s digest wake-up only when there are some', () => {const state = fixture(), lead = state.agents.find(a => a.id === 'lead')!expect(digestRequest(state, lead, EIGHT, [{ conversationId: 'g7', personId: 'ann', count: 1 }])!.text).toMatch(/\nDecisions waiting:\n- #7 Pricing: 1 for ann@example\.com$/)diff --git a/backend/src/superTabs/digest.ts b/backend/src/superTabs/digest.tsindex 62ddc7ffd..73e06cf48 100644--- a/backend/src/superTabs/digest.ts+++ b/backend/src/superTabs/digest.ts@@ -2,6 +2,7 @@ import { activeWork, author, stableId, type Agent, type Conversation, type Messaimport { agentDisplayName } from './agentNames.js'import { canReadGroup, ledProject, type SwarmProject } from './projects.js'import { reportGroups } from './projectUpdates.js'+import { workOver } from './decisions.js'import { DEFAULT_TIME_ZONE } from './costs/reflection.js'// Night shift (v2 B): people wake to one message per project saying what the Swarm did overnight. At the project's local@@ -96,7 +97,8 @@ export function decisionLines(state: SuperTabState, project: SwarmProject, waiticonst counts = new Map<string, Map<string, number>>()for (const { conversationId, personId, count } of waiting) {const group = groups.find(g => g.id === conversationId), asked = state.people.find(p => p.id === personId)- if (!group || !asked || !canReadGroup(state, { kind: 'person', userId: asked.id, email: asked.email }, group)) continue+ // None waits where the work is over (decisions.ts workOver).+ if (!group || !asked || workOver(state, group) || !canReadGroup(state, { kind: 'person', userId: asked.id, email: asked.email }, group)) continueconst people = counts.get(group.id) ?? new Map<string, number>()counts.set(group.id, people.set(asked.email, (people.get(asked.email) ?? 0) + count))}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 9aa260b28..8f166a30b 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -69,7 +69,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 { dropHeldTags, listMentions, markDone, mentionsWaiting, openTags, readMention, resolveByReply, resolveWhenWorked, writeMentions } from './mentions.js'-import { answerable, askDecisions, MAX_OPEN_DECISIONS, REFLECTION_DECISION, reflectionDecisions, expireReflections, fullFor, listDecisions, type DecisionList, readAskedDecision, recordAnswer, repeatOf, waitingFor, waitingIn, waitingInProject, writeDecisions } from './decisions.js'+import { answerable, askDecisions, MAX_OPEN_DECISIONS, REFLECTION_DECISION, reflectionDecisions, expireReflections, fullFor, listDecisions, type DecisionList, readAskedDecision, recordAnswer, repeatOf, 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'import { DEFAULT_ROUTING_POLICY, type RoutingPolicy } from './routingPolicy.js'@@ -1614,6 +1614,10 @@ export class SuperTabStore {if (command.type === 'decision.ask') effects.result.decisionIds = ids}if (effects.decisionAnswer) await recordAnswer(tx, tabId, effects.decisionAnswer, context.now)+ // Work this command ended (done, cancelled, archived) closes the decisions still waiting there (Dee, 10-31). After this+ // command's own answer and asks, so an answer in the same write counts and a reopened task's new ask is a new decision.+ const over = workEnded(original, effects.state)+ if (over.length) await withdrawIn(tx, tabId, over, context.now)if (claimed.length) {// Conflicts with a concurrent send of the same file: only one message can take it.const taken = await tx.superTabAttachment.updateMany({ where: { tabId, id: { in: claimed }, ...unused },@@ -2431,7 +2435,8 @@ export class SuperTabStore {const [rows, decisions] = await Promise.all([this.db.superTabMessage.findMany({ where: { tabId, conversationId, sequence: { gt: after } }, orderBy: [{ sequence: 'asc' }, { id: 'asc' }],take: CATCH_UP_SCAN + 1 }),- waitingFor(this.db, tabId, conversationId, user.sub),+ // None waits where the work is over, closed or not yet (decisions.ts workOver).+ workOver(state, group) ? 0 : waitingFor(this.db, tabId, conversationId, user.sub),])const scanned = rows.slice(0, CATCH_UP_SCAN), reads = readsRow(actor, buddy)// A task chat's copy of a Lead's notice stored before it was marked is read by no one, as on the page (pageReads.ts).@@ -3302,7 +3307,8 @@ export class SuperTabStore {// Only the group it reviews as the pass read it: one this write did not load would hide its open pull requests.const review = !finished && !!reviewOf && group.reviewOf === reviewOf && reviewClosable(state, group, now) && read(reviewPullRequests(state, group))if (!finished && !review) return false- if (await waitingIn(tx, tabId, groupId)) return false+ // Its work is over: a decision still waiting there waits no more (Dee, 10-31), as when the work ended by a command.+ await withdrawIn(tx, tabId, [groupId], now)group.archived = trueconst line = finished ? archiveLine(state, group, now) : reviewCloseLine(state, group, checked, now), rows = line ? [line] : []const sequences = numberMessages(state, rows, now)diff --git a/desktop/lib/super_tabs/catch_up_card.dart b/desktop/lib/super_tabs/catch_up_card.dartindex 398b11296..895b50591 100644--- a/desktop/lib/super_tabs/catch_up_card.dart+++ b/desktop/lib/super_tabs/catch_up_card.dart@@ -5,22 +5,32 @@ import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_icon_button.dart';import '../widgets/desktop_chrome.dart';import 'catch_up.dart';+import 'message_row.dart' show SuperTabLink;/// "While you were away", under the New messages line: what needs the reader,/// what is blocked and what landed, each item opening its message/// ([onOpen]), and Close ([onClose]). Each list has its words as well as its/// mark, so colour is never the only signal.+///+/// A count with a list of its own elsewhere opens it: the decisions waiting+/// ([onOpenDecisions]) and the tags beyond Needs you's ([onOpenMentions]).+/// Blocked's and Landed's counts have no such list and stay words, as does a+/// count whose callback is null.class SuperTabCatchUpCard extends StatelessWidget {const SuperTabCatchUpCard({super.key,required this.summary,required this.onOpen,required this.onClose,+ this.onOpenDecisions,+ this.onOpenMentions,});final SuperTabCatchUp summary;final ValueChanged<String> onOpen;final VoidCallback onClose;+ final VoidCallback? onOpenDecisions;+ final VoidCallback? onOpenMentions;@overrideWidget build(BuildContext context) {@@ -59,6 +69,8 @@ class SuperTabCatchUpCard extends StatelessWidget {AppIcons.hand,DesktopChrome.accent,summary.needsYou,+ onMore: onOpenMentions,+ moreKey: const ValueKey('super-catch-up-mentions'),),_section('Blocked',@@ -77,6 +89,8 @@ class SuperTabCatchUpCard extends StatelessWidget {decisions == 1? '1 decision waits for you': '$decisions decisions wait for you',+ onTap: onOpenDecisions,+ linkKey: const ValueKey('super-catch-up-decisions'),),// Never a partial summary read as the whole absence.if (summary.more)@@ -92,11 +106,17 @@ class SuperTabCatchUpCard extends StatelessWidget {);}- Widget _note(String text) => Padding(+ Widget _note(String text, {VoidCallback? onTap, Key? linkKey}) => Padding(padding: const EdgeInsets.only(top: grid.AppDesktop.controlGap),- child: Text(text, style: DesktopChrome.metadata()),+ child: _count(text, onTap: onTap, linkKey: linkKey),);+ /// [text] as a link to what it counts, or as words with nowhere to go.+ Widget _count(String text, {VoidCallback? onTap, Key? linkKey}) =>+ onTap == null+ ? Text(text, style: DesktopChrome.metadata())+ : _SuperTabCatchUpLink(key: linkKey, text: text, onTap: onTap);+Widget _header() => Row(children: [Icon(@@ -133,8 +153,10 @@ class SuperTabCatchUpCard extends StatelessWidget {String heading,IconData icon,Color color,- SuperTabCatchUpList list,- ) {+ SuperTabCatchUpList list, {+ VoidCallback? onMore,+ Key? moreKey,+ }) {if (list.items.isEmpty) return const SizedBox.shrink();return Padding(padding: const EdgeInsets.only(top: grid.AppDesktop.controlGap),@@ -155,7 +177,7 @@ class SuperTabCatchUpCard extends StatelessWidget {onOpen: () => onOpen(item.messageId),),if (list.more > 0)- Text('${list.more} more', style: DesktopChrome.metadata()),+ _count('${list.more} more', onTap: onMore, linkKey: moreKey),],),);@@ -213,3 +235,44 @@ class _SuperTabCatchUpRow extends StatelessWidget {),);}++/// A count that opens what it counts: accent words, a hand cursor and an+/// underline under the pointer, reached by Tab and pressed with Enter or+/// Space, the focus rim drawn as on the chat's other links ([SuperTabLink]).+class _SuperTabCatchUpLink extends StatefulWidget {+ const _SuperTabCatchUpLink({+ super.key,+ required this.text,+ required this.onTap,+ });++ final String text;+ final VoidCallback onTap;++ @override+ State<_SuperTabCatchUpLink> createState() => _SuperTabCatchUpLinkState();+}++class _SuperTabCatchUpLinkState extends State<_SuperTabCatchUpLink> {+ var _hovered = false;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return SuperTabLink(+ onTap: widget.onTap,+ label: widget.text,+ child: MouseRegion(+ onEnter: (_) => setState(() => _hovered = true),+ onExit: (_) => setState(() => _hovered = false),+ child: Text(+ widget.text,+ style: DesktopChrome.metadata(color: DesktopChrome.accent).copyWith(+ decoration: _hovered ? TextDecoration.underline : null,+ decorationColor: DesktopChrome.accent,+ ),+ ),+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 6d3513886..d43415160 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -1587,15 +1587,7 @@ class _SuperTabViewState extends State<SuperTabView>},// Activity on every platform (Lead, 10-31): the Mac's menu bar and Dock// still say what waits, and the sidebar lists it as Slack does.- onNotifications: () {- _closeSidebar();- setState(() {- _showNotifications = true;- _showThreads = false;- _showPullRequests = false;- });- widget.onCloseTerminal?.call();- },+ onNotifications: _openActivity,onOpenAgent: (agent) {_closeSidebar();setState(() {@@ -1653,6 +1645,25 @@ class _SuperTabViewState extends State<SuperTabView>if (mention != null) unawaited(_openMention(mention));}+ /// Shows Activity in the main pane, as its sidebar row does; with [filter],+ /// on that list (the catch-up card's counts). [from] is the controller the+ /// asking widget was built for: a press arriving once the view has moved to+ /// another Swarm opens nothing.+ void _openActivity({+ SuperTabActivityFilter? filter,+ SuperTabController? from,+ }) {+ if (!mounted || (from != null && from != c)) return;+ if (filter != null) SuperTabActivity.of(c).setFilter(filter);+ _closeSidebar();+ setState(() {+ _showNotifications = true;+ _showThreads = false;+ _showPullRequests = false;+ });+ widget.onCloseTerminal?.call();+ }+bool get _notificationsVisible =>_showNotifications && !_devicesVisible && !c.accessRevoked;@@ -3138,6 +3149,8 @@ class _SuperTabViewState extends State<SuperTabView>_ => false,},);+ // The controller these rows were built for, read when a row is pressed.+ final shownFor = c;Widget row(int index) {final entry = entries[index];final message = entry.message;@@ -3165,6 +3178,15 @@ class _SuperTabViewState extends State<SuperTabView>unawaited(_openMessage(c.selectedId, messageId)),onClose: () =>setState(() => _unread.catchUps.dismiss(c.selectedId)),+ // Activity lists only the reader's own decisions and tags.+ onOpenDecisions: () => _openActivity(+ filter: SuperTabActivityFilter.decisions,+ from: shownFor,+ ),+ onOpenMentions: () => _openActivity(+ filter: SuperTabActivityFilter.mentions,+ from: shownFor,+ ),),],// The message itself is kept in place: itsdiff --git a/desktop/test/super_tab_catch_up_shots_test.dart b/desktop/test/super_tab_catch_up_shots_test.dartindex 2f34cedf3..f062d9f7e 100644--- a/desktop/test/super_tab_catch_up_shots_test.dart+++ b/desktop/test/super_tab_catch_up_shots_test.dart@@ -1,6 +1,7 @@import 'dart:io';import 'dart:ui' as ui;+import 'package:flutter/gestures.dart';import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';import 'package:flutter_test/flutter_test.dart';@@ -28,18 +29,23 @@ Map<String, dynamic> _item(int sequence, String author, String text) => {};/// The chat opened after a while away: the New messages line with the-/// catch-up card under it, at normal and enlarged text.+/// catch-up card under it, at normal and enlarged text, and with the pointer+/// on its decisions link.void main() {setUpAll(() async {if (shots != null) await loadPreviewFonts();});- for (final (brightness, scale) in [- (Brightness.light, 1.0),- (Brightness.dark, 1.0),- (Brightness.dark, 1.8),+ for (final (brightness, scale, hovered) in [+ (Brightness.light, 1.0, false),+ (Brightness.dark, 1.0, false),+ (Brightness.dark, 1.8, false),+ (Brightness.light, 1.0, true),+ (Brightness.dark, 1.0, true),]) {- final name = '${brightness.name}${scale > 1 ? '-large-text' : ''}';+ final name =+ '${brightness.name}${scale > 1 ? '-large-text' : ''}'+ '${hovered ? '-decisions-hover' : ''}';testWidgets('screenshots for review ($name)', (tester) async {final picture = GlobalKey();final server = ConversationServer();@@ -112,6 +118,14 @@ void main() {);await tester.pumpAndSettle();expect(find.byKey(const ValueKey('super-catch-up')), findsOne);+ if (hovered) {+ final link = find.byKey(const ValueKey('super-catch-up-decisions'));+ expect(link, findsOne);+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse.addPointer(location: tester.getCenter(link));+ addTearDown(mouse.removePointer);+ await tester.pumpAndSettle();+ }expect(tester.takeException(), isNull);if (shots == null) return;await tester.runAsync(() async {diff --git a/desktop/test/super_tab_catch_up_test.dart b/desktop/test/super_tab_catch_up_test.dartindex 6b718698a..18b323f47 100644--- a/desktop/test/super_tab_catch_up_test.dart+++ b/desktop/test/super_tab_catch_up_test.dart@@ -1,10 +1,15 @@import 'dart:async';+import 'package:flutter/gestures.dart';import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/activity.dart';+import 'package:harness/super_tabs/activity_view.dart';import 'package:harness/super_tabs/catch_up.dart';+import 'package:harness/super_tabs/catch_up_card.dart';import 'package:harness/super_tabs/controller.dart';import 'package:harness/super_tabs/message_row.dart';import 'package:harness/super_tabs/view.dart';@@ -14,6 +19,8 @@ import 'support/super_tab_fixture.dart';const _card = ValueKey('super-catch-up');const _close = ValueKey('super-catch-up-close');const _line = ValueKey('super-new-messages-line');+const _decisions = ValueKey('super-catch-up-decisions');+const _mentions = ValueKey('super-catch-up-mentions');/// [count] messages in the Lead conversation from the Lead agent.ConversationServer _server(int count) {@@ -61,6 +68,15 @@ Map<String, dynamic> _summary({'needsYou': _list(needsYou, total: needsYouTotal > 0 ? needsYouTotal : null),};+/// Every list with more than it shows, and two decisions: Needs you 3 more,+/// Blocked 2 more, Landed 4 more.+Map<String, dynamic> _counted() => {+ ..._summary(decisions: 2),+ 'needsYou': _list([_item(25, 'Question 3')], total: 4),+ 'blocked': _list([_item(26, 'Stuck: no simulator', by: 'Iris')], total: 3),+ 'landed': _list([_item(27, 'Avatars')], total: 5),+};+void main() {Future<SuperTabController> show(WidgetTester tester,@@ -293,4 +309,166 @@ void main() {expect(find.byKey(_card), findsNothing);expect(find.byKey(_line), findsOneWidget);});++ group('the counts open what they count', () {+ Future<SuperTabController> showCounted(WidgetTester tester) async {+ tester.view.physicalSize = const Size(1200, 860);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);+ final server = _server(40)..markReadElsewhere('lead', 10);+ server.catchUps['lead'] = _counted();+ return show(tester, server);+ }++ Finder activityView() => find.byType(SuperTabActivityView);++ testWidgets('the decisions line opens Activity on Decisions', (+ tester,+ ) async {+ final c = await showCounted(tester);+ expect(+ find.descendant(+ of: find.byKey(_decisions),+ matching: find.text('2 decisions wait for you'),+ ),+ findsOneWidget,+ );+ expect(activityView(), findsNothing);+ await tester.tap(find.byKey(_decisions));+ await tester.pumpAndSettle();+ expect(activityView(), findsOneWidget);+ expect(SuperTabActivity.of(c).filter, SuperTabActivityFilter.decisions);+ });++ testWidgets("Needs you's more opens Activity on Mentions", (tester) async {+ final c = await showCounted(tester);+ expect(+ find.descendant(+ of: find.byKey(_mentions),+ matching: find.text('3 more'),+ ),+ findsOneWidget,+ );+ await tester.tap(find.byKey(_mentions));+ await tester.pumpAndSettle();+ expect(activityView(), findsOneWidget);+ expect(SuperTabActivity.of(c).filter, SuperTabActivityFilter.mentions);+ });++ for (final (key, filter, press, name) in [+ (+ _decisions,+ SuperTabActivityFilter.decisions,+ LogicalKeyboardKey.enter,+ 'Enter',+ ),+ (+ _mentions,+ SuperTabActivityFilter.mentions,+ LogicalKeyboardKey.space,+ 'Space',+ ),+ ]) {+ testWidgets('$name on the focused ${filter.name} link opens '+ 'it, the focus drawn', (tester) async {+ final c = await showCounted(tester);+ expect(find.byKey(key), findsOneWidget);+ // The link takes keyboard focus as the app's other controls do.+ final node = Focus.of(+ tester.element(+ find.descendant(of: find.byKey(key), matching: find.byType(Text)),+ ),+ );+ node.requestFocus();+ await tester.pumpAndSettle();+ expect(node.hasPrimaryFocus, isTrue);+ final rim = tester.widget<DecoratedBox>(+ find+ .descendant(+ of: find.byKey(key),+ matching: find.byType(DecoratedBox),+ )+ .first,+ );+ expect(+ (rim.decoration as BoxDecoration).border!.top.color,+ grid.AppDesktop.focus,+ );+ await tester.sendKeyEvent(press);+ await tester.pumpAndSettle();+ expect(activityView(), findsOneWidget);+ expect(SuperTabActivity.of(c).filter, filter);+ });+ }++ testWidgets('a hand over the link, which underlines it in the accent', (+ tester,+ ) async {+ await showCounted(tester);+ final text = find.descendant(+ of: find.byKey(_decisions),+ matching: find.text('2 decisions wait for you'),+ );+ TextStyle style() => tester.widget<Text>(text).style!;+ expect(style().decoration, isNot(TextDecoration.underline));+ expect(style().color, grid.AppPalette.accentOnSurface);+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse.addPointer(location: Offset.zero);+ addTearDown(mouse.removePointer);+ await mouse.moveTo(tester.getCenter(text));+ await tester.pumpAndSettle();+ expect(+ RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),+ SystemMouseCursors.click,+ );+ expect(style().decoration, TextDecoration.underline);+ });++ testWidgets("Blocked's and Landed's more are words, not links", (+ tester,+ ) async {+ await showCounted(tester);+ for (final more in ['2 more', '4 more']) {+ expect(inCard(more), findsOneWidget);+ expect(+ find.ancestor(of: inCard(more), matching: find.byType(SuperTabLink)),+ findsNothing,+ );+ expect(+ find.ancestor(of: inCard(more), matching: find.byType(InkWell)),+ findsNothing,+ );+ }+ // Only the two that have somewhere to go.+ expect(+ find.descendant(+ of: find.byKey(_card),+ matching: find.byType(SuperTabLink),+ ),+ findsNWidgets(2),+ );+ });+ });++ testWidgets('with nowhere to open, the counts are plain words', (+ tester,+ ) async {+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabCatchUpCard(+ summary: SuperTabCatchUp.fromJson(_counted()),+ onOpen: (_) {},+ onClose: () {},+ ),+ ),+ ),+ );+ expect(inCard('2 decisions wait for you'), findsOneWidget);+ expect(inCard('3 more'), findsOneWidget);+ expect(find.byKey(_decisions), findsNothing);+ expect(find.byKey(_mentions), findsNothing);+ expect(find.byType(SuperTabLink), findsNothing);+ });}