Skip to content

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.

Merge batch 11-04 b1105: #2883 #2853 #2854 #2855 (#2908)

0xken15cb6bb430ab89
diff --git a/backend/integration/superTabNotAvailable.test.ts b/backend/integration/superTabNotAvailable.test.ts
index 47c2374c2..7004090af 100644
--- a/backend/integration/superTabNotAvailable.test.ts
+++ b/backend/integration/superTabNotAvailable.test.ts
@@ -95,6 +95,7 @@ function calls(tab: string, chat: string, project: string) {
json('GET', 'GET /api/super-tabs/:tabId/mentions', `${t}/mentions?state=waiting`),
json('GET', 'GET /api/super-tabs/:tabId/decisions', `${t}/decisions?state=open`),
json('GET', 'GET /api/super-tabs/:tabId/leaderboard', `${t}/leaderboard?projectId=${project}`),
+ json('GET', 'GET /api/super-tabs/:tabId/proposals', `${t}/proposals?projectId=${project}`),
json('GET', 'GET /api/super-tabs/:tabId/sharing', `${t}/sharing`),
json('POST', 'POST /api/super-tabs/:tabId/sharing', `${t}/sharing`, { operationId: op(), revision: 0, access: { mode: 'link', role: 'viewer' } }),
json('GET', 'GET /api/super-tabs/:tabId/routing-policy', `${t}/routing-policy`),
diff --git a/backend/integration/superTabProposals.test.ts b/backend/integration/superTabProposals.test.ts
new file mode 100644
index 000000000..52a4f2518
--- /dev/null
+++ b/backend/integration/superTabProposals.test.ts
@@ -0,0 +1,69 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import type { PrismaClient } from '@prisma/client'
+import { applyCommand, type Command } from '../src/superTabs/commands.js'
+import { createSuperTab, type Actor, type SuperTabState } from '../src/superTabs/model.js'
+import { listNamedIndexes } from '../src/superTabs/parts/indexed.js'
+import { databaseProposalReads, openProposals } from '../src/superTabs/proposals.js'
+import { planDatabase } from './plans.test-support.js'
+
+// The Tasks view's Proposals (#2569) read the project chat's proposal roots and their threads as the chat page does. A busy
+// project chat holds thousands of rows, nearly all task lines and talk: the roots' read must not walk them.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+let state: SuperTabState
+const TAB = 'swarm', CHAT = 'lead', CHAT_ROWS = 3_000
+const owner: Actor = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }
+const T0 = Date.parse('2026-11-01T00:00:00.000Z')
+
+beforeAll(async () => {
+ ({ replica, db } = await planDatabase('swarm_proposals_test'))
+ await listNamedIndexes(db)
+ state = createSuperTab(TAB, 'Pilot', { id: 'owner', email: '[email protected]' }, 'test')
+ let next = 0
+ const run = (command: Command) => { state = applyCommand(state, owner, command, { operationId: `op${next++}`, now: T0,
+ contribution: { machineOwnerId: 'host', contributorId: 'owner' } }).state }
+ run({ type: 'project.cadence', projectId: 'lead', minutes: 5 })
+ run({ type: 'agent.add', conversationId: CHAT, harnessId: 'pm', machineId: 'machine', name: 'pm', configuration, lead: true })
+ const pm = state.conversations.find(c => c.id === CHAT)!.leadId!
+ const person = { kind: 'person', id: 'peer', name: '[email protected]', membershipGeneration: 'first' }
+ let sequence = 0
+ const message = (id: string, extra: Record<string, unknown> = {}) => ({ id, tabId: TAB, conversationId: CHAT, sequence: ++sequence, author: person,
+ text: 'Talk', recipientIds: [], mentions: [], thread: id, createdAt: new Date(T0 + sequence * 1000), ...extra })
+ const proposal = (id: string, title: string) => [
+ message(id, { text: `Let's build: ${title}`, source: { kind: 'buddy-proposal', personId: 'peer', buddyId: 'buddy', ownerMessageId: `ask-${id}` } }),
+ message(`${id}-details`, { author: { kind: 'agent', id: 'buddy', name: 'Buddy' }, text: 'Goal: ...', replyTo: id, thread: id }),
+ ]
+ const rows = [
+ ...proposal('open', 'Sync edits'),
+ ...proposal('answered', 'Answered'), message('answered-pm', { author: { kind: 'agent', id: pm, name: 'pm' }, replyTo: 'answered', thread: 'answered' }),
+ ...proposal('tasked', 'Tasked'), message('tasked-line', { author: { kind: 'agent', id: pm, name: 'pm' }, replyTo: 'tasked', thread: 'tasked',
+ source: { kind: 'system', ask: 'on-it' } }),
+ // From before threads: no thread at all, and nobody answered it.
+ { ...message('old', { text: "Let's build: Old proposal", source: { kind: 'buddy-proposal', personId: 'peer' } }), thread: undefined },
+ ]
+ // The project chat's other rows: task lines with their replies, and people talking.
+ for (let i = 0; rows.length < CHAT_ROWS; i++) {
+ rows.push(message(`line-${i}`, { source: { kind: 'task-line' } }), message(`line-${i}-reply`, { replyTo: `line-${i}`, thread: `line-${i}`, source: { kind: 'system', ask: 'on-it' } }),
+ message(`talk-${i}`))
+ }
+ // Another proposal last, so the newest rows are not all proposals.
+ rows.push(...proposal('newest', 'Newest'))
+ await db.superTabMessage.createMany({ data: rows.map(({ thread, ...row }) => ({ ...row, ...thread ? { thread } : {} })) as never })
+}, 180_000)
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+describe('the open-proposal read', () => {
+ it('lists the unanswered proposals, oldest first, from the chat the database holds', async () => {
+ const chat = state.conversations.find(c => c.id === CHAT)!
+ expect(await openProposals(state, chat, databaseProposalReads(db, TAB, CHAT))).toEqual([
+ { messageId: 'open', title: 'Sync edits', personId: 'peer', at: T0 + 1000 },
+ { messageId: 'old', title: 'Old proposal', personId: 'peer', at: T0 + 9000 },
+ { messageId: 'newest', title: 'Newest', personId: 'peer', at: expect.any(Number) },
+ ])
+ })
+})
diff --git a/backend/src/routes/superTabs.test.ts b/backend/src/routes/superTabs.test.ts
index b69ab13f7..19701decf 100644
--- a/backend/src/routes/superTabs.test.ts
+++ b/backend/src/routes/superTabs.test.ts
@@ -306,3 +306,34 @@ describe('a machine\'s readings for all its Swarms in one call (DB 2.5)', () =>
expect(calls).toHaveLength(1)
})
})
+
+// The Tasks view's Proposals (#2569): one project's open Buddy proposals, read by the store as the project chat's reader.
+describe('a project\'s open proposals', () => {
+ let app: FastifyInstance
+ const calls: unknown[][] = []
+ beforeEach(async () => {
+ calls.length = 0
+ app = Fastify()
+ app.setErrorHandler(errorHandler)
+ app.addHook('onRequest', async request => { request.user = { sub: 'u1', email: '[email protected]', autonomousEnv: 'prod', role: 'user' } as never })
+ const store = { proposals: async (...args: unknown[]) => { calls.push(args); return { proposals: [{ messageId: 'm1', title: 'Sync edits', personId: 'p1', at: 5 }] } } }
+ await app.register(superTabRoutes, { store: store as never, github: null, reads: {} as never, hosts: {} as never })
+ await app.ready()
+ })
+ afterEach(async () => { await app.close() })
+
+ it('answers the store\'s list for the project named, as the signed-in person', async () => {
+ const res = await app.inject({ method: 'GET', url: '/api/super-tabs/tab-1/proposals?projectId=app' })
+ expect(res.statusCode).toBe(200)
+ expect(res.json()).toEqual({ success: true, data: { proposals: [{ messageId: 'm1', title: 'Sync edits', personId: 'p1', at: 5 }] } })
+ expect(calls).toEqual([[expect.objectContaining({ sub: 'u1' }), 'tab-1', 'app']])
+ })
+
+ it('refuses a read that names no project, or anything else', async () => {
+ for (const query of ['', '?projectId=', '?projectId=app&asAgentId=a1']) {
+ const res = await app.inject({ method: 'GET', url: `/api/super-tabs/tab-1/proposals${query}` })
+ expect(res.statusCode, query).toBe(400)
+ }
+ expect(calls).toEqual([])
+ })
+})
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index b0975372b..bb796a393 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -99,6 +99,8 @@ const activityReadBody = z.object({ through: z.string().datetime() }).strict()
const threadParams = messageParams.extend({ threadId: id })
const fileParams = messageParams.extend({ messageId: id, attachmentId: id })
const noQuery = z.object({}).strict()
+// The project whose open Buddy proposals a person reads (superTabs/proposals.ts).
+const proposalsQuery = z.object({ projectId: id }).strict()
// The reader's own catch-up (superTabs/catchUp.ts): no asAgentId, since agents read every message as it comes.
const catchUpQuery = z.object({ after: z.coerce.number().int().nonnegative().safe() }).strict()
// Pages by (sequence, id) (design 4.6): `afterId`/`beforeId` go with `after`/`before`, from the previous page's `next`.
@@ -510,6 +512,10 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
if (wait) return sendError(reply.header('Retry-After', String(wait)), 'Too many thread reads. Try again in a moment.', 'RATE_LIMITED', 429)
return respond(reply, () => readFollowedThreads(store, req.user!, req.params.tabId))
})
+ // One project's Buddy proposals its PM has not answered, oldest first (superTabs/proposals.ts): the Tasks view's Proposals.
+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof proposalsQuery> }>('/api/super-tabs/:tabId/proposals',
+ { preHandler: [validateParams(tabParams), validateQuery(proposalsQuery)] },
+ (req, reply) => respond(reply, () => store.proposals(req.user!, req.params.tabId, req.query.projectId)))
// A person's Activity (superTabs/activity.ts): replies to their messages and reactions to them, read when its digest moves.
app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof noQuery> }>('/api/super-tabs/:tabId/activity',
{ preHandler: [validateParams(tabParams), validateQuery(noQuery)] }, async (req, reply) => {
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index bc1e148c1..ba48983a4 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -13,6 +13,7 @@ import { appendRouting, instructionsHash } from './instructions.js'
import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'
import { DEFAULT_ROUTING_POLICY, effectivePolicy } from './routingPolicy.js'
import { NOW, owner as richOwner, peer as richPeer, richSwarm } from './read/fixture.test-support.js'
+import { groupView } from './read/views.js'
const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
/** What an older client's routing, policy, skill-set or role save answers (project instructions, phase 4). */
@@ -5217,3 +5218,91 @@ describe('lead.switch', () => {
expect(failed.messages[0]!.text).toBe("Couldn't switch the PM: signed out. please retry. It is back on Codex.")
})
})
+
+// A project's Next up (Tasks view, #2569): a person or the project's PM orders it, one sparse rank per task, and the PM marks a
+// promise with a not-before date.
+describe('the Next-up queue (work.queue)', () => {
+ function queued() {
+ const f = routed()
+ const open = (title: string, projectId?: string) => f.run({ type: 'conversation.create', ...projectId ? { projectId } : {}, title, brief: `${title}.`, checks: [] })
+ .result.conversationId as string
+ const [a, b, c] = [open('Drafts'), open('Sync'), open('Search')] as [string, string, string]
+ const task = (id: string) => f.state.conversations.find(g => g.id === id)!
+ const queue = (conversationId: string, fields: { after?: string | null; notBefore?: string | null }) =>
+ commandSchema.parse({ type: 'work.queue', conversationId, ...fields })
+ return { f, a, b, c, open, task, queue }
+ }
+
+ it('moves a task after another for a person, between the two around it', () => {
+ const { f, a, b, c, task, queue } = queued()
+ f.run(queue(c, { after: a }))
+ expect(task(c).queueRank).toBeGreaterThan(task(a).number!)
+ expect(task(c).queueRank).toBeLessThan(task(b).number!)
+ // Only the task moved is written.
+ expect(task(a).queueRank).toBeUndefined()
+ expect(task(b).queueRank).toBeUndefined()
+ f.run(queue(b, { after: null }))
+ expect(task(b).queueRank).toBeLessThan(task(a).number!)
+ expect(groupView(task(c), new Set())).toMatchObject({ queueRank: task(c).queueRank })
+ })
+
+ it('takes the PM\'s not-before date, and clears it with null', () => {
+ const { f, a, task, queue } = queued()
+ f.run(queue(a, { notBefore: '2026-12-04' }), f.leadActor)
+ expect(task(a).notBefore).toBe('2026-12-04')
+ expect(task(a).queueRank).toBeUndefined()
+ expect(groupView(task(a), new Set())).toMatchObject({ notBefore: '2026-12-04' })
+ f.run(queue(a, { notBefore: null }), f.leadActor)
+ expect(task(a)).not.toHaveProperty('notBefore')
+ })
+
+ it('is refused to any other agent of the project', () => {
+ const { f, a, b, queue } = queued()
+ const engineer: Actor = { kind: 'agent', agentId: f.add('engineer'), machineOwnerId: 'host-owner' }
+ const before = structuredClone(f.state)
+ expect(() => f.run(queue(b, { after: a }), engineer)).toThrow(expect.objectContaining({ code: 'COORDINATOR_REQUIRED' }))
+ expect(() => f.run(queue(b, { notBefore: '2026-12-04' }), f.workerActor)).toThrow(expect.objectContaining({ code: 'COORDINATOR_REQUIRED' }))
+ expect(f.state).toEqual(before)
+ })
+
+ it('refuses to place a task after one that is not an open task of its project, or after itself', () => {
+ const { f, a, b, c, open, queue } = queued()
+ const other = f.run({ type: 'project.create', name: 'Firmware', visibility: 'public', brief: '' }).result as { projectId: string; conversationId: string }
+ const elsewhere = open('Flash', other.projectId)
+ const archived = open('Old')
+ f.run({ type: 'conversation.archive', conversationId: archived, archived: true })
+ const step = f.run({ type: 'conversation.create', title: 'Review', brief: 'Review it.', reviewOf: a, step: 'Review', checks: [] }).result.conversationId as string
+ const before = structuredClone(f.state)
+ for (const after of [elsewhere, other.conversationId, archived, step, b, 'lead', 'no-such-task']) {
+ expect(() => f.run(queue(b, { after })), after).toThrow(expect.objectContaining({ code: 'QUEUE_UNKNOWN', status: 400,
+ message: 'Name an open task of this project to place it after, or null for the top.' }))
+ }
+ // Nor does anything but an open task of the project move: its chat or a step.
+ for (const moved of ['lead', step]) expect(() => f.run(queue(moved, { after: c })), moved).toThrow(expect.objectContaining({ code: 'QUEUE_UNKNOWN', status: 400 }))
+ expect(() => f.run(queue(archived, { after: c }))).toThrow(expect.objectContaining({ code: 'ARCHIVED' }))
+ f.state.conversations.push({ id: 'private', title: 'Private', leadId: null, agentIds: [], archived: false, brief: '', checks: [], assignment: null,
+ lastMessageSequence: 0, audience: { people: [{ id: 'owner', generation: f.state.people[0]!.generation }] } })
+ // A Chat with PM from before Buddies is nobody's to read now (buddies.test.ts), so it reads as missing.
+ expect(() => f.run(queue('private', { after: c }))).toThrow(expect.objectContaining({ code: 'NOT_FOUND' }))
+ f.state.conversations.pop()
+ expect(f.state).toEqual(before)
+ })
+
+ it('refuses a malformed date, and a move with neither field', () => {
+ const parse = (fields: Record<string, unknown>) => commandSchema.safeParse({ type: 'work.queue', conversationId: 'task', ...fields }).success
+ for (const notBefore of ['2026-12-4', '2026-02-30', '2026-13-01', 'Dec 4', '2026-12-04T00:00:00Z', '']) expect(parse({ notBefore }), notBefore).toBe(false)
+ expect(parse({})).toBe(false)
+ expect(parse({ after: 'other', notBefore: '2028-02-29' })).toBe(true)
+ expect(parse({ after: null })).toBe(true)
+ expect(parse({ notBefore: null })).toBe(true)
+ })
+
+ it('does the work once when the same operation comes again', () => {
+ const { f, a, c, task, queue } = queued()
+ f.run(queue(c, { after: a, notBefore: '2026-12-04' }), owner, { operationId: 'move' })
+ const once = structuredClone(f.state)
+ expect(task(c)).toMatchObject({ queueRank: expect.any(Number), notBefore: '2026-12-04' })
+ f.run(queue(c, { after: a, notBefore: '2026-12-04' }), owner, { operationId: 'move' })
+ expect(f.state).toEqual(once)
+ })
+})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index a8a644eb8..cec8d53d0 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -54,6 +54,7 @@ import { askBuddyModel, buddyModelResult, sendBuddyHome, sessionModel } from './
import { launchRefusedLine, leadJoined, leadOvertaken, leadStartFailed, leadStarting, leadHost, LEAD_CAPABILITY, placeLead } from './leadStart.js'
import { appendRouting, coordinatorNameOf, routingSummary, FIRST_INSTRUCTIONS, FIRST_SUMMARY, instructionsHash, instructionsTextSchema, legacyRoleName, liveNotes, MAX_NOTES, noteTextSchema, roleNameSchema, summarySchema, type PmNote } from './instructions.js'
import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'
+import { placeAfter, queueSiblings } from './taskQueue.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
/** A route override's reason when its agent gave none: following another candidate needs none (project instructions). */
@@ -63,6 +64,12 @@ const NO_REASON = 'No reason given.'
export const IGNORED_NOTE = 'Routing and roles live in each project\'s instructions now. Update Harness to edit them there.'
const title = z.string().trim().min(1).max(160)
const reason = z.string().trim().min(1).max(300)
+/** A calendar day, YYYY-MM-DD, that exists. */
+const day = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Give the date as YYYY-MM-DD.')
+ .refine(value => {
+ const date = new Date(`${value}T00:00:00Z`)
+ return !Number.isNaN(date.getTime()) && date.toISOString().startsWith(value)
+ }, 'Give a date that exists.')
/** What a host reports it can do for a Product Manager's switch; a host from before it is never asked (HOST_OUTDATED). */
const SWITCH_CAPABILITY = 'leadSwitch'
const SWITCH_LEASE_MS = 15 * 60_000
@@ -215,6 +222,10 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('conversation.rename'), conversationId: id, title }).strict(),
z.object({ type: z.literal('conversation.archive'), conversationId: id, archived: z.boolean() }).strict(),
z.object({ type: z.literal('conversation.requester'), conversationId: id, personId: id.nullable() }).strict(),
+ // A task's place in its project's Next up (taskQueue.ts): `after` the open task it goes right after, null for the top, absent
+ // to stay; `notBefore` a day it should not start before, null to clear.
+ z.object({ type: z.literal('work.queue'), conversationId: id, after: id.nullable().optional(), notBefore: day.nullable().optional() }).strict()
+ .refine(c => c.after !== undefined || c.notBefore !== undefined, 'Give the task a place (after) or a not-before date.'),
// The Lead's record that a request's pull request merged (leaderboard/record.ts recordMerged); `mergedAt` for a backfill.
// `fixes`: the merged PR this one fixes, for its model's fixes after merge (leaderboard/record.ts recordFix).
z.object({ type: z.literal('conversation.merged'), conversationId: id, pullRequestUrl: z.string().max(400).regex(PULL_REQUEST_URL),
@@ -2060,6 +2071,23 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
else delete group.requesterId
break
}
+ case 'work.queue': {
+ chatOnly(command.conversationId)
+ coordinatorOrPerson(state, actor, command.conversationId)
+ const task = open(state, command.conversationId)
+ // One answer for whatever is not an open task of this project, so it never tells what another project holds.
+ const siblings = queueSiblings(state, groupProject(state, task))
+ if (!siblings.includes(task)) fail('QUEUE_UNKNOWN', 'Only an open task of a project moves in its Next up.', 400)
+ if (command.after !== undefined) {
+ if (command.after !== null && (command.after === task.id || !siblings.some(s => s.id === command.after))) {
+ fail('QUEUE_UNKNOWN', 'Name an open task of this project to place it after, or null for the top.', 400)
+ }
+ for (const [groupId, rank] of placeAfter(siblings, task.id, command.after)) conversation(state, groupId).queueRank = rank
+ }
+ if (command.notBefore === null) delete task.notBefore
+ else if (command.notBefore !== undefined) task.notBefore = command.notBefore
+ break
+ }
case 'conversation.merged': {
chatOnly(command.conversationId)
projectChatWork(command.conversationId)
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 570be3b1f..5a505388c 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -392,6 +392,10 @@ export interface Conversation {
stepUp?: StepUp
/** The last route, start or assignment on its task by an agent of its project, or its coordinator's post there (commands.ts). */
leadAction?: { kind: 'assign' | 'route' | 'start' | 'post'; at: number }
+ /** Its place in its project's Next up (taskQueue.ts), set by work.queue. Absent: it sorts by its number. */
+ queueRank?: number
+ /** The day (YYYY-MM-DD) its work should not start before, a promise the PM marks with work.queue. */
+ notBefore?: string
}
/** A step up: the attempt it opened (2 or 3), the least quality from then on, why, when, and what the failed attempt left for
* the next one's brief; the failed start that caused it, if one did. */
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index c844cb5b3..65186793f 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -16,7 +16,7 @@ const conversation: Required<Conversation> = {
task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', teamWritten: true, step: 'Review', reviewStamp: { assignmentId: 'w', handoff: 1 }, checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, lastPersonSequence: 0, pullRequestUrls: [], pullRequestEvents: {}, cards: {},
messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' }, reactionSeq: 0,
requesterId: 'p', ledger: {}, proposals: [], buddyName: 'Sparky', buddySessions: [], buddyDownTold: true, liveness: { state: 'quiet', why: 'silent', since: 1 }, leadAction: { kind: 'post', at: 1 },
- stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' },
+ stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' }, queueRank: 1.5, notBefore: '2026-12-04',
}
describe('the light conversation projection (parts/light.ts)', () => {
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index a6af96c23..7370f99e5 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -27,7 +27,7 @@ export const GROUP_FIELDS = {
always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status',
'assignment.lost'],
whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],
- unread: ['number', 'brief', 'reviewOf', 'teamWritten', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'lastPersonSequence', 'pullRequestUrls', 'pullRequestEvents', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp',
+ unread: ['number', 'brief', 'reviewOf', 'teamWritten', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'lastPersonSequence', 'pullRequestUrls', 'pullRequestEvents', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp', 'queueRank', 'notBefore',
'assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf', 'assignment.reviewFoundAt', 'assignment.changesRequestedAt', 'assignment.toldEngineerAt',
'assignment.handoffs', 'assignment.verdicts'],
} as const
diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.ts
index 66977978c..d42ba8c87 100644
--- a/backend/src/superTabs/parts/touches.ts
+++ b/backend/src/superTabs/parts/touches.ts
@@ -119,6 +119,11 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState
leadCheck(projectOfGroup(command.conversationId)?.id)
member(command.personId ?? undefined)
break
+ // A move reads that the task it goes after is still open in the project: archiving it meets the move here.
+ case 'work.queue':
+ leadCheck(projectOfGroup(command.conversationId)?.id)
+ group(command.after ?? undefined)
+ break
case 'message.send': {
// Every start a post makes, a thread session's or the one Buddy's in an older project chat (commands.ts
// startOldChatBuddy), counts its machine's slots, as buddy.create's does, and meets a concurrent removal of the Buddy it
diff --git a/backend/src/superTabs/proposals.test.ts b/backend/src/superTabs/proposals.test.ts
new file mode 100644
index 000000000..67b23bf99
--- /dev/null
+++ b/backend/src/superTabs/proposals.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command } from './commands.js'
+import { createSuperTab, type Actor, type Author, type SuperTabState } from './model.js'
+import type { ThreadReply } from './pageReads.js'
+import { MAX_PROPOSALS, openProposals, proposalChat, type ProposalReads, type ProposalRoot } from './proposals.js'
+
+// The Tasks view's Proposals (#2569): a project's Buddy proposals its PM has not answered, by #2867's rule (threads.ts askOf).
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }
+const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }
+
+/** A Swarm whose project chat has its PM, and peer, a member. */
+function swarm() {
+ let state = createSuperTab('swarm', 'Pilot', { id: 'owner', email: owner.email }, 'test')
+ state.people.push({ id: 'peer', email: peer.email, role: 'collaborator', generation: 'first' })
+ let next = 0
+ const run = (command: Command, actor: Actor = owner) => {
+ state = applyCommand(state, actor, command, { operationId: `op${next++}`, now: 1000,
+ contribution: { machineOwnerId: 'host', contributorId: 'owner' } }).state
+ }
+ run({ type: 'project.cadence', projectId: 'lead', minutes: 5 })
+ run({ type: 'agent.add', conversationId: 'lead', harnessId: 'pm', machineId: 'machine', name: 'pm', configuration, lead: true })
+ const chat = () => state.conversations.find(c => c.id === 'lead')!
+ return { run, chat, get state(): SuperTabState { return state }, pm: chat().leadId! }
+}
+
+const person = (id: string): Author => ({ kind: 'person', id, name: id, membershipGeneration: 'first' })
+const agent = (id: string): Author => ({ kind: 'agent', id, name: id, membershipGeneration: 'first' })
+/** A proposal's root as buddy.propose posts it, at sequence [at]. */
+const root = (id: string, at: number, title = `Proposal ${id}`): ProposalRoot => ({ id, sequence: at, text: `Let's build: ${title}`, createdAt: new Date(at),
+ source: { kind: 'buddy-proposal', personId: 'peer', buddyId: 'buddy', ownerMessageId: `ask-${id}` } })
+/** A thread's rows as pageThreads gives them: its root, then each reply. */
+const rows = (of: ProposalRoot, ...replies: Array<{ author: Author; ask?: ThreadReply['ask'] }>): ThreadReply[] => [
+ { thread: of.id, id: of.id, author: person('peer'), mentions: [], sequence: of.sequence, createdAt: of.createdAt, agentOnly: false, routing: false, kind: 'buddy-proposal' },
+ ...replies.map((reply, i) => ({ thread: of.id, id: `${of.id}-r${i}`, author: reply.author, mentions: [], sequence: of.sequence + i + 1,
+ createdAt: new Date(of.createdAt.getTime() + i + 1), agentOnly: false, routing: false, ...reply.ask ? { kind: 'system', ask: reply.ask } : {} })),
+]
+
+/** The chat as the database reads it: roots newest first before a sequence, and the threads of the roots named. */
+function chatReads(roots: ProposalRoot[], threads: ThreadReply[]) {
+ const calls: Array<{ before: number | undefined; take: number }> = []
+ const reads: ProposalReads = {
+ roots: async (before, take) => {
+ calls.push({ before, take })
+ return roots.filter(r => before === undefined || r.sequence < before).sort((a, b) => b.sequence - a.sequence).slice(0, take)
+ },
+ threads: async ids => threads.filter(row => ids.includes(row.thread)),
+ }
+ return { reads, calls }
+}
+
+describe('a project\'s open proposals', () => {
+ it('lists those its PM has not answered, oldest first: none it replied to in their thread, and none a task marks', async () => {
+ const s = swarm(), details = { author: agent('buddy') }
+ const [open, answered, onIt, closed, personal, old] = [root('open', 10, 'Sync edits'), root('answered', 20), root('on-it', 30), root('closed', 40),
+ root('personal', 50, 'Offline drafts'), root('old', 5, 'Old proposal')]
+ const { reads } = chatReads([open, answered, onIt, closed, personal, old], [
+ ...rows(open, details),
+ ...rows(answered, details, { author: agent(s.pm) }),
+ // A task opened from it replies in its thread with its row's tag (taskLine.ts).
+ ...rows(onIt, details, { author: person('owner'), ask: 'on-it' }),
+ ...rows(closed, details, { author: person('owner'), ask: 'closed' }),
+ // A person's reply, the owner's too, is not the PM's answer.
+ ...rows(personal, details, { author: person('owner') }),
+ // A proposal from before #2867 with no reply at all has no thread summary: nobody answered it.
+ ])
+ expect(await openProposals(s.state, s.chat(), reads)).toEqual([
+ { messageId: 'old', title: 'Old proposal', personId: 'peer', at: 5 },
+ { messageId: 'open', title: 'Sync edits', personId: 'peer', at: 10 },
+ { messageId: 'personal', title: 'Offline drafts', personId: 'peer', at: 50 },
+ ])
+ })
+
+ it('keeps the newest 100 open, read in batches, and reads no further once it has them', async () => {
+ const s = swarm()
+ const roots = Array.from({ length: 250 }, (_, i) => root(`p${i}`, i + 1))
+ const { reads, calls } = chatReads(roots, roots.flatMap(r => rows(r, { author: agent('buddy') })))
+ const listed = await openProposals(s.state, s.chat(), reads)
+ expect(listed).toHaveLength(MAX_PROPOSALS)
+ expect(listed.map(p => p.messageId)).toEqual(roots.slice(-MAX_PROPOSALS).map(r => r.id))
+ expect(calls).toEqual([{ before: undefined, take: MAX_PROPOSALS }])
+ // Answered ones are read past, a batch at a time.
+ const answered = chatReads(roots, roots.flatMap(r => rows(r, { author: agent(r.sequence > 200 ? s.pm : 'buddy') })))
+ expect((await openProposals(s.state, s.chat(), answered.reads)).map(p => p.messageId)).toEqual(roots.slice(100, 200).map(r => r.id))
+ expect(answered.calls.map(c => c.before)).toEqual([undefined, 151])
+ })
+
+ it('is read only by those who read the project chat', () => {
+ const s = swarm()
+ expect(proposalChat(s.state, peer, 'lead').id).toBe('lead')
+ s.run({ type: 'project.sharing', projectId: 'lead', visibility: 'private', memberIds: [] })
+ expect(() => proposalChat(s.state, peer, 'lead')).toThrow(expect.objectContaining({ code: 'NOT_FOUND', status: 404 }))
+ expect(() => proposalChat(s.state, owner, 'no-such-project')).toThrow(expect.objectContaining({ code: 'NOT_FOUND', status: 404 }))
+ expect(proposalChat(s.state, owner, 'lead').id).toBe('lead')
+ })
+})
diff --git a/backend/src/superTabs/proposals.ts b/backend/src/superTabs/proposals.ts
new file mode 100644
index 000000000..2f3999d78
--- /dev/null
+++ b/backend/src/superTabs/proposals.ts
@@ -0,0 +1,72 @@
+/**
+ * A project's Buddy proposals its PM has not answered (the Tasks view's Proposals, #2569), by #2867's rule as the chat shows
+ * it (threads.ts askOf): no mark from a task opened from it, and no reply in its thread from the project chat's lead agent.
+ * Nothing is stored for it: the roots are read from the project chat, and their threads as the chat page reads them.
+ */
+import type { Prisma } from '@prisma/client'
+import type { Actor, Conversation, SuperTabState } from './model.js'
+import { pageThreads, type ThreadReply } from './pageReads.js'
+import { readBy } from './parts/indexed.js'
+import { readConversation, readProject } from './projects.js'
+import { threadSummaries } from './threads.js'
+
+type Transaction = Prisma.TransactionClient
+
+/** The most a read lists: the newest open ones, shown oldest first. Far above today's under 10 open per project. */
+export const MAX_PROPOSALS = 100
+/** The most proposal roots one read looks through, newest first, for the open ones: answered ones past this are not read. */
+export const MAX_ROOTS = 1_000
+/** The words buddy.propose puts before a proposal's name (commands.ts), which the apps leave out. */
+const ROOT_PREFIX = "Let's build: "
+
+export interface OpenProposal { messageId: string; title: string; personId?: string; at: number }
+/** A proposal's root as the read takes it from the chat. */
+export interface ProposalRoot { id: string; sequence: number; text: string; source: Record<string, unknown>; createdAt: Date }
+/** The chat's proposal roots newest first, before a sequence (all of them without one); and the threads of some roots. */
+export interface ProposalReads {
+ roots(before: number | undefined, take: number): Promise<ProposalRoot[]>
+ threads(rootIds: string[]): Promise<ThreadReply[]>
+}
+
+/** The project chat [projectId] names, for a reader who may read it, as the messages read checks it; else NOT_FOUND. */
+export function proposalChat(state: SuperTabState, actor: Actor, projectId: string): Conversation {
+ return readConversation(state, actor, readProject(state, actor, projectId).leadConversationId)
+}
+
+/** The open proposals in [chat], oldest first: the newest MAX_PROPOSALS, read a batch of roots at a time. */
+export async function openProposals(state: SuperTabState, chat: Conversation, reads: ProposalReads): Promise<OpenProposal[]> {
+ const open: OpenProposal[] = []
+ for (let before: number | undefined, read = 0; open.length < MAX_PROPOSALS && read < MAX_ROOTS;) {
+ const roots = await reads.roots(before, MAX_PROPOSALS)
+ if (!roots.length) break
+ read += roots.length
+ // A root with no reply has no summary: nobody answered it.
+ const asks = new Map(threadSummaries(state, chat, await reads.threads(roots.map(r => r.id))).map(t => [t.id, t.ask]))
+ for (const root of roots) {
+ if (asks.has(root.id) && asks.get(root.id) !== 'proposal') continue
+ const personId = root.source.personId
+ open.push({ messageId: root.id, title: root.text.startsWith(ROOT_PREFIX) ? root.text.slice(ROOT_PREFIX.length) : root.text,
+ ...typeof personId === 'string' ? { personId } : {}, at: root.createdAt.getTime() })
+ }
+ if (roots.length < MAX_PROPOSALS) break
+ before = roots.at(-1)!.sequence
+ }
+ return open.slice(0, MAX_PROPOSALS).reverse()
+}
+
+const date = (value: unknown): Date => new Date((value as { $date?: string } | null)?.$date ?? value as string)
+
+/** The reads of [chatId], from the database: its roots by the conversation's sequence index, newest first; its threads as
+ * the chat page reads them (pageThreads). A proposal root is the only row of its command, so no other shares its sequence. */
+export function databaseProposalReads(tx: Transaction, tabId: string, chatId: string): ProposalReads {
+ return {
+ roots: async (before, take) => (await readBy(tx, 'SuperTabMessage', 'sequence', [
+ { $match: { tabId, conversationId: chatId, ...before === undefined ? {} : { sequence: { $lt: before } }, 'source.kind': 'buddy-proposal' } },
+ // Its own thread's root (none before threads).
+ { $match: { $expr: { $eq: [{ $ifNull: ['$thread', '$_id'] }, '$_id'] } } },
+ { $sort: { sequence: -1, _id: -1 } }, { $limit: take }, { $project: { _id: 1, sequence: 1, text: 1, source: 1, createdAt: 1 } }]))
+ .map(row => ({ id: row._id as string, sequence: row.sequence as number, text: row.text as string, source: row.source as Record<string, unknown>,
+ createdAt: date(row.createdAt) })),
+ threads: rootIds => pageThreads(tx, tabId, chatId, rootIds),
+ }
+}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 28ab1b623..7c309a21c 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -21,6 +21,7 @@ import { agentGatheredCount, agentGatheredDeliveries, agentOpenDeliveries, CANCE
import { deliveriesByMessage } from './read/pageDeliveries.js'
import { restoreDelivery } from './deliveryCompaction.js'
import { threadSummaries } from './threads.js'
+import { databaseProposalReads, openProposals, proposalChat, type OpenProposal } from './proposals.js'
import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVATAR_TYPES, checkedType, directUploads, errorCode, EXPIRED_UPLOAD, HOURLY_UPLOAD_BYTES, HOURLY_UPLOADS, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, MAX_FORM_ATTACHMENT_BYTES, objectKeyFor, peekType, PENDING_UPLOAD_PURPOSE, publicUrl, TOO_LARGE_MESSAGE, trimPrefix, typeFromHead, UPLOAD_LINK_MS,
type Attachment, type Attachments, type AttachmentStore, type AvatarStore } from './attachments.js'
import { FileLinks } from './fileLinks.js'
@@ -2752,6 +2753,19 @@ export class SuperTabStore {
reactionSeq: group.reactionSeq ?? 0 }
}
+ /** One project's Buddy proposals its PM has not answered, oldest first (proposals.ts), for a person who reads its chat:
+ * anyone else is answered as for a project that is not there. */
+ async proposals(user: AuthUser, tabId: string, projectId: string): Promise<{ proposals: OpenProposal[] }> {
+ this.personOnly(user)
+ let { state } = await this.readLoad(user, tabId)
+ const actor = await this.actor(this.db, user, state)
+ // The project chat is never archived, but a quiet one is not in the first load.
+ const chatId = readProject(state, actor, projectId).leadConversationId
+ if (!state.conversations.some(c => c.id === chatId)) ({ state } = await this.readLoad(user, tabId, { groupIds: [chatId] }))
+ const chat = proposalChat(state, actor, projectId)
+ return { proposals: await openProposals(state, chat, databaseProposalReads(this.db, tabId, chat.id)) }
+ }
+
/** The main-chat excerpt a Buddy thread session starts from: main-stream rows at or before `from` it may read (never a session
* thread's, never a reply only in its thread), by the conversation's sequence index, at most 50 rows read for 10 kept. */
private async sessionExcerpt(tx: Transaction, tabId: string, conversationId: string, from: number,
diff --git a/backend/src/superTabs/taskQueue.test.ts b/backend/src/superTabs/taskQueue.test.ts
new file mode 100644
index 000000000..27115eefb
--- /dev/null
+++ b/backend/src/superTabs/taskQueue.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest'
+import { placeAfter, queueKey, queueOrder } from './taskQueue.js'
+
+// A project's Next up (Tasks view, #2569): one sparse rank per task, so a move rewrites only the task moved.
+const task = (id: string, number: number, queueRank?: number) => ({ id, number, ...queueRank === undefined ? {} : { queueRank } })
+
+describe('the Next-up queue order', () => {
+ const tasks = [task('a', 1), task('b', 2), task('c', 3)]
+
+ it('sorts an unranked task by its number, so a new task comes last', () => {
+ expect(queueKey(task('a', 7))).toBe(7)
+ expect(queueKey(task('a', 7, 0.5))).toBe(0.5)
+ expect(queueKey({})).toBe(0)
+ const moved = [task('a', 1, 3.5), task('b', 2), task('c', 3), task('new', 4)]
+ expect(queueOrder(moved).map(t => t.id)).toEqual(['b', 'c', 'a', 'new'])
+ // A tie goes by number.
+ expect(queueOrder([task('late', 9, 2), task('early', 2)]).map(t => t.id)).toEqual(['early', 'late'])
+ })
+
+ it('moves a task to the top, one below the first', () => {
+ expect(placeAfter(tasks, 'c', null)).toEqual(new Map([['c', 0]]))
+ })
+
+ it('moves a task between two others, at their midpoint', () => {
+ expect(placeAfter(tasks, 'c', 'a')).toEqual(new Map([['c', 1.5]]))
+ expect(placeAfter(tasks, 'a', 'b')).toEqual(new Map([['a', 2.5]]))
+ })
+
+ it('moves a task to the bottom, one past the last', () => {
+ expect(placeAfter(tasks, 'a', 'c')).toEqual(new Map([['a', 4]]))
+ })
+
+ it('renumbers every task 1..n in order once a gap runs out', () => {
+ const tight = [task('a', 1, 1), task('b', 2, 1 + 5e-7), task('c', 3)]
+ expect(placeAfter(tight, 'c', 'a')).toEqual(new Map([['a', 1], ['c', 2], ['b', 3]]))
+ // Two tasks at the same rank leave no gap either.
+ const tied = [task('a', 1, 2), task('b', 2), task('c', 3)]
+ expect(placeAfter(tied, 'c', 'a')).toEqual(new Map([['a', 1], ['c', 2], ['b', 3]]))
+ })
+
+ it('lands in the same place when the same move comes again', () => {
+ const once = placeAfter(tasks, 'c', 'a')
+ const after = tasks.map(t => ({ ...t, ...once.has(t.id) ? { queueRank: once.get(t.id)! } : {} }))
+ expect(placeAfter(after, 'c', 'a')).toEqual(once)
+ })
+})
diff --git a/backend/src/superTabs/taskQueue.ts b/backend/src/superTabs/taskQueue.ts
new file mode 100644
index 000000000..1994a3d41
--- /dev/null
+++ b/backend/src/superTabs/taskQueue.ts
@@ -0,0 +1,36 @@
+/**
+ * A project's Next up (Tasks view, #2569): one sparse rank per task, so a move rewrites only the task moved. An unranked
+ * task sorts by its number, so tasks from before ranks keep their order and a new task joins the bottom.
+ */
+import type { Conversation, SuperTabState } from './model.js'
+import { groupProject, type SwarmProject } from './projects.js'
+
+type Queued = Pick<Conversation, 'id' | 'number' | 'queueRank'>
+/** Closer than this, two ranks leave no room between them: the whole queue is numbered again. */
+const MIN_GAP = 1e-6
+
+export const queueKey = (task: Pick<Conversation, 'number' | 'queueRank'>): number => task.queueRank ?? task.number ?? 0
+
+/** [tasks] in queue order; a tie goes by number. */
+export const queueOrder = <T extends Queued>(tasks: readonly T[]): T[] =>
+ [...tasks].sort((a, b) => queueKey(a) - queueKey(b) || (a.number ?? 0) - (b.number ?? 0))
+
+/** The tasks a project's Next up orders: open, never its chat, a Buddy chat, a private chat or a step. */
+export function queueSiblings(state: SuperTabState, project: SwarmProject): Conversation[] {
+ return state.conversations.filter(c => !c.archived && !c.kind && !c.audience && !c.reviewOf && c.id !== project.leadConversationId
+ && groupProject(state, c).id === project.id)
+}
+
+/** The ranks to write to put [taskId] right after [after] (null: the top): usually the task's alone, every task's 1..n once
+ * the gap it lands in runs out. */
+export function placeAfter(siblings: readonly Queued[], taskId: string, after: string | null): Map<string, number> {
+ const others = queueOrder(siblings.filter(s => s.id !== taskId))
+ const moved = siblings.find(s => s.id === taskId)!
+ if (after === null) return new Map([[taskId, others.length ? queueKey(others[0]!) - 1 : queueKey(moved)]])
+ const at = others.findIndex(s => s.id === after), previous = others[at]!, next = others[at + 1]
+ if (!next) return new Map([[taskId, queueKey(previous) + 1]])
+ const low = queueKey(previous), high = queueKey(next)
+ if (high - low >= MIN_GAP) return new Map([[taskId, (low + high) / 2]])
+ const order = [...others.slice(0, at + 1), moved, ...others.slice(at + 1)]
+ return new Map(order.map((s, i) => [s.id, i + 1]))
+}
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 484fcb7f7..5d9c2faab 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -8,5 +8,5 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts',
'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',
'integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts',
'integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',
- 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
+ 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.ts
index 527744c2d..147adf699 100644
--- a/cli/src/lib/swarmSkills.spec.ts
+++ b/cli/src/lib/swarmSkills.spec.ts
@@ -103,6 +103,8 @@ describe('built-in Swarm skills', () => {
// The thread line (Dee's threads, 2026-10-29): the Lead answers inside the thread of the message it answers. The Lead's
// alone, in both modes, right after its write-like-a-colleague line.
const thread = '- Answer a message inside its thread: post with --reply-to that message, and your reply joins its thread. Many people talk to you at once; answers in the main chat bury each other. Post at the top level only to start a new topic.\n'
+ // The Next-up line (Tasks view, #2569): the Lead's alone, in both modes, where it keeps work moving.
+ const queue = '- Keep the project\'s Next up in the order work should start: work.queue with after (null for the top) moves a task, and notBefore (YYYY-MM-DD) marks a promise such as removing a route after a date.\n'
const limit = '- A task lost to a usage limit resumes by itself in the same session when the limit resets (its wake-up says when). Hand it on at once only to another account or engine with allowance now, with its pushed branch and last progress note.\n'
// On by default since quiet project chats (Dee, 2026-10-31); a person moves it or turns it off.
const digest = '- Morning digest: every project has one by default, at 08:00 Vietnam time. When a person asks, move it to their local time and time zone ("project.digest" with time "08:00" and timeZone "Asia/Ho_Chi_Minh"), or turn it off with time null. When it wakes you, check that each pull request under Shipped is merged, then post one message to the people in the project chat.\n'
@@ -301,7 +303,7 @@ describe('built-in Swarm skills', () => {
expect([cardLead, cardDev, cardReview].map(line => text.split(line).length)).toEqual([role === 'lead' ? 2 : 1, role === 'dev' ? 2 : 1, role === 'review' ? 2 : 1])
expect(sha(approved(text, 'orchestration', role).replace(whoReaches(role), '').replace(reactions(role), '').replace(twoHours, '').replace(terminal, '').replace(update, '').replace(overlap, '').replace(local, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '')
.replace(limit, '').replace(digest, '').replace(decision, '').replace(ask, '').replace(requests, '').replace(shared, '').replace(report, '').replace(quiet, '')
- .replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, '').replace(thread, '')
+ .replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, '').replace(thread, '').replace(queue, '')
.replace(cardLead, '').replace(cardDev, '').replace(cardReview, ''))).toBe(sha256)
}
})
@@ -315,6 +317,16 @@ describe('built-in Swarm skills', () => {
expect(read('review', 'orchestration')).toContain(`- Pass or fail the independent check, with the revision and verdict as evidence.\n${cardReview}`)
expect(read('review', 'default')).toContain(`- Pass or fail the independent check with the revision and verdict.\n${cardReview}`)
})
+ it('tells each Lead, and no other role, to keep Next up in order with work.queue, and the tools how to send it', () => {
+ const read = (role: 'lead' | 'dev' | 'review', mode: 'orchestration' | 'default') =>
+ readFileSync(prepareSwarmSkill(fixture(), { role, key: 'session', mode }).file, 'utf8')
+ expect(read('lead', 'orchestration')).toContain(`- Keep each worker supplied: have its next group ready before it finishes, so nobody waits for you.\n${queue}`)
+ expect(read('lead', 'default')).toContain(`- When a worker finishes: reuse, keep or stop. Prefer stop.\n${queue}`)
+ for (const mode of ['orchestration', 'default'] as const) {
+ for (const role of ['lead', 'dev', 'review'] as const) expect(read(role, mode).split(queue), `${mode} ${role}`).toHaveLength(role === 'lead' ? 2 : 1)
+ }
+ expect(SWARM_TOOLS_SKILL).toContain('- `{"type":"work.queue","conversationId":"GROUP","after":"GROUP"}` places an open task right after another in its project\'s Next up (`"after":null` for the top). `"notBefore":"2026-12-04"` marks a day it should not start before (null clears it); send either or both. Only a person or the project\'s coordinator may send it.\n')
+ })
it('adds the 2-hour line to section 7 right after the stall rule', () => {
const text = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session' }).file, 'utf8')
expect(text).toContain(`post in its chat why it waits; report on-screen trust, sign-in or permission questions in chat, naming the machine owner who can answer.\n${twoHours}`)
@@ -477,7 +489,7 @@ describe('built-in Swarm skills', () => {
expect([cardLead, cardDev, cardReview].map(line => text.split(line).length)).toEqual([role === 'lead' ? 2 : 1, role === 'dev' ? 2 : 1, role === 'review' ? 2 : 1])
expect(sha(approved(text, 'default', role).replace(whoReaches(role), '').replace(reactions(role), '').replace(terminal, '').replace(update, '').replace(overlap, '').replace(localDefault, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '')
.replace(limit, '').replace(digest, '').replace(decision, '').replace(ask, '').replace(requestsLast, '').replace(sharedLast, '').replace(report, '').replace(quiet, '')
- .replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, '').replace(thread, '')
+ .replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, '').replace(thread, '').replace(queue, '')
.replace(cardLead, '').replace(cardDev, '').replace(cardReview, ''))).toBe(sha256)
expect(prepared.instructions).toMatch(/^Use the built-in swarm-tools skill /)
expect(prepared.instructions).toContain(`use the swarm-${role} skill instead: read ${JSON.stringify(prepared.file)}.`)
diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.ts
index 7765d1013..022720ae0 100644
--- a/cli/src/lib/swarmSkills.ts
+++ b/cli/src/lib/swarmSkills.ts
@@ -127,6 +127,7 @@ For large work, post the group plan and get the owner's ok before assigning; onc
- When a worker seems stuck, read its terminal; answer prompts within its task; ask the owner before approving anything risky.
- Codex's "Update available" screen on a worker is dismissed with Esc alone, never a number and Enter (on a misread row that runs the update) and never as a question for the owner. The host does it for Swarm agents when the screen is exactly that prompt; if one still waits on it, press Esc yourself.
- Keep each worker supplied: have its next group ready before it finishes, so nobody waits for you.
+- Keep the project's Next up in the order work should start: work.queue with after (null for the top) moves a task, and notBefore (YYYY-MM-DD) marks a promise such as removing a route after a date.
- Cancel a duplicate, obsolete or wrong task with a reason.
- When a worker finishes: reuse, keep or stop. Prefer stop unless more work is coming soon.
@@ -465,6 +466,7 @@ Keep each Builder's list a few tasks deep; do the easy, self-contained parts fir
- A Builder or Reviewer blocked on a missing tool, device or sign-in: within minutes, route the task again with what was missing in its needs (fix its required machine if that is the one without it), assign it to a machine and account that has it, then stop the blocked agent unless other work fits its machine. A Mac's own account and its Team account are different: the Team account has none of the owner's tools, devices or sign-ins. If none has it, tag the requester with the choice.
- Settle ambiguities you can and record "Ruling: what — why — cost if wrong".
- When a worker finishes: reuse, keep or stop. Prefer stop.
+- Keep the project's Next up in the order work should start: work.queue with after (null for the top) moves a task, and notBefore (YYYY-MM-DD) marks a promise such as removing a route after a date.
## 5. Review and accept
- Work that will be merged, or carries medium risk or more, gets a Reviewer. When its Builder marks ready for review with a pull request link, the Swarm opens "Review: <group>", assigns a free Reviewer and tells you in one line; cancel it there if it is not needed. When no Reviewer is free, route it, start one, assign it and add it to the Builder's group. Without a pull request link, create the review group yourself the same way.
diff --git a/cli/src/lib/swarmTools.ts b/cli/src/lib/swarmTools.ts
index 4e32a638a..d71707b6f 100644
--- a/cli/src/lib/swarmTools.ts
+++ b/cli/src/lib/swarmTools.ts
@@ -57,6 +57,7 @@ Task and group commands:
- \`{"type":"work.define","conversationId":"GROUP","task":{...},"checks":[...]}\` sets or replaces the task of a group already open (same shape).
- \`{"type":"conversation.agent","conversationId":"GROUP","agentId":"AGENT","present":true,"lead":false}\` adds an agent to a group (\`present\` false removes it).
- \`{"type":"conversation.requester","conversationId":"GROUP","personId":"PERSON"}\` names who asked for a group already open (null clears).
+- \`{"type":"work.queue","conversationId":"GROUP","after":"GROUP"}\` places an open task right after another in its project's Next up (\`"after":null\` for the top). \`"notBefore":"2026-12-04"\` marks a day it should not start before (null clears it); send either or both. Only a person or the project's coordinator may send it.
- \`{"type":"work.assign","conversationId":"GROUP","agentId":"AGENT","routeDecisionId":"DECISION"}\` assigns a group's task. \`routeDecisionId\` names the route's decision when you assign one of its candidates, so it records what ran.
- \`{"type":"work.status","conversationId":"GROUP","assignmentId":"current","status":"working","result":null}\` is your status for the Swarm. status: \`working\` (add a one-line note in result of what is done and next), \`review\` (ready for review: result holds the revision and the pull request link; send it once per new head), \`done\` (result: exact revision, evidence, deliverable links), \`blocked\` (result: why, and what would unblock you), \`needs_human\` (result: one short question), \`stopped\`. Set working again once it moves. A work.status \`done\` or \`stopped\` carries the session's token totals by itself.
- \`needs_human\` may carry \`"ask":{"personId":"PERSON","options":["A","B"],"recommended":0,"unblocks":"what the answer unblocks"}\`: 2 to 5 options, opened as a decision for that person. Keep working on your recommendation, marked provisional, until a notice says it was answered; then read the answer with \`decisions --answered\`. The notice carries none of it.
diff --git a/desktop/lib/shared/theme/app_icons.dart b/desktop/lib/shared/theme/app_icons.dart
index f65e0aec4..b43e0fc4d 100644
--- a/desktop/lib/shared/theme/app_icons.dart
+++ b/desktop/lib/shared/theme/app_icons.dart
@@ -185,6 +185,7 @@ abstract final class AppIcons {
static const sparkles = LucideIcons.sparkles400;
static const square = LucideIcons.square400;
static const squareCheck = LucideIcons.squareCheck400;
+ static const squareKanban = LucideIcons.squareKanban400;
static const squarePlus = LucideIcons.squarePlus400;
static const squareTerminal = LucideIcons.squareTerminal400;
static const star = LucideIcons.star400;
diff --git a/desktop/lib/super_tabs/backend_transport.dart b/desktop/lib/super_tabs/backend_transport.dart
index 0fa550a7c..771a59a8f 100644
--- a/desktop/lib/super_tabs/backend_transport.dart
+++ b/desktop/lib/super_tabs/backend_transport.dart
@@ -19,7 +19,7 @@ final _swarmRoute = RegExp(
'|/list|/invitations|/deleted'
'|/$_tab/(?:parts|changes|commands|mentions|decisions|leaderboard|sharing'
'|routing-policy|groups|groups/$_id|join|join/preview|native'
- '|activity|activity/read|threads|inbox'
+ '|activity|activity/read|threads|inbox|proposals'
'|conversations/$_id/(?:messages|catch-up|read|notifications'
'|threads/$_id/(?:read|follow)'
'|messages/$_id/attachments/$_id)'
diff --git a/desktop/lib/super_tabs/backlog.dart b/desktop/lib/super_tabs/backlog.dart
index ece842b0a..6d883e051 100644
--- a/desktop/lib/super_tabs/backlog.dart
+++ b/desktop/lib/super_tabs/backlog.dart
@@ -25,9 +25,9 @@ const superTabBacklogShippedWindow = Duration(days: 7);
/// Whether [task] has shipped (task #2558): a recorded merge of any of its pull
/// requests (a batch's counts, its own closed), or Done with none to merge. Its
/// `shippedAt` alone cannot say: the server sets that at the first Done.
-bool _shipped(SuperTabConversation task, Object? status) =>
+bool superTabTaskShipped(SuperTabConversation task) =>
task.cards.pullRequests.any((card) => card.merged) ||
- (status == 'done' &&
+ (task.assignment?['status'] == 'done' &&
task.cards.pullRequests.isEmpty &&
task.pullRequestUrls.isEmpty);
@@ -43,7 +43,7 @@ SuperTabBacklogGroup? superTabBacklogGroupOf(
final at = task.shippedAt;
final inWindow =
at != null && now.difference(at) <= superTabBacklogShippedWindow;
- if (at != null && _shipped(task, status)) {
+ if (at != null && superTabTaskShipped(task)) {
if (inWindow) return SuperTabBacklogGroup.shipped;
// Past the window, unless it is back at work.
if (task.closed || status == 'done') return null;
@@ -79,31 +79,45 @@ SuperTabBacklogGroup? superTabBacklogGroupOf(
}
/// Every task of the Swarm the controller holds, open and closed, and of
-/// [closed], those read for the list alone, across projects, newest first: the
-/// groups the server lets this reader read, less project chats, Buddy chats,
-/// steps and private chats, as the sidebar lists a project's work
-/// (project_sidebar.dart superTabOpenWorkgroups). What the controller holds is
-/// newer than a read, so it wins.
+/// [closed], those read for the list alone, across projects, newest first.
List<SuperTabConversation> superTabBacklogTasks(
SuperTabController c, {
Iterable<SuperTabConversation> closed = const [],
}) {
- final snapshot = c.snapshot;
- if (snapshot == null) return const [];
final byProject = closed.groupListsBy((g) => g.projectId);
final tasks = [
- for (final project in snapshot.projects)
- for (final g in superTabListedWork([
- ...c.projectConversations(project.id),
- for (final g in byProject[project.id] ?? const <SuperTabConversation>[])
- if (snapshot.conversation(g.id) == null) g,
- ]))
- if (g.id != project.leadConversationId &&
- !g.isBuddyChat &&
- !c.hiddenByBuddies(g))
- g,
+ for (final project in c.snapshot?.projects ?? const <SuperTabProject>[])
+ ...superTabProjectTasks(
+ c,
+ project,
+ closed: byProject[project.id] ?? const [],
+ ),
];
// A stable sort keeps the snapshot's order among unnumbered ones.
mergeSort(tasks, compare: (a, b) => (b.number ?? 0).compareTo(a.number ?? 0));
return tasks;
}
+
+/// [project]'s tasks the controller holds, open and closed, and of [closed],
+/// those read for a list alone: the groups the server lets this reader read,
+/// less its chat, Buddy chats, steps and private chats. What the controller
+/// holds is newer than a read, so it wins.
+List<SuperTabConversation> superTabProjectTasks(
+ SuperTabController c,
+ SuperTabProject project, {
+ Iterable<SuperTabConversation> closed = const [],
+}) {
+ final snapshot = c.snapshot;
+ if (snapshot == null) return const [];
+ return [
+ for (final g in superTabListedWork([
+ ...c.projectConversations(project.id),
+ for (final g in closed)
+ if (snapshot.conversation(g.id) == null) g,
+ ]))
+ if (g.id != project.leadConversationId &&
+ !g.isBuddyChat &&
+ !c.hiddenByBuddies(g))
+ g,
+ ];
+}
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index bf1dfda05..387ef13ae 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -16,6 +16,7 @@ import 'message_link.dart';
import 'identity.dart' show superTabMachineName;
import 'machine_status.dart' show kSuperTabMachineOfflineAfter;
import 'model.dart';
+import 'task_groups.dart';
import 'buddy_chat.dart';
import 'project_github.dart';
import 'parts.dart';
@@ -23,7 +24,6 @@ import 'read_marks.dart';
import 'reading.dart';
import 'linked_tasks.dart';
import 'task_steps.dart';
-import 'task_groups.dart';
/// A messages read started beside a state read, and what it asked for.
typedef _EarlyRead = ({String query, Future<Map<String, dynamic>> page});
@@ -200,9 +200,6 @@ class SuperTabController extends ChangeNotifier {
final order = initial['sendOrder'];
if (order is List) _sendOrder.addAll(order.whereType<String>());
_savedSelection = initial['selectedId'] is String;
- expandedProjects.addAll(
- (initial['expandedProjects'] as List? ?? const []).whereType<String>(),
- );
expandedMachines.addAll(
(initial['expandedMachines'] as List? ?? const []).whereType<String>(),
);
@@ -993,7 +990,6 @@ class SuperTabController extends ChangeNotifier {
/// Each conversation's reads under way, newest and older apart: an older
/// page asked for during a poll's read is a read of its own.
final _reading = <(String, bool), Future<void>>{};
- final expandedProjects = <String>{};
final expandedMachines = <String>{};
bool devicesSelected = false;
bool projectsGroupOpen = true, machinesGroupOpen = true;
@@ -1042,42 +1038,6 @@ class SuperTabController extends ChangeNotifier {
_changed();
}
- void toggleProject(String id) {
- if (!expandedProjects.remove(id)) {
- expandedProjects.add(id);
- unawaited(loadDormant(id));
- }
- _saveSoon();
- _changed();
- }
-
- /// Projects whose "Closed (N)" row is open; every one starts collapsed and
- /// the choice is not saved.
- final closedOpenProjects = <String>{};
-
- void toggleClosed(String projectId) {
- if (!closedOpenProjects.remove(projectId)) {
- closedOpenProjects.add(projectId);
- }
- _changed();
- }
-
- /// Each project's task groups folded or unfolded against their default
- /// (`<project>/<group>`), remembered as Closed is: not saved.
- final _taskGroupsToggled = <String>{};
-
- /// Whether [group] of [projectId]'s tasks is folded in the sidebar; only
- /// The rest starts folded.
- bool taskGroupFolded(String projectId, SuperTabTaskGroup group) =>
- group.foldedByDefault !=
- _taskGroupsToggled.contains('$projectId/${group.name}');
-
- void toggleTaskGroup(String projectId, SuperTabTaskGroup group) {
- final key = '$projectId/${group.name}';
- if (!_taskGroupsToggled.remove(key)) _taskGroupsToggled.add(key);
- _changed();
- }
-
/// Open decisions the reader set aside in their Buddy chat (Not now, Hide):
/// saved on this computer for this reader, so they stay folded after a
/// restart. A decision asked later is not among them, so it shows.
@@ -2685,7 +2645,6 @@ class SuperTabController extends ChangeNotifier {
'tabId': tabId,
'accountId': accountId,
'selectedId': selectedId,
- 'expandedProjects': expandedProjects.toList(),
'expandedMachines': expandedMachines.toList(),
'decisionsAside': _decisionsAside.toList(),
'devicesSelected': devicesSelected,
@@ -3112,6 +3071,20 @@ class SuperTabController extends ChangeNotifier {
null;
}
+ /// Moves [taskId] right after [after] in its project's shared Next up, or to
+ /// its top when [after] is null, for everyone (backend taskQueue.ts). Null
+ /// once the server took it; otherwise why it did not.
+ Future<String?> queueTask(String taskId, {required String? after}) async {
+ final done = await command({
+ 'type': 'work.queue',
+ 'conversationId': taskId,
+ 'after': after,
+ });
+ return done != null
+ ? null
+ : operationError ?? 'Another change is on its way. Try again.';
+ }
+
/// Moves the reader's one Buddy onto [gridModel], a model shared in the
/// Swarm, or back to their own subscription when null (backend
/// buddyModel.ts). Its machine carries it out; the Buddy's `modelRequest`
@@ -3390,12 +3363,10 @@ class SuperTabController extends ChangeNotifier {
if (id == selectedId && !devicesSelected) return true;
_acted();
final group = snapshot!.conversation(id)!;
- // A workgroup is shown under its project, so its project opens. A Buddy
- // chat has its own row under Buddies and leaves projects as they were.
+ // A task's project's closed tasks, read once: the quick switcher finds an
+ // archived one by its number (#N). A Buddy chat reads none.
if (!snapshot!.isProjectLead(id) && !group.isBuddyChat) {
- expandedProjects.add(group.projectId);
unawaited(loadDormant(group.projectId));
- if (group.closed) closedOpenProjects.add(group.projectId);
}
_moveView(to: id);
// Held from an earlier visit: what arrived meanwhile is not among them.
@@ -3678,10 +3649,7 @@ class SuperTabController extends ChangeNotifier {
..._readAt.keys,
..._refused.keys,
..._threadDraftConversations.values,
- ].any(removed.contains) ||
- expandedProjects.any(
- (id) => !next.projects.any((project) => project.id == id),
- );
+ ].any(removed.contains);
_messages.removeWhere((id, _) => !allowed.contains(id));
_staleHeld.removeWhere((id) => !allowed.contains(id));
_quoted.removeWhere((id, _) => !allowed.contains(id));
@@ -3708,9 +3676,6 @@ class SuperTabController extends ChangeNotifier {
_refused.removeWhere((id, _) => removed.contains(id));
_before.removeWhere((id, _) => !allowed.contains(id));
_readAt.removeWhere((id, _) => removed.contains(id));
- expandedProjects.removeWhere(
- (id) => !next.projects.any((project) => project.id == id),
- );
if (!allowed.contains(selectedId)) {
selectedId = next.projects.firstOrNull?.leadConversationId ?? 'lead';
}
@@ -3727,9 +3692,6 @@ class SuperTabController extends ChangeNotifier {
// A read for the parts before has nothing to give these.
_dormantPages.clear();
_dormantReads.clear();
- for (final project in expandedProjects) {
- unawaited(loadDormant(project));
- }
if (_closedShippedSince case final since?) {
_forgetClosedShipped();
unawaited(readClosedShipped(since));
@@ -4113,6 +4075,83 @@ class SuperTabController extends ChangeNotifier {
);
}
+ /// Each project's Buddy proposals the PM has not answered, oldest first, as
+ /// last read (backend proposals read, #2867's rule, task #2569), and the
+ /// project chat's last sequence that read saw: the next read waits for the
+ /// chat to move, as only a message there can answer or add one, and for a
+ /// minute since the last (the PM, 2026-11-04: the read looks through the
+ /// whole chat, and repeated reads are the backend's biggest cost).
+ final _proposals = <String, List<SuperTabProposal>>{};
+ final _proposalsAt = <String, int>{};
+ final _proposalsReadAt = <String, DateTime>{};
+ final _proposalReads = <String, Future<void>>{};
+ final _proposalsLater = <String, Timer>{};
+ static const proposalsEvery = Duration(minutes: 1);
+
+ List<SuperTabProposal> proposalsOf(String projectId) =>
+ _proposals[projectId] ?? const [];
+
+ /// Reads [projectId]'s open proposals once its chat has moved since the last
+ /// read; joins a read under way. A failed read keeps what was shown and is
+ /// tried again when the chat next moves.
+ Future<void> readProposals(String projectId) {
+ final project = snapshot?.projectById(projectId);
+ if (_disposed || accessRevoked || project == null) return Future.value();
+ final at =
+ snapshot!
+ .conversation(project.leadConversationId)
+ ?.lastMessageSequence ??
+ 0;
+ if (_proposalsAt[projectId] == at) return Future.value();
+ if (_proposalReads[projectId] case final reading?) return reading;
+ final last = _proposalsReadAt[projectId];
+ final wait = last == null
+ ? Duration.zero
+ : proposalsEvery - clock.now().difference(last);
+ if (wait > Duration.zero) {
+ // One read for every move in the minute, once it is up.
+ _proposalsLater[projectId] ??= Timer(wait, () {
+ _proposalsLater.remove(projectId);
+ unawaited(readProposals(projectId));
+ });
+ return Future.value();
+ }
+ _proposalsReadAt[projectId] = clock.now();
+ late final Future<void> reading;
+ reading = _readProposals(projectId, at).whenComplete(() {
+ if (identical(_proposalReads[projectId], reading)) {
+ _proposalReads.remove(projectId);
+ }
+ });
+ return _proposalReads[projectId] = reading;
+ }
+
+ Future<void> _readProposals(String projectId, int at) async {
+ _proposalsAt[projectId] = at;
+ try {
+ final answer = await request(
+ 'GET',
+ '$_path/proposals?projectId=${Uri.encodeQueryComponent(projectId)}',
+ );
+ if (_disposed || accessRevoked) return;
+ _proposals[projectId] = List.unmodifiable([
+ for (final raw in answer['proposals'] as List? ?? const [])
+ if (raw is Map && raw['messageId'] is String)
+ SuperTabProposal.fromJson(superTabMap(raw)),
+ ]);
+ _changed();
+ } catch (failure) {
+ if (_disposed) return;
+ if (_isUpdateRequired(failure)) return _requireUpdate();
+ // A backend from before the read has none to give (404): said once.
+ appLog.warn(
+ 'swarm',
+ 'proposals read failed: '
+ '${failure is SuperTabFailure ? '${failure.code} (status ${failure.statusCode})' : failure.runtimeType}',
+ );
+ }
+ }
+
void _forgetClosedShipped() {
_closedShippedEpoch++;
_closedShippedRead = null;
@@ -5254,6 +5293,9 @@ class SuperTabController extends ChangeNotifier {
_machinesChanged.dispose();
_closedShippedChanged.dispose();
_silenceWatch?.cancel();
+ for (final later in _proposalsLater.values) {
+ later.cancel();
+ }
for (final then in _onDispose) {
then();
}
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 14398826a..96bace68f 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -384,6 +384,8 @@ class SuperTabConversation {
(row['shippedAt'] as num).toInt(),
)
: null,
+ queueRank = (row['queueRank'] as num?)?.toDouble(),
+ notBefore = DateTime.tryParse(row['notBefore'] as String? ?? ''),
lastMessageSequence = (row['lastMessageSequence'] as num?)?.toInt() ?? 0,
lastMainSequence = (row['lastMainSequence'] as num?)?.toInt(),
lastPersonSequence = (row['lastPersonSequence'] as num?)?.toInt() ?? 0,
@@ -480,6 +482,15 @@ class SuperTabConversation {
/// (a pull request card's `merged` is); null until then, and from a server
/// that does not say.
final DateTime? shippedAt;
+
+ /// Its place in its project's shared Next up, set by a person or the PM
+ /// (backend taskQueue.ts); null until someone moves it, when its number
+ /// places it (task_groups.dart).
+ final double? queueRank;
+
+ /// The day before which its work may not start, a promise the PM keeps
+ /// ("remove the preview route after Dec 4"); null when there is none.
+ final DateTime? notBefore;
final Map<String, dynamic>? assignment;
/// Whether its task waits on purpose or is stuck, as the server last found
diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dart
index ef1bd4290..f13d57120 100644
--- a/desktop/lib/super_tabs/project_sidebar.dart
+++ b/desktop/lib/super_tabs/project_sidebar.dart
@@ -1,10 +1,8 @@
import 'dart:async';
-import 'package:collection/collection.dart' show mergeSort;
+import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-import '../core/machine_resources.dart';
import '../shared/theme/app_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_icon_button.dart';
@@ -18,20 +16,12 @@ import '../widgets/harness_activity_mark.dart';
import 'activity.dart';
import 'attention.dart';
import 'controller.dart';
-import 'identity.dart';
-import 'leaderboard/models_section.dart';
-import 'leaderboard/reader.dart';
-import 'local_models.dart';
import 'buddies.dart';
-import 'machines.dart';
-import 'linked_tasks.dart';
import 'model.dart';
import 'buddy_rows.dart';
import 'section_heading.dart';
import 'swarm_switcher.dart';
import 'task_groups.dart';
-import 'task_status.dart';
-import 'workgroup_name.dart';
import 'project_github.dart';
import 'private_project_lock.dart';
import '../widgets/laid_out_list.dart';
@@ -240,28 +230,30 @@ class ProjectSidebar extends StatelessWidget {
}) {
final project = reading?.project;
final selected = !_paneCovered && controller.selectedId == group.id;
- final waiting = reading == null
- ? needsHuman(group) > 0
- : reading.waiting.isNotEmpty;
- // Open, a project's row is its own chat's, as each workgroup under it
- // has its own; collapsed, it is bold for anything it hides. Both by what
- // is for a person (#2427), never agents' progress alone.
+ // A project's row is bold for anything in it for a person (#2427), its
+ // tasks' too, never agents' progress alone.
final unread = reading == null
? controller.unreadShown(group)
- : controller.expandedProjects.contains(project?.id)
- ? reading.unread.contains(group.id)
: reading.unread.isNotEmpty;
- // Only what opening this row shows, so opening it clears the number (Dee,
- // Slack's way). Tags in the task conversations it hides make it bold, and
- // are on their own rows and in Activity.
- final badge = attention?.mentionsIn(group.id) ?? 0;
- final badgeTooltip = attention?.badgeTooltipIn(group.id);
+ // Tags in its chat, which opening it clears (Dee, Slack's way), and the
+ // tasks that need the reader, so someone in another project still sees
+ // them (task #2569). Tags in tasks make it bold, and are in Activity.
+ final mentions = attention?.mentionsIn(group.id) ?? 0;
+ final needsYou = reading?.needsYou ?? 0;
+ final badge = mentions + needsYou;
+ final badgeTooltip = needsYou == 0
+ ? attention?.badgeTooltipIn(group.id)
+ : [
+ if (mentions > 0)
+ attention?.badgeTooltipIn(group.id) ??
+ (mentions == 1 ? '1 mention' : '$mentions mentions'),
+ needsYou == 1 ? '1 task needs you' : '$needsYou tasks need you',
+ ].join(' · ');
return _drawRow(
group,
project: project,
key: key,
selected: selected,
- waiting: waiting,
unread: unread,
badge: badge,
badgeTooltip: badgeTooltip,
@@ -270,39 +262,6 @@ class ProjectSidebar extends StatelessWidget {
);
}
- /// A workgroup's row from what its project's reading already asked.
- /// A task row's status, kept current by its own clock, for its line and
- /// its tooltip alike; any other row is built without one.
- Widget _withTaskStatus(
- SuperTabConversation group,
- Widget Function(SuperTabTaskStatus? status) build, {
- required bool task,
- }) => task
- ? SuperTabTaskClock(
- group: group,
- personName: _personName,
- builder: (_, status) => build(status),
- )
- : build(null);
-
- /// A member as the Humans list names them, for a task's "Waiting on …".
- String? _personName(String personId) => switch (controller.snapshot?.people
- .where((p) => p.id == personId)
- .firstOrNull) {
- final person? => superTabPersonName(person.email),
- null => null,
- };
-
- Widget _workgroupRow(SuperTabConversation group, _ProjectReading reading) =>
- _drawRow(
- group,
- selected: !_paneCovered && controller.selectedId == group.id,
- waiting: reading.waiting.contains(group.id),
- unread: reading.unread.contains(group.id),
- badge: attention?.mentionsIn(group.id) ?? 0,
- badgeTooltip: attention?.badgeTooltipIn(group.id),
- );
-
Widget _drawRow(
SuperTabConversation group, {
SuperTabProject? project,
@@ -310,7 +269,6 @@ class ProjectSidebar extends StatelessWidget {
String? label,
String? key,
required bool selected,
- required bool waiting,
required bool unread,
int badge = 0,
String? badgeTooltip,
@@ -320,14 +278,11 @@ class ProjectSidebar extends StatelessWidget {
VoidCallback? onTap,
bool tappable = true,
}) {
- final expanded =
- project != null && controller.expandedProjects.contains(project.id);
- // A collapsed project shows as selected while one of its conversations it
- // hides is open; the reader's Buddy chat has a row of its own.
+ // A project shows as selected while one of its tasks is open; the
+ // reader's Buddy chat has a row of its own.
final highlighted =
selected ||
(project != null &&
- !expanded &&
!_paneCovered &&
selectedProjectId == project.id &&
controller.selectedId != buddyChat?.id);
@@ -356,206 +311,144 @@ class ProjectSidebar extends StatelessWidget {
child: Row(
children: [
Expanded(
- child: _arrowToggles(
- project,
- expanded: expanded,
- child: InkWell(
- key: ValueKey(key ?? 'super-group-${group.id}'),
- onTap: !tappable
- ? null
- : onTap ??
- // A second click on the open project shows its
- // workgroups (Quiet Swarm: no chevrons).
- (project != null &&
- !_paneCovered &&
- controller.selectedId == group.id
- ? () => controller.toggleProject(project.id)
- : () => onSelect(group.id)),
- hoverColor: Colors.transparent,
- focusColor: grid.AppSurface.hoverFill,
- borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
- child: Row(
- children: [
- SizedBox(width: SuperTabSectionHeading.indentFor(0)),
- SizedBox(
- width: _iconColumn,
- child: project != null
- ? _channelMark(isPrivate: project.isPrivate)
- : label != null
- ? Icon(
- AppIcons.bot,
- size: AppIcons.inlineSize,
- color: DesktopChrome.foreground,
- )
+ child: InkWell(
+ key: ValueKey(key ?? 'super-group-${group.id}'),
+ onTap: !tappable ? null : onTap ?? () => onSelect(group.id),
+ hoverColor: Colors.transparent,
+ focusColor: grid.AppSurface.hoverFill,
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ child: Row(
+ children: [
+ SizedBox(width: SuperTabSectionHeading.indentFor(0)),
+ SizedBox(
+ width: _iconColumn,
+ child: project != null
+ ? _channelMark(isPrivate: project.isPrivate)
+ : label != null
+ ? Icon(
+ AppIcons.bot,
+ size: AppIcons.inlineSize,
+ color: DesktopChrome.foreground,
+ )
+ : null,
+ ),
+ Expanded(
+ child: Semantics(
+ label: project?.isPrivate == true
+ ? 'Private project'
: null,
- ),
- Expanded(
- child: Semantics(
- label: project?.isPrivate == true
- ? 'Private project'
- : null,
- selected: selected,
- child: _withTaskStatus(
- group,
- task: project == null && label == null,
- (status) => Tooltip(
- // Beside the row, level with it, never over
- // the rows below (Huy, 11-03, #2427).
- positionDelegate: _besideTheRow,
- // Compact: a long name wraps rather than
- // needing more room than the window has right
- // of the list.
- constraints: const BoxConstraints(maxWidth: 260),
- message:
- label ??
- project?.name ??
- [
- SuperTabWorkgroupName.plain(group),
- if (status != null)
- superTabTaskStatusText(status),
- ].join('\n'),
- child: ConstrainedBox(
- // A project and its tasks a little taller
- // than other rows (Huy, 11-03, #2427).
- constraints: BoxConstraints(
- minHeight: label == null
- ? SwarmType.projectRowHeight(
- compact: compact,
- )
- : SwarmType.sidebarRowHeight(
- compact: compact,
- ),
- ),
- child: Padding(
- padding: EdgeInsets.symmetric(
- vertical: label == null
- ? SwarmType.projectRowPadding(
- compact: compact,
+ selected: selected,
+ child: Tooltip(
+ // Beside the row, level with it, never over
+ // the rows below (Huy, 11-03, #2427).
+ positionDelegate: _besideTheRow,
+ // Compact: a long name wraps rather than
+ // needing more room than the window has right
+ // of the list.
+ constraints: const BoxConstraints(maxWidth: 260),
+ message: label ?? project!.name,
+ child: ConstrainedBox(
+ // A project a little taller than other rows
+ // (Huy, 11-03, #2427).
+ constraints: BoxConstraints(
+ minHeight: label == null
+ ? SwarmType.projectRowHeight(compact: compact)
+ : SwarmType.sidebarRowHeight(
+ compact: compact,
+ ),
+ ),
+ child: Padding(
+ padding: EdgeInsets.symmetric(
+ vertical: label == null
+ ? SwarmType.projectRowPadding(
+ compact: compact,
+ )
+ : SwarmType.sidebarRowPadding(
+ compact: compact,
+ ),
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: label != null
+ ? Text(
+ label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: style,
)
- : SwarmType.sidebarRowPadding(
- compact: compact,
- ),
- ),
- child: Row(
- children: [
- Expanded(
- child: label != null
- ? Text(
- label,
+ : Column(
+ crossAxisAlignment:
+ CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ project!.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: style,
- )
- : project == null
- // One line, as Slack's (Huy,
- // 11-03, #2427): the state is the
- // mark at its right and the
- // tooltip, and a screen reader
- // still hears it (#957).
- ? Semantics(
- label: status == null
- ? null
- : superTabTaskStatusText(
- status,
- ),
- child: SuperTabWorkgroupName(
- group,
- style: style,
- quietNumber: true,
- ),
- )
- : Column(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- project.name,
- maxLines: 1,
- overflow:
- TextOverflow.ellipsis,
- style: style,
- ),
- // Teammates' agents cannot push to its repository yet (project_github.dart).
- ProjectGitHubLine(
- controller: controller,
- project: project,
- ),
- ],
),
- ),
- if (badge > 0) ...[
- const SizedBox(width: 8),
- Semantics(
- label:
- badgeTooltip ??
- (badge == 1
- ? '1 mention'
- : '$badge mentions'),
- excludeSemantics: true,
- child: SuperTabCountBadge(
- badge,
- key: ValueKey(
- 'super-mentions-${group.id}',
- ),
- tooltip: badgeTooltip,
+ // Teammates' agents cannot push to its repository yet (project_github.dart).
+ ProjectGitHubLine(
+ controller: controller,
+ project: project,
+ ),
+ ],
),
+ ),
+ if (badge > 0) ...[
+ const SizedBox(width: 8),
+ Semantics(
+ label:
+ badgeTooltip ??
+ (badge == 1
+ ? '1 mention'
+ : '$badge mentions'),
+ excludeSemantics: true,
+ child: SuperTabCountBadge(
+ badge,
+ key: ValueKey(
+ 'super-mentions-${group.id}',
),
- ],
- if (muted) ...[
- const SizedBox(width: 8),
- Tooltip(
- message: 'Muted',
- child: Icon(
- AppIcons.bellOff,
- key: ValueKey(
- 'super-muted-${group.id}',
- ),
- size: 14,
- color: DesktopChrome.muted,
- ),
+ tooltip: badgeTooltip,
+ ),
+ ),
+ ],
+ if (muted) ...[
+ const SizedBox(width: 8),
+ Tooltip(
+ message: 'Muted',
+ child: Icon(
+ AppIcons.bellOff,
+ key: ValueKey(
+ 'super-muted-${group.id}',
),
- ],
- ],
- ),
- ),
+ size: 14,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ],
+ ],
),
),
),
),
),
- SizedBox(
- // A project's row keeps no column for a mark it does
- // not have: its red number ends where Activity's does.
- width: project != null && trailing == null
- ? _rowEnd
- : _iconColumn,
- // Unread is drawn as a bold name; a screen reader
- // hears it said, as it heard the dot it replaces.
- child: Semantics(
- label: unread ? 'Unread messages' : null,
- child: Center(
- // What waits on the reader is Activity's to say; a
- // project's row says only what opening it shows.
- child: waiting && project == null
- ? Tooltip(
- message: 'Needs a human',
- child: Text(
- '?',
- style: DesktopChrome.control(
- color: grid.AppPalette.warn,
- medium: true,
- ),
- ),
- )
- : project == null && label == null
- ? SuperTabTaskMark(group)
- : trailing,
- ),
- ),
+ ),
+ SizedBox(
+ // A project's row keeps no column for a mark it does
+ // not have: its red number ends where Activity's does.
+ width: project != null && trailing == null
+ ? _rowEnd
+ : _iconColumn,
+ // Unread is drawn as a bold name; a screen reader
+ // hears it said, as it heard the dot it replaces.
+ child: Semantics(
+ label: unread ? 'Unread messages' : null,
+ child: Center(child: trailing),
),
- ],
- ),
+ ),
+ ],
),
),
),
@@ -565,123 +458,6 @@ class ProjectSidebar extends StatelessWidget {
);
}
- /// On a focused project name, → shows its conversations and ← hides them.
- /// An arrow that would change nothing moves focus as it does elsewhere.
- Widget _arrowToggles(
- SuperTabProject? project, {
- required bool expanded,
- required Widget child,
- }) => project == null
- ? child
- : Focus(
- canRequestFocus: false,
- skipTraversal: true,
- onKeyEvent: (node, event) {
- final keyboard = HardwareKeyboard.instance;
- final toggles =
- event is! KeyUpEvent &&
- !keyboard.isShiftPressed &&
- !keyboard.isControlPressed &&
- !keyboard.isAltPressed &&
- !keyboard.isMetaPressed &&
- (event.logicalKey == LogicalKeyboardKey.arrowRight
- ? !expanded
- : event.logicalKey == LogicalKeyboardKey.arrowLeft &&
- expanded);
- if (!toggles) return KeyEventResult.ignored;
- controller.toggleProject(project.id);
- return KeyEventResult.handled;
- },
- child: child,
- );
-
- /// A project's "Closed (N)" row and, when it is open, the closed groups under it: archived ones and finished
- /// ones that left the active set, as read for the project so far.
- List<Widget> _closed(_ProjectReading reading) {
- final project = reading.project;
- final groups = reading.conversations
- .where(
- (g) =>
- g.id != project.leadConversationId &&
- !g.isBuddyChat &&
- !controller.hiddenByBuddies(g) &&
- g.closed,
- )
- .toList();
- if (groups.isEmpty) return const [];
- final open = controller.closedOpenProjects.contains(project.id);
- return [
- Padding(
- padding: const EdgeInsets.only(bottom: 2),
- child: Material(
- color: Colors.transparent,
- borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
- clipBehavior: Clip.antiAlias,
- child: Semantics(
- button: true,
- expanded: open,
- child: InkWell(
- key: ValueKey('super-closed-${project.id}'),
- onTap: () => controller.toggleClosed(project.id),
- hoverColor: grid.AppSurface.hoverFill,
- focusColor: grid.AppSurface.hoverFill,
- borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
- child: Row(
- children: [
- SizedBox(width: SuperTabSectionHeading.indentFor(0)),
- const SizedBox(width: _iconColumn),
- Expanded(
- child: ConstrainedBox(
- constraints: BoxConstraints(
- minHeight: SwarmType.sidebarRowHeight(compact: compact),
- ),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- 'Closed (${groups.length})',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: SwarmType.sidebar(
- compact: compact,
- color: DesktopChrome.muted,
- ),
- ),
- ),
- ),
- ),
- SizedBox(
- width: _iconColumn,
- child: Icon(
- open ? AppIcons.chevronDown : AppIcons.chevronRight,
- size: AppIcons.inlineSize,
- color: DesktopChrome.muted,
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- if (open) ...[
- for (final group in groups) _row(group),
- if (controller.hasEarlierDormant(project.id))
- _navigationRow(
- key: 'super-closed-earlier-${project.id}',
- label: controller.dormantLoading(project.id)
- ? 'Loading…'
- : 'Show earlier',
- icon: AppIcons.chevronDown,
- onTap: controller.dormantLoading(project.id)
- ? null
- : () => unawaited(
- controller.loadDormant(project.id, earlier: true),
- ),
- ),
- ],
- ];
- }
-
/// The signed-in person's Buddy chat in each project, there from the start
/// (Lead's ruling, 10-29): the PM's private lines to them land there, and it
/// offers to start their Buddy. A viewer, who opens nothing, sees only the
@@ -767,7 +543,6 @@ class ProjectSidebar extends StatelessWidget {
key: 'super-swarm-buddy',
selected:
chat != null && !_paneCovered && controller.selectedId == chat.id,
- waiting: false,
// Muted, it is greyed and never bold, as every chat (_drawRow).
unread: chat != null && controller.unreadShown(chat),
trailing: agent == null ? null : _buddyMark(agent),
@@ -800,128 +575,6 @@ class ProjectSidebar extends StatelessWidget {
);
}
- /// A project's open conversations, newest first: the most recently created
- /// has the highest number, and one without a number predates numbering.
- List<SuperTabConversation> _newestFirst(_ProjectReading reading) =>
- superTabOpenWorkgroups(
- controller,
- reading.project,
- reading.conversations,
- );
-
- /// A task group's heading under a project, as the mockup Huy approved
- /// draws it: "▾ Needs you 1". It folds and unfolds the group, by click,
- /// Enter or Space.
- Widget _taskGroupHeading(
- SuperTabProject project,
- SuperTabTaskGroup group,
- int count,
- ) {
- final folded = controller.taskGroupFolded(project.id, group);
- final style = SwarmType.sidebar(
- compact: compact,
- color: DesktopChrome.muted,
- );
- return Padding(
- padding: const EdgeInsets.only(bottom: 2),
- child: Material(
- color: Colors.transparent,
- borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
- clipBehavior: Clip.antiAlias,
- child: Semantics(
- button: true,
- expanded: !folded,
- child: InkWell(
- key: ValueKey('super-task-group-${project.id}-${group.name}'),
- onTap: () => controller.toggleTaskGroup(project.id, group),
- hoverColor: grid.AppSurface.hoverFill,
- focusColor: grid.AppSurface.hoverFill,
- borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
- child: Row(
- children: [
- SizedBox(width: SuperTabSectionHeading.indentFor(0)),
- SizedBox(
- width: _iconColumn,
- child: Icon(
- folded ? AppIcons.chevronRight : AppIcons.chevronDown,
- size: AppIcons.inlineSize,
- color: DesktopChrome.muted,
- ),
- ),
- Flexible(
- child: ConstrainedBox(
- constraints: BoxConstraints(
- minHeight: SwarmType.sidebarRowHeight(compact: compact),
- ),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- group.label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: style,
- ),
- ),
- ),
- ),
- const SizedBox(width: 8),
- Text('$count', style: style),
- const SizedBox(width: _rowEnd),
- ],
- ),
- ),
- ),
- ),
- );
- }
-
- /// A project's open tasks in their groups (Huy, #2309): each group with a
- /// row the unread filter keeps gets its heading, then its rows newest
- /// first; a folded one shows only the open chat's row.
- List<Widget> _workgroups(_ProjectReading reading) {
- final project = reading.project;
- final groups = _newestFirst(reading)
- .where((g) => _keptByFilter(g, reading))
- .toList();
- final grouped = superTabGroupTasks(
- groups,
- readerId: controller.accountId,
- mentions: (g) => attention?.mentionsIn(g.id) ?? 0,
- // Asked once per build already (_ProjectReading).
- needsHuman: (g) => reading.waiting.contains(g.id) ? 1 : 0,
- );
- return groups.isEmpty
- ? [
- Padding(
- padding: EdgeInsets.fromLTRB(
- SuperTabSectionHeading.indentFor(0) + _iconColumn,
- 8,
- 12,
- 10,
- ),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- 'No workgroups yet',
- style: DesktopChrome.metadata(),
- ),
- ),
- ),
- ]
- : [
- for (final MapEntry(key: taskGroup, value: rows) in grouped.entries)
- if (rows.isNotEmpty) ...[
- _taskGroupHeading(project, taskGroup, rows.length),
- for (final group in rows)
- // The open chat stays listed, Manage or Devices over it
- // too: its row is the way back to it.
- if (!controller.taskGroupFolded(project.id, taskGroup) ||
- controller.selectedId == group.id)
- _workgroupRow(group, reading),
- ],
- ];
- }
-
/// Whether the unread filter keeps [read]'s project: its chat or an open
/// workgroup is unread or tags the reader, or the open chat is in it.
/// By the rule its rows are bold by (#2427): what is for a person.
@@ -931,15 +584,12 @@ class ProjectSidebar extends StatelessWidget {
read.mentions > 0 ||
(read.lead != null && controller.unreadForPeople(read.lead!));
- /// Whether the unread filter keeps [group]'s row: a project's chat or task
- /// by what makes it bold ([reading]'s, review of #2790), a Buddy chat by
- /// any new message, as its row is bold.
- bool _keptByFilter(SuperTabConversation group, [_ProjectReading? reading]) =>
+ /// Whether the unread filter keeps a Buddy chat's row: any new message, as
+ /// its row is bold.
+ bool _keptByFilter(SuperTabConversation group) =>
!controller.unreadOnly ||
(!_paneCovered && controller.selectedId == group.id) ||
- (reading != null
- ? reading.unread.contains(group.id)
- : controller.unreadShown(group)) ||
+ controller.unreadShown(group) ||
(attention?.mentionsIn(group.id) ?? 0) > 0;
/// Every project with its workgroups, by name from A to Z. The round dial
@@ -958,21 +608,7 @@ class ProjectSidebar extends StatelessWidget {
Column(
key: ValueKey('super-project-${project.id}'),
mainAxisSize: MainAxisSize.min,
- children: [
- _row(read.lead!, reading: read),
- if (controller.expandedProjects.contains(project.id)) ...[
- // Built when the list lays the project out, not on every
- // rebuild: an expanded project off screen costs nothing, as
- // the 8 newest did behind "… N more" (#2309).
- Builder(
- builder: (_) => Column(
- mainAxisSize: MainAxisSize.min,
- children: _workgroups(read),
- ),
- ),
- ..._closed(read),
- ],
- ],
+ children: [_row(read.lead!, reading: read)],
),
),
]..sort((a, b) => a.$1.toLowerCase().compareTo(b.$1.toLowerCase()));
@@ -1193,10 +829,28 @@ class _ProjectReading {
sidebar.controller.snapshot?.conversation(project.leadConversationId);
late final buddyChat = sidebar.controller.buddyChat(project.id);
- /// The open conversations that need a human, and those with unread messages;
- /// never the reader's Buddy chat, which has its own row under Buddies.
- Set<String> get waiting => _open.waiting;
- Set<String> get unread => _open.unread;
+ /// The open conversations with unread messages; never the reader's Buddy
+ /// chat, which has its own row under Buddies.
+ late final Set<String> unread = {
+ for (final g in conversations)
+ if (!g.closed &&
+ !g.isBuddyChat &&
+ g.audience == null &&
+ (sidebar.controller.unreadForPeople(g) ||
+ (sidebar.attention?.mentionsIn(g.id) ?? 0) > 0))
+ g.id,
+ };
+
+ /// How many of its tasks need the reader: what its row's badge adds.
+ late final int needsYou = superTabTasksNeedingYouIn(
+ superTabProjectBoard(
+ sidebar.controller,
+ project,
+ now: clock.now(),
+ needsHuman: sidebar.needsHuman,
+ attention: sidebar.attention,
+ ),
+ );
/// Tags of the reader in the project's chat and its open workgroups: why the
/// unread filter keeps a collapsed project. Never its number ([_row]).
@@ -1213,87 +867,27 @@ class _ProjectReading {
attention.mentionsIn(g.id),
].fold(0, (a, b) => a + b),
};
-
- /// A row is bold when a person wrote there or the reader is tagged there
- /// (#2427): what there is to read. Agents' progress alone leaves it, and a
- /// wait is its ? mark, not bold (review of #2790). Each conversation's wait
- /// is asked once per build.
- late final _open = () {
- final waiting = <String>{}, unread = <String>{};
- final controller = sidebar.controller;
- for (final g in conversations) {
- if (g.closed || g.isBuddyChat || g.audience != null) continue;
- final waits = sidebar.needsHuman(g) > 0;
- if (waits) waiting.add(g.id);
- if (controller.unreadForPeople(g) ||
- (sidebar.attention?.mentionsIn(g.id) ?? 0) > 0) {
- unread.add(g.id);
- }
- }
- return (waiting: waiting, unread: unread);
- }();
-}
-
-/// A project's open workgroups as the sidebar lists them, newest first: the
-/// most recently created has the highest number, and one without a number
-/// predates numbering.
-List<SuperTabConversation> superTabOpenWorkgroups(
- SuperTabController controller,
- SuperTabProject project, [
- List<SuperTabConversation>? conversations,
-]) {
- final groups =
- superTabListedWork(
- conversations ?? controller.projectConversations(project.id),
- )
- .where(
- (g) =>
- g.id != project.leadConversationId &&
- !g.isBuddyChat &&
- !controller.hiddenByBuddies(g) &&
- !g.closed,
- )
- .toList();
- // A stable sort keeps the backend's order among unnumbered ones.
- mergeSort(
- groups,
- compare: (a, b) => (b.number ?? 0).compareTo(a.number ?? 0),
- );
- return groups;
}
/// The chats in the order the sidebar lists them, for Option+Shift+Down and
/// Up (Slack's next unread): the reader's one Buddy chat (`# buddy`, first
-/// under Projects), each project from A to Z, its chat then its open
-/// workgroups in their groups (#2309), each newest first, then the reader's
-/// project Buddy chats. [needsHuman] is the sidebar's. The round dial swipes
-/// projects in this A to Z order too (cli superTabs/cards.ts `leadsOf`): the
-/// two must match.
-List<String> superTabSidebarOrder(
- SuperTabController controller, {
- int Function(SuperTabConversation group)? needsHuman,
-}) {
+/// under Projects), each project's chat from A to Z, then the reader's
+/// project Buddy chats. Tasks are in each project's Tasks view, not here
+/// (task #2569). The round dial swipes projects in this A to Z order too (cli
+/// superTabs/cards.ts `leadsOf`): the two must match.
+List<String> superTabSidebarOrder(SuperTabController controller) {
final snapshot = controller.snapshot;
if (snapshot == null) return const [];
final projects = [...snapshot.projects]
..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
- final attention = SuperTabAttention.of(controller);
return [
if (controller.oneBuddy)
if (controller.buddyChat(SuperTabController.kSwarmBuddyKey)
case final chat?)
chat.id,
- for (final project in projects) ...[
+ for (final project in projects)
if (snapshot.conversation(project.leadConversationId) != null)
project.leadConversationId,
- for (final tasks in superTabGroupTasks(
- superTabOpenWorkgroups(controller, project),
- readerId: controller.accountId,
- mentions: (g) => attention.mentionsIn(g.id),
- needsHuman: needsHuman,
- ).values)
- for (final group in tasks) group.id,
- ],
for (final project in projects)
if (controller.buddyChat(project.id) case final chat?) chat.id,
];
diff --git a/desktop/lib/super_tabs/task_card.dart b/desktop/lib/super_tabs/task_card.dart
new file mode 100644
index 000000000..001c5afc8
--- /dev/null
+++ b/desktop/lib/super_tabs/task_card.dart
@@ -0,0 +1,123 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../widgets/desktop_chrome.dart';
+
+/// One card of a project's Tasks view, on the Board and as a List row alike:
+/// its title (up to two lines), then its caption, and "Needs you" with a red
+/// dot when it waits on the reader. New replies make the title bold with a dot,
+/// said to a screen reader, so colour is never the only signal.
+class SuperTabTaskCard extends StatelessWidget {
+ const SuperTabTaskCard({
+ super.key,
+ required this.title,
+ required this.caption,
+ required this.needsYou,
+ required this.unread,
+ required this.onOpen,
+ this.titleLines = 2,
+ this.trailing,
+ });
+
+ final String title, caption;
+ final bool needsYou, unread;
+ final VoidCallback onOpen;
+ final int titleLines;
+ final Widget? trailing;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final muted = DesktopChrome.metadata();
+ final dot = SizedBox.square(
+ dimension: grid.AppDesktop.controlGap,
+ child: DecoratedBox(
+ decoration: ShapeDecoration(
+ color: grid.AppPalette.dangerFill,
+ shape: const CircleBorder(),
+ ),
+ ),
+ );
+ return Semantics(
+ button: true,
+ label: [
+ title,
+ caption,
+ if (needsYou) 'Needs you',
+ if (unread) 'New replies',
+ ].join(', '),
+ excludeSemantics: true,
+ child: InkWell(
+ onTap: onOpen,
+ hoverColor: grid.AppSurface.hoverFill,
+ focusColor: grid.AppSurface.hoverFill,
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: grid.AppDesktop.controlGap,
+ vertical: grid.AppDesktop.menuInset,
+ ),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (needsYou)
+ Row(
+ children: [
+ dot,
+ const SizedBox(width: grid.AppDesktop.menuInset),
+ Text(
+ 'Needs you',
+ style: DesktopChrome.metadata(
+ color: DesktopChrome.foreground,
+ ),
+ ),
+ ],
+ ),
+ Text(
+ title,
+ maxLines: titleLines,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(
+ color: DesktopChrome.foreground,
+ medium: unread,
+ ),
+ ),
+ if (caption.isNotEmpty)
+ Text(
+ caption,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: muted,
+ ),
+ ],
+ ),
+ ),
+ if (unread) ...[
+ const SizedBox(width: grid.AppDesktop.menuInset),
+ Padding(
+ padding: const EdgeInsets.only(
+ top: grid.AppDesktop.menuInset,
+ ),
+ child: SizedBox.square(
+ dimension: grid.AppDesktop.controlGap,
+ child: DecoratedBox(
+ decoration: ShapeDecoration(
+ color: grid.AppPalette.accent,
+ shape: const CircleBorder(),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ?trailing,
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/task_groups.dart b/desktop/lib/super_tabs/task_groups.dart
index a221c1a38..a74a55293 100644
--- a/desktop/lib/super_tabs/task_groups.dart
+++ b/desktop/lib/super_tabs/task_groups.dart
@@ -1,77 +1,270 @@
+import 'package:collection/collection.dart';
+
+import 'attention.dart';
+import 'backlog.dart';
+import 'controller.dart';
+import 'identity.dart';
import 'model.dart';
-/// The groups a project's open tasks are listed in under it in the sidebar, in
-/// this order (Huy, #2309): a busy project's list read as one long run of
-/// unread rows.
-enum SuperTabTaskGroup {
- needsYou('Needs you'),
+/// A Buddy proposal in a project's chat that the PM has not answered yet, as
+/// the proposals read answers it (backend proposals.ts), not part of the
+/// Swarm's state: its root message, its title, and the person it was sent for.
+class SuperTabProposal {
+ SuperTabProposal.fromJson(Map<String, dynamic> answer)
+ : messageId = answer['messageId'] as String,
+ title = answer['title'] as String? ?? '',
+ personId = answer['personId'] as String?,
+ at = DateTime.fromMillisecondsSinceEpoch(
+ (answer['at'] as num? ?? 0).toInt(),
+ );
+ final String messageId, title;
+ final String? personId;
+ final DateTime at;
+}
+
+/// The columns of a project's Tasks view, in this order (Dee, task #2569):
+/// where each ask is on its way from proposal to shipped.
+enum SuperTabTaskColumn {
+ proposals('Proposals'),
+ nextUp('Next up'),
working('Working'),
- waitingOnOthers('Waiting on others'),
- rest('The rest');
+ waiting('Waiting'),
+ shipped('Shipped');
- const SuperTabTaskGroup(this.label);
+ const SuperTabTaskColumn(this.label);
final String label;
+}
+
+/// Where a task is listed: its column, whether it waits on the reader (a mark
+/// in its column, never a column of its own), and what its caption says of
+/// its state, or nothing.
+typedef SuperTabTaskPlace = ({
+ SuperTabTaskColumn column,
+ bool needsYou,
+ String? state,
+});
+
+const _months = [
+ 'Jan',
+ 'Feb',
+ 'Mar',
+ 'Apr',
+ 'May',
+ 'Jun',
+ 'Jul',
+ 'Aug',
+ 'Sep',
+ 'Oct',
+ 'Nov',
+ 'Dec',
+];
- /// Only The rest starts folded: the first screen is what needs the reader
- /// and what is moving.
- bool get foldedByDefault => this == rest;
+/// The pull request a caption names: "PR #12", or none for a task without one.
+String? _pullRequest(SuperTabConversation task) {
+ final url =
+ task.cards.pullRequests.firstOrNull?.url ??
+ task.pullRequestUrls.firstOrNull;
+ final number = url == null ? null : Uri.tryParse(url)?.pathSegments.last;
+ return number == null || int.tryParse(number) == null ? null : 'PR #$number';
}
-/// Which group [group] is listed in, for the reader [readerId]: tagged, or
-/// waited on (by name, or by no one named), or asked in its agent's terminal
-/// ([needsHuman]) is theirs; a wait on someone or something else, or a stuck
-/// task the PM hands on, is others'; an agent moving or starting is working.
-/// The task line says the same states (task_status.dart).
-SuperTabTaskGroup superTabTaskGroupOf(
- SuperTabConversation group, {
+/// [task]'s place for the reader [readerId] at [now]; null for one that is
+/// not listed: cancelled, stopped, closed without shipping, or shipped before
+/// the window. It needs the reader as the sidebar's groups did: tagged
+/// ([mentions]), waited on by name or by no one named, or asked in its agent's
+/// terminal ([needsHuman]). [personName] names the person a wait is on.
+SuperTabTaskPlace? superTabTaskPlaceOf(
+ SuperTabConversation task, {
required String readerId,
+ required DateTime now,
int mentions = 0,
int needsHuman = 0,
+ String? Function(String personId)? personName,
}) {
- if (mentions > 0) return SuperTabTaskGroup.needsYou;
- final liveness = group.liveness;
- if (liveness == null) {
- if (needsHuman > 0) return SuperTabTaskGroup.needsYou;
- return const {'working', 'planned'}.contains(group.assignment?['status'])
- ? SuperTabTaskGroup.working
- : SuperTabTaskGroup.rest;
+ final assignment = task.assignment;
+ final status = assignment?['status'];
+ final liveness = task.liveness;
+ final (state, why) = (liveness?['state'], liveness?['why']);
+ final pullRequest = _pullRequest(task);
+ final person = liveness?['personId'] as String?;
+ final needsYou =
+ mentions > 0 ||
+ needsHuman > 0 ||
+ (person ?? readerId) == readerId &&
+ (state == 'waiting' && why == 'person' || status == 'needs_human');
+ SuperTabTaskPlace at(SuperTabTaskColumn column, [String? words]) =>
+ (column: column, needsYou: needsYou, state: words);
+ SuperTabTaskPlace waiting(String words) =>
+ at(SuperTabTaskColumn.waiting, words);
+ // Shipped means merged; finished with nothing to merge is Done (#2872).
+ final merged = task.cards.pullRequests.any((card) => card.merged);
+ if (superTabTaskShipped(task)) {
+ final shipped = task.shippedAt;
+ final old = shipped == null
+ ? task.closed
+ : now.difference(shipped) > superTabBacklogShippedWindow;
+ return old
+ ? null
+ : at(SuperTabTaskColumn.shipped, merged ? pullRequest : 'Done');
}
- return switch ((liveness['state'], liveness['why'])) {
- ('waiting', 'person') => switch (liveness['personId']) {
- final String person when person != readerId =>
- SuperTabTaskGroup.waitingOnOthers,
- _ => SuperTabTaskGroup.needsYou,
+ if (task.closed || status == 'cancelled' || status == 'stopped') {
+ return null;
+ }
+ if (status == 'done') return waiting('ready to merge');
+ if (assignment == null) {
+ final date = task.notBefore;
+ return at(
+ SuperTabTaskColumn.nextUp,
+ date == null ? null : 'not before ${_months[date.month - 1]} ${date.day}',
+ );
+ }
+ return switch ((state, why)) {
+ ('waiting', 'starting') => at(SuperTabTaskColumn.working, pullRequest),
+ ('waiting', 'review') => waiting('in review'),
+ ('waiting', 'revision') => waiting('changes requested'),
+ ('waiting', 'person') => waiting(
+ '${(person == null ? null : personName?.call(person)) ?? 'someone'} to decide',
+ ),
+ ('waiting', 'blocked') => waiting('blocked'),
+ ('waiting', 'queued') => waiting('waiting for a machine'),
+ ('quiet', _) => waiting('quiet'),
+ ('orphaned', _) => waiting('agent lost'),
+ _ => switch (status) {
+ 'review' => waiting('in review'),
+ 'needs_human' => waiting('someone to decide'),
+ 'blocked' => waiting('blocked'),
+ 'lost' => waiting('agent lost'),
+ _ when assignment['agentId'] is! String => waiting(
+ 'waiting for a machine',
+ ),
+ _ => at(SuperTabTaskColumn.working, pullRequest),
},
- // An agent at a question makes no progress, so its task goes quiet
- // after 30 minutes: the question still waits on the reader.
- ('quiet', _) when needsHuman > 0 => SuperTabTaskGroup.needsYou,
- ('waiting', 'review' || 'revision' || 'blocked' || 'queued') ||
- ('quiet' || 'orphaned', _) => SuperTabTaskGroup.waitingOnOthers,
- ('waiting', 'starting') => SuperTabTaskGroup.working,
- _ => SuperTabTaskGroup.rest,
};
}
-/// [tasks] in their groups, in the groups' order and each in the order given:
-/// how the sidebar lists them and how next unread walks them.
-Map<SuperTabTaskGroup, List<SuperTabConversation>> superTabGroupTasks(
+/// One card of the Tasks view: a task, or a Buddy proposal not yet a task.
+typedef SuperTabTaskEntry = ({
+ SuperTabConversation? task,
+ SuperTabProposal? proposal,
+ bool needsYou,
+ String? state,
+});
+
+/// Where [task] sits in its project's shared Next up: the rank a person or the
+/// PM gave it, else its number, so a new task joins the bottom.
+double _queueKey(SuperTabConversation task) =>
+ task.queueRank ?? (task.number ?? 0).toDouble();
+
+int _queueOrder(SuperTabConversation a, SuperTabConversation b) =>
+ switch (_queueKey(a).compareTo(_queueKey(b))) {
+ 0 => (a.number ?? 0).compareTo(b.number ?? 0),
+ final c => c,
+ };
+
+/// [tasks] in their project's shared Next-up order, as the server keeps it
+/// (backend taskQueue.ts): what a move is placed against.
+List<SuperTabConversation> superTabQueueOrder(
+ Iterable<SuperTabConversation> tasks,
+) => [...tasks]..sort(_queueOrder);
+
+/// The project's Tasks view, read by Board, List and the badges alike: every
+/// column, in order and empty or not, each listing what needs the reader
+/// first, then proposals oldest first, Next up in the shared order, Working
+/// and Waiting newest first, and Shipped by when it shipped, newest first.
+Map<SuperTabTaskColumn, List<SuperTabTaskEntry>> superTabTaskBoard(
Iterable<SuperTabConversation> tasks, {
+ Iterable<SuperTabProposal> proposals = const [],
required String readerId,
+ required DateTime now,
int Function(SuperTabConversation task)? mentions,
int Function(SuperTabConversation task)? needsHuman,
+ String? Function(String personId)? personName,
}) {
- final grouped = {
- for (final group in SuperTabTaskGroup.values)
- group: <SuperTabConversation>[],
+ final board = {
+ for (final column in SuperTabTaskColumn.values)
+ column: <SuperTabTaskEntry>[],
};
+ board[SuperTabTaskColumn.proposals]!.addAll([
+ for (final proposal in [...proposals]..sort((a, b) => a.at.compareTo(b.at)))
+ (task: null, proposal: proposal, needsYou: false, state: null),
+ ]);
for (final task in tasks) {
- grouped[superTabTaskGroupOf(
- task,
- readerId: readerId,
- mentions: mentions?.call(task) ?? 0,
- needsHuman: needsHuman?.call(task) ?? 0,
- )]!
- .add(task);
+ final place = superTabTaskPlaceOf(
+ task,
+ readerId: readerId,
+ now: now,
+ mentions: mentions?.call(task) ?? 0,
+ // A closed task's agent asks nothing: only open ones are asked.
+ needsHuman: task.closed ? 0 : needsHuman?.call(task) ?? 0,
+ personName: personName,
+ );
+ if (place == null) continue;
+ board[place.column]!.add((
+ task: task,
+ proposal: null,
+ needsYou: place.needsYou,
+ state: place.state,
+ ));
+ }
+ int order(
+ SuperTabTaskColumn column,
+ SuperTabTaskEntry a,
+ SuperTabTaskEntry b,
+ ) {
+ if (a.needsYou != b.needsYou) return a.needsYou ? -1 : 1;
+ final (x, y) = (a.task, b.task);
+ if (x == null || y == null) return 0;
+ return switch (column) {
+ SuperTabTaskColumn.nextUp => _queueOrder(x, y),
+ SuperTabTaskColumn.shipped => (y.shippedAt ?? now).compareTo(
+ x.shippedAt ?? now,
+ ),
+ _ => (y.number ?? 0).compareTo(x.number ?? 0),
+ };
}
- return grouped;
+
+ for (final MapEntry(key: column, value: entries) in board.entries) {
+ mergeSort(entries, compare: (a, b) => order(column, a, b));
+ }
+ return board;
+}
+
+/// How many cards of [board] need the reader: the red count on the header's
+/// Tasks icon, and what the project's sidebar row adds to its badge.
+int superTabTasksNeedingYouIn(
+ Map<SuperTabTaskColumn, List<SuperTabTaskEntry>> board,
+) => board.values.expand((entries) => entries).where((e) => e.needsYou).length;
+
+/// [project]'s Tasks view for the reader of [c] at [now]: its open tasks, the
+/// shipped ones it read for the window ([SuperTabController.closedShipped]),
+/// and its open proposals. [needsHuman] says which tasks' agents asked the
+/// reader in their terminal.
+Map<SuperTabTaskColumn, List<SuperTabTaskEntry>> superTabProjectBoard(
+ SuperTabController c,
+ SuperTabProject project, {
+ required DateTime now,
+ int Function(SuperTabConversation task)? needsHuman,
+ SuperTabAttention? attention,
+}) {
+ final tags = attention ?? SuperTabAttention.of(c);
+ final people = {
+ for (final person in c.snapshot?.people ?? const <SuperTabPerson>[])
+ person.id: superTabPersonName(person.email),
+ };
+ return superTabTaskBoard(
+ superTabProjectTasks(
+ c,
+ project,
+ closed: [
+ for (final g in c.closedShipped)
+ if (g.projectId == project.id) g,
+ ],
+ ),
+ proposals: c.proposalsOf(project.id),
+ readerId: c.accountId,
+ now: now,
+ mentions: (task) => tags.mentionsIn(task.id),
+ needsHuman: needsHuman,
+ personName: (id) => people[id],
+ );
}
diff --git a/desktop/lib/super_tabs/tasks_view.dart b/desktop/lib/super_tabs/tasks_view.dart
new file mode 100644
index 000000000..1f1ad5997
--- /dev/null
+++ b/desktop/lib/super_tabs/tasks_view.dart
@@ -0,0 +1,502 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../core/local_key_value_store.dart';
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../widgets/desktop_chrome.dart';
+import '../widgets/laid_out_list.dart';
+import 'attention.dart';
+import 'backlog.dart';
+import 'controller.dart';
+import 'machine_status.dart';
+import 'model.dart';
+import 'task_card.dart';
+import 'task_groups.dart';
+
+/// A project's Tasks view (Dee, task #2569): every ask from proposal to
+/// shipped, as a Board (the default) or a List, with Mine and Search. It reads
+/// only what the controller holds, and the shipped tasks it reads for the
+/// window, so cards move as the work does.
+class SuperTabTasksView extends StatefulWidget {
+ const SuperTabTasksView({
+ super.key,
+ required this.controller,
+ required this.project,
+ required this.needsHuman,
+ required this.onOpenTask,
+ required this.onOpenProposal,
+ this.storage,
+ this.now = DateTime.now,
+ });
+
+ final SuperTabController controller;
+ final SuperTabProject project;
+
+ /// Which tasks' agents asked the reader in their terminal (the sidebar's).
+ final int Function(SuperTabConversation task) needsHuman;
+ final ValueChanged<String> onOpenTask;
+
+ /// Opens a proposal's thread in the project chat, by its message id.
+ final ValueChanged<String> onOpenProposal;
+
+ /// Where Board or List, and Mine, are kept for this reader on this Mac.
+ final LocalKeyValueStore? storage;
+ final DateTime Function() now;
+
+ static String storageKey(String accountId) =>
+ 'super-tab-tasks-view/$accountId';
+
+ @override
+ State<SuperTabTasksView> createState() => _SuperTabTasksViewState();
+}
+
+class _SuperTabTasksViewState extends State<SuperTabTasksView> {
+ bool _list = false, _mine = false;
+ String _query = '';
+
+ /// List's sections folded: Shipped starts so; not kept.
+ final _folded = {SuperTabTaskColumn.shipped};
+
+ /// Next up as the reader just ordered it, by task id, until the server
+ /// answers; and why the last move was refused.
+ List<String>? _moving;
+ String? _moveError;
+
+ /// Whether the last drag ended over Next up: a card dropped anywhere else
+ /// goes back.
+ bool _droppedOnNextUp = false;
+ final _nextUpKey = GlobalKey();
+
+ @override
+ void initState() {
+ super.initState();
+ unawaited(_restore());
+ _readShipped();
+ }
+
+ @override
+ void didUpdateWidget(SuperTabTasksView old) {
+ super.didUpdateWidget(old);
+ if (!identical(old.controller, widget.controller)) _readShipped();
+ }
+
+ void _readShipped() => unawaited(
+ widget.controller.readClosedShipped(
+ widget.now().subtract(superTabBacklogShippedWindow),
+ ),
+ );
+
+ String get _key => SuperTabTasksView.storageKey(widget.controller.accountId);
+
+ Future<void> _restore() async {
+ final raw = await widget.storage?.read(_key);
+ if (raw == null || !mounted) return;
+ try {
+ final saved = jsonDecode(raw);
+ if (saved is! Map) return;
+ setState(() {
+ _list = saved['layout'] == 'list';
+ _mine = saved['mine'] == true;
+ });
+ } on FormatException {
+ // A copy this build cannot read: the defaults stand, and the next
+ // choice replaces it.
+ }
+ }
+
+ void _choose({bool? list, bool? mine}) {
+ setState(() {
+ _list = list ?? _list;
+ _mine = mine ?? _mine;
+ });
+ unawaited(
+ widget.storage?.write(
+ _key,
+ jsonEncode({'layout': _list ? 'list' : 'board', 'mine': _mine}),
+ ),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final c = widget.controller;
+ return ListenableBuilder(
+ listenable: Listenable.merge([
+ c,
+ c.closedShippedChanged,
+ SuperTabAttention.of(c),
+ ]),
+ builder: (context, _) => _build(context),
+ );
+ }
+
+ String? _person(String? id) => id == null
+ ? null
+ : widget.controller.snapshot?.people
+ .where((p) => p.id == id)
+ .firstOrNull
+ ?.shownName;
+
+ bool _keeps(SuperTabTaskEntry entry) {
+ final reader = widget.controller.accountId;
+ final asker = entry.task?.requesterId ?? entry.proposal?.personId;
+ final title = entry.task?.title ?? entry.proposal!.title;
+ return (!_mine || asker == reader) &&
+ (_query.isEmpty || title.toLowerCase().contains(_query.toLowerCase()));
+ }
+
+ Widget _build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final c = widget.controller;
+ final project =
+ c.snapshot?.projects
+ .where((p) => p.id == widget.project.id)
+ .firstOrNull ??
+ widget.project;
+ final now = widget.now();
+ // After the frame: a build changes nothing outside itself.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) unawaited(c.readProposals(project.id));
+ });
+ final board = superTabProjectBoard(
+ c,
+ project,
+ now: now,
+ needsHuman: widget.needsHuman,
+ );
+ final shown = {
+ for (final MapEntry(:key, :value) in board.entries)
+ key: value.where(_keeps).toList(),
+ };
+ final empty = board.values.every((entries) => entries.isEmpty);
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _bar(context),
+ Expanded(
+ child: empty
+ ? Center(
+ child: Text(
+ 'No tasks yet',
+ style: DesktopChrome.control(color: DesktopChrome.muted),
+ ),
+ )
+ : _list
+ ? _listView(shown, now)
+ : _boardView(shown, now),
+ ),
+ ],
+ );
+ }
+
+ /// The view's own bar: Board or List, Mine and Search, nothing else.
+ Widget _bar(BuildContext context) => Padding(
+ padding: const EdgeInsets.fromLTRB(
+ grid.AppDesktop.groupGap,
+ grid.AppDesktop.controlGap,
+ grid.AppDesktop.groupGap,
+ grid.AppDesktop.controlGap,
+ ),
+ child: Row(
+ children: [
+ Text('Tasks', style: DesktopChrome.text(medium: true)),
+ if (_moveError case final error?) ...[
+ const SizedBox(width: grid.AppDesktop.groupGap),
+ Flexible(
+ child: Text(
+ error,
+ key: const ValueKey('super-tasks-move-error'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ ],
+ const Spacer(),
+ DesktopPill(
+ key: const ValueKey('super-tasks-layout-board'),
+ label: 'Board',
+ selected: !_list,
+ onPressed: () => _choose(list: false),
+ ),
+ const SizedBox(width: grid.AppDesktop.listRowGap),
+ DesktopPill(
+ key: const ValueKey('super-tasks-layout-list'),
+ label: 'List',
+ selected: _list,
+ onPressed: () => _choose(list: true),
+ ),
+ const SizedBox(width: grid.AppDesktop.groupGap),
+ DesktopPill(
+ key: const ValueKey('super-tasks-mine'),
+ label: 'Mine',
+ selected: _mine,
+ tooltip: 'Only the tasks you asked for',
+ onPressed: () => _choose(mine: !_mine),
+ ),
+ const SizedBox(width: grid.AppDesktop.controlGap),
+ SizedBox(
+ width: _searchWidth,
+ child: TextField(
+ key: const ValueKey('super-tasks-search'),
+ onChanged: (query) => setState(() => _query = query.trim()),
+ textInputAction: TextInputAction.search,
+ style: grid.kFieldTextStyle,
+ decoration: InputDecoration(
+ hintText: 'Search',
+ isDense: true,
+ prefixIcon: Icon(
+ AppIcons.search,
+ size: grid.kFieldIconSize,
+ color: grid.AppPalette.textFaint,
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+
+ static const _searchWidth = 220.0;
+ static const _columnGap = grid.AppDesktop.groupGap;
+
+ Widget _heading(SuperTabTaskColumn column, int count, {bool? folded}) {
+ final style = DesktopChrome.control(medium: true);
+ final row = Row(
+ children: [
+ if (folded != null)
+ Icon(
+ folded ? AppIcons.chevronRight : AppIcons.chevronDown,
+ size: AppIcons.inlineSize,
+ color: DesktopChrome.muted,
+ ),
+ if (folded != null) const SizedBox(width: grid.AppDesktop.menuInset),
+ Text(column.label, style: style),
+ const SizedBox(width: grid.AppDesktop.controlGap),
+ Text('$count', style: DesktopChrome.metadata()),
+ ],
+ );
+ final key = ValueKey('super-tasks-heading-${column.name}');
+ final padded = Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: grid.AppDesktop.controlGap,
+ vertical: grid.AppDesktop.menuInset,
+ ),
+ child: row,
+ );
+ if (folded == null) return KeyedSubtree(key: key, child: padded);
+ return Semantics(
+ button: true,
+ expanded: !folded,
+ child: InkWell(
+ key: key,
+ onTap: () => setState(() {
+ if (!_folded.remove(column)) _folded.add(column);
+ }),
+ hoverColor: grid.AppSurface.hoverFill,
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ child: padded,
+ ),
+ );
+ }
+
+ /// The caption under a card's title: who asked, the agent on it and its
+ /// state, joined by middle dots; a proposal's says who asked and how long
+ /// ago. No task numbers, machines or models.
+ String _caption(SuperTabTaskEntry entry, DateTime now) {
+ final snapshot = widget.controller.snapshot;
+ if (entry.proposal case final proposal?) {
+ return [
+ ?_person(proposal.personId),
+ superTabAgoShort(now.difference(proposal.at)),
+ ].join(' · ');
+ }
+ final task = entry.task!;
+ final agentId = task.assignment?['agentId'];
+ return [
+ ?_person(task.requesterId),
+ if (agentId is String && snapshot != null)
+ snapshot.agentName(agentId, fallback: 'Agent unavailable'),
+ ?entry.state,
+ ].join(' · ');
+ }
+
+ Widget _card(SuperTabTaskEntry entry, DateTime now, {required bool list}) {
+ final task = entry.task;
+ final id = task?.id ?? entry.proposal!.messageId;
+ return SuperTabTaskCard(
+ key: ValueKey('super-task-card-$id'),
+ title: task?.title ?? entry.proposal!.title,
+ caption: _caption(entry, now),
+ needsYou: entry.needsYou,
+ unread: task != null && widget.controller.unreadShown(task),
+ titleLines: list ? 1 : 2,
+ onOpen: () =>
+ task == null ? widget.onOpenProposal(id) : widget.onOpenTask(task.id),
+ );
+ }
+
+ Widget _boardView(
+ Map<SuperTabTaskColumn, List<SuperTabTaskEntry>> shown,
+ DateTime now,
+ ) => Padding(
+ padding: const EdgeInsets.symmetric(horizontal: grid.AppDesktop.controlGap),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ for (final column in SuperTabTaskColumn.values) ...[
+ if (column != SuperTabTaskColumn.values.first)
+ const SizedBox(width: _columnGap),
+ Expanded(
+ child: Column(
+ key: ValueKey('super-tasks-column-${column.name}'),
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _heading(column, shown[column]!.length),
+ Expanded(
+ child: column == SuperTabTaskColumn.nextUp
+ ? _nextUp(shown[column]!, now)
+ : LaidOutListView.builder(
+ itemCount: shown[column]!.length,
+ itemBuilder: (context, i) => Padding(
+ padding: const EdgeInsets.only(
+ bottom: grid.AppDesktop.listRowGap,
+ ),
+ child: _card(shown[column]![i], now, list: false),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ],
+ ),
+ );
+
+ Widget _listView(
+ Map<SuperTabTaskColumn, List<SuperTabTaskEntry>> shown,
+ DateTime now,
+ ) {
+ final rows = <Widget>[
+ for (final column in SuperTabTaskColumn.values) ...[
+ _heading(
+ column,
+ shown[column]!.length,
+ folded: _folded.contains(column),
+ ),
+ if (!_folded.contains(column))
+ for (final entry in shown[column]!) _card(entry, now, list: true),
+ ],
+ ];
+ return LaidOutListView.builder(
+ padding: const EdgeInsets.symmetric(horizontal: grid.AppDesktop.groupGap),
+ itemCount: rows.length,
+ itemBuilder: (context, i) => rows[i],
+ );
+ }
+
+ /// Next up in the order the reader just set, while the server has not
+ /// answered yet.
+ List<SuperTabTaskEntry> _inOrder(List<SuperTabTaskEntry> entries) {
+ final moving = _moving;
+ if (moving == null) return entries;
+ final at = {for (final (i, id) in moving.indexed) id: i};
+ return [...entries]..sort(
+ (a, b) => (at[a.task!.id] ?? moving.length).compareTo(
+ at[b.task!.id] ?? moving.length,
+ ),
+ );
+ }
+
+ /// Puts [ordered]'s card at [to] in place and tells the server, which keeps
+ /// the order for everyone. Refused, the card goes back and the bar says why.
+ Future<void> _move(List<SuperTabTaskEntry> ordered, int from, int to) async {
+ if (from == to || to < 0 || to >= ordered.length) return;
+ final ids = [for (final e in ordered) e.task!.id];
+ final id = ids.removeAt(from);
+ ids.insert(to, id);
+ setState(() {
+ _moving = ids;
+ _moveError = null;
+ });
+ // The column lifts what needs the reader, so its neighbours on screen are
+ // not its neighbours in the shared order: it goes right before the first
+ // card under it that is not lifted, or last (reviews of #2883).
+ final queue = [
+ for (final task in superTabQueueOrder([for (final e in ordered) e.task!]))
+ if (task.id != id) task.id,
+ ];
+ final lifted = {
+ for (final e in ordered)
+ if (e.needsYou) e.task!.id,
+ };
+ final below = ids
+ .skip(to + 1)
+ .where((other) => !lifted.contains(other))
+ .firstOrNull;
+ final at = below == null ? queue.length : queue.indexOf(below);
+ final refused = await widget.controller.queueTask(
+ id,
+ after: at == 0 ? null : queue[at - 1],
+ );
+ if (!mounted) return;
+ setState(() {
+ _moving = null;
+ _moveError = refused;
+ });
+ }
+
+ /// Next up, the one column a card is dragged in (or moved with ⌥↑ and ⌥↓):
+ /// its order is the project's shared queue.
+ Widget _nextUp(List<SuperTabTaskEntry> entries, DateTime now) {
+ final ordered = _inOrder(entries);
+ return Listener(
+ key: _nextUpKey,
+ onPointerUp: (event) {
+ final box = _nextUpKey.currentContext?.findRenderObject() as RenderBox?;
+ _droppedOnNextUp =
+ box != null &&
+ (Offset.zero & box.size).contains(event.localPosition);
+ },
+ child: ReorderableListView.builder(
+ buildDefaultDragHandles: false,
+ itemCount: ordered.length,
+ onReorderItem: (from, to) {
+ if (_droppedOnNextUp) unawaited(_move(ordered, from, to));
+ },
+ itemBuilder: (context, i) {
+ final id = ordered[i].task!.id;
+ return ReorderableDragStartListener(
+ key: ValueKey('super-task-drag-$id'),
+ index: i,
+ child: Padding(
+ padding: const EdgeInsets.only(
+ bottom: grid.AppDesktop.listRowGap,
+ ),
+ child: CallbackShortcuts(
+ bindings: {
+ const SingleActivator(
+ LogicalKeyboardKey.arrowUp,
+ alt: true,
+ ): () =>
+ unawaited(_move(ordered, i, i - 1)),
+ const SingleActivator(
+ LogicalKeyboardKey.arrowDown,
+ alt: true,
+ ): () =>
+ unawaited(_move(ordered, i, i + 1)),
+ },
+ child: _card(ordered[i], now, list: false),
+ ),
+ ),
+ );
+ },
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 029f72ef4..22838173b 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -1,4 +1,7 @@
import 'dart:async';
+
+import 'package:clock/clock.dart';
+
import 'dart:math' as math;
import 'package:flutter/foundation.dart' show kIsWeb;
@@ -74,6 +77,9 @@ import 'pane_layout.dart';
import 'view_room.dart';
import 'swarm_type.dart';
import 'visible_tick.dart';
+import 'buddy_rows.dart';
+import 'task_groups.dart';
+import 'tasks_view.dart';
import '../widgets/dial_list_scroll.dart';
import '../widgets/laid_out_list.dart';
@@ -152,6 +158,10 @@ class _SuperTabViewState extends State<SuperTabView>
bool _rosterOpen = false;
bool _showPullRequests = false;
+ /// The project's Tasks view holds the main pane (task #2569), as Pull
+ /// requests does for a task.
+ bool _showTasks = false;
+
bool _showNotifications = false;
/// Manage holds the main pane; [_manageTab] is which of its pages, but for
@@ -495,6 +505,7 @@ class _SuperTabViewState extends State<SuperTabView>
_devicesVisible ||
_terminalsVisible ||
_showPullRequests ||
+ _showTasks ||
_showNotifications ||
_showManage) {
return false;
@@ -728,10 +739,7 @@ class _SuperTabViewState extends State<SuperTabView>
bool _jumpUnread(int step) {
final snapshot = c.snapshot;
if (snapshot == null || c.accessRevoked) return false;
- final order = superTabSidebarOrder(
- c,
- needsHuman: (group) => _needsHuman(group).length,
- );
+ final order = superTabSidebarOrder(c);
var at = order.indexOf(c.selectedId);
if (at < 0) at = step > 0 ? -1 : order.length;
for (var i = at + step; i >= 0 && i < order.length; i += step) {
@@ -740,7 +748,7 @@ class _SuperTabViewState extends State<SuperTabView>
widget.onCloseTerminal?.call();
setState(() {
_showNotifications = _showManage = false;
- _showPullRequests = false;
+ _showPullRequests = _showTasks = false;
});
unawaited(c.select(group.id));
return true;
@@ -1634,7 +1642,7 @@ class _SuperTabViewState extends State<SuperTabView>
onNotifications: _openActivity,
needsHuman: (group) => _needsHuman(group).length,
onSelect: (id) {
- setState(() => _showNotifications = _showManage = false);
+ setState(() => _showNotifications = _showManage = _showTasks = false);
c.select(id);
_closeSidebar();
},
@@ -1648,7 +1656,7 @@ class _SuperTabViewState extends State<SuperTabView>
Future<bool> _openBuddyChat(String projectId) {
setState(() {
_showNotifications = _showManage = false;
- _showPullRequests = false;
+ _showPullRequests = _showTasks = false;
});
widget.onCloseTerminal?.call();
_closeSidebar();
@@ -1665,7 +1673,7 @@ class _SuperTabViewState extends State<SuperTabView>
setState(() {
_showNotifications = true;
_showManage = false;
- _showPullRequests = false;
+ _showPullRequests = _showTasks = false;
});
if (request.kind != 'mention') return;
final mention = SuperTabMentions.of(c).waiting
@@ -1683,7 +1691,7 @@ class _SuperTabViewState extends State<SuperTabView>
setState(() {
_showNotifications = true;
_showManage = false;
- _showPullRequests = false;
+ _showPullRequests = _showTasks = false;
});
widget.onCloseTerminal?.call();
}
@@ -1711,7 +1719,7 @@ class _SuperTabViewState extends State<SuperTabView>
_closeSidebar();
setState(() {
_showManage = true;
- _showNotifications = _showPullRequests = false;
+ _showNotifications = _showPullRequests = _showTasks = false;
if (_manageTab == SuperTabManageTab.devices && !_hasDevices) {
_manageTab = SuperTabManageTab.machines;
}
@@ -1746,7 +1754,7 @@ class _SuperTabViewState extends State<SuperTabView>
_closeSidebar();
setState(() {
_showNotifications = _showManage = false;
- _showPullRequests = false;
+ _showPullRequests = _showTasks = false;
});
c.select(conversationId);
return true;
@@ -1824,7 +1832,7 @@ class _SuperTabViewState extends State<SuperTabView>
final shownBy = _rowShowing(id, messageId) ?? messageId;
setState(() {
_showNotifications = _showManage = false;
- _showPullRequests = false;
+ _showPullRequests = _showTasks = false;
_back = null;
_target = shownBy;
_openedAtMessage = id;
@@ -2192,7 +2200,7 @@ class _SuperTabViewState extends State<SuperTabView>
void _openAgent(SuperTabAgent agent) {
setState(() {
- _showPullRequests = false;
+ _showPullRequests = _showTasks = false;
_rosterOpen = false;
});
widget.onOpenTerminal(agent);
@@ -2473,14 +2481,99 @@ class _SuperTabViewState extends State<SuperTabView>
VoidCallback? _openTerminals(SuperTabConversation group) =>
_terminalCount(group) > 0 && c.canWrite
? () {
- setState(() => _showPullRequests = false);
+ setState(() => _showPullRequests = _showTasks = false);
widget.onOpenGroupTerminals?.call();
}
: null;
void _openPullRequests() {
widget.onCloseTerminal?.call();
- setState(() => _showPullRequests = true);
+ setState(() {
+ _showPullRequests = true;
+ _showTasks = false;
+ });
+ }
+
+ /// Opens [group]'s project's Tasks view; from a task's chat, its project's
+ /// chat is selected under it.
+ void _openTasks(SuperTabConversation group) {
+ final project = c.snapshot?.projectById(group.projectId);
+ if (project == null) return;
+ widget.onCloseTerminal?.call();
+ if (c.selectedId != project.leadConversationId) {
+ unawaited(c.select(project.leadConversationId));
+ }
+ setState(() {
+ _showTasks = true;
+ _showPullRequests = false;
+ });
+ }
+
+ /// A task's chat, opened from its card: read first when it is one of the
+ /// shipped tasks only the Tasks view holds.
+ Future<void> _openTask(String id) async {
+ if (!await c.loadGroup(id) || !mounted) return;
+ _openConversation(id);
+ }
+
+ /// How many of [project]'s tasks need the reader: the Tasks icon's count.
+ int _tasksNeedingYou(SuperTabProject project) => superTabTasksNeedingYouIn(
+ superTabProjectBoard(
+ c,
+ project,
+ now: clock.now(),
+ needsHuman: (g) => _needsHuman(g).length,
+ ),
+ );
+
+ /// The open project's Tasks view, while it holds the pane.
+ Widget _tasksPage() {
+ final project = _showTasks
+ ? c.snapshot?.projectById(c.selected?.projectId ?? '')
+ : null;
+ if (project == null) return const SizedBox.shrink();
+ return SuperTabTasksView(
+ key: ValueKey('super-tasks-${project.id}'),
+ controller: c,
+ project: project,
+ storage: widget.app?.localStore,
+ needsHuman: (g) => _needsHuman(g).length,
+ onOpenTask: (id) => unawaited(_openTask(id)),
+ onOpenProposal: (id) =>
+ _openThreadFromList(project.leadConversationId, id),
+ );
+ }
+
+ /// The Tasks icon of a project's header and of its tasks' (Dee, task
+ /// #2569): selected while the board shows, and in a task opened from it;
+ /// its red count is the tasks that need the reader, none at 0.
+ Widget _tasksButton(SuperTabConversation group, {required bool task}) {
+ final project = c.snapshot!.projectById(group.projectId)!;
+ final selected = task || (_showTasks && !_terminalsVisible);
+ final count = _tasksNeedingYou(project);
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ fingerTarget(
+ enabled: _phone,
+ AppIconButton(
+ key: const ValueKey('super-tasks'),
+ icon: AppIcons.squareKanban,
+ size: AppIcons.inlineSize,
+ tooltip: 'Tasks',
+ selected: selected,
+ color: selected ? DesktopChrome.foreground : DesktopChrome.muted,
+ onPressed: () => _openTasks(group),
+ ),
+ ),
+ if (count > 0)
+ SuperTabCountBadge(
+ count,
+ key: const ValueKey('super-tasks-badge'),
+ tooltip: count == 1 ? '1 task needs you' : '$count tasks need you',
+ ),
+ ],
+ );
}
/// Members takes the right side from an open thread, as in Slack.
@@ -2541,6 +2634,13 @@ class _SuperTabViewState extends State<SuperTabView>
// The one Buddy has one chat, as a project does; it has no pull requests.
final oneBuddy = group?.isSwarmBuddyChat == true;
final restsOnChat = isProject || oneBuddy;
+ // A project's task: its header leads back to the board it came from.
+ final isTask =
+ group != null &&
+ !isProject &&
+ !oneBuddy &&
+ !group.isBuddyChat &&
+ c.snapshot?.projectById(group.projectId) != null;
return Container(
constraints: const BoxConstraints(minHeight: 52),
// A phone's rows line up (Huy, 2026-11-02): the sidebar icon starts at
@@ -2606,7 +2706,10 @@ class _SuperTabViewState extends State<SuperTabView>
if (group != null && !_devicesVisible && !_listViewHoldsThePane) ...[
// A project's chat is where its header rests: the button back
// to it shows only from another view (Quiet Swarm, screen 1).
- if (!restsOnChat || _terminalsVisible || _showPullRequests)
+ if (!restsOnChat ||
+ _terminalsVisible ||
+ _showPullRequests ||
+ _showTasks)
fingerTarget(
enabled: _phone,
AppIconButton(
@@ -2614,12 +2717,13 @@ class _SuperTabViewState extends State<SuperTabView>
icon: AppIcons.messageSquare,
size: AppIcons.inlineSize,
tooltip: 'Chat',
- selected: !_terminalsVisible && !_showPullRequests,
- color: !_terminalsVisible && !_showPullRequests
+ selected:
+ !_terminalsVisible && !_showPullRequests && !_showTasks,
+ color: !_terminalsVisible && !_showPullRequests && !_showTasks
? DesktopChrome.foreground
: DesktopChrome.muted,
onPressed: () {
- setState(() => _showPullRequests = false);
+ setState(() => _showPullRequests = _showTasks = false);
widget.onCloseTerminal?.call();
_readVisibleTailAfterFrame();
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -2645,6 +2749,10 @@ class _SuperTabViewState extends State<SuperTabView>
),
),
],
+ if (isProject || isTask) ...[
+ const SizedBox(width: 4),
+ _tasksButton(group, task: isTask),
+ ],
if (!isProject) ...[
if (!_menuNamesViews && !oneBuddy) ...[
const SizedBox(width: 4),
@@ -3164,7 +3272,7 @@ class _SuperTabViewState extends State<SuperTabView>
},
references: _references,
onOpenGroup: (id) {
- setState(() => _showPullRequests = false);
+ setState(() => _showPullRequests = _showTasks = false);
c.select(id);
c.selectTerminal(id, null);
},
@@ -4439,7 +4547,7 @@ class _SuperTabViewState extends State<SuperTabView>
onInvite: widget.onInvite,
onOpenAgent: (agent) {
setState(() {
- _showPullRequests = false;
+ _showPullRequests = _showTasks = false;
_rosterOpen = false;
_showManage = _showNotifications = false;
});
@@ -4451,7 +4559,7 @@ class _SuperTabViewState extends State<SuperTabView>
},
onAnswer: (id) {
setState(() {
- _showPullRequests = false;
+ _showPullRequests = _showTasks = false;
_rosterOpen = false;
});
unawaited(c.select(id));
@@ -4503,6 +4611,8 @@ class _SuperTabViewState extends State<SuperTabView>
? 1
: _showPullRequests
? 2
+ : _showTasks
+ ? 5
: 0,
children: [
_conversation(narrow),
@@ -4540,6 +4650,7 @@ class _SuperTabViewState extends State<SuperTabView>
facts: _facts,
)
: const SizedBox.shrink(),
+ _tasksPage(),
],
),
),
diff --git a/desktop/test/benchmarks/super_tab_sidebar_benchmark.dart b/desktop/test/benchmarks/super_tab_sidebar_benchmark.dart
index 55eb49b3c..d9a6946d8 100644
--- a/desktop/test/benchmarks/super_tab_sidebar_benchmark.dart
+++ b/desktop/test/benchmarks/super_tab_sidebar_benchmark.dart
@@ -79,11 +79,7 @@ void main() {
}
}
final controller = server.controller(
- initial: {
- 'tabId': 'tab',
- 'accountId': 'owner',
- 'expandedProjects': ids,
- },
+ initial: {'tabId': 'tab', 'accountId': 'owner'},
);
await controller.refresh();
diff --git a/desktop/test/super_tab_activity_test.dart b/desktop/test/super_tab_activity_test.dart
index cb315bfb5..d52908571 100644
--- a/desktop/test/super_tab_activity_test.dart
+++ b/desktop/test/super_tab_activity_test.dart
@@ -11,13 +11,18 @@ import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/model.dart';
import 'package:harness/super_tabs/parts.dart';
import 'package:harness/super_tabs/project_sidebar.dart';
-import 'package:harness/super_tabs/task_groups.dart';
import 'package:harness/super_tabs/view.dart';
-import 'package:harness/super_tabs/workgroup_name.dart';
import 'package:harness/widgets/desktop_chrome.dart';
import 'super_tab_attention_test.dart'
- show close, fromLead, inRow, openHere, projectServer, unreadThread;
+ show
+ close,
+ fromLead,
+ inRow,
+ openHere,
+ projectServer,
+ rowText,
+ unreadThread;
import 'support/buddy_fixture.dart';
import 'support/super_tab_fixture.dart';
@@ -334,8 +339,8 @@ void main() {
});
group('next unread chat follows the sidebar\'s order', () {
- test('projects A to Z, each chat then its newest workgroups first, then '
- 'Buddy chats', () async {
+ test('projects\' chats A to Z; their tasks are in the Tasks view, not '
+ 'here', () async {
final server = projectServer();
(server.state['projects'] as List).add(
projectFixture('alpha', 'alpha', 'alpha-chat'),
@@ -351,12 +356,7 @@ void main() {
'number': 20,
});
final c = await open(server);
- expect(superTabSidebarOrder(c), [
- 'alpha-chat',
- 'lead',
- 'newer',
- 'offline',
- ]);
+ expect(superTabSidebarOrder(c), ['alpha-chat', 'lead']);
});
});
@@ -552,35 +552,24 @@ void main() {
testWidgets('Activity takes Notifications\' place; a muted chat is '
'greyed with its mark and no number ($brightness)', (tester) async {
final server = projectServer();
- fromLead(server, 'News', conversationId: 'offline');
- server.tag('message-1', conversationId: 'offline');
+ fromLead(server, 'News');
+ server.tag('message-1');
final c = await openHere(server);
await SuperTabAttention.of(c).mentions.load();
- c.toggleProject('lead');
- // A muted chat's tag needs no one: it is in The rest, unfolded here.
- c.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
- await c.setNotify('offline', SuperTabNotify.muted);
+ await c.setNotify('lead', SuperTabNotify.muted);
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);
+ expect(find.byKey(const ValueKey('super-muted-lead')), findsOneWidget);
expect(
- find.byKey(const ValueKey('super-muted-offline')),
- findsOneWidget,
- );
- expect(
- inRow('super-group-offline', find.byType(SuperTabCountBadge)),
+ inRow('super-group-lead', find.byType(SuperTabCountBadge)),
findsNothing,
);
- // The workgroup's name, drawn in the row's style.
- final name = tester.widget<SuperTabWorkgroupName>(
- find.descendant(
- of: find.byKey(const ValueKey('super-group-offline')),
- matching: find.byType(SuperTabWorkgroupName),
- ),
- );
- expect(name.style.color, DesktopChrome.muted);
- expect(name.style.fontWeight, isNot(grid.AppFont.semibold));
+ // The project's name, drawn in the row's style: never bold, though
+ // its chat has news.
+ final name = rowText(tester, 'super-group-lead', 'web-project');
+ expect(name.style?.fontWeight, isNot(grid.AppFont.semibold));
await close(tester, c);
});
}
@@ -588,32 +577,33 @@ void main() {
testWidgets('the unread filter lists only unread chats and the open one, '
'and hides muted ones', (tester) async {
final server = projectServer();
- (server.state['conversations'] as List)
- ..add({
- ...conversationFixture('quiet', 'Quiet'),
- 'projectId': 'lead',
- 'number': 13,
- })
- ..add({
- ...conversationFixture('hushed', 'Hushed'),
- 'projectId': 'lead',
- 'number': 14,
+ // Projects of their own: the sidebar lists project chats, not tasks.
+ for (final id in ['quiet', 'hushed', 'news']) {
+ (server.state['projects'] as List).add(
+ projectFixture(id, '$id-project', id),
+ );
+ (server.state['conversations'] as List).add({
+ ...conversationFixture(id, id),
+ 'projectId': id,
});
- fromLead(server, 'Read');
- server.markReadElsewhere('lead', server.revision);
- fromLead(server, 'News', conversationId: 'offline');
+ }
+ fromLead(server, 'Read', conversationId: 'quiet');
+ server.markReadElsewhere('quiet', server.revision);
+ fromLead(server, 'News', conversationId: 'news');
fromLead(server, 'Hushed news', conversationId: 'hushed');
final c = await openHere(server);
- c.toggleProject('lead');
- // Workgroups with no work are in The rest, unfolded here (#2309).
- c.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
await c.setNotify('hushed', SuperTabNotify.muted);
await pumpSidebar(tester, c);
expect(find.byKey(const ValueKey('super-group-quiet')), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('super-unread-only')));
await tester.pumpAndSettle();
expect(c.unreadOnly, isTrue);
- expect(find.byKey(const ValueKey('super-group-offline')), findsOneWidget);
+ expect(find.byKey(const ValueKey('super-group-news')), findsOneWidget);
+ // The open chat stays listed.
+ expect(
+ find.byKey(ValueKey('super-group-${c.selectedId}')),
+ findsOneWidget,
+ );
expect(find.byKey(const ValueKey('super-group-quiet')), findsNothing);
expect(find.byKey(const ValueKey('super-group-hushed')), findsNothing);
await close(tester, c);
diff --git a/desktop/test/super_tab_attention_shots_test.dart b/desktop/test/super_tab_attention_shots_test.dart
index a262d5858..3bfdc76c5 100644
--- a/desktop/test/super_tab_attention_shots_test.dart
+++ b/desktop/test/super_tab_attention_shots_test.dart
@@ -164,7 +164,6 @@ void main() {
hasLength(1),
);
c.select('roster');
- if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');
final picture = GlobalKey();
await tester.pumpWidget(
MaterialApp(
diff --git a/desktop/test/super_tab_attention_test.dart b/desktop/test/super_tab_attention_test.dart
index c10db2da7..bb2b68639 100644
--- a/desktop/test/super_tab_attention_test.dart
+++ b/desktop/test/super_tab_attention_test.dart
@@ -13,7 +13,6 @@ import 'package:harness/super_tabs/buddy_rows.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/model.dart';
import 'package:harness/super_tabs/project_sidebar.dart';
-import 'package:harness/super_tabs/task_groups.dart';
import 'package:harness/widgets/desktop_chrome.dart';
import 'support/super_tab_fixture.dart';
@@ -171,20 +170,17 @@ void main() {
return (c, attention);
}
- testWidgets('a tag in a task conversation shows no number on the '
- 'collapsed row, which is still bold and kept by the unread filter', (
- tester,
- ) async {
+ testWidgets('a tag in a task conversation counts on the project row as '
+ 'a task that needs the reader; the row is bold and kept by the '
+ 'unread filter', (tester) async {
final server = projectServer();
fromLead(server, 'Please look', conversationId: 'offline');
server.tag('message-1', conversationId: 'offline');
final (c, attention) = await opened(server);
await pumpSidebar(tester, c, attention);
expect(attention.mentionsIn('offline'), 1);
- expect(
- inRow('super-group-lead', find.byType(SuperTabCountBadge)),
- findsNothing,
- );
+ expect(attention.mentionsIn('lead'), 0);
+ expect(inRow('super-group-lead', find.text('1')), findsOneWidget);
expect(
rowText(tester, 'super-group-lead', 'web-project').style?.fontWeight,
FontWeight.w600,
@@ -192,27 +188,19 @@ void main() {
c.toggleUnreadOnly();
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('super-group-lead')), findsOneWidget);
- // Still listed where it can be opened, and on its own row once expanded.
+ // Still listed where it can be opened (Activity).
expect(attention.mentions.waiting, hasLength(1));
- c.toggleProject('lead');
- await tester.pumpAndSettle();
- expect(inRow('super-group-offline', find.text('1')), findsOneWidget);
await close(tester, c);
});
- testWidgets('a tag in the project chat counts collapsed or open, and '
- 'reading it clears it', (tester) async {
+ testWidgets('a tag in the project chat counts, and reading it clears '
+ 'it', (tester) async {
final server = projectServer();
server.tag('message-1', messageSequence: 1);
fromLead(server, 'Please look');
final (c, attention) = await opened(server);
await pumpSidebar(tester, c, attention);
expect(inRow('super-group-lead', find.text('1')), findsOneWidget);
- c.toggleProject('lead');
- await tester.pumpAndSettle();
- expect(inRow('super-group-lead', find.text('1')), findsOneWidget);
- c.toggleProject('lead');
- await tester.pumpAndSettle();
c.select('lead');
await tester.pumpAndSettle();
c.markRead('lead');
@@ -316,16 +304,22 @@ void main() {
) async {
final server = projectServer();
fromLead(server, 'In the task', conversationId: 'offline');
- server.tag('message-1', conversationId: 'offline');
+ server.tag('message-1', conversationId: 'offline', messageSequence: 1);
server.tag('message-1', messageSequence: 1);
fromLead(server, 'In the chat');
final (c, attention) = await opened(server);
await pumpSidebar(tester, c, attention);
- expect(inRow('super-group-lead', find.text('1')), findsOneWidget);
+ // The chat's tag and the task that needs the reader.
+ expect(inRow('super-group-lead', find.text('2')), findsOneWidget);
c.select('lead');
await tester.pumpAndSettle();
c.markRead('lead');
await tester.pumpAndSettle();
+ expect(inRow('super-group-lead', find.text('1')), findsOneWidget);
+ c.select('offline');
+ await tester.pumpAndSettle();
+ c.markRead('offline');
+ await tester.pumpAndSettle();
expect(find.byType(SuperTabCountBadge), findsNothing);
await close(tester, c);
});
@@ -345,8 +339,8 @@ void main() {
});
});
- testWidgets('a tag in the chat and thread counts on its row; a decision '
- 'on its row; plain unread is bold with no '
+ testWidgets('a task\'s tags in its chat and thread and its decision make '
+ 'it a task that needs the reader; plain unread is bold with no '
'number', (tester) async {
final server = projectServer();
server.followedThreads = {
@@ -364,21 +358,15 @@ void main() {
await attention.mentions.load();
await attention.decisions.load();
await attention.load();
- c.toggleProject('lead');
await pumpSidebar(tester, c, attention);
// The workgroup: one tag in its chat, one in its thread, and one decision.
- expect(
- inRow('super-group-offline', find.byType(SuperTabCountBadge)),
- findsOneWidget,
- );
- expect(inRow('super-group-offline', find.text('3')), findsOneWidget);
+ expect(attention.mentionsIn('offline'), 3);
// The unread thread is still available in Activity's New replies.
expect(attention.threadMentions, 1);
- // The project chat: unread, nothing for the reader, so no number.
- expect(
- inRow('super-group-lead', find.byType(SuperTabCountBadge)),
- findsNothing,
- );
+ // The project chat: unread, nothing for the reader in it, so its
+ // number is the one task that needs the reader.
+ expect(attention.mentionsIn('lead'), 0);
+ expect(inRow('super-group-lead', find.text('1')), findsOneWidget);
expect(
rowText(tester, 'super-group-lead', 'web-project').style?.fontWeight,
grid.AppFont.semibold,
@@ -386,22 +374,28 @@ void main() {
await close(tester, c);
});
- testWidgets('a collapsed project counts its own chat\'s tags, not those of '
- 'the workgroups it hides', (tester) async {
+ testWidgets('a project counts its own chat\'s tags and its tasks that '
+ 'need the reader, not each tag in them', (tester) async {
final server = projectServer();
server.followedThreads = {'unread': [], 'read': [], 'more': false};
fromLead(server, 'News', conversationId: 'offline');
server.tag('message-1', conversationId: 'offline');
+ server.tag('message-1', conversationId: 'offline', threadId: 'message-1');
server.tag('message-1');
final c = await openHere(server);
final attention = SuperTabAttention.of(c);
await attention.mentions.load();
await pumpSidebar(tester, c, attention);
- expect(inRow('super-group-lead', find.text('1')), findsOneWidget);
- c.toggleProject('lead');
- await tester.pumpAndSettle();
- expect(inRow('super-group-lead', find.text('1')), findsOneWidget);
- expect(inRow('super-group-offline', find.text('1')), findsOneWidget);
+ expect(attention.mentionsIn('offline'), 2);
+ expect(inRow('super-group-lead', find.text('2')), findsOneWidget);
+ expect(
+ tester
+ .widget<SuperTabCountBadge>(
+ find.byKey(const ValueKey('super-mentions-lead')),
+ )
+ .tooltip,
+ '1 tag · 1 task needs you',
+ );
await close(tester, c);
});
});
@@ -436,35 +430,29 @@ void main() {
'read': [],
'more': false,
};
- // A second workgroup, open on screen, so the project's row is
- // neither selected nor unread.
- (server.state['conversations'] as List).add({
- ...conversationFixture('open', 'Open now'),
- 'projectId': 'lead',
- 'number': 13,
- });
+ // A second project with news, and a third open on screen, so the
+ // first project's row is neither selected nor unread.
+ for (final id in ['news', 'open']) {
+ (server.state['projects'] as List).add(
+ projectFixture(id, '$id-project', id),
+ );
+ (server.state['conversations'] as List).add({
+ ...conversationFixture(id, id),
+ 'projectId': id,
+ });
+ }
fromLead(server, 'Read news');
server.markReadElsewhere('lead', server.revision);
- fromLead(server, 'Unread news', conversationId: 'offline');
+ fromLead(server, 'Unread news', conversationId: 'news');
final c = await openHere(server);
final attention = SuperTabAttention.of(c);
await attention.load();
c.select('open');
- if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');
- // Workgroups with no work are in The rest, unfolded here (#2309).
- c.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
await pumpSidebar(tester, c, attention, brightness: brightness);
final read = rowText(tester, 'super-group-lead', 'web-project');
expect(read.style?.color, DesktopChrome.muted);
expect(read.style?.fontWeight, isNot(grid.AppFont.semibold));
- final unread = tester.widget<Text>(
- find
- .descendant(
- of: find.byKey(const ValueKey('super-group-offline')),
- matching: find.byType(Text),
- )
- .first,
- );
+ final unread = rowText(tester, 'super-group-news', 'news-project');
expect(unread.style?.color, DesktopChrome.foreground);
expect(unread.style?.fontWeight, grid.AppFont.semibold);
await close(tester, c);
@@ -476,9 +464,18 @@ void main() {
'highlight', (tester) async {
final server = projectServer();
server.followedThreads = {'unread': [], 'read': [], 'more': false};
+ // Another project's chat open, so this row is not highlighted: a project
+ // shows as selected while one of its tasks is open.
+ (server.state['projects'] as List).add(
+ projectFixture('other', 'other-project', 'other'),
+ );
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('other', 'other'),
+ 'projectId': 'other',
+ });
final c = await openHere(server);
final attention = SuperTabAttention.of(c);
- c.select('offline');
+ c.select('other');
await pumpSidebar(tester, c, attention);
final row = find.byKey(const ValueKey('super-group-lead'));
final groundFinder = find
@@ -991,40 +988,6 @@ void main() {
});
});
- testWidgets('a read workgroup with a tag of the reader is listed under '
- 'Needs you while The rest is folded', (tester) async {
- final server = projectServer();
- server.followedThreads = {'unread': [], 'read': [], 'more': false};
- final groups = server.state['conversations'] as List;
- // Nine newer workgroups than "offline" (number 12), all read.
- for (var n = 20; n < 29; n++) {
- groups.add({
- ...conversationFixture('g$n', 'Work $n'),
- 'projectId': 'lead',
- 'number': n,
- });
- }
- fromLead(server, 'Please look', conversationId: 'offline');
- // From a server that does not say where the tag is: it counts until
- // answered, though the chat is read.
- server.tag('message-1', conversationId: 'offline');
- server.markReadElsewhere('offline', server.revision);
- final c = await openHere(server);
- final attention = SuperTabAttention.of(c);
- await attention.mentions.load();
- expect(c.unread(c.snapshot!.conversation('offline')!), isFalse);
- c.toggleProject('lead');
- await pumpSidebar(tester, c, attention);
- expect(
- find.byKey(const ValueKey('super-task-group-lead-needsYou')),
- findsOneWidget,
- );
- expect(find.byKey(const ValueKey('super-group-g28')), findsNothing);
- expect(find.byKey(const ValueKey('super-group-offline')), findsOneWidget);
- expect(inRow('super-group-offline', find.text('1')), findsOneWidget);
- await close(tester, c);
- });
-
group('tags from the Threads view (merge check of 67c32a3)', () {
/// Kestrel is an agent of "offline", not of "lead"; "offline" has a
/// thread at message-1 with a new reply.
diff --git a/desktop/test/super_tab_attention_wave2_test.dart b/desktop/test/super_tab_attention_wave2_test.dart
index 0e4bc2bbc..7e86d31af 100644
--- a/desktop/test/super_tab_attention_wave2_test.dart
+++ b/desktop/test/super_tab_attention_wave2_test.dart
@@ -190,6 +190,7 @@ Future<(SuperTabController, GlobalKey)> _show(
WidgetTester tester,
Brightness brightness, {
String selected = 'web-lead',
+ ConversationServer? server,
}) async {
final previous = grid.AppTheme.brightness.value;
grid.AppTheme.brightness.value = brightness;
@@ -199,7 +200,7 @@ Future<(SuperTabController, GlobalKey)> _show(
addTearDown(tester.view.reset);
final app = createApp(connected: true);
addTearDown(app.dispose);
- final server = _wave2();
+ server ??= _wave2();
final c = server.controller(
initial: {'tabId': 'tab', 'accountId': 'owner', 'selectedId': selected},
);
@@ -209,7 +210,6 @@ Future<(SuperTabController, GlobalKey)> _show(
await attention.decisions.load();
await attention.load();
await c.select(selected);
- if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');
final picture = GlobalKey();
await tester.pumpWidget(
MaterialApp(
@@ -264,37 +264,43 @@ void main() {
'Option+Shift+Down opens the next unread chat in sidebar order, '
'skipping the muted one; Up goes back',
(tester) async {
- final (c, _) = await _show(tester, Brightness.dark, selected: 'lead');
- // Sidebar order: openharness (lead, offline 1600, routing 1598, roster
- // 1597 muted), then website (web-lead).
- final order = [
- for (final id in ['lead', 'offline', 'routing', 'roster', 'web-lead'])
- if (c.unreadShown(c.snapshot!.conversation(id)!)) id,
- ];
- expect(order, isNot(contains('roster')));
+ // A third project between the two, its chat unread and muted.
+ final server = _wave2();
+ (server.state['projects'] as List).add(
+ projectFixture('road', 'roadmap', 'road-lead'),
+ );
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('road-lead', 'Lead'),
+ 'projectId': 'road',
+ });
+ _fromLead(server, 'Muted plans.', 'road-lead');
+ (server.state['chatSettings'] as Map)['owner']['road-lead'] = 'muted';
+ final (c, _) = await _show(
+ tester,
+ Brightness.dark,
+ selected: 'lead',
+ server: server,
+ );
+ // Sidebar order: openharness (lead), roadmap (road-lead, muted), then
+ // website (web-lead). Tasks are in the Tasks view, not here.
+ expect(c.unreadShown(c.snapshot!.conversation('offline')!), isTrue);
+ expect(
+ c.unreadShown(c.snapshot!.conversation('road-lead')!),
+ isFalse,
+ );
await tester.tap(find.byKey(const ValueKey('super-message-composer')));
await tester.pumpAndSettle();
await _keys(tester, [
LogicalKeyboardKey.altLeft,
LogicalKeyboardKey.shiftLeft,
], LogicalKeyboardKey.arrowDown);
- expect(c.selectedId, 'offline');
- await _keys(tester, [
- LogicalKeyboardKey.altLeft,
- LogicalKeyboardKey.shiftLeft,
- ], LogicalKeyboardKey.arrowDown);
- expect(c.selectedId, 'routing');
- await _keys(tester, [
- LogicalKeyboardKey.altLeft,
- LogicalKeyboardKey.shiftLeft,
- ], LogicalKeyboardKey.arrowDown);
- // The muted Desktop roster is passed over.
+ // The unread tasks and the muted roadmap chat are passed over.
expect(c.selectedId, 'web-lead');
await _keys(tester, [
LogicalKeyboardKey.altLeft,
LogicalKeyboardKey.shiftLeft,
], LogicalKeyboardKey.arrowUp);
- expect(c.selectedId, 'routing');
+ expect(c.selectedId, 'lead');
await _done(tester, c);
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
@@ -306,7 +312,7 @@ void main() {
(tester) async {
final (c, _) = await _show(tester, Brightness.dark, selected: 'lead');
final order = [
- for (final id in ['lead', 'offline', 'routing', 'roster', 'web-lead'])
+ for (final id in ['lead', 'web-lead'])
if (c.unreadShown(c.snapshot!.conversation(id)!)) id,
];
expect(order.length, greaterThan(1));
@@ -361,20 +367,21 @@ void main() {
testWidgets(
'the chat menu\'s Notifications sets Muted, and the row greys',
(tester) async {
+ // A project's chat: the sidebar lists no tasks (task #2569).
final (c, _) = await _show(
tester,
Brightness.dark,
- selected: 'offline',
+ selected: 'web-lead',
);
- await tester.tap(find.byKey(const ValueKey('super-group-options')));
+ await tester.tap(find.byKey(const ValueKey('super-project-menu')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('super-notify-menu')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('super-notify-muted')));
await tester.pumpAndSettle();
- expect(c.notifyOf('offline'), SuperTabNotify.muted);
+ expect(c.notifyOf('web-lead'), SuperTabNotify.muted);
expect(
- find.byKey(const ValueKey('super-muted-offline')),
+ find.byKey(const ValueKey('super-muted-web-lead')),
findsOneWidget,
);
await _done(tester, c);
diff --git a/desktop/test/super_tab_buddies_test.dart b/desktop/test/super_tab_buddies_test.dart
index 3cdafd1ce..7c6c56d8c 100644
--- a/desktop/test/super_tab_buddies_test.dart
+++ b/desktop/test/super_tab_buddies_test.dart
@@ -12,7 +12,6 @@ import 'package:harness/super_tabs/buddies.dart' show kBuddyEngineRefusals;
import 'package:harness/super_tabs/buddy_machines.dart' show kBuddyNoMachine;
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/view.dart';
-import 'package:harness/super_tabs/task_groups.dart';
import 'support/buddy_fixture.dart';
import 'support/pm_chat_fixture.dart';
@@ -1504,15 +1503,8 @@ void main() {
},
});
final c = await show(tester, server);
- if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');
- // Workgroups with no work are in The rest, unfolded here (#2309).
- c.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
await tester.pumpAndSettle();
- expect(
- find.byKey(const ValueKey('super-group-offline')),
- findsOneWidget,
- );
expect(find.byKey(const ValueKey('super-group-private')), findsNothing);
expect(find.text('Pricing talk'), findsNothing);
expect(await c.select('private'), isTrue);
diff --git a/desktop/test/super_tab_buddy_chat_counts_test.dart b/desktop/test/super_tab_buddy_chat_counts_test.dart
index c90fb2b87..c5ead7e4a 100644
--- a/desktop/test/super_tab_buddy_chat_counts_test.dart
+++ b/desktop/test/super_tab_buddy_chat_counts_test.dart
@@ -25,7 +25,6 @@ import 'package:harness/super_tabs/buddy_chat_shortcut.dart';
import 'package:harness/super_tabs/buddy_rows.dart';
import 'package:harness/super_tabs/project_sidebar.dart';
import 'package:harness/super_tabs/view.dart';
-import 'package:harness/super_tabs/task_groups.dart';
import 'package:harness/widgets/desktop_chrome.dart';
import 'box_render_preview_test.dart' show loadPreviewFonts;
@@ -501,7 +500,7 @@ void main() {
),
findsNothing,
);
- c.toggleProject('lead');
+ await c.select('lead');
await tester.pumpAndSettle();
expect(
find.descendant(of: projectRow, matching: find.text('#')),
@@ -518,34 +517,6 @@ void main() {
},
);
- testWidgets('shows a workgroup by its number in grey, with no #', (
- tester,
- ) async {
- final server = riverSwarm();
- (server.state['conversations'] as List).last['number'] = 196;
- final c = await show(tester, server);
- c.toggleProject('lead');
- // Workgroups with no work are in The rest, unfolded here (#2309).
- c.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
- await tester.pumpAndSettle();
- final row = find.byKey(const ValueKey('super-group-offline'));
- final name = find.descendant(
- of: row,
- matching: find.text('196 Offline editing'),
- );
- expect(name, findsOne);
- expect(
- find.descendant(of: row, matching: find.textContaining('#')),
- findsNothing,
- );
- final number =
- (tester.widget<Text>(name).textSpan! as TextSpan).children!.first;
- expect(number.toPlainText(), '196 ');
- // Fainter and smaller than the title in the sidebar (Huy, 11-03, #2427).
- expect(number.style?.color, grid.AppPalette.textFaint);
- await close(tester, c);
- });
-
testWidgets(
'the shortcut leaves Notifications for the chat, first opened or already selected',
(tester) async {
@@ -569,7 +540,7 @@ void main() {
);
testWidgets(
- 'the header names a workgroup as the sidebar does: its number in grey, no #',
+ 'the header names a workgroup by its number in grey, no #',
(tester) async {
final server = riverSwarm();
(server.state['conversations'] as List).last['number'] = 196;
@@ -578,16 +549,11 @@ void main() {
await tester.pumpAndSettle();
expect(find.text('#196 Offline editing'), findsNothing);
- final names = find.text('196 Offline editing');
- // The header's and the sidebar row's: the header's number in grey,
- // the sidebar's fainter still (Huy, 11-03, #2427).
- expect(names, findsNWidgets(2));
+ // The header's alone: the sidebar lists no tasks (task #2569).
+ final name = tester.widget<Text>(find.text('196 Offline editing'));
expect(
- {
- for (final name in tester.widgetList<Text>(names))
- (name.textSpan! as TextSpan).children!.first.style?.color,
- },
- {DesktopChrome.muted, grid.AppPalette.textFaint},
+ (name.textSpan! as TextSpan).children!.first.style?.color,
+ DesktopChrome.muted,
);
await close(tester, c);
},
@@ -955,12 +921,10 @@ void main() {
image.dispose();
});
- c.expandedProjects.clear();
if (c.projectsGroupOpen) c.toggleProjectsGroup();
await tester.pumpAndSettle();
await shot('collapsed');
c.toggleProjectsGroup();
- c.toggleProject('lead');
await tester.pumpAndSettle();
await shot('expanded');
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/super_tab_chat_test.dart b/desktop/test/super_tab_chat_test.dart
index a4c144cb2..3640ecf9f 100644
--- a/desktop/test/super_tab_chat_test.dart
+++ b/desktop/test/super_tab_chat_test.dart
@@ -395,10 +395,9 @@ void main() {
expect(projectWeight(), grid.AppFont.semibold);
await tester.tap(find.byKey(const ValueKey('super-group-lead')));
await tester.pumpAndSettle();
- // A workgroup with no work is in The rest, which starts folded (#2309).
- await tester.tap(find.byKey(const ValueKey('super-task-group-lead-rest')));
- await tester.pumpAndSettle();
- await tester.tap(find.byKey(const ValueKey('super-group-offline')));
+ expect(projectWeight(), grid.AppFont.semibold);
+ // Opened as the project's Tasks view opens it (task #2569).
+ await c.select('offline');
await tester.pumpAndSettle();
expect(find.text('An unread workgroup update'), findsOneWidget);
expect(c.unread(c.selected!), isFalse);
diff --git a/desktop/test/super_tab_closed_groups_test.dart b/desktop/test/super_tab_closed_groups_test.dart
index 5d91ad55d..276bfcc5f 100644
--- a/desktop/test/super_tab_closed_groups_test.dart
+++ b/desktop/test/super_tab_closed_groups_test.dart
@@ -5,7 +5,6 @@ import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:harness/super_tabs/project_sidebar.dart';
import 'package:harness/super_tabs/view.dart';
import 'box_render_preview_test.dart' show loadPreviewFonts;
@@ -55,32 +54,14 @@ void main() {
await loadPreviewFonts();
}
});
- final closedRow = find.byKey(const ValueKey('super-closed-lead'));
-
- testWidgets('a project with no archived groups has no Closed row', (
- tester,
- ) async {
- final server = ConversationServer();
- final controller = server.controller();
- await controller.refresh();
- await tester.pumpWidget(_app(server, controller));
- await tester.pumpAndSettle();
- expect(closedRow, findsNothing);
- expect(find.textContaining('Closed ('), findsNothing);
- await tester.pumpWidget(const SizedBox());
- await controller.flush();
- controller.dispose();
- });
for (final brightness in Brightness.values) {
testWidgets(
- 'Closed (N) starts collapsed, lists archived groups, opens one read-only and reopens it (${brightness.name})',
+ 'a closed group opens read-only and reopens (${brightness.name})',
(tester) async {
await tester.binding.setSurfaceSize(const Size(1280, 800));
addTearDown(() => tester.binding.setSurfaceSize(null));
final server = ConversationServer();
- await tester.binding.setSurfaceSize(const Size(1280, 800));
- addTearDown(() => tester.binding.setSurfaceSize(null));
final oldBrightness = grid.AppTheme.brightness.value;
final oldPalette = grid.AppTheme.palette.value;
grid.AppTheme.brightness.value = brightness;
@@ -91,11 +72,6 @@ void main() {
});
final groups = server.state['conversations'] as List;
groups[1]['archived'] = true;
- groups.add({
- ...conversationFixture('second', 'Second closed'),
- 'projectId': 'lead',
- 'archived': true,
- });
server.append(
'Verified the offline result.',
conversationId: 'offline',
@@ -104,30 +80,11 @@ void main() {
await controller.refresh();
await tester.pumpWidget(_app(server, controller, brightness));
await tester.pumpAndSettle();
- final sidebar = find.byType(ProjectSidebar);
- Finder inside(Finder f) => find.descendant(of: sidebar, matching: f);
- if (closedRow.evaluate().isEmpty) {
- await tester.tap(find.byKey(const ValueKey('super-group-lead')));
- await tester.pumpAndSettle();
- }
-
- expect(inside(find.text('Closed (2)')), findsOneWidget);
- expect(find.byKey(const ValueKey('super-group-offline')), findsNothing);
- expect(find.byKey(const ValueKey('super-group-second')), findsNothing);
-
- await tester.tap(closedRow);
- await tester.pumpAndSettle();
- expect(
- find.byKey(const ValueKey('super-group-offline')),
- findsOneWidget,
- );
- expect(
- find.byKey(const ValueKey('super-group-second')),
- findsOneWidget,
- );
- await _shot(tester, 'closed-open-${brightness.name}');
-
- await tester.tap(find.byKey(const ValueKey('super-group-offline')));
+ // The sidebar lists no tasks, open or closed (task #2569): the
+ // closed one is read and opened as the Tasks view opens it.
+ expect(find.textContaining('Closed ('), findsNothing);
+ await controller.loadDormant('lead');
+ await controller.select('offline');
await tester.pumpAndSettle();
expect(controller.selectedId, 'offline');
expect(find.text('Verified the offline result.'), findsOneWidget);
@@ -146,12 +103,7 @@ void main() {
'conversationId': 'offline',
'archived': false,
});
- expect(inside(find.text('Closed (1)')), findsOneWidget);
expect(find.byKey(const ValueKey('super-group-reopen')), findsNothing);
- expect(
- find.byKey(const ValueKey('super-group-offline')),
- findsOneWidget,
- );
expect(
tester
.widget<TextField>(
@@ -167,42 +119,4 @@ void main() {
},
);
}
-
- testWidgets(
- 'closed groups read a page at a time; Show earlier reads the next',
- (tester) async {
- await tester.binding.setSurfaceSize(const Size(1280, 800));
- addTearDown(() => tester.binding.setSurfaceSize(null));
- final server = ConversationServer()..parts.dormantPage = 1;
- final groups = server.state['conversations'] as List;
- groups[1]['archived'] = true;
- groups.add({
- ...conversationFixture('second', 'Second closed'),
- 'projectId': 'lead',
- 'archived': true,
- });
- final controller = server.controller();
- await controller.refresh();
- await tester.pumpWidget(_app(server, controller));
- await tester.pumpAndSettle();
- if (closedRow.evaluate().isEmpty) {
- await tester.tap(find.byKey(const ValueKey('super-group-lead')));
- await tester.pumpAndSettle();
- }
- expect(find.text('Closed (1)'), findsOneWidget);
- await tester.tap(closedRow);
- await tester.pumpAndSettle();
- final earlier = find.byKey(const ValueKey('super-closed-earlier-lead'));
- expect(earlier, findsOneWidget);
- await tester.tap(earlier);
- await tester.pumpAndSettle();
- expect(find.text('Closed (2)'), findsOneWidget);
- expect(earlier, findsNothing);
- expect(find.byKey(const ValueKey('super-group-offline')), findsOneWidget);
- expect(find.byKey(const ValueKey('super-group-second')), findsOneWidget);
- await tester.pumpWidget(const SizedBox());
- await controller.flush();
- controller.dispose();
- },
- );
}
diff --git a/desktop/test/super_tab_decisions_test.dart b/desktop/test/super_tab_decisions_test.dart
index 0f1f9dfd0..e39aace8c 100644
--- a/desktop/test/super_tab_decisions_test.dart
+++ b/desktop/test/super_tab_decisions_test.dart
@@ -85,9 +85,6 @@ Future<SuperTabController> showView(
),
);
await tester.pumpAndSettle();
- // The project's rows show once it is expanded.
- if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');
- await tester.pumpAndSettle();
return c;
}
diff --git a/desktop/test/super_tab_devices_preview_test.dart b/desktop/test/super_tab_devices_preview_test.dart
index 8a11f38db..4dabe2a14 100644
--- a/desktop/test/super_tab_devices_preview_test.dart
+++ b/desktop/test/super_tab_devices_preview_test.dart
@@ -168,7 +168,8 @@ void main() {
await persisted.load();
expect(persisted.rootOf('m', 'native-0'), _finderRoot);
}
- await tester.tap(find.byKey(const ValueKey('super-group-offline')));
+ // Back to the task, as its Tasks view opens it.
+ await c.select('offline');
await tester.pumpAndSettle();
expect(c.devicesSelected, isFalse);
expectPreview();
diff --git a/desktop/test/super_tab_dormant_groups_test.dart b/desktop/test/super_tab_dormant_groups_test.dart
index 06f4eda8f..8d4b9722e 100644
--- a/desktop/test/super_tab_dormant_groups_test.dart
+++ b/desktop/test/super_tab_dormant_groups_test.dart
@@ -42,12 +42,11 @@ void main() {
});
});
- test('a first load has only active groups; expanding the project reads the others', () async {
+ test('a first load has only active groups; reading the project\'s closed ones reads the others', () async {
final c = open();
await c.refresh();
expect(c.snapshot!.conversation('old'), isNull);
expect(c.dormantLoaded('lead'), isFalse);
- c.toggleProject('lead');
await c.loadDormant('lead');
expect(reads, ['/api/super-tabs/tab/groups?dormant=1&projectId=lead']);
expect(c.dormantLoaded('lead'), isTrue);
@@ -58,10 +57,7 @@ void main() {
expect(finished.archived, isFalse);
expect(finished.closed, isTrue);
expect(c.snapshot!.conversation('offline')!.closed, isFalse);
- // Read once: collapsing and expanding again reads nothing more.
- c
- ..toggleProject('lead')
- ..toggleProject('lead');
+ // Read once: asking again reads nothing more.
await c.loadDormant('lead');
expect(reads, hasLength(1));
});
@@ -70,7 +66,6 @@ void main() {
server.parts.dormantPage = 1;
final c = open();
await c.refresh();
- c.toggleProject('lead');
await c.loadDormant('lead');
expect(c.hasEarlierDormant('lead'), isTrue);
final first = c.snapshot!.conversations.where((g) => g.closed).length;
@@ -248,13 +243,12 @@ void main() {
await again.refresh();
await again.flush();
expect(again.draft('finished'), 'A last note');
- again.toggleProject('lead');
await again.loadDormant('lead');
expect(again.unread(again.snapshot!.conversation('finished')!), isFalse);
},
);
- test('a reload while closed groups are being read reads them again for the new parts', () async {
+ test('a reload while closed groups are being read keeps none of that read; the next ask reads them for the new parts', () async {
Completer<void>? hold;
reads = [];
final c = SuperTabController(
@@ -272,7 +266,6 @@ void main() {
);
await c.refresh();
hold = Completer<void>();
- c.toggleProject('lead');
final stale = c.loadDormant('lead');
// Who may see what changed meanwhile: the next read loads in full.
server.parts.epoch++;
@@ -281,8 +274,12 @@ void main() {
hold = null;
waiting.complete();
await stale;
- // The reload asked for them again by itself: nothing else asks.
await pumpEventQueue();
+ // Read for the parts before: not kept. The sidebar lists no closed
+ // tasks, so nothing asks again by itself (task #2569).
+ expect(c.dormantLoaded('lead'), isFalse);
+ expect(c.snapshot!.conversation('old'), isNull);
+ await c.loadDormant('lead');
expect(reads.where((p) => p.contains('dormant=1')), hasLength(2));
expect(c.dormantLoaded('lead'), isTrue);
expect(c.snapshot!.conversation('old')!.closed, isTrue);
diff --git a/desktop/test/super_tab_humans_shots_test.dart b/desktop/test/super_tab_humans_shots_test.dart
index d4140bb4a..fe0a86bb8 100644
--- a/desktop/test/super_tab_humans_shots_test.dart
+++ b/desktop/test/super_tab_humans_shots_test.dart
@@ -50,7 +50,6 @@ void main() {
),
),
);
- c.expandedProjects.clear();
if (!c.projectsGroupOpen) c.toggleProjectsGroup();
await tester.pumpAndSettle();
diff --git a/desktop/test/super_tab_new_messages_test.dart b/desktop/test/super_tab_new_messages_test.dart
index 06eedb255..a7674e148 100644
--- a/desktop/test/super_tab_new_messages_test.dart
+++ b/desktop/test/super_tab_new_messages_test.dart
@@ -731,14 +731,16 @@ void main() {
'name': 'Worker',
};
final c = await show(tester, server);
+ // The sidebar lists no tasks (task #2569): the task's news makes its
+ // project's row bold.
+ final name = c.snapshot!.projects.single.name;
FontWeight? weight() => tester
.widget<RichText>(
find.descendant(
- of: find.byKey(const ValueKey('super-group-offline')),
+ of: find.byKey(const ValueKey('super-group-lead')),
matching: find.byWidgetPredicate(
(widget) =>
- widget is RichText &&
- widget.text.toPlainText() == 'Offline editing',
+ widget is RichText && widget.text.toPlainText() == name,
),
),
)
@@ -747,9 +749,6 @@ void main() {
?.fontWeight;
await tester.tap(find.byKey(const ValueKey('super-group-lead')));
await tester.pumpAndSettle();
- // A workgroup with no work is in The rest, which starts folded (#2309).
- await tester.tap(find.byKey(const ValueKey('super-task-group-lead-rest')));
- await tester.pumpAndSettle();
expect(weight(), grid.AppFont.semibold);
// Read on another device.
server.markReadElsewhere('offline', 3);
diff --git a/desktop/test/super_tab_polish_test.dart b/desktop/test/super_tab_polish_test.dart
index 420d9ea76..38cc0021a 100644
--- a/desktop/test/super_tab_polish_test.dart
+++ b/desktop/test/super_tab_polish_test.dart
@@ -313,7 +313,6 @@ void main() {
addTearDown(() => grid.AppTheme.brightness.value = previous);
final server = polishFixture(), c = server.controller();
await c.refresh();
- c.toggleProject('lead');
var opened = '';
final boundary = GlobalKey();
await tester.pumpWidget(
@@ -411,7 +410,6 @@ void main() {
await mouse.addPointer(location: Offset.zero);
for (final target in [
('project-hover', const ValueKey('super-group-lead')),
- ('workgroup-hover', const ValueKey('super-group-offline')),
]) {
await mouse.moveTo(tester.getCenter(find.byKey(target.$2)));
await tester.pump();
diff --git a/desktop/test/super_tab_project_rows_shots_test.dart b/desktop/test/super_tab_project_rows_shots_test.dart
index 414204437..f877eec22 100644
--- a/desktop/test/super_tab_project_rows_shots_test.dart
+++ b/desktop/test/super_tab_project_rows_shots_test.dart
@@ -11,8 +11,7 @@ import 'support/capture.dart';
import 'support/humans_fixture.dart';
import 'support/super_tab_fixture.dart';
-/// Set to a folder to write the project rows' pictures there: a project
-/// collapsed and expanded, in both themes.
+/// Set to a folder to write the project rows' pictures there, in both themes.
final shots = Platform.environment['SUPER_TAB_SIDEBAR_SHOTS'];
void main() {
@@ -82,10 +81,7 @@ void main() {
);
}
- controller.expandedProjects.clear();
await take('collapsed');
- controller.toggleProject('lead');
- await take('expanded');
await tester.pumpWidget(const SizedBox());
await controller.flush();
controller.dispose();
diff --git a/desktop/test/super_tab_quiet_polish_test.dart b/desktop/test/super_tab_quiet_polish_test.dart
index 721b02bbe..568455a6d 100644
--- a/desktop/test/super_tab_quiet_polish_test.dart
+++ b/desktop/test/super_tab_quiet_polish_test.dart
@@ -40,15 +40,16 @@ Map<String, dynamic> _said(int sequence, String text) => {
void main() {
group('project rows', () {
- testWidgets('a project waiting on a person shows no question mark; its '
- 'task still does', (tester) async {
+ testWidgets('a project waiting on a person shows no question mark, open '
+ 'or not', (tester) async {
final server = swarm();
wait(server);
await showView(tester, server);
expect(find.text('?'), findsNothing);
await tester.tap(find.text('web-project').first);
await tester.pumpAndSettle();
- expect(find.text('?'), findsOneWidget);
+ // Its task is in the Tasks view, not listed under it (task #2569).
+ expect(find.text('?'), findsNothing);
await tester.pump(const Duration(milliseconds: 300));
});
diff --git a/desktop/test/super_tab_quiet_sidebar_test.dart b/desktop/test/super_tab_quiet_sidebar_test.dart
index 2508da27f..72aa20ba8 100644
--- a/desktop/test/super_tab_quiet_sidebar_test.dart
+++ b/desktop/test/super_tab_quiet_sidebar_test.dart
@@ -122,22 +122,23 @@ void main() {
});
testWidgets(
- 'a project row has no chevron; a second click shows its workgroups',
+ 'a project row has no chevron; every click selects its chat and lists '
+ 'no tasks',
(tester) async {
final c = await show(tester);
expect(
find.byKey(const ValueKey('super-project-toggle-lead')),
findsNothing,
);
- await c.select('lead');
+ await c.select('offline');
await tester.pump();
- expect(c.expandedProjects, isNot(contains('lead')));
await tester.tap(find.byKey(const ValueKey('super-group-lead')));
await tester.pump();
- expect(c.expandedProjects, contains('lead'));
+ expect(c.selectedId, 'lead');
await tester.tap(find.byKey(const ValueKey('super-group-lead')));
await tester.pump();
- expect(c.expandedProjects, isNot(contains('lead')));
+ expect(c.selectedId, 'lead');
+ expect(find.byKey(const ValueKey('super-group-offline')), findsNothing);
await tester.pump(const Duration(seconds: 1));
},
);
diff --git a/desktop/test/super_tab_saved_view_test.dart b/desktop/test/super_tab_saved_view_test.dart
index f975eb23b..d0a281171 100644
--- a/desktop/test/super_tab_saved_view_test.dart
+++ b/desktop/test/super_tab_saved_view_test.dart
@@ -1621,7 +1621,7 @@ void _reviewTests() {
async.elapse(const Duration(seconds: 20));
store.writes.clear();
c!.markRead('lead');
- c!.toggleProject('lead');
+ c!.toggleProjectsGroup();
async.elapse(const Duration(seconds: 20));
expect(store.writes.where((k) => k == _viewKey), isEmpty);
client.dispose();
diff --git a/desktop/test/super_tab_sidebar_reads_light_test.dart b/desktop/test/super_tab_sidebar_reads_light_test.dart
index fe4076a00..418f2f3ce 100644
--- a/desktop/test/super_tab_sidebar_reads_light_test.dart
+++ b/desktop/test/super_tab_sidebar_reads_light_test.dart
@@ -1,23 +1,18 @@
-// Task #2427 (Huy, 11-03): the Swarm sidebar reads light like Slack. A task row is bold only for what is for a person: a
-// person's new message, a mention of the reader, or the task waiting on a person. Agents' progress messages leave it in
-// regular weight and grey, as every read row is.
+// Task #2427 (Huy, 11-03): the Swarm sidebar reads light like Slack. A project row is bold only for what is for a
+// person in it or its tasks: a person's new message, a mention of the reader. Agents' progress messages leave it in
+// regular weight and grey, as every read row is. The sidebar lists no tasks (task #2569): a project's row says them.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:flutter/gestures.dart';
import 'package:harness/super_tabs/controller.dart';
-import 'package:harness/super_tabs/project_sidebar.dart';
-import 'package:harness/super_tabs/task_groups.dart';
import 'package:harness/super_tabs/swarm_type.dart';
import 'package:harness/super_tabs/view.dart';
-import 'package:harness/widgets/desktop_chrome.dart';
import 'support/humans_fixture.dart';
import 'support/super_tab_fixture.dart';
void main() {
final project = find.byKey(const ValueKey('super-group-lead'));
- final g1 = find.byKey(const ValueKey('super-group-g1'));
Future<SuperTabController> show(
WidgetTester tester,
@@ -46,10 +41,6 @@ void main() {
),
);
await tester.pumpAndSettle();
- controller.toggleProject('lead');
- // A task with no agent is in The rest, folded until opened (#2733).
- controller.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
- await tester.pumpAndSettle();
return controller;
}
@@ -59,7 +50,7 @@ void main() {
controller.dispose();
}
- /// The title's style in [row]: the RichText that holds "Workgroup 1".
+ /// The title's style in [row]: the RichText that holds [title].
TextStyle titleStyle(WidgetTester tester, Finder row, String title) {
final text = tester.widget<RichText>(
find
@@ -86,266 +77,84 @@ void main() {
await tester.pumpAndSettle();
}
- testWidgets('a task with only agents\' new messages reads regular and grey', (
- tester,
- ) async {
- final server = humansSwarm();
- addNumberedWorkgroups(server, 1);
- final controller = await show(tester, server);
- server.append('Working on it.', conversationId: 'g1', agent: true);
- server.append(
- 'Pushed the first commit.',
- conversationId: 'g1',
- agent: true,
- );
- await news(tester, controller);
- final style = titleStyle(tester, g1, 'Workgroup 1');
- expect(style.fontWeight, isNot(grid.AppFont.semibold));
- expect(style.color, DesktopChrome.muted);
- // Collapsed, the project is not bold for agents' messages either.
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
- expect(
- titleStyle(tester, project, 'Pilot').fontWeight,
- isNot(grid.AppFont.semibold),
- );
- await close(tester, controller);
- });
-
testWidgets(
- 'a person\'s new message makes a task bold, and its collapsed project',
+ 'a task with only agents\' new messages leaves its project regular',
(tester) async {
final server = humansSwarm();
addNumberedWorkgroups(server, 1);
final controller = await show(tester, server);
- server.append('Can you check this?', conversationId: 'g1');
- await news(tester, controller);
- final style = titleStyle(tester, g1, 'Workgroup 1');
- expect(style.fontWeight, grid.AppFont.semibold);
- expect(style.color, DesktopChrome.foreground);
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
- expect(
- titleStyle(tester, project, 'Pilot').fontWeight,
- grid.AppFont.semibold,
+ server.append('Working on it.', conversationId: 'g1', agent: true);
+ server.append(
+ 'Pushed the first commit.',
+ conversationId: 'g1',
+ agent: true,
);
- await close(tester, controller);
- },
- );
-
- testWidgets(
- 'a mention of the reader makes a task bold, though an agent wrote it',
- (tester) async {
- final server = humansSwarm();
- addNumberedWorkgroups(server, 1);
- final controller = await show(tester, server);
- server.tag('tag-1', conversationId: 'g1');
await news(tester, controller);
+ expect(find.byKey(const ValueKey('super-group-g1')), findsNothing);
expect(
- titleStyle(tester, g1, 'Workgroup 1').fontWeight,
- grid.AppFont.semibold,
+ titleStyle(tester, project, 'Pilot').fontWeight,
+ isNot(grid.AppFont.semibold),
);
await close(tester, controller);
},
);
- testWidgets('the open task is regular weight, carried by its highlight', (
+ testWidgets('a person\'s new message in a task makes its project bold', (
tester,
) async {
final server = humansSwarm();
addNumberedWorkgroups(server, 1);
final controller = await show(tester, server);
- await controller.select('g1');
- await tester.pumpAndSettle();
- final style = titleStyle(tester, g1, 'Workgroup 1');
- expect(style.fontWeight, isNot(grid.AppFont.semibold));
- expect(style.fontWeight, isNot(grid.AppFont.medium));
- expect(style.color, DesktopChrome.foreground);
+ server.append('Can you check this?', conversationId: 'g1');
+ await news(tester, controller);
+ expect(
+ titleStyle(tester, project, 'Pilot').fontWeight,
+ grid.AppFont.semibold,
+ );
await close(tester, controller);
});
- /// Workgroup 1 at work: an agent on it, its last progress a minute ago.
- void working(ConversationServer server) {
- final groups = (server.state['conversations'] as List)
- .cast<Map<String, dynamic>>();
- groups.firstWhere((g) => g['id'] == 'g1')['assignment'] = {
- 'id': 'a1',
- 'agentId': 'lead',
- 'status': 'working',
- 'progressAt': DateTime.now()
- .subtract(const Duration(minutes: 1))
- .millisecondsSinceEpoch,
- };
- }
-
testWidgets(
- 'a task row is one line, its state a mark at the right, still said to a screen reader',
+ 'a mention of the reader in a task makes its project bold, though an '
+ 'agent wrote it',
(tester) async {
- final semantics = tester.ensureSemantics();
final server = humansSwarm();
addNumberedWorkgroups(server, 1);
- working(server);
final controller = await show(tester, server);
- expect(find.byKey(const ValueKey('super-task-line-g1')), findsNothing);
- expect(find.byKey(const ValueKey('super-task-mark-g1')), findsOneWidget);
- // One line: the row is a sidebar row's height, as a project's is.
- expect(tester.getSize(g1).height, tester.getSize(project).height);
- expect(
- tester.getSize(g1).height,
- lessThanOrEqualTo(SwarmType.sidebarRowHeight(compact: false) + 5),
- );
+ server.tag('tag-1', conversationId: 'g1');
+ await news(tester, controller);
expect(
- tester.getSemantics(g1).getSemanticsData().label,
- contains('Working'),
+ titleStyle(tester, project, 'Pilot').fontWeight,
+ grid.AppFont.semibold,
);
- semantics.dispose();
await close(tester, controller);
},
);
- testWidgets('the task number is smaller and fainter than its title', (
- tester,
- ) async {
- final server = humansSwarm();
- addNumberedWorkgroups(server, 1);
- final controller = await show(tester, server);
- final title = titleStyle(tester, g1, 'Workgroup 1');
- final number = titleStyle(tester, g1, '1 ');
- expect(number.fontSize, lessThan(title.fontSize!));
- expect(number.color, grid.AppPalette.textFaint);
- await close(tester, controller);
- });
-
- testWidgets('the tooltip opens beside the list, not over the rows below', (
+ // Huy, 11-03, on the first after-shots: "a little more height on the
+ // projects, it will look cleaner". A project's row is 4 points taller; the
+ // rest of the sidebar keeps Slack's pitch.
+ testWidgets('a project\'s row is 4 points taller than other sidebar rows', (
tester,
) async {
final server = humansSwarm();
addNumberedWorkgroups(server, 1);
- working(server);
final controller = await show(tester, server);
- final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
- addTearDown(mouse.removePointer);
- await mouse.addPointer(location: Offset.zero);
- await mouse.moveTo(tester.getCenter(g1));
- await tester.pumpAndSettle(const Duration(seconds: 2));
- final tip = find.textContaining('Workgroup 1\n');
- expect(tip, findsOneWidget);
- // The tooltip's whole box, its padding and border included, clears the row and its state mark.
- final bubble = find
- .ancestor(of: tip, matching: find.byType(DecoratedBox))
- .first;
- final row = tester.getRect(g1), box = tester.getRect(bubble);
- expect(box.left, greaterThanOrEqualTo(row.right));
+ final other = SwarmType.sidebarRowHeight(compact: false);
expect(
- box.left,
- greaterThanOrEqualTo(
- tester.getRect(find.byKey(const ValueKey('super-task-mark-g1'))).right,
- ),
+ tester.getSize(find.byKey(const ValueKey('super-activity'))).height,
+ other,
);
- // Level with its row, not hanging below it.
- expect(box.center.dy, closeTo(row.center.dy, row.height));
- await mouse.moveTo(Offset.zero);
- await tester.pumpAndSettle(const Duration(seconds: 2));
+ expect(tester.getSize(project).height, other + 4);
await close(tester, controller);
- }, variant: TargetPlatformVariant.all());
-
- // The screenshot's case (review of the first after-shot): a 300-point
- // sidebar in a 620-point window had too little room right of the list
- // for a one-line tooltip, and keeping it on screen pushed it back over
- // the rows. A compact tooltip wraps instead.
- testWidgets('a compact tooltip wraps beside a narrow window\'s list', (
- tester,
- ) async {
- await tester.binding.setSurfaceSize(const Size(620, 500));
- addTearDown(() => tester.binding.setSurfaceSize(null));
- final server = humansSwarm();
- addNumberedWorkgroups(server, 1);
- working(server);
- (server.state['conversations'] as List)
- .cast<Map<String, dynamic>>()
- .firstWhere((g) => g['id'] == 'g1')['title'] =
- 'Desktop: a machine\'s Team account setup prompt';
- final controller = server.controller(
- account: 'peer',
- initial: {
- 'tabId': 'tab',
- 'accountId': 'peer',
- 'selectedId': 'lead',
- 'expandedProjects': ['lead'],
- },
- );
- await controller.refresh();
- await tester.pumpWidget(
- MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: Scaffold(
- body: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- SizedBox(
- width: 300,
- child: ProjectSidebar(
- controller: controller,
- onSelect: controller.select,
- needsHuman: (_) => 0,
- ),
- ),
- const Expanded(child: SizedBox()),
- ],
- ),
- ),
- ),
- );
- await tester.pumpAndSettle();
- final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
- addTearDown(mouse.removePointer);
- await mouse.addPointer(location: Offset.zero);
- await mouse.moveTo(tester.getCenter(g1));
- await tester.pumpAndSettle(const Duration(seconds: 2));
- final bubble = find
- .ancestor(
- of: find.textContaining('setup prompt\n'),
- matching: find.byType(DecoratedBox),
- )
- .first;
- expect(
- tester.getRect(bubble).left,
- greaterThanOrEqualTo(tester.getRect(g1).right),
- );
- expect(tester.getRect(bubble).right, lessThanOrEqualTo(620));
- await mouse.moveTo(Offset.zero);
- await tester.pumpAndSettle(const Duration(seconds: 2));
- await tester.pumpWidget(const SizedBox());
- await controller.flush();
- controller.dispose();
});
- // Huy, 11-03, on the first after-shots: "a little more height on the
- // projects, it will look cleaner". The rows under Projects (a project and
- // its tasks) are 4 points taller; the rest of the sidebar keeps Slack's pitch.
- testWidgets(
- 'a project\'s and a task\'s rows are 4 points taller than other sidebar rows',
- (tester) async {
- final server = humansSwarm();
- addNumberedWorkgroups(server, 1);
- final controller = await show(tester, server);
- final other = SwarmType.sidebarRowHeight(compact: false);
- expect(
- tester.getSize(find.byKey(const ValueKey('super-activity'))).height,
- other,
- );
- expect(tester.getSize(project).height, other + 4);
- expect(tester.getSize(g1).height, other + 4);
- await close(tester, controller);
- },
- );
-
// Review of #2790 (Sedge, Plover): a wait made a row bold, for every
// viewer, and opening the task did not clear it, while a screen reader
- // heard "Unread messages". A wait is no unread message: its ? mark and
- // Activity say it, and the row is bold only for what there is to read.
+ // heard "Unread messages". A wait is no unread message: Activity says it,
+ // and the row is bold only for what there is to read.
testWidgets(
- 'a waiting task is not bold, whoever it waits on, and its ? mark says it',
+ 'a waiting task does not make its project bold, whoever it waits on',
(tester) async {
final semantics = tester.ensureSemantics();
final server = humansSwarm();
@@ -364,21 +173,16 @@ void main() {
};
}
final controller = await show(tester, server);
- final g2 = find.byKey(const ValueKey('super-group-g2'));
- for (final (row, title) in [(g1, 'Workgroup 1'), (g2, 'Workgroup 2')]) {
- expect(
- titleStyle(tester, row, title).fontWeight,
- isNot(grid.AppFont.semibold),
- );
- expect(
- find.descendant(of: row, matching: find.text('?')),
- findsOneWidget,
- );
- expect(
- tester.getSemantics(row).getSemanticsData().label,
- isNot(contains('Unread messages')),
- );
- }
+ await controller.select('offline');
+ await tester.pumpAndSettle();
+ expect(
+ titleStyle(tester, project, 'Pilot').fontWeight,
+ isNot(grid.AppFont.semibold),
+ );
+ expect(
+ tester.getSemantics(project).getSemanticsData().label,
+ isNot(contains('Unread messages')),
+ );
semantics.dispose();
await close(tester, controller);
},
@@ -390,20 +194,35 @@ void main() {
'the Unread filter keeps what is bold, and hides agents\' progress alone',
(tester) async {
final server = humansSwarm();
- addNumberedWorkgroups(server, 2);
+ // Two more projects, one task each: one with agents' progress alone,
+ // one with a person's message.
+ for (final (id, name) in [('busy', 'Busy'), ('asked', 'Asked')]) {
+ (server.state['projects'] as List).add(
+ projectFixture(id, name, '$id-chat'),
+ );
+ (server.state['conversations'] as List)
+ ..add({...conversationFixture('$id-chat', name), 'projectId': id})
+ ..add({
+ ...conversationFixture('$id-task', '$name work'),
+ 'projectId': id,
+ 'number': 1,
+ });
+ }
final controller = await show(tester, server);
- final g2 = find.byKey(const ValueKey('super-group-g2'));
server.append(
'Pushed the next commit.',
- conversationId: 'g1',
+ conversationId: 'busy-task',
agent: true,
);
- server.append('Can you check this?', conversationId: 'g2');
+ server.append('Can you check this?', conversationId: 'asked-task');
await news(tester, controller);
controller.toggleUnreadOnly();
await tester.pumpAndSettle();
- expect(g1, findsNothing);
- expect(g2, findsOneWidget);
+ expect(find.byKey(const ValueKey('super-group-busy-chat')), findsNothing);
+ expect(
+ find.byKey(const ValueKey('super-group-asked-chat')),
+ findsOneWidget,
+ );
await close(tester, controller);
},
);
diff --git a/desktop/test/super_tab_sidebar_rows_test.dart b/desktop/test/super_tab_sidebar_rows_test.dart
index 4ef2abb66..577886df2 100644
--- a/desktop/test/super_tab_sidebar_rows_test.dart
+++ b/desktop/test/super_tab_sidebar_rows_test.dart
@@ -6,15 +6,14 @@ import 'package:harness/shared/theme/app_icons.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/buddy_rows.dart';
-import 'package:harness/super_tabs/task_groups.dart';
import 'package:harness/super_tabs/view.dart';
import 'support/humans_fixture.dart';
import 'support/super_tab_fixture.dart';
/// The sidebar's rows: a Buddy chat click highlights only that row; a
-/// project's row opens its chat and a second click shows or hides its
-/// conversations (Quiet Swarm); in Manage, a machine click
+/// project's row opens its chat, every click, and lists no tasks (task
+/// #2569: they are in the project's Tasks view); in Manage, a machine click
/// expands it, and its details are in the right-click menu.
void main() {
final dm = find.byKey(const ValueKey('super-buddy-lead'));
@@ -24,9 +23,8 @@ void main() {
Future<SuperTabController> show(
WidgetTester tester,
- ConversationServer server, {
- bool restFolded = false,
- }) async {
+ ConversationServer server,
+ ) async {
await tester.binding.setSurfaceSize(const Size(1300, 900));
addTearDown(() => tester.binding.setSurfaceSize(null));
final controller = server.controller(
@@ -34,9 +32,6 @@ void main() {
initial: {'tabId': 'tab', 'accountId': 'peer', 'selectedId': 'lead'},
);
await controller.refresh();
- // These workgroups have no work, so they are in The rest, which starts
- // folded (#2309): unfolded here, where the rows are what is tested.
- if (!restFolded) controller.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
await tester.pumpWidget(
MaterialApp(
theme: grid.buildAppTheme(brightness: Brightness.light),
@@ -70,125 +65,70 @@ void main() {
),
);
- testWidgets(
- 'a Buddy chat click highlights only that row and leaves projects collapsed',
- (tester) async {
- final controller = await show(tester, humansSwarm());
- // Its chat exists already: opening it again is a plain selection.
- await controller.openBuddyChat('lead');
- await controller.select('lead');
- controller.expandedProjects.clear();
- await tester.pumpAndSettle();
-
- await tester.tap(dm);
- await tester.pumpAndSettle();
- expect(controller.selectedId, controller.buddyChat('lead')!.id);
- expect(controller.expandedProjects, isEmpty);
- expect(workgroup, findsNothing);
- expect(tester.widget<SuperTabBuddyRow>(dm).selected, isTrue);
- await close(tester, controller);
- },
- );
-
- testWidgets(
- 'a Buddy chat opened for the first time leaves projects collapsed',
- (tester) async {
- final controller = await show(tester, humansSwarm());
- controller.expandedProjects.clear();
- await tester.pumpAndSettle();
- await tester.tap(dm);
- await tester.pumpAndSettle();
- expect(controller.selectedId, controller.buddyChat('lead')!.id);
- expect(controller.expandedProjects, isEmpty);
- await close(tester, controller);
- },
- );
-
- testWidgets(
- 'a Buddy click leaves a collapsed project collapsed and an expanded one expanded',
- (tester) async {
- final controller = await show(tester, humansSwarm());
- // A task of the project is open, and its list was then hidden: the
- // project shows as selected, as in the report.
- await controller.select('offline');
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
- expect(controller.expandedProjects, isEmpty);
- expect(controller.selectedId, 'offline');
+ testWidgets('a Buddy chat click highlights only that row', (tester) async {
+ final controller = await show(tester, humansSwarm());
+ // Its chat exists already: opening it again is a plain selection.
+ await controller.openBuddyChat('lead');
+ await controller.select('lead');
+ await tester.pumpAndSettle();
- await tester.tap(dm);
- await tester.pumpAndSettle();
- expect(controller.selectedId, controller.buddyChat('lead')!.id);
- expect(controller.expandedProjects, isEmpty);
- expect(workgroup, findsNothing);
+ await tester.tap(dm);
+ await tester.pumpAndSettle();
+ expect(controller.selectedId, controller.buddyChat('lead')!.id);
+ expect(workgroup, findsNothing);
+ expect(tester.widget<SuperTabBuddyRow>(dm).selected, isTrue);
+ await close(tester, controller);
+ });
- // Open, and a task selected: the Buddy click leaves the list showing.
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
- await controller.select('offline');
- await tester.pumpAndSettle();
- await tester.tap(dm);
- await tester.pumpAndSettle();
- expect(controller.selectedId, controller.buddyChat('lead')!.id);
- expect(controller.expandedProjects, {'lead'});
- expect(workgroup, findsOneWidget);
- await close(tester, controller);
- },
- );
+ testWidgets('a Buddy chat opened for the first time is selected', (
+ tester,
+ ) async {
+ final controller = await show(tester, humansSwarm());
+ await tester.tap(dm);
+ await tester.pumpAndSettle();
+ expect(controller.selectedId, controller.buddyChat('lead')!.id);
+ expect(workgroup, findsNothing);
+ await close(tester, controller);
+ });
- testWidgets(
- 'a project name click opens its chat and leaves its list as it was',
- (tester) async {
- final controller = await show(tester, humansSwarm());
- await controller.openBuddyChat('lead');
- controller.expandedProjects.clear();
- await tester.pumpAndSettle();
+ testWidgets('a project name click opens its chat, and comes back to it', (
+ tester,
+ ) async {
+ final controller = await show(tester, humansSwarm());
+ await controller.openBuddyChat('lead');
+ await tester.pumpAndSettle();
- await tester.tap(find.text('Pilot'));
- await tester.pumpAndSettle();
- expect(controller.selectedId, 'lead');
- expect(controller.expandedProjects, isEmpty);
- expect(workgroup, findsNothing);
+ await tester.tap(find.text('Pilot'));
+ await tester.pumpAndSettle();
+ expect(controller.selectedId, 'lead');
+ expect(workgroup, findsNothing);
- // Open, and the chat left for the Buddy chat: the name comes back to
- // it without closing the list.
- controller.toggleProject('lead');
- await tester.tap(dm);
- await tester.pumpAndSettle();
- await tester.tap(find.text('Pilot'));
- await tester.pumpAndSettle();
- expect(controller.selectedId, 'lead');
- expect(controller.expandedProjects, {'lead'});
- expect(workgroup, findsOneWidget);
- await close(tester, controller);
- },
- );
+ // The chat left for the Buddy chat: the name comes back to it.
+ await tester.tap(dm);
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Pilot'));
+ await tester.pumpAndSettle();
+ expect(controller.selectedId, 'lead');
+ expect(workgroup, findsNothing);
+ await close(tester, controller);
+ });
testWidgets(
- 'a second click on the open project toggles its list and leaves its chat open',
+ 'a second click on the open project leaves its chat open and lists no '
+ 'tasks',
(tester) async {
final controller = await show(tester, humansSwarm());
await controller.openBuddyChat('lead');
- controller.expandedProjects.clear();
await tester.tap(dm);
await tester.pumpAndSettle();
expect(chevronIn(project), findsNothing);
- // The first opens its chat, and leaves its list.
await tester.tap(project);
await tester.pumpAndSettle();
expect(controller.selectedId, 'lead');
- expect(controller.expandedProjects, isEmpty);
await tester.tap(project);
await tester.pumpAndSettle();
- expect(controller.expandedProjects, {'lead'});
- expect(workgroup, findsOneWidget);
- expect(controller.selectedId, 'lead');
-
- await tester.tap(project);
- await tester.pumpAndSettle();
- expect(controller.expandedProjects, isEmpty);
expect(workgroup, findsNothing);
expect(controller.selectedId, 'lead');
await close(tester, controller);
@@ -227,67 +167,39 @@ void main() {
?.fontWeight;
testWidgets(
- 'an unread project and workgroup show their names in bold, with no dot',
+ 'a project with an unread task shows its name in bold, with no dot',
(tester) async {
- // Not "Offline editing": it waits for a person, which shows "?" there.
+ // Not "Offline editing": it waits for a person.
final server = humansSwarm();
addNumberedWorkgroups(server, 1);
final controller = await show(tester, server);
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
- final g1 = find.byKey(const ValueKey('super-group-g1'));
- final name = tester
- .widget<RichText>(
- find.descendant(of: g1, matching: find.byType(RichText)).first,
- )
- .text
- .toPlainText();
- // Read: the project open (medium), the workgroup in ordinary weight.
expect(weightOf(tester, project, 'Pilot'), isNot(grid.AppFont.semibold));
- expect(weightOf(tester, g1, name), grid.AppFont.regular);
server.append('New work', conversationId: 'g1');
await controller.select('offline');
await controller.refresh();
await tester.pumpAndSettle();
- // Open, the project's row is its own chat's, as in Slack: only the
- // workgroup with news is bold (Dee, 10-31).
- expect(weightOf(tester, project, 'Pilot'), isNot(grid.AppFont.semibold));
- expect(weightOf(tester, g1, name), grid.AppFont.semibold);
- expect(unreadDot(project), findsNothing);
- expect(unreadDot(g1), findsNothing);
- // Collapsed, it is bold for what it hides.
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
+ // Bold for what its tasks hold.
expect(weightOf(tester, project, 'Pilot'), grid.AppFont.semibold);
+ expect(unreadDot(project), findsNothing);
await close(tester, controller);
},
);
testWidgets(
- 'a screen reader hears an unread row as unread, and a read one not',
+ 'a screen reader hears a project with an unread task as unread, and a '
+ 'read one not',
(tester) async {
final semantics = tester.ensureSemantics();
final server = humansSwarm();
addNumberedWorkgroups(server, 2);
final controller = await show(tester, server);
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
- final g1 = find.byKey(const ValueKey('super-group-g1'));
- final g2 = find.byKey(const ValueKey('super-group-g2'));
expect(spoken(tester, project), isNot(contains('Unread messages')));
- expect(spoken(tester, g1), isNot(contains('Unread messages')));
server.append('New work', conversationId: 'g1');
await controller.select('offline');
await controller.refresh();
await tester.pumpAndSettle();
- expect(spoken(tester, project), isNot(contains('Unread messages')));
- expect(spoken(tester, g1), contains('Unread messages'));
- expect(spoken(tester, g2), isNot(contains('Unread messages')));
- // Collapsed, the project is heard as unread for what it hides.
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
expect(spoken(tester, project), contains('Unread messages'));
semantics.dispose();
await close(tester, controller);
@@ -325,205 +237,55 @@ void main() {
semantics.dispose();
});
- testWidgets(
- 'projects start collapsed, and each account keeps its own choice',
- (tester) async {
- final server = humansSwarm();
- var controller = await show(tester, server);
- expect(controller.expandedProjects, isEmpty);
- expect(workgroup, findsNothing);
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
- await close(tester, controller);
-
- Future<SuperTabController> reopen(String account) async {
- final next = server.controller(account: account, initial: server.saved);
- await next.refresh();
- next.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: SuperTabView(
- controller: next,
- onInvite: () {},
- onAddAgent: (_) {},
- onOpenTerminal: (_) {},
- machineName: (_) => 'Studio',
- ),
- ),
- ),
- );
- await tester.pumpAndSettle();
- return next;
- }
-
- controller = await reopen('peer');
- expect(workgroup, findsOneWidget);
- await close(tester, controller);
-
- controller = await reopen('owner');
- expect(workgroup, findsNothing);
- await close(tester, controller);
- },
- );
-
- testWidgets(
- 'an open project lists every open conversation newest first, with no "… N more"',
- (tester) async {
- final server = humansSwarm();
- addNumberedWorkgroups(server, 11);
- final controller = await show(tester, server);
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
-
- Finder row(String id) => find.byKey(ValueKey('super-group-$id'));
- // The unnumbered "Offline editing" predates numbering: last.
- final shown = [for (var n = 11; n >= 1; n--) row('g$n'), workgroup];
- for (final finder in shown) {
- expect(finder, findsOneWidget);
- }
- for (var i = 1; i < shown.length; i++) {
- expect(
- tester.getTopLeft(shown[i]).dy,
- greaterThan(tester.getTopLeft(shown[i - 1]).dy),
- );
- }
- expect(find.textContaining('more'), findsNothing);
- await close(tester, controller);
- },
- );
-
- testWidgets(
- 'an older conversation that is open stays listed in a folded group',
- (tester) async {
- final server = humansSwarm();
- addNumberedWorkgroups(server, 11);
- final controller = await show(tester, server, restFolded: true);
- await controller.select('g1');
- await tester.pumpAndSettle();
- expect(find.byKey(const ValueKey('super-group-g1')), findsOneWidget);
- expect(find.byKey(const ValueKey('super-group-g2')), findsNothing);
- await close(tester, controller);
- },
- );
-
- testWidgets(
- 'a conversation waiting on a person is listed under Needs you while The rest is folded',
- (tester) async {
- final server = humansSwarm();
- addNumberedWorkgroups(server, 11);
- // #2 waits for a person to answer its Engineer.
- (server.state['conversations'] as List)
- .cast<Map<String, dynamic>>()
- .firstWhere((g) => g['id'] == 'g2')
- ..['agentIds'] = ['lead-agent']
- ..['assignment'] = {'agentId': 'lead-agent', 'status': 'needs_human'};
- final controller = await show(tester, server, restFolded: true);
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
- expect(find.byKey(const ValueKey('super-group-g2')), findsOneWidget);
- expect(find.byKey(const ValueKey('super-group-g3')), findsNothing);
- expect(
- find.byKey(const ValueKey('super-task-group-lead-needsYou')),
- findsOneWidget,
- );
- await close(tester, controller);
- },
- );
-
- testWidgets(
- 'a collapsed project holding the open conversation shows as selected',
- (tester) async {
- final server = humansSwarm();
- addNumberedWorkgroups(server, 1);
- final controller = await show(tester, server);
- Color? projectFill() => tester
- .widget<Material>(
- find.ancestor(of: project, matching: find.byType(Material)).first,
- )
- .color;
- await controller.select('g1');
- await tester.pumpAndSettle();
- expect(projectFill(), Colors.transparent);
-
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
- expect(controller.selectedId, 'g1');
- expect(projectFill(), grid.AppSurface.selectedFill);
+ testWidgets('a project holding the open conversation shows as selected', (
+ tester,
+ ) async {
+ final server = humansSwarm();
+ addNumberedWorkgroups(server, 1);
+ final controller = await show(tester, server);
+ await controller.openBuddyChat('lead');
+ Color? projectFill() => tester
+ .widget<Material>(
+ find.ancestor(of: project, matching: find.byType(Material)).first,
+ )
+ .color;
+ await tester.tap(dm);
+ await tester.pumpAndSettle();
+ expect(projectFill(), Colors.transparent);
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
- expect(projectFill(), Colors.transparent);
- await close(tester, controller);
- },
- );
+ await controller.select('g1');
+ await tester.pumpAndSettle();
+ expect(controller.selectedId, 'g1');
+ expect(projectFill(), grid.AppSurface.selectedFill);
+ await close(tester, controller);
+ });
testWidgets('an arrow a project name cannot use moves focus as usual', (
tester,
) async {
final controller = await show(tester, humansSwarm());
- controller.toggleProject('lead');
- await tester.pumpAndSettle();
- expect(controller.expandedProjects, {'lead'});
Focus.of(tester.element(find.text('Pilot'))).requestFocus();
await tester.pumpAndSettle();
final name = primaryFocus;
- // Already open: → goes on from the name.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.pumpAndSettle();
- expect(controller.expandedProjects, {'lead'});
expect(primaryFocus, isNot(same(name)));
+ expect(workgroup, findsNothing);
await close(tester, controller);
});
- testWidgets(
- 'Enter on a project name opens it; → and ← show and hide its conversations',
- (tester) async {
- final controller = await show(tester, humansSwarm());
- await controller.openBuddyChat('lead');
- controller.expandedProjects.clear();
- await tester.tap(dm);
- await tester.pumpAndSettle();
- Future<void> focusName() async {
- Focus.of(tester.element(find.text('Pilot'))).requestFocus();
- await tester.pumpAndSettle();
- }
-
- await focusName();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(controller.selectedId, 'lead');
- expect(controller.expandedProjects, isEmpty);
-
- // Opening the chat moved focus into it.
- await focusName();
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
- await tester.pumpAndSettle();
- expect(controller.expandedProjects, {'lead'});
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
- await tester.pumpAndSettle();
- expect(controller.expandedProjects, isEmpty);
- expect(controller.selectedId, 'lead');
- await close(tester, controller);
- },
- );
-
- testWidgets('the focused open project toggles with Enter and with Space', (
- tester,
- ) async {
+ testWidgets('Enter on a project name opens its chat', (tester) async {
final controller = await show(tester, humansSwarm());
- controller.expandedProjects.clear();
+ await controller.openBuddyChat('lead');
+ await tester.tap(dm);
await tester.pumpAndSettle();
- expect(controller.selectedId, 'lead');
Focus.of(tester.element(find.text('Pilot'))).requestFocus();
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
- expect(controller.expandedProjects, {'lead'});
- await tester.sendKeyEvent(LogicalKeyboardKey.space);
- await tester.pumpAndSettle();
- expect(controller.expandedProjects, isEmpty);
+ expect(controller.selectedId, 'lead');
+ expect(workgroup, findsNothing);
await close(tester, controller);
});
diff --git a/desktop/test/super_tab_sidebar_scale_test.dart b/desktop/test/super_tab_sidebar_scale_test.dart
index d95f3b619..a6d4aaa77 100644
--- a/desktop/test/super_tab_sidebar_scale_test.dart
+++ b/desktop/test/super_tab_sidebar_scale_test.dart
@@ -99,13 +99,13 @@ void main() {
final ids = _manyProjects(server);
final controller = _CountingController(
server,
- initial: {
- 'tabId': 'tab',
- 'accountId': 'owner',
- 'expandedProjects': ids,
- },
+ initial: {'tabId': 'tab', 'accountId': 'owner'},
);
await controller.refresh();
+ // Every project's closed groups held too, as a Tasks view reads them.
+ for (final id in ids) {
+ await controller.loadDormant(id);
+ }
expect(controller.snapshot!.conversations, hasLength(2 + 19 + 20 * 201));
final asked = <String, int>{};
@@ -141,9 +141,13 @@ void main() {
expect(controller.buddyChatLookups.keys, unorderedEquals(ids));
expect(controller.buddyChatLookups.values, everyElement(1));
- // Each project's 150 open workgroups and its Lead; never the reader's
- // Buddy chat, which waits on no human.
- expect(asked, hasLength(20 * 151 + 1));
+ // Each project's 150 open workgroups, as its Tasks board places them
+ // for its badge (task #2569), and "offline"; never a closed one, whose
+ // agent asks nothing, nor a project's chat or the reader's Buddy chat,
+ // which wait on no human.
+ expect(asked, hasLength(20 * 150 + 1));
+ expect(asked.keys.where((id) => id.startsWith('lead')), isEmpty);
+ expect(asked.keys.where((id) => id.startsWith('buddy-')), isEmpty);
expect(asked.values, everyElement(1));
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/super_tab_sidebar_test.dart b/desktop/test/super_tab_sidebar_test.dart
index 4cc09183e..055e54c24 100644
--- a/desktop/test/super_tab_sidebar_test.dart
+++ b/desktop/test/super_tab_sidebar_test.dart
@@ -220,7 +220,7 @@ void main() {
for (final scale in [1.0, 2.0]) {
testWidgets(
'flat navigation shares text and selection bounds; a project row '
- 'opens its chat and shows its workgroups at ${scale}x',
+ 'opens its chat on every click and lists no tasks at ${scale}x',
(tester) async {
addTearDown(() => tester.binding.setSurfaceSize(null));
final app = createApp(connected: true);
@@ -266,16 +266,12 @@ void main() {
await tester.pumpAndSettle();
expect(controller.selectedId, 'lead');
expect(inRow('super-group-lead', find.text('#')), findsOneWidget);
- // A second click shows its workgroups (no chevrons: Quiet Swarm).
+ // A second click keeps its chat and lists no tasks: they are in the
+ // project's Tasks view (task #2569).
await tester.tap(project);
await tester.pumpAndSettle();
- // A workgroup with no work is in The rest, which starts folded (#2309).
- await tester.tap(
- find.byKey(const ValueKey('super-task-group-lead-rest')),
- );
- await tester.pumpAndSettle();
- final work = find.byKey(const ValueKey('super-group-offline'));
- expect(work, findsOneWidget);
+ expect(controller.selectedId, 'lead');
+ expect(find.byKey(const ValueKey('super-group-offline')), findsNothing);
final textX = tester
.getTopLeft(inRow('super-group-lead', find.text('web-project')))
.dx;
@@ -283,38 +279,28 @@ void main() {
find.text('Activity'),
find.text('Manage'),
sample,
- // A workgroup's number is grey, with no #: it is no channel.
- inRow('super-group-offline', find.text('12 Offline editing')),
- // Its group's heading lines up with it.
- inRow('super-task-group-lead-rest', find.text('The rest')),
]) {
expect(tester.getTopLeft(label).dx, textX, reason: '$label');
}
- // Unread is a bold name, with no dot in either row (Dee, 2026-10-29).
- expect(unreadDot('offline'), findsNothing);
+ // Unread is a bold name, with no dot (Dee, 2026-10-29).
expect(unreadDot('lead'), findsNothing);
- for (final row in [activity, manage, work]) {
+ for (final row in [activity, manage, empty]) {
final bounds = tester.getRect(row);
expect(bounds.left, tester.getRect(project).left);
expect(bounds.right, tester.getRect(project).right);
}
- await tester.tap(work);
- await tester.pumpAndSettle();
- expect(controller.selectedId, 'offline');
- await tester.tap(empty);
+ await controller.select('offline');
await tester.pumpAndSettle();
- expect(controller.selectedId, 'empty-lead');
- expect(find.text('No workgroups yet'), findsNothing);
- await tester.tap(empty);
- await tester.pumpAndSettle();
- expect(find.text('No workgroups yet'), findsOneWidget);
- expect(tester.getTopLeft(find.text('No workgroups yet')).dx, textX);
- // Another click hides them again.
await tester.tap(empty);
await tester.pumpAndSettle();
expect(controller.selectedId, 'empty-lead');
- expect(find.text('No workgroups yet'), findsNothing);
+ for (var click = 0; click < 2; click++) {
+ await tester.tap(empty);
+ await tester.pumpAndSettle();
+ expect(controller.selectedId, 'empty-lead');
+ expect(find.text('No workgroups yet'), findsNothing);
+ }
// The plain rows retain keyboard operation and do not create tabs.
Focus.of(tester.element(find.text('Activity'))).requestFocus();
@@ -339,17 +325,17 @@ void main() {
grid.AppSurface.selectedFill,
);
expect(
- rowMaterial(tester, 'super-group-offline').color,
+ rowMaterial(tester, 'super-group-empty-lead').color,
Colors.transparent,
);
- // Returning to the already selected workgroup still leaves it.
- await tester.tap(work);
+ // Returning to the already selected chat still leaves it.
+ await tester.tap(empty);
await tester.pumpAndSettle();
expect(controller.devicesSelected, isFalse);
- expect(controller.selectedId, 'offline');
+ expect(controller.selectedId, 'empty-lead');
expect(
- rowMaterial(tester, 'super-group-offline').color,
+ rowMaterial(tester, 'super-group-empty-lead').color,
grid.AppSurface.selectedFill,
);
expect(rowMaterial(tester, 'super-manage').color, Colors.transparent);
@@ -359,8 +345,8 @@ void main() {
);
}
- testWidgets('reads like a chat app: Activity, Projects A to Z with their '
- 'workgroups, Buddies, then Manage; no # product-managers', (
+ testWidgets('reads like a chat app: Activity, Projects A to Z, Buddies, '
+ 'then Manage; no # product-managers, no tasks', (
tester,
) async {
addTearDown(() => tester.binding.setSurfaceSize(null));
@@ -375,19 +361,13 @@ void main() {
});
server.state['leadsConversationId'] = 'leads';
final controller = await projectSidebar(server);
- controller
- ..toggleProject('lead')
- ..toggleProject('empty');
await pumpSidebar(tester, controller, app);
final order = [
find.byKey(const ValueKey('super-activity')),
find.text('Projects'),
find.byKey(const ValueKey('super-group-empty-lead')),
- find.text('No workgroups yet'),
find.byKey(const ValueKey('super-group-lead')),
- // Its one workgroup has no work: The rest, folded (#2309).
- find.byKey(const ValueKey('super-task-group-lead-rest')),
find.text('Buddies'),
find.byKey(const ValueKey('super-buddy-lead')),
find.byKey(const ValueKey('super-buddy-empty')),
@@ -415,6 +395,9 @@ void main() {
}
expect(find.byKey(const ValueKey('super-group-leads')), findsNothing);
expect(find.text('product-managers'), findsNothing);
+ // Tasks are in each project's Tasks view (task #2569).
+ expect(find.byKey(const ValueKey('super-group-offline')), findsNothing);
+ expect(find.text('No workgroups yet'), findsNothing);
expect(
inRow('super-buddy-lead', find.text('(web-project)')),
findsOneWidget,
diff --git a/desktop/test/super_tab_task_columns_test.dart b/desktop/test/super_tab_task_columns_test.dart
new file mode 100644
index 000000000..96397f56b
--- /dev/null
+++ b/desktop/test/super_tab_task_columns_test.dart
@@ -0,0 +1,360 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/task_groups.dart';
+
+import 'support/super_tab_fixture.dart';
+
+final _now = DateTime(2026, 11, 4, 9);
+final _pr = 'https://github.com/autonomous-ai/openharness/pull/12';
+
+SuperTabConversation _task({
+ String id = 't',
+ int number = 1,
+ String? status,
+ Map<String, dynamic>? liveness,
+ bool archived = false,
+ bool merged = false,
+ bool linked = false,
+ DateTime? shippedAt,
+ num? queueRank,
+ String? notBefore,
+}) => SuperTabConversation.fromJson({
+ ...conversationFixture(id, 'Task $id'),
+ 'number': number,
+ 'archived': archived,
+ if (status != null)
+ 'assignment': {'agentId': 'a1', 'status': status, 'progressAt': 1},
+ 'liveness': ?liveness,
+ if (linked || merged) 'pullRequestUrls': [_pr],
+ if (linked || merged)
+ 'cards': {
+ 'pullRequests': [
+ {'url': _pr, 'messageId': 'm-$id', if (merged) 'mergedAt': 1},
+ ],
+ },
+ if (shippedAt != null) 'shippedAt': shippedAt.millisecondsSinceEpoch,
+ 'queueRank': ?queueRank,
+ 'notBefore': ?notBefore,
+});
+
+Map<String, dynamic> _waiting(String why, {String? personId}) => {
+ 'state': 'waiting',
+ 'why': why,
+ 'since': 1,
+ 'personId': ?personId,
+};
+
+SuperTabTaskPlace? _place(
+ SuperTabConversation task, {
+ int mentions = 0,
+ int needsHuman = 0,
+}) => superTabTaskPlaceOf(
+ task,
+ readerId: 'me',
+ now: _now,
+ mentions: mentions,
+ needsHuman: needsHuman,
+ personName: (id) => const {'ken': 'Ken', 'me': 'Dee'}[id],
+);
+
+/// The Tasks view's columns (Dee, task #2569): one function places every task
+/// for Board, List and the badge alike.
+void main() {
+ test('the columns read in the board\'s order', () {
+ expect(SuperTabTaskColumn.values.map((c) => c.label), [
+ 'Proposals',
+ 'Next up',
+ 'Working',
+ 'Waiting',
+ 'Shipped',
+ ]);
+ });
+
+ test('every state has its column and caption', () {
+ final cases = <(String, SuperTabConversation, int, SuperTabTaskPlace?)>[
+ (
+ 'nobody on it',
+ _task(),
+ 0,
+ (column: .nextUp, needsYou: false, state: null),
+ ),
+ (
+ 'not before a date',
+ _task(notBefore: '2026-12-04'),
+ 0,
+ (column: .nextUp, needsYou: false, state: 'not before Dec 4'),
+ ),
+ (
+ 'working',
+ _task(status: 'working'),
+ 0,
+ (column: .working, needsYou: false, state: null),
+ ),
+ (
+ 'planned',
+ _task(status: 'planned'),
+ 0,
+ (column: .working, needsYou: false, state: null),
+ ),
+ (
+ 'working with its pull request',
+ _task(status: 'working', linked: true),
+ 0,
+ (column: .working, needsYou: false, state: 'PR #12'),
+ ),
+ (
+ 'starting its agent',
+ _task(status: 'working', liveness: _waiting('starting')),
+ 0,
+ (column: .working, needsYou: false, state: null),
+ ),
+ (
+ 'in review',
+ _task(status: 'review', liveness: _waiting('review')),
+ 0,
+ (column: .waiting, needsYou: false, state: 'in review'),
+ ),
+ (
+ 'changes requested',
+ _task(status: 'working', liveness: _waiting('revision')),
+ 0,
+ (column: .waiting, needsYou: false, state: 'changes requested'),
+ ),
+ (
+ 'waiting on Ken',
+ _task(
+ status: 'needs_human',
+ liveness: _waiting('person', personId: 'ken'),
+ ),
+ 0,
+ (column: .waiting, needsYou: false, state: 'Ken to decide'),
+ ),
+ (
+ 'waiting on the reader',
+ _task(
+ status: 'needs_human',
+ liveness: _waiting('person', personId: 'me'),
+ ),
+ 0,
+ (column: .waiting, needsYou: true, state: 'Dee to decide'),
+ ),
+ (
+ 'needs_human, no one named',
+ _task(status: 'needs_human', liveness: _waiting('person')),
+ 0,
+ (column: .waiting, needsYou: true, state: 'someone to decide'),
+ ),
+ (
+ 'quiet with a question in its terminal',
+ _task(status: 'working', liveness: {'state': 'quiet', 'since': 1}),
+ 1,
+ (column: .waiting, needsYou: true, state: 'quiet'),
+ ),
+ (
+ 'quiet',
+ _task(status: 'working', liveness: {'state': 'quiet', 'since': 1}),
+ 0,
+ (column: .waiting, needsYou: false, state: 'quiet'),
+ ),
+ (
+ 'a question in a working task\'s terminal',
+ _task(status: 'working'),
+ 1,
+ (column: .working, needsYou: true, state: null),
+ ),
+ (
+ 'its agent lost',
+ _task(
+ status: 'working',
+ liveness: {'state': 'orphaned', 'why': 'lost', 'since': 1},
+ ),
+ 0,
+ (column: .waiting, needsYou: false, state: 'agent lost'),
+ ),
+ (
+ 'queued for a machine',
+ _task(status: 'working', liveness: _waiting('queued')),
+ 0,
+ (column: .waiting, needsYou: false, state: 'waiting for a machine'),
+ ),
+ (
+ 'blocked',
+ _task(status: 'blocked', liveness: _waiting('blocked')),
+ 0,
+ (column: .waiting, needsYou: false, state: 'blocked'),
+ ),
+ (
+ 'done, its pull request not merged',
+ _task(
+ status: 'done',
+ linked: true,
+ shippedAt: _now.subtract(const Duration(hours: 1)),
+ ),
+ 0,
+ (column: .waiting, needsYou: false, state: 'ready to merge'),
+ ),
+ (
+ 'finished with no pull request',
+ _task(
+ status: 'done',
+ shippedAt: _now.subtract(const Duration(hours: 1)),
+ ),
+ 0,
+ (column: .shipped, needsYou: false, state: 'Done'),
+ ),
+ (
+ 'merged 2 days ago, archived',
+ _task(
+ status: 'done',
+ merged: true,
+ archived: true,
+ shippedAt: _now.subtract(const Duration(days: 2)),
+ ),
+ 0,
+ (column: .shipped, needsYou: false, state: 'PR #12'),
+ ),
+ (
+ 'merged 8 days ago',
+ _task(
+ status: 'done',
+ merged: true,
+ archived: true,
+ shippedAt: _now.subtract(const Duration(days: 8)),
+ ),
+ 0,
+ null,
+ ),
+ ('cancelled', _task(status: 'cancelled'), 0, null),
+ ('stopped', _task(status: 'stopped'), 0, null),
+ (
+ 'closed without shipping',
+ _task(status: 'working', archived: true),
+ 0,
+ null,
+ ),
+ ];
+ for (final (name, task, needsHuman, expected) in cases) {
+ expect(_place(task, needsHuman: needsHuman), expected, reason: name);
+ }
+ });
+
+ test('a tag of the reader marks the task in its own column', () {
+ expect(_place(_task(), mentions: 1), (
+ column: SuperTabTaskColumn.nextUp,
+ needsYou: true,
+ state: null,
+ ));
+ expect(
+ _place(
+ _task(
+ status: 'done',
+ merged: true,
+ shippedAt: _now.subtract(const Duration(days: 1)),
+ ),
+ mentions: 1,
+ ),
+ (column: SuperTabTaskColumn.shipped, needsYou: true, state: 'PR #12'),
+ );
+ });
+
+ group('the board', () {
+ Map<SuperTabTaskColumn, List<String>> ids(
+ Iterable<SuperTabConversation> tasks, {
+ Iterable<SuperTabProposal> proposals = const [],
+ Set<String> tagged = const {},
+ }) => {
+ for (final MapEntry(:key, :value) in superTabTaskBoard(
+ tasks,
+ proposals: proposals,
+ readerId: 'me',
+ now: _now,
+ mentions: (t) => tagged.contains(t.id) ? 1 : 0,
+ ).entries)
+ key: [for (final e in value) e.task?.id ?? e.proposal!.messageId],
+ };
+
+ test('every column is there, empty or not', () {
+ expect(ids(const []).keys, SuperTabTaskColumn.values);
+ expect(ids(const []).values.every((c) => c.isEmpty), isTrue);
+ });
+
+ test('Next up keeps the shared order; a new task joins the bottom', () {
+ final board = ids([
+ _task(id: 'new', number: 30),
+ _task(id: 'third', number: 10, queueRank: 25.5),
+ _task(id: 'first', number: 20, queueRank: 1),
+ _task(id: 'second', number: 5),
+ ]);
+ expect(board[SuperTabTaskColumn.nextUp], [
+ 'first',
+ 'second',
+ 'third',
+ 'new',
+ ]);
+ });
+
+ test('a task that needs the reader comes first in its column', () {
+ final board = ids(
+ [
+ _task(id: 'a', number: 1, status: 'working'),
+ _task(id: 'b', number: 2, status: 'working'),
+ _task(id: 'c', number: 3, status: 'working'),
+ ],
+ tagged: {'a'},
+ );
+ expect(board[SuperTabTaskColumn.working], ['a', 'c', 'b']);
+ });
+
+ test('Shipped is newest first; Proposals oldest first', () {
+ final board = ids(
+ [
+ _task(
+ id: 'old',
+ status: 'done',
+ merged: true,
+ shippedAt: _now.subtract(const Duration(days: 3)),
+ ),
+ _task(
+ id: 'new',
+ status: 'done',
+ shippedAt: _now.subtract(const Duration(hours: 3)),
+ ),
+ ],
+ proposals: [
+ SuperTabProposal.fromJson({
+ 'messageId': 'p2',
+ 'title': 'Later',
+ 'at': _now.millisecondsSinceEpoch,
+ }),
+ SuperTabProposal.fromJson({
+ 'messageId': 'p1',
+ 'title': 'Earlier',
+ 'personId': 'scholes',
+ 'at': _now.subtract(const Duration(days: 9)).millisecondsSinceEpoch,
+ }),
+ ],
+ );
+ expect(board[SuperTabTaskColumn.shipped], ['new', 'old']);
+ expect(board[SuperTabTaskColumn.proposals], ['p1', 'p2']);
+ });
+
+ test('the badge counts the tasks that need the reader', () {
+ final board = superTabTaskBoard(
+ [
+ _task(id: 'a', status: 'working'),
+ _task(
+ id: 'b',
+ status: 'needs_human',
+ liveness: _waiting('person', personId: 'me'),
+ ),
+ _task(id: 'c'),
+ _task(id: 'gone', status: 'cancelled'),
+ ],
+ readerId: 'me',
+ now: _now,
+ mentions: (t) => t.id == 'c' || t.id == 'gone' ? 1 : 0,
+ );
+ expect(superTabTasksNeedingYouIn(board), 2);
+ });
+ });
+}
diff --git a/desktop/test/super_tab_task_groups_shots_test.dart b/desktop/test/super_tab_task_groups_shots_test.dart
deleted file mode 100644
index c1c330544..000000000
--- a/desktop/test/super_tab_task_groups_shots_test.dart
+++ /dev/null
@@ -1,178 +0,0 @@
-import 'dart:io';
-
-import 'package:flutter/material.dart';
-import 'package:flutter/rendering.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:harness/super_tabs/activity.dart';
-import 'package:harness/super_tabs/attention.dart';
-import 'package:harness/super_tabs/project_sidebar.dart';
-import 'package:harness/super_tabs/view.dart';
-
-import 'support/capture.dart';
-import 'support/super_tab_fixture.dart';
-
-/// Set to a folder to write the PR's pictures of the task groups (#2309) there.
-final shots = Platform.environment['SUPER_TAB_SIDEBAR_SHOTS'];
-
-/// A busy project, as Huy's: something waits on the reader, several agents
-/// work, some wait on review or another person, and older tasks rest.
-ConversationServer busyProject() {
- final now = DateTime.now().millisecondsSinceEpoch;
- int ago(int minutes) => now - minutes * 60000;
- final server = ConversationServer();
- server.state['people'] = [
- {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
- {'id': 'ken', 'email': '[email protected]', 'role': 'collaborator'},
- ];
- server.state['projects'] = [
- projectFixture('lead', 'openharness', 'lead'),
- projectFixture('site', 'website', 'site-chat'),
- ];
- var sequence = 0;
- Map<String, dynamic> task(
- String id,
- int number,
- String title, {
- String? status,
- Map<String, dynamic>? liveness,
- bool unread = false,
- }) => {
- ...conversationFixture(id, title),
- 'projectId': 'lead',
- 'number': number,
- 'lastMessageSequence': unread ? ++sequence : 0,
- if (status != null)
- 'assignment': {'agentId': 'a1', 'status': status, 'progressAt': ago(3)},
- 'liveness': ?liveness,
- };
- Map<String, dynamic> waiting(String why, int minutes, {String? personId}) => {
- 'state': 'waiting',
- 'why': why,
- 'since': ago(minutes),
- 'personId': ?personId,
- };
- (server.state['conversations'] as List)
- ..removeWhere((g) => (g as Map)['id'] == 'offline')
- ..addAll(<Map<String, dynamic>>[
- task(
- 't1',
- 2309,
- 'Sidebar: tasks in foldable groups',
- status: 'needs_human',
- liveness: waiting('person', 4, personId: 'owner'),
- unread: true,
- ),
- task(
- 't2',
- 2311,
- 'Web: thread bar on a phone',
- status: 'working',
- unread: true,
- ),
- task('t3', 2307, 'Dial: recap answers at once', status: 'working'),
- task(
- 't4',
- 2305,
- 'Hub reports hide for everyone',
- status: 'working',
- liveness: waiting('starting', 1),
- ),
- task(
- 't5',
- 2304,
- 'Typography pass on Activity',
- status: 'review',
- liveness: waiting('review', 12),
- unread: true,
- ),
- task(
- 't6',
- 2302,
- 'Machine names in review',
- status: 'needs_human',
- liveness: waiting('person', 40, personId: 'ken'),
- ),
- task(
- 't7',
- 2298,
- 'Remove machine privacy',
- status: 'working',
- liveness: {'state': 'quiet', 'since': ago(34)},
- ),
- task('t8', 2290, 'Sidebar groups for Buddy chats', unread: true),
- task('t9', 2287, 'Older: thread pane width'),
- task('t10', 2281, 'Older: release notes copy', status: 'done'),
- {...conversationFixture('site-chat', 'website'), 'projectId': 'site'},
- ]);
- return server;
-}
-
-void main() {
- setUpAll(() => loadCaptureFonts(shots));
-
- for (final brightness in Brightness.values) {
- for (final (name, size) in [
- ('desktop', const Size(1100, 760)),
- ('phone', const Size(390, 844)),
- ]) {
- testWidgets('the task groups at $name width in ${brightness.name}', (
- tester,
- ) async {
- if (shots == null) return;
- final previous = grid.AppTheme.brightness.value;
- grid.AppTheme.brightness.value = brightness;
- addTearDown(() => grid.AppTheme.brightness.value = previous);
- tester.view.devicePixelRatio = 2;
- tester.view.physicalSize = size * 2;
- addTearDown(tester.view.reset);
- final c = busyProject().controller();
- await c.refresh();
- if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');
- await c.select('lead');
- final picture = GlobalKey();
- await tester.pumpWidget(
- MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: brightness),
- home: RepaintBoundary(
- key: picture,
- child: Scaffold(
- // On a phone the web app shows the sidebar on its own.
- body: name == 'phone'
- ? ListenableBuilder(
- listenable: c,
- builder: (context, _) => ProjectSidebar(
- controller: c,
- needsHuman: (_) => 0,
- onSelect: c.select,
- attention: SuperTabAttention.of(c),
- activity: SuperTabActivity.of(c),
- onNotifications: () {},
- ),
- )
- : SuperTabView(
- controller: c,
- onInvite: () {},
- onAddAgent: (_) {},
- onOpenTerminal: (_) {},
- machineName: (_) => 'Team Mac',
- ),
- ),
- ),
- ),
- );
- await tester.pumpAndSettle();
- await captureBoundary(
- tester,
- picture.currentContext!.findRenderObject()! as RenderRepaintBoundary,
- shots,
- 'task-groups-$name-${brightness.name}',
- );
- await tester.pumpWidget(const SizedBox());
- await c.flush();
- c.dispose();
- }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
- }
- }
-}
diff --git a/desktop/test/super_tab_task_groups_test.dart b/desktop/test/super_tab_task_groups_test.dart
index 3bb25b97c..dbc409858 100644
--- a/desktop/test/super_tab_task_groups_test.dart
+++ b/desktop/test/super_tab_task_groups_test.dart
@@ -1,13 +1,10 @@
import 'package:flutter/material.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/attention.dart';
import 'package:harness/super_tabs/controller.dart';
-import 'package:harness/super_tabs/model.dart';
import 'package:harness/super_tabs/project_sidebar.dart';
-import 'package:harness/super_tabs/task_groups.dart';
import 'support/super_tab_fixture.dart';
@@ -74,9 +71,6 @@ Future<SuperTabController> pumpGrouped(
addTearDown(() => tester.binding.setSurfaceSize(null));
final c = server.controller();
await c.refresh();
- for (final project in ['lead', 'alpha']) {
- if (!c.expandedProjects.contains(project)) c.toggleProject(project);
- }
await tester.pumpWidget(
MaterialApp(
theme: grid.buildAppTheme(brightness: Brightness.light),
@@ -105,371 +99,82 @@ Future<void> closeGrouped(WidgetTester tester, SuperTabController c) async {
c.dispose();
}
-Finder heading(String project, SuperTabTaskGroup group) =>
- find.byKey(ValueKey('super-task-group-$project-${group.name}'));
Finder row(String id) => find.byKey(ValueKey('super-group-$id'));
-/// A project's open tasks in the sidebar, in four foldable groups (Huy, #2309): Needs you, Working, Waiting on
-/// others, The rest.
+/// A project's tasks live in its Tasks view (Dee, task #2569): the sidebar
+/// lists no task under a project, its row's badge counts the tasks that need
+/// the reader, and next unread goes from chat to chat.
void main() {
- SuperTabConversation task({String? status, Map<String, dynamic>? liveness}) =>
- SuperTabConversation.fromJson({
- ...conversationFixture('t', 'Task'),
- if (status != null)
- 'assignment': {'agentId': 'a1', 'status': status, 'progressAt': 1},
- 'liveness': ?liveness,
- });
- Map<String, dynamic> waiting(String why, {String? personId}) => {
- 'state': 'waiting',
- 'why': why,
- 'since': 1,
- 'personId': ?personId,
- };
-
- group('which group a task is in', () {
- SuperTabTaskGroup of(
- SuperTabConversation g, {
- int mentions = 0,
- int needsHuman = 0,
- }) => superTabTaskGroupOf(
- g,
- readerId: 'me',
- mentions: mentions,
- needsHuman: needsHuman,
- );
-
- test('the groups read in the sidebar\'s order, The rest folded', () {
- expect(SuperTabTaskGroup.values.map((g) => g.label), [
- 'Needs you',
- 'Working',
- 'Waiting on others',
- 'The rest',
- ]);
- expect(SuperTabTaskGroup.values.where((g) => g.foldedByDefault), [
- SuperTabTaskGroup.rest,
- ]);
+ testWidgets('a project lists no tasks under it, open or closed', (
+ tester,
+ ) async {
+ final server = groupedServer();
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('old', 'old'),
+ 'projectId': 'lead',
+ 'number': 2,
+ 'archived': true,
});
-
- test(
- 'a task that tags the reader needs them, whatever else it waits on',
- () {
- expect(of(task(), mentions: 1), SuperTabTaskGroup.needsYou);
- expect(
- of(
- task(
- status: 'needs_human',
- liveness: waiting('person', personId: 'other'),
- ),
- mentions: 2,
- ),
- SuperTabTaskGroup.needsYou,
- );
- },
+ final c = await pumpGrouped(tester, server);
+ await c.select('lead');
+ await tester.pumpAndSettle();
+ await tester.tap(row('lead'));
+ await tester.pumpAndSettle();
+ for (final id in [
+ 'mine',
+ 'busy-old',
+ 'busy-new',
+ 'review',
+ 'quiet-chat',
+ 'alpha-busy',
+ 'old',
+ ]) {
+ expect(row(id), findsNothing, reason: id);
+ }
+ expect(
+ find.byWidgetPredicate(
+ (w) =>
+ w.key is ValueKey<String> &&
+ ((w.key as ValueKey<String>).value.startsWith(
+ 'super-task-group-',
+ ) ||
+ (w.key as ValueKey<String>).value.startsWith('super-closed-')),
+ ),
+ findsNothing,
);
-
- test('a wait on the reader, or on no one named, needs them', () {
- expect(
- of(
- task(
- status: 'needs_human',
- liveness: waiting('person', personId: 'me'),
- ),
- ),
- SuperTabTaskGroup.needsYou,
- );
- expect(
- of(task(status: 'needs_human', liveness: waiting('person'))),
- SuperTabTaskGroup.needsYou,
- );
- });
-
- test('a question left unanswered past quiet still needs the reader', () {
- // An agent at a question makes no progress: after 30 minutes the
- // backend marks its task quiet (liveness.ts TASK_QUIET_MS).
- expect(
- of(
- task(status: 'working', liveness: {'state': 'quiet', 'since': 1}),
- needsHuman: 1,
- ),
- SuperTabTaskGroup.needsYou,
- );
- });
-
- test('a question in a working task\'s terminal needs the reader', () {
- expect(
- of(task(status: 'working'), needsHuman: 1),
- SuperTabTaskGroup.needsYou,
- );
- });
-
- test('a wait on another person, a review, a revision, a block or a machine waits on others', () {
- for (final g in [
- task(
- status: 'needs_human',
- liveness: waiting('person', personId: 'other'),
- ),
- task(status: 'review', liveness: waiting('review')),
- task(status: 'working', liveness: waiting('revision')),
- task(status: 'blocked', liveness: waiting('blocked')),
- task(status: 'working', liveness: waiting('queued')),
- ]) {
- expect(
- of(g, needsHuman: 1),
- SuperTabTaskGroup.waitingOnOthers,
- reason: '${g.liveness}',
- );
- }
- });
-
- test('a stuck task waits on others: the PM hands it on', () {
- expect(
- of(task(status: 'working', liveness: {'state': 'quiet', 'since': 1})),
- SuperTabTaskGroup.waitingOnOthers,
- );
- expect(
- of(
- task(
- status: 'working',
- liveness: {'state': 'orphaned', 'why': 'lost', 'since': 1},
- ),
- ),
- SuperTabTaskGroup.waitingOnOthers,
- );
- });
-
- test('a task moving or starting its agent is working', () {
- expect(of(task(status: 'working')), SuperTabTaskGroup.working);
- expect(of(task(status: 'planned')), SuperTabTaskGroup.working);
- expect(
- of(task(status: 'working', liveness: waiting('starting'))),
- SuperTabTaskGroup.working,
- );
- });
-
- test('anything else is the rest', () {
- expect(of(task()), SuperTabTaskGroup.rest);
- expect(of(task(status: 'done')), SuperTabTaskGroup.rest);
- expect(of(task(status: 'stopped')), SuperTabTaskGroup.rest);
- expect(
- of(
- task(
- status: 'working',
- liveness: {'state': 'unheard-of', 'since': 1},
- ),
- ),
- SuperTabTaskGroup.rest,
- );
- });
+ expect(row('lead'), findsOneWidget);
+ expect(row('alpha-chat'), findsOneWidget);
+ await closeGrouped(tester, c);
});
- group('the sidebar lists a project\'s tasks in its groups', () {
- testWidgets(
- 'headings in order with their counts, each task under its own, newest first',
- (tester) async {
- final c = await pumpGrouped(tester, groupedServer());
- final top = {
- for (final g in SuperTabTaskGroup.values)
- g: tester.getTopLeft(heading('lead', g)).dy,
- };
- expect(
- SuperTabTaskGroup.values.map((g) => top[g]).toList(),
- orderedEquals([...top.values]..sort()),
- );
- for (final (g, count) in [
- (SuperTabTaskGroup.needsYou, '1'),
- (SuperTabTaskGroup.working, '2'),
- (SuperTabTaskGroup.waitingOnOthers, '1'),
- (SuperTabTaskGroup.rest, '1'),
- ]) {
- expect(
- find.descendant(
- of: heading('lead', g),
- matching: find.text(g.label),
- ),
- findsOneWidget,
- );
- expect(
- find.descendant(of: heading('lead', g), matching: find.text(count)),
- findsOneWidget,
- reason: g.label,
- );
- }
- double y(String id) => tester.getTopLeft(row(id)).dy;
- expect(y('mine'), greaterThan(top[SuperTabTaskGroup.needsYou]!));
- expect(y('mine'), lessThan(top[SuperTabTaskGroup.working]!));
- expect(y('busy-new'), greaterThan(top[SuperTabTaskGroup.working]!));
- expect(y('busy-new'), lessThan(y('busy-old')));
- expect(
- y('busy-old'),
- lessThan(top[SuperTabTaskGroup.waitingOnOthers]!),
- );
- expect(
- y('review'),
- greaterThan(top[SuperTabTaskGroup.waitingOnOthers]!),
- );
- expect(y('review'), lessThan(top[SuperTabTaskGroup.rest]!));
- await closeGrouped(tester, c);
- },
- );
-
- testWidgets(
- 'The rest starts folded; its heading shows and hides its tasks',
- (tester) async {
- final c = await pumpGrouped(tester, groupedServer());
- expect(heading('lead', SuperTabTaskGroup.rest), findsOneWidget);
- expect(row('quiet-chat'), findsNothing);
- await tester.tap(heading('lead', SuperTabTaskGroup.rest));
- await tester.pumpAndSettle();
- expect(row('quiet-chat'), findsOneWidget);
- await tester.tap(heading('lead', SuperTabTaskGroup.rest));
- await tester.pumpAndSettle();
- expect(row('quiet-chat'), findsNothing);
- await closeGrouped(tester, c);
- },
- );
-
- testWidgets(
- 'a fold is the project\'s own, and outlasts hiding the project',
- (tester) async {
- final c = await pumpGrouped(tester, groupedServer());
- await tester.tap(heading('lead', SuperTabTaskGroup.working));
- await tester.pumpAndSettle();
- expect(row('busy-new'), findsNothing);
- expect(row('alpha-busy'), findsOneWidget);
- c.toggleProject('lead');
- await tester.pumpAndSettle();
- expect(heading('lead', SuperTabTaskGroup.working), findsNothing);
- c.toggleProject('lead');
- await tester.pumpAndSettle();
- expect(heading('lead', SuperTabTaskGroup.working), findsOneWidget);
- expect(row('busy-new'), findsNothing);
- await closeGrouped(tester, c);
- },
- );
-
- testWidgets(
- 'the open chat in a folded group still shows under its heading',
- (tester) async {
- final c = await pumpGrouped(tester, groupedServer());
- await c.select('quiet-chat');
- await tester.pumpAndSettle();
- expect(row('quiet-chat'), findsOneWidget);
- expect(
- tester.getTopLeft(row('quiet-chat')).dy,
- greaterThan(
- tester.getTopLeft(heading('lead', SuperTabTaskGroup.rest)).dy,
- ),
- );
- await closeGrouped(tester, c);
- },
- );
-
- testWidgets(
- 'under the unread filter, groups list only unread tasks and count those',
- (tester) async {
- final server = groupedServer();
- for (final g
- in (server.state['conversations'] as List)
- .cast<Map<String, dynamic>>()) {
- // A person wrote there: what the filter counts, as the bold does
- // (#2427).
- if (g['id'] == 'busy-old' || g['id'] == 'quiet-chat') {
- g['lastMessageSequence'] = 5;
- g['lastPersonSequence'] = 5;
- }
- }
- final c = await pumpGrouped(tester, server);
- c.toggleUnreadOnly();
- await tester.pumpAndSettle();
- expect(heading('lead', SuperTabTaskGroup.needsYou), findsNothing);
- expect(
- heading('lead', SuperTabTaskGroup.waitingOnOthers),
- findsNothing,
- );
- expect(row('busy-old'), findsOneWidget);
- expect(row('busy-new'), findsNothing);
- expect(
- find.descendant(
- of: heading('lead', SuperTabTaskGroup.working),
- matching: find.text('1'),
- ),
- findsOneWidget,
- );
- expect(
- find.descendant(
- of: heading('lead', SuperTabTaskGroup.rest),
- matching: find.text('1'),
- ),
- findsOneWidget,
- );
- expect(row('quiet-chat'), findsNothing);
- await closeGrouped(tester, c);
- },
+ testWidgets('a project\'s badge adds the tasks that need the reader', (
+ tester,
+ ) async {
+ final c = await pumpGrouped(tester, groupedServer());
+ // `mine` waits on the reader by name; nothing in alpha does.
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('super-mentions-lead')),
+ matching: find.text('1'),
+ ),
+ findsOneWidget,
);
-
- testWidgets('Tab reaches a heading, and Enter folds it', (tester) async {
- final c = await pumpGrouped(tester, groupedServer());
- const key = ValueKey('super-task-group-lead-needsYou');
- bool onHeading() {
- final focused = tester.binding.focusManager.primaryFocus?.context;
- if (focused == null) return false;
- var found = focused.widget.key == key;
- focused.visitAncestorElements((e) {
- if (e.widget.key == key) found = true;
- return !found;
- });
- return found;
- }
-
- for (var i = 0; i < 60 && !onHeading(); i++) {
- await tester.sendKeyEvent(LogicalKeyboardKey.tab);
- await tester.pump();
- }
- expect(onHeading(), isTrue);
- expect(row('mine'), findsOneWidget);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(row('mine'), findsNothing);
- await closeGrouped(tester, c);
- });
-
- testWidgets(
- 'a phone-wide sidebar, as the web app draws it on a phone, shows the same groups',
- (tester) async {
- final c = await pumpGrouped(
- tester,
- groupedServer(),
- size: const Size(390, 844),
- );
- for (final g in SuperTabTaskGroup.values) {
- expect(heading('lead', g), findsOneWidget, reason: g.label);
- }
- expect(tester.takeException(), isNull);
- await closeGrouped(tester, c);
- },
+ expect(
+ find.byKey(const ValueKey('super-mentions-alpha-chat')),
+ findsNothing,
);
+ await closeGrouped(tester, c);
});
- group('next unread follows the groups', () {
- testWidgets(
- 'each project\'s chat, then its tasks in group order, each group newest first',
- (tester) async {
- final server = groupedServer();
- final c = server.controller();
- await c.refresh();
- expect(superTabSidebarOrder(c), [
- 'alpha-chat',
- 'alpha-busy',
- 'lead',
- 'mine',
- 'busy-new',
- 'busy-old',
- 'review',
- 'quiet-chat',
- ]);
- await c.flush();
- c.dispose();
- },
- );
- });
+ test(
+ 'next unread goes from project chat to project chat, past tasks',
+ () async {
+ final server = groupedServer();
+ final c = server.controller();
+ await c.refresh();
+ expect(superTabSidebarOrder(c), ['alpha-chat', 'lead']);
+ await c.flush();
+ c.dispose();
+ },
+ );
}
diff --git a/desktop/test/super_tab_task_status_shots_test.dart b/desktop/test/super_tab_task_status_shots_test.dart
deleted file mode 100644
index 932a70492..000000000
--- a/desktop/test/super_tab_task_status_shots_test.dart
+++ /dev/null
@@ -1,146 +0,0 @@
-import 'dart:io';
-
-import 'package:clock/clock.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/view.dart';
-import 'package:harness/terminal/terminal_typography.dart';
-
-import 'support/capture.dart';
-import 'support/humans_fixture.dart';
-import 'support/super_tab_fixture.dart';
-
-/// Set to a folder to write the PR's pictures of the task status lines there.
-final shots = Platform.environment['SUPER_TAB_TASK_SHOTS'];
-
-/// The four rows of the mockup Ken approved (#957), in both appearances.
-void main() {
- setUpAll(() async {
- await loadCaptureFonts(shots);
- if (shots == null || !Platform.isMacOS) return;
- // The marks are drawn in the status bar's monospace, with the OS symbol
- // font for the spinner's Braille, as on a Mac.
- Future<void> face(String family, String path) async {
- final bytes = ByteData.sublistView(await File(path).readAsBytes());
- await (FontLoader(family)..addFont(Future.value(bytes))).load();
- }
-
- for (final family in {terminalFontFamily, ...terminalFontFallback}) {
- await face(family, '/System/Library/Fonts/SFNSMono.ttf');
- }
- await face('Apple Symbols', '/System/Library/Fonts/Apple Symbols.ttf');
- });
- // The real clock: the rows are drawn again as the picture is taken.
- final now = DateTime.now().toUtc();
- int ago(int minutes) =>
- now.subtract(Duration(minutes: minutes)).millisecondsSinceEpoch;
-
- for (final brightness in Brightness.values) {
- testWidgets('task status lines in ${brightness.name}', (tester) async {
- if (shots == null) return;
- final previous = grid.AppTheme.brightness.value;
- grid.AppTheme.brightness.value = brightness;
- addTearDown(() => grid.AppTheme.brightness.value = previous);
- tester.view.devicePixelRatio = 2;
- tester.view.physicalSize = const Size(2400, 1200);
- addTearDown(tester.view.reset);
- final server = humansSwarm();
- Map<String, dynamic> task(
- String id,
- int number,
- String title,
- Map<String, dynamic>? assignment, {
- Map<String, dynamic>? liveness,
- Map<String, dynamic>? leadAction,
- }) => {
- ...conversationFixture(id, title),
- 'number': number,
- 'assignment': assignment,
- 'liveness': ?liveness,
- 'leadAction': ?leadAction,
- };
- Map<String, dynamic> work(String status, {String? result, int? at}) => {
- 'id': 'a-$status',
- 'agentId': 'w',
- 'status': status,
- 'result': result,
- 'progressAt': ?at,
- };
- (server.state['conversations'] as List)
- ..removeWhere((g) => (g as Map)['id'] == 'offline')
- ..addAll(<Map<String, dynamic>>[
- task('ws', 931, 'WS Phase 1a', work('working', at: ago(4))),
- task(
- 'buddies',
- 937,
- 'Buddies leave Agents list',
- work('needs_human', result: 'mockup OK?'),
- liveness: {
- 'state': 'waiting',
- 'why': 'person',
- 'since': ago(12),
- 'personId': 'owner',
- },
- ),
- task(
- 'codex',
- 294,
- 'Codex update screen',
- null,
- liveness: {'state': 'waiting', 'why': 'queued', 'since': ago(25)},
- leadAction: {'kind': 'route', 'at': ago(2)},
- ),
- task(
- 'security',
- 919,
- 'Security review 2',
- work('working', at: ago(34)),
- liveness: {'state': 'quiet', 'why': 'silent', 'since': ago(34)},
- leadAction: {'kind': 'assign', 'at': ago(1)},
- ),
- ]);
- final c = server.controller(
- account: 'peer',
- initial: {'tabId': 'tab', 'accountId': 'peer', 'selectedId': 'lead'},
- );
- await c.refresh();
- c.expandedProjects.add('lead');
- final picture = GlobalKey();
- await withClock(
- Clock.fixed(now),
- () => tester.pumpWidget(
- MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: brightness),
- home: RepaintBoundary(
- key: picture,
- child: Scaffold(
- body: SuperTabView(
- controller: c,
- onInvite: () {},
- onAddAgent: (_) {},
- onOpenTerminal: (_) {},
- machineName: (_) => 'Studio',
- ),
- ),
- ),
- ),
- ),
- );
- // The working mark spins, so the page never settles.
- await tester.pump(const Duration(milliseconds: 100));
- await captureBoundary(
- tester,
- picture.currentContext!.findRenderObject()! as RenderRepaintBoundary,
- shots,
- 'task-status-${brightness.name}',
- );
- await tester.pumpWidget(const SizedBox());
- await c.flush();
- c.dispose();
- }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
- }
-}
diff --git a/desktop/test/super_tab_task_status_test.dart b/desktop/test/super_tab_task_status_test.dart
index 49d006bed..d39aeafb6 100644
--- a/desktop/test/super_tab_task_status_test.dart
+++ b/desktop/test/super_tab_task_status_test.dart
@@ -2,14 +2,11 @@ import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/harness_activity.dart';
import 'package:harness/super_tabs/model.dart';
import 'package:harness/super_tabs/task_status.dart';
-import 'package:harness/super_tabs/view.dart';
import 'package:harness/widgets/harness_activity_mark.dart';
-import 'support/humans_fixture.dart';
import 'support/super_tab_fixture.dart';
/// The line under each task row (#957, the mockup Ken approved): whether the
@@ -306,87 +303,6 @@ void main() {
}
});
- testWidgets(
- // One line per task (Huy, 11-03, #2427): its state is the mark at its right, the tooltip and what a screen reader
- // hears; no line under its name.
- 'a task row in the sidebar is one line, its mark at its right, its state in the tooltip and spoken, naming the person',
- (tester) async {
- await tester.binding.setSurfaceSize(const Size(1300, 900));
- addTearDown(() => tester.binding.setSurfaceSize(null));
- final server = humansSwarm();
- final group = (server.state['conversations'] as List)
- .cast<Map<String, dynamic>>()
- .firstWhere((g) => g['id'] == 'offline');
- group['assignment'] = {
- 'id': 'a',
- 'agentId': 'w',
- 'status': 'needs_human',
- 'result': 'mockup OK?',
- };
- group['liveness'] = state(
- 'waiting',
- 'person',
- minute * 12,
- personId: 'owner',
- );
- final controller = server.controller(
- account: 'peer',
- initial: {'tabId': 'tab', 'accountId': 'peer', 'selectedId': 'lead'},
- );
- await controller.refresh();
- controller.expandedProjects.add('lead');
- await withClock(
- Clock.fixed(now),
- () => tester.pumpWidget(
- MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.light),
- home: Scaffold(
- body: SuperTabView(
- controller: controller,
- onInvite: () {},
- onAddAgent: (_) {},
- onOpenTerminal: (_) {},
- machineName: (_) => 'Studio',
- ),
- ),
- ),
- ),
- );
- final row = find.byKey(const ValueKey('super-group-offline'));
- expect(
- find.descendant(
- of: row,
- matching: find.byKey(const ValueKey('super-task-line-offline')),
- ),
- findsNothing,
- );
- expect(
- find.descendant(
- of: row,
- matching: find.bySemanticsLabel(
- RegExp('Waiting on ken · mockup OK\\? · 12m'),
- ),
- ),
- findsOneWidget,
- );
- expect(
- find.descendant(
- of: row,
- matching: find.byKey(const ValueKey('super-task-mark-offline')),
- ),
- findsOneWidget,
- );
- // A line the sidebar cuts short is whole in the row's tooltip.
- expect(
- find.byTooltip('Offline editing\nWaiting on ken · mockup OK? · 12m'),
- findsOneWidget,
- );
- await tester.pumpWidget(const SizedBox());
- await controller.flush();
- controller.dispose();
- },
- );
-
testWidgets(
'nothing for finished work, a group without work, or a wait an older backend sent no state for',
(tester) async {
diff --git a/desktop/test/super_tab_tasks_header_test.dart b/desktop/test/super_tab_tasks_header_test.dart
new file mode 100644
index 000000000..12b5905a5
--- /dev/null
+++ b/desktop/test/super_tab_tasks_header_test.dart
@@ -0,0 +1,100 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/widgets/app_icon_button.dart';
+import 'package:harness/super_tabs/buddy_rows.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'super_tab_tasks_view_test.dart' show tasksServer;
+import 'support/super_tab_fixture.dart';
+
+Finder _key(String key) => find.byKey(ValueKey(key));
+
+Future<SuperTabController> _showView(
+ WidgetTester tester,
+ ConversationServer server,
+) async {
+ await tester.binding.setSurfaceSize(const Size(1500, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.light),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return c;
+}
+
+bool _selected(WidgetTester tester) =>
+ tester.widget<AppIconButton>(_key('super-tasks')).selected == true;
+
+/// The project header's Tasks icon (Dee, task #2569): it opens the project's
+/// Tasks view, with a red count of the tasks that need the reader.
+void main() {
+ testWidgets('the project header reads Terminals, Tasks, then Members', (
+ tester,
+ ) async {
+ await _showView(tester, tasksServer());
+ double x(String key) => tester.getCenter(_key(key)).dx;
+ expect(x('super-terminals'), lessThan(x('super-tasks')));
+ expect(x('super-tasks'), lessThan(x('super-members-button')));
+ });
+
+ testWidgets('a red count of the tasks that need the reader, none at 0', (
+ tester,
+ ) async {
+ await _showView(tester, tasksServer());
+ expect(
+ tester.widget<SuperTabCountBadge>(_key('super-tasks-badge')).count,
+ 1,
+ );
+ await tester.pumpWidget(const SizedBox());
+ await _showView(tester, tasksServer(empty: true));
+ expect(_key('super-tasks'), findsOneWidget);
+ expect(_key('super-tasks-badge'), findsNothing);
+ });
+
+ testWidgets('Tasks opens the Board, and Chat goes back to the chat', (
+ tester,
+ ) async {
+ await _showView(tester, tasksServer());
+ expect(_key('super-tasks-column-working'), findsNothing);
+ await tester.tap(_key('super-tasks'));
+ await tester.pumpAndSettle();
+ expect(_key('super-tasks-column-working'), findsOneWidget);
+ expect(_selected(tester), isTrue);
+ await tester.tap(_key('super-chat'));
+ await tester.pumpAndSettle();
+ expect(_key('super-tasks-column-working'), findsNothing);
+ expect(_selected(tester), isFalse);
+ });
+
+ testWidgets('a card opens its task with Tasks selected; Tasks brings the '
+ 'board back', (tester) async {
+ final c = await _showView(tester, tasksServer());
+ await tester.tap(_key('super-tasks'));
+ await tester.pumpAndSettle();
+ await tester.tap(_key('super-task-card-tag'));
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'tag');
+ expect(_key('super-tasks-column-working'), findsNothing);
+ expect(_selected(tester), isTrue);
+ await tester.tap(_key('super-tasks'));
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'lead');
+ expect(_key('super-tasks-column-working'), findsOneWidget);
+ });
+}
diff --git a/desktop/test/super_tab_tasks_shots_test.dart b/desktop/test/super_tab_tasks_shots_test.dart
new file mode 100644
index 000000000..07ebfb8e9
--- /dev/null
+++ b/desktop/test/super_tab_tasks_shots_test.dart
@@ -0,0 +1,94 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/view.dart';
+
+import 'super_tab_tasks_view_test.dart' show tasksServer, taskFixture;
+import 'support/capture.dart';
+
+/// Set to a folder to write the PR's screenshots there.
+final shots = Platform.environment['SUPER_TAB_TASKS_SHOTS'];
+
+/// A project's Tasks view as the PR shows it (Dee, task #2569): Board and
+/// List, in both appearances, with a Needs-you card and the header's count.
+void main() {
+ setUpAll(() => loadCaptureFonts(shots));
+
+ for (final brightness in Brightness.values) {
+ for (final layout in ['board', 'list']) {
+ testWidgets('screenshots for review ($layout, ${brightness.name})', (
+ tester,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(1440, 820));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final before = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = before);
+ final server = tasksServer();
+ (server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
+ taskFixture(
+ 'dial',
+ 'Dial thread alerts',
+ 15,
+ requester: 'scholes',
+ status: 'working',
+ ),
+ taskFixture(
+ 'grouping',
+ 'Task chat grouping',
+ 16,
+ requester: 'scholes',
+ status: 'review',
+ liveness: {'state': 'waiting', 'why': 'review', 'since': 1},
+ ),
+ taskFixture(
+ 'long',
+ 'A long title that takes both of its two lines on the board, and '
+ 'then some more words that are cut',
+ 17,
+ requester: 'tony',
+ ),
+ ]);
+ // A promise the PM keeps, as the mockup's preview route.
+ (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((g) => g['id'] == 'preview')
+ ..['notBefore'] = '2026-12-04'
+ ..['requesterId'] = 'ken';
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('super-tasks')));
+ await tester.pumpAndSettle();
+ if (layout == 'list') {
+ await tester.tap(
+ find.byKey(const ValueKey('super-tasks-layout-list')),
+ );
+ await tester.pumpAndSettle();
+ }
+ expect(find.text('Needs you'), findsOneWidget);
+ expect(find.byKey(const ValueKey('super-tasks-badge')), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await captureWindow(tester, shots, 'tasks-$layout-${brightness.name}');
+ });
+ }
+ }
+}
diff --git a/desktop/test/super_tab_tasks_view_test.dart b/desktop/test/super_tab_tasks_view_test.dart
new file mode 100644
index 000000000..19a6d2c47
--- /dev/null
+++ b/desktop/test/super_tab_tasks_view_test.dart
@@ -0,0 +1,630 @@
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.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/controller.dart';
+import 'package:harness/super_tabs/tasks_view.dart';
+
+import 'support/memory_key_value_store.dart';
+import 'support/super_tab_fixture.dart';
+
+final _now = DateTime(2026, 11, 4, 9);
+const _repo = 'https://github.com/autonomous-ai/openharness/pull';
+
+Map<String, dynamic> taskFixture(
+ String id,
+ String title,
+ int number, {
+ String? requester,
+ String? status,
+ String? agent,
+ Map<String, dynamic>? liveness,
+ int? pullRequest,
+ bool merged = false,
+ bool archived = false,
+ DateTime? shippedAt,
+}) => {
+ ...conversationFixture(id, title),
+ 'projectId': 'lead',
+ 'number': number,
+ 'archived': archived,
+ 'requesterId': ?requester,
+ if (status != null)
+ 'assignment': {
+ 'id': 'as-$id',
+ 'agentId': agent ?? 'finch',
+ 'status': status,
+ 'progressAt': 1,
+ },
+ 'liveness': ?liveness,
+ if (pullRequest != null) ...{
+ 'pullRequestUrls': ['$_repo/$pullRequest'],
+ 'cards': {
+ 'pullRequests': [
+ {
+ 'url': '$_repo/$pullRequest',
+ 'messageId': 'pr-$id',
+ if (merged) 'mergedAt': 1,
+ },
+ ],
+ },
+ },
+ if (shippedAt != null) 'shippedAt': shippedAt.millisecondsSinceEpoch,
+};
+
+/// The project of the mockup Dee confirmed: a proposal, two tasks nobody is on
+/// yet, one working with its pull request, one waiting on the reader, and one
+/// shipped two days ago and archived since.
+ConversationServer tasksServer({bool empty = false}) {
+ final server = ConversationServer();
+ server.state['projects'] = [projectFixture('lead', 'openharness', 'lead')];
+ // The backend's read of the project's unanswered proposals (#2867's rule).
+ if (!empty) {
+ server.proposals['lead'] = [
+ {
+ 'messageId': 'p-new',
+ 'title': 'Rename a Swarm from the phone',
+ 'personId': 'tony',
+ 'at': _now.subtract(const Duration(minutes: 23)).millisecondsSinceEpoch,
+ },
+ {
+ 'messageId': 'p-old',
+ 'title': 'Backlog shows nothing in Mine',
+ 'personId': 'scholes',
+ 'at': _now
+ .subtract(const Duration(minutes: 3, days: 2))
+ .millisecondsSinceEpoch,
+ },
+ ];
+ }
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ {'id': 'scholes', 'email': '[email protected]', 'role': 'member'},
+ {'id': 'tony', 'email': '[email protected]', 'role': 'member'},
+ {'id': 'ken', 'email': '[email protected]', 'role': 'member'},
+ ];
+ server.state['agents'] = [
+ {
+ 'id': 'finch',
+ 'name': 'Engineer',
+ 'displayName': 'Finch2',
+ 'machineId': 'studio',
+ 'harnessId': 'h1',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ },
+ ];
+ (server.state['conversations'] as List).removeWhere(
+ (g) => (g as Map)['id'] == 'offline',
+ );
+ if (!empty) {
+ (server.state['conversations'] as List)..addAll(<Map<String, dynamic>>[
+ taskFixture(
+ 'shipped-means',
+ 'Shipped means merged',
+ 10,
+ requester: 'scholes',
+ ),
+ taskFixture('preview', 'Remove the old preview route', 11),
+ taskFixture(
+ 'tag',
+ 'One tag per ask',
+ 12,
+ requester: 'owner',
+ status: 'working',
+ pullRequest: 2867,
+ ),
+ taskFixture(
+ 'test-copy',
+ 'First run of the test copy',
+ 13,
+ requester: 'ken',
+ status: 'needs_human',
+ liveness: {
+ 'state': 'waiting',
+ 'why': 'person',
+ 'personId': 'owner',
+ 'since': 1,
+ },
+ ),
+ taskFixture(
+ 'sender',
+ 'Task chat keeps its sender',
+ 9,
+ requester: 'scholes',
+ status: 'done',
+ pullRequest: 2870,
+ merged: true,
+ archived: true,
+ shippedAt: _now.subtract(const Duration(days: 2)),
+ ),
+ ]);
+ }
+ return server;
+}
+
+Finder _column(String name) => find.byKey(ValueKey('super-tasks-column-$name'));
+Finder _card(String id) => find.byKey(ValueKey('super-task-card-$id'));
+
+Future<SuperTabController> _show(
+ WidgetTester tester,
+ ConversationServer server, {
+ MemoryKeyValueStore? storage,
+ List<String>? opened,
+ List<String>? openedProposals,
+ Set<String> asking = const {},
+}) async {
+ await tester.binding.setSurfaceSize(const Size(1400, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.light),
+ home: Scaffold(
+ body: SuperTabTasksView(
+ controller: c,
+ project: c.snapshot!.projects.single,
+ storage: storage ?? MemoryKeyValueStore(),
+ needsHuman: (task) => asking.contains(task.id) ? 1 : 0,
+ onOpenTask: (id) => opened?.add(id),
+ onOpenProposal: (id) => openedProposals?.add(id),
+ now: () => _now,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return c;
+}
+
+Future<void> _close(WidgetTester tester, SuperTabController c) async {
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+}
+
+List<String> _cardsIn(WidgetTester tester, String column) {
+ final cards = find.descendant(
+ of: _column(column),
+ matching: find.byWidgetPredicate(
+ (w) =>
+ w.key is ValueKey<String> &&
+ (w.key as ValueKey<String>).value.startsWith('super-task-card-'),
+ ),
+ );
+ final found = [
+ for (final e in cards.evaluate())
+ (
+ (e.widget.key as ValueKey<String>).value.substring(
+ 'super-task-card-'.length,
+ ),
+ tester.getTopLeft(find.byWidget(e.widget)).dy,
+ ),
+ ]..sort((a, b) => a.$2.compareTo(b.$2));
+ return [for (final (id, _) in found) id];
+}
+
+/// A project's Tasks view (Dee, task #2569): Board by default, or List, with
+/// Mine and Search, every ask from proposal to shipped.
+void main() {
+ testWidgets('Board shows the five columns in order, each with its count', (
+ tester,
+ ) async {
+ final c = await _show(tester, tasksServer());
+ final names = ['proposals', 'nextUp', 'working', 'waiting', 'shipped'];
+ final lefts = [for (final n in names) tester.getTopLeft(_column(n)).dx];
+ expect(lefts, orderedEquals([...lefts]..sort()));
+ for (final (name, label, count) in [
+ ('proposals', 'Proposals', '2'),
+ ('nextUp', 'Next up', '2'),
+ ('working', 'Working', '1'),
+ ('waiting', 'Waiting', '1'),
+ ('shipped', 'Shipped', '1'),
+ ]) {
+ final heading = find.byKey(ValueKey('super-tasks-heading-$name'));
+ expect(
+ find.descendant(of: heading, matching: find.text(label)),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: heading, matching: find.text(count)),
+ findsOneWidget,
+ reason: label,
+ );
+ }
+ await _close(tester, c);
+ });
+
+ testWidgets('an empty column keeps its heading with 0', (tester) async {
+ final server = tasksServer();
+ (server.state['conversations'] as List).removeWhere(
+ (g) => (g as Map)['id'] == 'tag',
+ );
+ final c = await _show(tester, server);
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('super-tasks-heading-working')),
+ matching: find.text('0'),
+ ),
+ findsOneWidget,
+ );
+ await _close(tester, c);
+ });
+
+ testWidgets('a project with no tasks says so', (tester) async {
+ final c = await _show(tester, tasksServer(empty: true));
+ expect(find.text('No tasks yet'), findsOneWidget);
+ expect(_column('proposals'), findsNothing);
+ await _close(tester, c);
+ });
+
+ testWidgets('cards read the title, then requester · agent · state', (
+ tester,
+ ) async {
+ final c = await _show(tester, tasksServer());
+ Finder inCard(String id, String text) =>
+ find.descendant(of: _card(id), matching: find.text(text));
+ expect(inCard('tag', 'One tag per ask'), findsOneWidget);
+ expect(inCard('tag', 'dee · Finch2 · PR #2867'), findsOneWidget);
+ expect(inCard('shipped-means', 'scholes'), findsOneWidget);
+ expect(inCard('sender', 'scholes · Finch2 · PR #2870'), findsOneWidget);
+ expect(
+ inCard('test-copy', 'ken15 · Finch2 · dee to decide'),
+ findsOneWidget,
+ );
+ // No task numbers, machines or models.
+ expect(find.textContaining('#12'), findsNothing);
+ expect(find.textContaining('studio'), findsNothing);
+ expect(find.textContaining('claude'), findsNothing);
+ await _close(tester, c);
+ });
+
+ testWidgets('a task that needs the reader says so, first in its column', (
+ tester,
+ ) async {
+ final server = tasksServer();
+ (server.state['conversations'] as List).add(
+ taskFixture(
+ 'later',
+ 'Dial thread alerts',
+ 20,
+ status: 'review',
+ liveness: {'state': 'waiting', 'why': 'review', 'since': 1},
+ ),
+ );
+ final c = await _show(tester, server);
+ expect(_cardsIn(tester, 'waiting'), ['test-copy', 'later']);
+ expect(
+ find.descendant(of: _card('test-copy'), matching: find.text('Needs you')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: _card('later'), matching: find.text('Needs you')),
+ findsNothing,
+ );
+ await _close(tester, c);
+ });
+
+ testWidgets('Proposals lists the unanswered ones oldest first', (
+ tester,
+ ) async {
+ final opened = <String>[];
+ final c = await _show(tester, tasksServer(), openedProposals: opened);
+ expect(_cardsIn(tester, 'proposals'), ['p-old', 'p-new']);
+ expect(
+ find.descendant(of: _card('p-new'), matching: find.text('tony · 23m')),
+ findsOneWidget,
+ );
+ await tester.tap(_card('p-old'));
+ expect(opened, ['p-old']);
+ await _close(tester, c);
+ });
+
+ testWidgets('a card click opens its task', (tester) async {
+ final opened = <String>[];
+ final c = await _show(tester, tasksServer(), opened: opened);
+ await tester.tap(_card('tag'));
+ expect(opened, ['tag']);
+ await _close(tester, c);
+ });
+
+ testWidgets('List shows the same groups as sections, Shipped folded', (
+ tester,
+ ) async {
+ final c = await _show(tester, tasksServer());
+ await tester.tap(find.byKey(const ValueKey('super-tasks-layout-list')));
+ await tester.pumpAndSettle();
+ final names = ['proposals', 'nextUp', 'working', 'waiting', 'shipped'];
+ final tops = [
+ for (final n in names)
+ tester.getTopLeft(find.byKey(ValueKey('super-tasks-heading-$n'))).dy,
+ ];
+ expect(tops, orderedEquals([...tops]..sort()));
+ expect(_card('tag'), findsOneWidget);
+ expect(_card('sender'), findsNothing);
+ await tester.tap(find.byKey(const ValueKey('super-tasks-heading-shipped')));
+ await tester.pumpAndSettle();
+ expect(_card('sender'), findsOneWidget);
+ await _close(tester, c);
+ });
+
+ testWidgets('Mine keeps the reader\'s asks; Search keeps matching titles', (
+ tester,
+ ) async {
+ final c = await _show(tester, tasksServer());
+ await tester.tap(find.byKey(const ValueKey('super-tasks-mine')));
+ await tester.pumpAndSettle();
+ expect(_card('tag'), findsOneWidget);
+ expect(_card('test-copy'), findsNothing);
+ expect(_card('p-old'), findsNothing);
+ await tester.tap(find.byKey(const ValueKey('super-tasks-mine')));
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const ValueKey('super-tasks-search')),
+ 'preview',
+ );
+ await tester.pumpAndSettle();
+ expect(_card('preview'), findsOneWidget);
+ expect(_card('tag'), findsNothing);
+ expect(_card('p-old'), findsNothing);
+ await _close(tester, c);
+ });
+
+ testWidgets('List and Mine are remembered for the reader on this Mac', (
+ tester,
+ ) async {
+ final storage = MemoryKeyValueStore();
+ var c = await _show(tester, tasksServer(), storage: storage);
+ await tester.tap(find.byKey(const ValueKey('super-tasks-layout-list')));
+ await tester.tap(find.byKey(const ValueKey('super-tasks-mine')));
+ await tester.pumpAndSettle();
+ await _close(tester, c);
+ c = await _show(tester, tasksServer(), storage: storage);
+ // List draws Shipped folded and the board's columns not at all.
+ expect(_column('working'), findsNothing);
+ expect(_card('tag'), findsOneWidget);
+ expect(_card('test-copy'), findsNothing);
+ await _close(tester, c);
+ });
+
+ testWidgets('a card moves as its work moves, with no reload', (tester) async {
+ final server = tasksServer();
+ final c = await _show(tester, server);
+ expect(_cardsIn(tester, 'nextUp'), contains('preview'));
+ final preview = (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((g) => g['id'] == 'preview');
+ preview['assignment'] = {
+ 'id': 'as-preview',
+ 'agentId': 'finch',
+ 'status': 'working',
+ 'progressAt': 1,
+ };
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(_cardsIn(tester, 'nextUp'), isNot(contains('preview')));
+ expect(_cardsIn(tester, 'working'), contains('preview'));
+ await _close(tester, c);
+ });
+
+ testWidgets('a new proposal shows once the chat moves, at most a read a '
+ 'minute', (tester) async {
+ final server = tasksServer();
+ final c = await _show(tester, server);
+ final reads = server.proposalReads.length;
+ await c.refresh();
+ await tester.pumpAndSettle();
+ // Nothing moved in the chat: nothing is read again.
+ expect(server.proposalReads.length, reads);
+ server.proposals['lead']!.add({
+ 'messageId': 'p-newest',
+ 'title': 'Device as your Buddy',
+ 'personId': 'owner',
+ 'at': _now.millisecondsSinceEpoch,
+ });
+ server.append('Device as your Buddy');
+ await c.refresh();
+ await tester.pumpAndSettle();
+ // Within a minute of the last read: it waits (PM, 2026-11-04).
+ expect(server.proposalReads.length, reads);
+ expect(_cardsIn(tester, 'proposals'), ['p-old', 'p-new']);
+ server.append('and another');
+ await c.refresh();
+ await tester.pump(const Duration(minutes: 1));
+ await tester.pumpAndSettle();
+ // One read for both moves.
+ expect(server.proposalReads.length, reads + 1);
+ expect(_cardsIn(tester, 'proposals'), ['p-old', 'p-new', 'p-newest']);
+ await _close(tester, c);
+ });
+
+ testWidgets(
+ 'an older server with no proposals read leaves the column empty',
+ (tester) async {
+ final server = tasksServer()..proposalsUnsupported = true;
+ final c = await _show(tester, server);
+ expect(_cardsIn(tester, 'proposals'), isEmpty);
+ expect(_card('tag'), findsOneWidget);
+ await _close(tester, c);
+ },
+ );
+
+ group('Next up, in the shared order', () {
+ ConversationServer queued() {
+ final server = tasksServer();
+ (server.state['conversations'] as List).add(
+ taskFixture('third', 'Rename the round dial', 14),
+ );
+ return server;
+ }
+
+ Iterable<Map> moves(ConversationServer server) => [
+ for (final post in server.posts)
+ if ((post['command'] as Map?)?['type'] == 'work.queue')
+ post['command'] as Map,
+ ];
+
+ Future<void> dragTo(WidgetTester tester, String id, Offset to) async {
+ final gesture = await tester.startGesture(tester.getCenter(_card(id)));
+ await tester.pump(kLongPressTimeout);
+ for (var i = 1; i <= 10; i++) {
+ final from = tester.getCenter(_card(id));
+ await gesture.moveTo(Offset.lerp(from, to, i / 10)!);
+ await tester.pump(const Duration(milliseconds: 16));
+ }
+ await gesture.up();
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets('a drag to the top sets the order for everyone, and it holds', (
+ tester,
+ ) async {
+ final server = queued();
+ var c = await _show(tester, server);
+ expect(_cardsIn(tester, 'nextUp'), ['shipped-means', 'preview', 'third']);
+ await dragTo(
+ tester,
+ 'third',
+ tester.getTopLeft(_card('shipped-means')) + const Offset(20, 2),
+ );
+ expect(moves(server), [
+ {'type': 'work.queue', 'conversationId': 'third', 'after': null},
+ ]);
+ expect(_cardsIn(tester, 'nextUp'), ['third', 'shipped-means', 'preview']);
+ await _close(tester, c);
+ // Read again, as another person or a restart reads it.
+ c = await _show(tester, server);
+ expect(_cardsIn(tester, 'nextUp'), ['third', 'shipped-means', 'preview']);
+ await _close(tester, c);
+ });
+
+ testWidgets('a drop under a Needs-you card lands where it was dropped, '
+ 'in the shared order too', (tester) async {
+ final server = queued();
+ // `preview` needs the reader, so it shows first though it is second in
+ // the queue.
+ var c = await _show(tester, server, asking: {'preview'});
+ expect(_cardsIn(tester, 'nextUp'), ['preview', 'shipped-means', 'third']);
+ await dragTo(
+ tester,
+ 'third',
+ tester.getTopLeft(_card('shipped-means')) + const Offset(20, 2),
+ );
+ // Before `shipped-means`, the card under the drop: the queue's top.
+ expect(moves(server), [
+ {'type': 'work.queue', 'conversationId': 'third', 'after': null},
+ ]);
+ await _close(tester, c);
+ c = await _show(tester, server, asking: {'preview'});
+ expect(_cardsIn(tester, 'nextUp'), ['preview', 'third', 'shipped-means']);
+ await _close(tester, c);
+ });
+
+ testWidgets('a drop above a Needs-you card ranked last goes to the top of '
+ 'the rest', (tester) async {
+ final server = queued();
+ // `third` needs the reader: it shows first, though it is last in the
+ // queue.
+ var c = await _show(tester, server, asking: {'third'});
+ expect(_cardsIn(tester, 'nextUp'), ['third', 'shipped-means', 'preview']);
+ await dragTo(
+ tester,
+ 'preview',
+ tester.getTopLeft(_card('third')) + const Offset(20, 2),
+ );
+ expect(moves(server), [
+ {'type': 'work.queue', 'conversationId': 'preview', 'after': null},
+ ]);
+ await _close(tester, c);
+ c = await _show(tester, server, asking: {'third'});
+ expect(_cardsIn(tester, 'nextUp'), ['third', 'preview', 'shipped-means']);
+ await _close(tester, c);
+ // Without the lift, as everyone else sees it.
+ c = await _show(tester, server);
+ expect(_cardsIn(tester, 'nextUp'), ['preview', 'shipped-means', 'third']);
+ await _close(tester, c);
+ });
+
+ testWidgets('a card dropped on another column goes back', (tester) async {
+ final server = queued();
+ final c = await _show(tester, server);
+ await dragTo(tester, 'preview', tester.getCenter(_column('working')));
+ expect(moves(server), isEmpty);
+ expect(_cardsIn(tester, 'nextUp'), ['shipped-means', 'preview', 'third']);
+ expect(_cardsIn(tester, 'working'), ['tag']);
+ await _close(tester, c);
+ });
+
+ testWidgets('only Next up can be dragged', (tester) async {
+ final c = await _show(tester, queued());
+ expect(
+ find.byKey(const ValueKey('super-task-drag-preview')),
+ findsOneWidget,
+ );
+ for (final id in ['tag', 'test-copy', 'sender', 'p-old']) {
+ expect(find.byKey(ValueKey('super-task-drag-$id')), findsNothing);
+ }
+ await _close(tester, c);
+ });
+
+ testWidgets('a focused card moves up with ⌥↑ and down with ⌥↓', (
+ tester,
+ ) async {
+ final server = queued();
+ final c = await _show(tester, server);
+ Focus.of(tester.element(find.text('Rename the round dial')))
+ .requestFocus();
+ await tester.pump();
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.alt);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.alt);
+ await tester.pumpAndSettle();
+ expect(_cardsIn(tester, 'nextUp'), ['shipped-means', 'third', 'preview']);
+ Focus.of(tester.element(find.text('Shipped means merged')))
+ .requestFocus();
+ await tester.pump();
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.alt);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.alt);
+ await tester.pumpAndSettle();
+ expect(moves(server), [
+ {
+ 'type': 'work.queue',
+ 'conversationId': 'third',
+ 'after': 'shipped-means',
+ },
+ {
+ 'type': 'work.queue',
+ 'conversationId': 'shipped-means',
+ 'after': 'third',
+ },
+ ]);
+ expect(_cardsIn(tester, 'nextUp'), ['third', 'shipped-means', 'preview']);
+ await _close(tester, c);
+ });
+
+ testWidgets('a refused move puts the card back and says why', (
+ tester,
+ ) async {
+ final server = queued()
+ ..refuse = {
+ 'code': 'COORDINATOR_REQUIRED',
+ 'message': 'Only a person or the PM can reorder tasks.',
+ };
+ final c = await _show(tester, server);
+ await dragTo(
+ tester,
+ 'third',
+ tester.getTopLeft(_card('shipped-means')) + const Offset(20, 2),
+ );
+ expect(_cardsIn(tester, 'nextUp'), ['shipped-means', 'preview', 'third']);
+ expect(
+ find.text('Only a person or the PM can reorder tasks.'),
+ findsOneWidget,
+ );
+ await _close(tester, c);
+ });
+ });
+}
diff --git a/desktop/test/super_tab_update_required_test.dart b/desktop/test/super_tab_update_required_test.dart
index 2e968a063..e493ca926 100644
--- a/desktop/test/super_tab_update_required_test.dart
+++ b/desktop/test/super_tab_update_required_test.dart
@@ -83,7 +83,6 @@ void main() {
);
reads = [];
await c.refresh();
- c.toggleProject('lead');
await c.loadDormant('lead');
expect(c.updateRequired, isTrue);
expect(c.error, update);
diff --git a/desktop/test/super_tab_view_test.dart b/desktop/test/super_tab_view_test.dart
index c29637661..76216b630 100644
--- a/desktop/test/super_tab_view_test.dart
+++ b/desktop/test/super_tab_view_test.dart
@@ -15,6 +15,19 @@ import 'package:harness/shared/widgets/app_icon_button.dart';
import 'support/super_tab_fixture.dart';
import 'support/super_tab_members.dart';
+/// Adds a project named [name] whose chat is `other-chat`.
+void _secondProject(ConversationServer server, String name) {
+ server.state['projects'] = [
+ ...(server.state['projects'] as List?) ??
+ [projectFixture('lead', server.state['name'] as String, 'lead')],
+ projectFixture('other', name, 'other-chat'),
+ ];
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('other-chat', 'Lead'),
+ 'projectId': 'other',
+ });
+}
+
void main() {
testWidgets('rapid pending rows have independent identity and dimmed text', (
tester,
@@ -256,6 +269,9 @@ void main() {
final server = ConversationServer();
(server.state['conversations'] as List)[1]['title'] =
'Offline editing across mobile and desktop';
+ // A second project with a long name: the sidebar lists projects, not
+ // tasks (task #2569).
+ _secondProject(server, 'Offline editing across mobile and desktop');
final controller = server.controller();
await controller.refresh();
await tester.pumpWidget(
@@ -283,12 +299,10 @@ void main() {
await tester.tap(find.byTooltip('Conversations'));
await tester.pumpAndSettle();
}
- await tester.tap(find.byKey(const ValueKey('super-group-lead')));
- await tester.pumpAndSettle();
- // A workgroup with no work is in The rest, which starts folded (#2309).
- await tester.tap(find.byKey(const ValueKey('super-task-group-lead-rest')));
+ await tester.tap(find.byKey(const ValueKey('super-group-other-chat')));
await tester.pumpAndSettle();
- await tester.tap(find.byKey(const ValueKey('super-group-offline')));
+ expect(controller.selectedId, 'other-chat');
+ await controller.select('offline');
await tester.pumpAndSettle();
expect(controller.selectedId, 'offline');
expect(find.text('New group'), findsNothing);
@@ -340,6 +354,7 @@ void main() {
await tester.binding.setSurfaceSize(const Size(600, 520));
addTearDown(() => tester.binding.setSurfaceSize(null));
final server = ConversationServer();
+ _secondProject(server, 'second-project');
final controller = server.controller();
await controller.refresh();
await tester.pumpWidget(
@@ -375,16 +390,9 @@ void main() {
expect(server.posts, isEmpty);
await tester.tap(find.byTooltip('Conversations'));
await tester.pumpAndSettle();
- await tester.tap(find.byKey(const ValueKey('super-group-lead')));
- await tester.pumpAndSettle();
- // A workgroup with no work is in The rest, which starts folded (#2309).
- await tester.tap(
- find.byKey(const ValueKey('super-task-group-lead-rest')),
- );
- await tester.pumpAndSettle();
- await tester.tap(find.byKey(const ValueKey('super-group-offline')));
+ await tester.tap(find.byKey(const ValueKey('super-group-other-chat')));
await tester.pumpAndSettle();
- expect(controller.selectedId, 'offline');
+ expect(controller.selectedId, 'other-chat');
expect(field.focusNode!.hasFocus, isTrue);
expect(controller.draft('lead'), 'Keep this draft');
expect(tester.takeException(), isNull);
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index 391763178..51bb0110f 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -654,6 +654,14 @@ class ConversationServer {
if (!agent) group['lastPersonSequence'] = revision;
}
+ /// Each project's unanswered Buddy proposals, as the backend's proposals
+ /// read answers them (task #2569), by project id; [proposalReads] records
+ /// each read's path. With [proposalsUnsupported], it answers 404 as a
+ /// backend from before the read does.
+ final proposals = <String, List<Map<String, dynamic>>>{};
+ final proposalReads = <String>[];
+ bool proposalsUnsupported = false;
+
/// The read marks this device sent, in order: {conversationId, sequence}.
final readMarkPosts = <Map<String, dynamic>>[];
@@ -1419,6 +1427,38 @@ class ConversationServer {
'brief': command['brief'] ?? '',
});
output.addAll({'projectId': id, 'conversationId': leadId});
+ } else if (command['type'] == 'work.queue') {
+ // As backend taskQueue.ts places it: right after `after` among the
+ // project's open tasks, by rank or else number; null for the top.
+ final groups = (state['conversations'] as List)
+ .cast<Map<String, dynamic>>();
+ final task = groups.firstWhere(
+ (g) => g['id'] == command['conversationId'],
+ );
+ num key(Map<String, dynamic> g) =>
+ (g['queueRank'] ?? g['number'] ?? 0) as num;
+ final siblings =
+ groups
+ .where(
+ (g) =>
+ g['projectId'] == task['projectId'] &&
+ g['archived'] != true &&
+ g['number'] != null &&
+ g['id'] != task['id'],
+ )
+ .toList()
+ ..sort((a, b) => key(a).compareTo(key(b)));
+ final after = command['after'];
+ if (after == null) {
+ task['queueRank'] = siblings.isEmpty ? 1 : key(siblings.first) - 1;
+ } else {
+ final i = siblings.indexWhere((g) => g['id'] == after);
+ final next = i + 1 < siblings.length ? siblings[i + 1] : null;
+ task['queueRank'] = next == null
+ ? key(siblings[i]) + 1
+ : (key(siblings[i]) + key(next)) / 2;
+ }
+ revision++;
} else if (command['type'] == 'conversation.archive') {
(state['conversations'] as List)
.cast<Map<String, dynamic>>()
@@ -1528,6 +1568,15 @@ class ConversationServer {
}
return {'attachment': await answer(uri.pathSegments.last)};
}
+ if (uri.pathSegments.last == 'proposals') {
+ proposalReads.add(path);
+ if (proposalsUnsupported) {
+ throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);
+ }
+ return {
+ 'proposals': [...?proposals[uri.queryParameters['projectId']]],
+ };
+ }
if (uri.pathSegments.last == 'threads' ||
uri.pathSegments.last == 'inbox') {
threadListReads.add(path);
diff --git a/desktop/test/swarm_projects_test.dart b/desktop/test/swarm_projects_test.dart
index f9093894f..a3378d182 100644
--- a/desktop/test/swarm_projects_test.dart
+++ b/desktop/test/swarm_projects_test.dart
@@ -7,7 +7,6 @@ import 'package:harness/super_tabs/view.dart';
import 'package:harness/super_tabs/section_heading.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/project_visibility.dart';
-import 'package:harness/super_tabs/task_groups.dart';
import 'support/super_tab_fixture.dart';
import 'support/super_tab_members.dart';
@@ -59,7 +58,7 @@ void main() {
c.dispose();
}
- testWidgets('project rows open lead chats and reveal numbered workgroups', (
+ testWidgets('project rows open lead chats and list no workgroups', (
tester,
) async {
final server = projectsServer(), c = server.controller();
@@ -93,20 +92,18 @@ void main() {
);
expect(c.selectedId, 'lead');
expect(find.text('12 Offline editing'), findsNothing);
- // Already open: a click on it shows its workgroups.
+ // Already open: a click on it keeps its chat, and lists no workgroups:
+ // they are in the project's Tasks view (task #2569).
await tester.tap(find.byKey(const ValueKey('super-group-lead')));
await tester.pumpAndSettle();
- // A workgroup with no work is in The rest, which starts folded (#2309).
- await tester.tap(find.byKey(const ValueKey('super-task-group-lead-rest')));
- await tester.pumpAndSettle();
- expect(find.text('12 Offline editing'), findsOneWidget);
- await tester.tap(find.byKey(const ValueKey('super-group-offline')));
+ expect(c.selectedId, 'lead');
+ expect(find.text('12 Offline editing'), findsNothing);
+ await c.select('offline');
await tester.pumpAndSettle();
expect(c.selectedId, 'offline');
await tester.tap(find.byKey(const ValueKey('super-group-design-lead')));
await tester.pumpAndSettle();
expect(c.selectedId, 'design-lead');
- expect(c.expandedProjects, {'lead'});
await tester.tap(find.byKey(const ValueKey('super-group-lead')));
await tester.pumpAndSettle();
expect(c.selectedId, 'lead');
@@ -117,70 +114,36 @@ void main() {
await unmount(tester, c);
});
- testWidgets(
- 'project and workgroup rows align, and a project row works from the keyboard',
- (tester) async {
- final server = projectsServer(), c = server.controller();
- await mount(tester, c);
- // Workgroups with no work are in The rest, unfolded here (#2309).
- c.toggleTaskGroup('lead', SuperTabTaskGroup.rest);
- final project = find.byKey(const ValueKey('super-group-lead'));
- final projectName = find.descendant(
- of: project,
- matching: find.text('Lamp OS'),
- );
- // Enter on the project opens its chat; → shows its workgroups.
- await c.select('offline');
- c.expandedProjects.remove('lead');
- await tester.pumpAndSettle();
- Focus.of(tester.element(projectName)).requestFocus();
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(c.expandedProjects, isEmpty);
- expect(c.selectedId, 'lead');
- Focus.of(tester.element(projectName)).requestFocus();
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
- await tester.pumpAndSettle();
- expect(c.expandedProjects, {'lead'});
-
- final workgroup = find.byKey(const ValueKey('super-group-offline'));
- final projectBounds = tester.getRect(project);
- final workgroupBounds = tester.getRect(workgroup);
- expect(workgroupBounds.left, projectBounds.left);
- expect(
- workgroupBounds.right,
- tester.getRect(find.byKey(const ValueKey('super-group-lead'))).right,
- );
- // Workgroups share the project name column in the compact sidebar.
- expect(
- tester.getTopLeft(find.text('12 Offline editing')).dx,
- tester.getTopLeft(projectName).dx,
- );
-
- // A child row's formerly empty inset is part of its one click target.
- await tester.tapAt(workgroupBounds.centerLeft + const Offset(8, 0));
- await tester.pumpAndSettle();
- expect(c.selectedId, 'offline');
- // From a workgroup, the project row opens the project's chat and keeps
- // its workgroups shown; ← hides them.
- Focus.of(tester.element(projectName)).requestFocus();
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(c.selectedId, 'lead');
- expect(c.expandedProjects, {'lead'});
+ testWidgets('a project row works from the keyboard', (tester) async {
+ final server = projectsServer(), c = server.controller();
+ await mount(tester, c);
+ final projectName = find.descendant(
+ of: find.byKey(const ValueKey('super-group-lead')),
+ matching: find.text('Lamp OS'),
+ );
+ // From a workgroup, Enter on the project opens its chat; → and ← show
+ // nothing more: its workgroups are in its Tasks view (task #2569).
+ await c.select('offline');
+ await tester.pumpAndSettle();
+ Focus.of(tester.element(projectName)).requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'lead');
+ for (final arrow in [
+ LogicalKeyboardKey.arrowRight,
+ LogicalKeyboardKey.arrowLeft,
+ ]) {
Focus.of(tester.element(projectName)).requestFocus();
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
+ await tester.sendKeyEvent(arrow);
await tester.pumpAndSettle();
expect(c.selectedId, 'lead');
- expect(c.expandedProjects, isEmpty);
- expect(server.posts, isEmpty);
- await unmount(tester, c);
- },
- );
+ expect(find.byKey(const ValueKey('super-group-offline')), findsNothing);
+ }
+ expect(server.posts, isEmpty);
+ await unmount(tester, c);
+ });
testWidgets('project pull requests include its workgroups and stay scoped', (
tester,
@@ -303,14 +266,13 @@ void main() {
},
);
- test('project revocation removes cached text, drafts, terminals and expanded state', () async {
+ test('project revocation removes cached text, drafts and terminals', () async {
final server = projectsServer(), c = server.controller();
server.append('Private design', conversationId: 'design-lead');
await c.refresh();
await c.loadMessages('design-lead');
c.select('design-lead');
c.setDraft('design-lead', 'Private response');
- c.toggleProject('design');
expect(c.messages('design-lead'), hasLength(1));
(server.state['projects'] as List).removeLast();
(server.state['conversations'] as List).removeLast();
@@ -320,7 +282,6 @@ void main() {
expect(c.selectedId, 'lead');
expect(c.messages('design-lead'), isEmpty);
expect(c.draft('design-lead'), isEmpty);
- expect(c.expandedProjects, isNot(contains('design')));
expect(
(server.saved!['drafts'] as Map).containsKey('design-lead'),
isFalse,
diff --git a/docs/plans/2026-11-04-tasks-board-plan.md b/docs/plans/2026-11-04-tasks-board-plan.md
new file mode 100644
index 000000000..2d3e3974f
--- /dev/null
+++ b/docs/plans/2026-11-04-tasks-board-plan.md
@@ -0,0 +1,385 @@
+# Project Tasks view (Board and List) Implementation Plan
+
+> **For agentic workers:** Follow the project's Engineer workflow: this plan is the draft pull request's first commit;
+> each plan task commits its failing test, watches it fail, then commits the code that passes it; one independent review
+> step on the pull request. Backend and CLI tasks (1, 2, 4) and Desktop tasks (5–10) share only the wire fields named in
+> their Interfaces, so the two halves may run in parallel.
+
+**Goal:** One place per project to see its work, from proposal to shipped: a Tasks view in the project header (Board by
+default, or List), with a red count of the tasks that need the reader, in place of the sidebar's task groups. It
+strengthens "Tell the PM what you want, and your crew ships it": every ask is in view until it ships, so none is
+forgotten.
+
+**Architecture:** One Desktop function places each task in a column (Proposals, Next up, Working, Waiting, Shipped) with
+a Needs-you mark and a caption state. Board, List, the header badge and the project row's badge all use it. The server
+keeps a shared Next-up order as one sparse rank per task, so moving a card rewrites only that task. It sets the rank
+with one command a person or the PM sends; the rank arrives through the change feed the app already reads, so cards
+move with no reload or poll. A project's unanswered Buddy proposals come from one read that applies #2867's rule (a
+proposal with no task reply and no PM reply in its thread), however old. The app reads it again only once the project
+chat has moved, since only a message there can add or answer one (PM's ruling, 2026-11-04: no backfill, no writes to
+stored rows).
+
+**Tech Stack:** TypeScript, Zod, Vitest (backend, CLI); Flutter/Dart (Desktop).
+
+**Spec:** Task #2569 in Super Tab conversation 4f517cb03e671a3604090a53 (Dee, 2026-11-04; brief from River the same
+day). It builds on #2867 (ask state: `✋ Proposal`) and #2872 (Backlog's Shipped means merged).
+
+## Global Constraints
+
+- The mockup Dee confirmed, and only this:
+
+ ```
+ # openharness Chat Terminals Tasks (3) People
+
+ Tasks [ Board | List ] Mine Search
+
+ Proposals 2 Next up 3 Working 2 Waiting 2 Shipped 9
+ Backlog shows Shipped means One tag per ● Needs you Task chat keeps
+ nothing in Mine merged ask First run of its sender
+ scholes · 3m scholes dee · Finch2 · the test copy diego · 1h
+ PR #2867 ken15 · Dee to
+ Rename a Swarm Remove the old decide
+ from the phone preview route Dial thread
+ tony · 23m River · not alerts Task chat …
+ before Dec 4 diego · Larch4 grouping
+ diego · in review
+ ```
+
+ The PM confirmed (2026-11-04) that only Tasks joins the project header, between Terminals and People. A project-wide
+ Pull requests view is a later task.
+- Columns, in this order: Proposals, Next up, Working, Waiting, Shipped. Not listed: cancelled, declined or stopped.
+- Proposals: Buddy proposals the PM has not answered (#2867's `✋ Proposal`), however old, oldest first.
+- Next up: open tasks nobody is moving yet, in the shared queue order. New tasks join the bottom.
+- Working: an agent is working or starting.
+- Waiting: in review, changes requested, waiting on a person, blocked, queued for a machine, or its agent lost or quiet.
+ The caption says on what: "in review", "Ken to decide", "waiting for a machine", "agent lost".
+- Shipped: merged in the last 7 days, archived tasks included, newest first. Finished with no pull request: "Done".
+- Needs you: tagged, waited on by name, or asked in its agent's terminal. The task stays in its column, shows a red dot
+ and the words "Needs you", and sorts first in its column. The Tasks icon shows a red count, with no badge at 0. The
+ project's sidebar row adds them to its badge.
+- Card: the title (up to two lines), then a caption: requester · agent · state, joined by " · ". No task numbers,
+ machines or models. A click opens the task's chat with the Tasks icon selected; the Tasks icon brings the board back.
+- Drag only inside Next up. A drop anywhere else goes back, and no other column shows a drop target. Keyboard: a focused
+ Next-up card moves with ⌥↑ and ⌥↓.
+- "not before <date>" on a Next-up card, set by the PM.
+- List: the same groups as sections, in the same order, with Shipped folded. Each row has the title and the same
+ caption.
+- Board or List, and Mine, are remembered per person on this Mac.
+- The view's bar holds a Board/List switch, Mine (tasks I asked for) and Search (by title), and nothing else.
+- Sidebar: no task rows under a project. Needs you, Working, Waiting on others, The rest and Closed (N) all go. Next
+ unread skips tasks. Task replies stay in Activity ▸ New replies and show as an unread dot on the card.
+- An empty column shows its header with 0. A project with no tasks shows "No tasks yet".
+- Manage ▸ Backlog stays.
+- Harness Design Language (desktop/design/desktop-design-system.md, icon-design-system.md):
+ - flat rows, with the caption on the second line
+ - colour is never the only signal
+ - no explanatory sentences
+ - tokens, never hard-coded colours or sizes
+- The header's Pull requests view is the model for how Tasks opens and closes.
+- The phone app (mobile/) is untouched. No Swarm code goes in cli/src/core.
+- Desktop tests use a memory store and a fake sign-in, and never sign the Mac out of the real CLI.
+- The PR body starts with "Requested by [email protected] through Harness.".
+
+## Design
+
+- **Growth.** A task's rank and date live on its group and go when the group goes: project or Swarm deletion, as today.
+ The proposals read stores nothing. It answers at most 100, oldest first.
+- **Concurrency.** Both are written in the command's existing state transaction, so two moves serialize. A move names
+ the task it goes after, never an index, so a stale view still lands where the person dropped the card.
+- **Read cost.** A move rewrites one group's part. Renumbering a whole queue happens only when two ranks get closer than
+ 1e-6, about 40 moves into the same gap. The proposals read runs once when the view opens, then again only after the
+ project chat moves, and at most once a minute per project (PM, 2026-11-04). It finds the chat's proposal roots, then
+ reads their threads the way the chat page does.
+- **Known limit.** Finding the roots looks through every message of the project chat: 3,002 rows for 5 proposals,
+ measured. The fix is a small indexed marker on proposal messages, with the existing ones marked once. That is a write
+ to stored rows, so it waits for Ken's go, and becomes its own follow-up task once he agrees.
+- **Scale.** At 10x, 300 open tasks in a project, a move is still one write. The first warning is the proposals read's
+ time on a project chat with 10x the messages, in the read measures.
+- **Compatibility.**
+ - An older client ignores `queueRank` and `notBefore`, and never asks for proposals.
+ - A new client on an older backend orders Next up by number (oldest first) and shows no Proposals. When the backend
+ refuses `work.queue` with `VALIDATION_ERROR`, the card goes back and the view says "Update Harness's server to
+ reorder".
+- **Migration and rollback.**
+ - No migration for ranks: an unranked task sorts by its number.
+ - Proposals need none: the read applies #2867's rule to rows as they are stored.
+ - Rollback leaves the fields unread, and an older backend drops nothing it does not know.
+- **Audience.**
+ - The proposals read answers only a reader of the project chat, by the check the messages read makes.
+ - `work.queue` is refused unless the sender is a person who can write in the project, or that project's PM
+ (`coordinatorOrPerson`).
+- **Identity.** No command takes a person from its sender. The proposal's `personId` is the one the server recorded
+ when it posted it.
+- **Failure.**
+ - A refused move puts the card back and names why in the view's bar.
+ - A failed read of Shipped's archived tasks shows "Couldn't load older shipped tasks", as Backlog does.
+- **Platforms.**
+ - Backend.
+ - CLI skill text.
+ - Desktop on macOS, Linux, Windows and web, through the shared Flutter code; tested on macOS.
+ - The phone is untouched.
+
+## Review Focus
+
+- A task's column moves live: a status change, a merge, a lost agent, a reply that tags the reader. Board and List read
+ the controller's snapshot each build, so a test changes the server state and pumps, with no reload.
+- Two people reorder at once, or one drops on a stale board: the move names its neighbour, and the server's order wins
+ on the next change. Test: a move after a task that has since left Next up is refused, and the card goes back.
+- A task tagged for the reader in Shipped, or a quiet task with a question: Needs you is a mark, not a column. Test both.
+- A project whose PM is gone (no lead agent): proposals stay listed, and a person can still reorder.
+- Long titles and names, 160–200% text, an empty project, a column of 0. These go in the screenshot test.
+
+## Task 1: Backend: a task's queue rank and not-before date
+
+**Files:**
+
+- Modify: `backend/src/superTabs/model.ts` (Conversation: `queueRank?: number`, `notBefore?: string`)
+- Modify: `backend/src/superTabs/commands.ts` (schema and handler)
+- Create: `backend/src/superTabs/taskQueue.ts`, `backend/src/superTabs/taskQueue.test.ts`
+- Test: `backend/src/superTabs/commands.test.ts`
+
+**Interfaces:**
+
+- Produces:
+ - command `{ type: 'work.queue', conversationId: string, after?: string | null, notBefore?: string | null }`
+ - `after` absent: the task stays where it is. `null`: it goes to the top. An id: it goes right after that task.
+ - `notBefore` is `YYYY-MM-DD`; `null` clears it.
+ - At least one of the two is given.
+ - group fields `queueRank?: number` and `notBefore?: string`, read by Desktop.
+- `queueKey(g) = g.queueRank ?? g.number ?? 0`. Siblings are the project's open tasks:
+ - not archived
+ - not the project chat, a Buddy chat or a private chat
+ - no `reviewOf`
+- `placeAfter(siblings, taskId, after): Map<string, number>` returns the ranks to write:
+ - usually just the moved task's: the midpoint between `after` and the next sibling, `min - 1` for the top,
+ `max + 1` for the bottom
+ - when the gap falls below 1e-6, every sibling, as 1..n in order
+
+- [ ] Write failing tests:
+ - `taskQueue.test.ts`: `placeAfter` to top, to the middle, to the bottom, and renumbering once gaps run out. An
+ unranked task sorts by its number, so a new task comes last.
+ - `commands.test.ts`:
+ - a person moves a task after another, and the group reads `queueRank` between them
+ - the PM sets `notBefore: '2026-12-04'`, then clears it with `null`
+ - refused:
+ - an Engineer agent (`COORDINATOR_REQUIRED`)
+ - `after` naming a task of another project, an archived task, a step or itself (`QUEUE_UNKNOWN`, 400)
+ - a malformed date, or neither field given (validation)
+ - after a refusal, `f.state` is unchanged
+ - the same operation id sent again does the work once
+- [ ] Run `cd backend && npx vitest run src/superTabs/taskQueue.test.ts src/superTabs/commands.test.ts -t queue`:
+ FAIL.
+- [ ] Implement `taskQueue.ts` and the `work.queue` case: `chatOnly`, `open()`, `coordinatorOrPerson`, then
+ `placeAfter`.
+- [ ] Run again: PASS. Commit.
+
+## Task 2: Backend: a read of a project's unanswered proposals
+
+**Files:**
+
+- Modify: `backend/src/routes/superTabs.ts` and `backend/src/superTabs/read/service.ts` (`GET /super-tabs/:tabId/proposals?projectId=P`)
+- Test: beside the read's service tests
+
+**Interfaces:**
+
+- Produces:
+ - `{ proposals: [{ messageId, title, personId?, at }] }`, oldest first, at most 100
+ - `title` is the root's text, less an older root's "Let's build: "
+ - `personId` is the root's `source.personId`; `at` is its creation time in ms
+- How it reads: find the project chat's `buddy-proposal` roots, then summarize their threads through `pageThreads` and
+ `threadSummaries`. Keep those whose `ask` is `'proposal'` (#2867's `askOf`).
+- [ ] Write failing tests:
+ - an unanswered proposal is listed
+ - one the PM replied to is not
+ - one a task was opened from is not
+ - an old root that still reads "Let's build: …" is listed with its title alone
+ - a reader who cannot read the project chat is refused
+ - the cap holds
+- [ ] Run: FAIL. Implement. Run: PASS. Commit. If finding the roots needs a new index, it goes in its own commit and
+ the PM is told before Ready.
+
+## Task 4: CLI: the PM keeps Next up in order
+
+**Files:**
+
+- Modify: `cli/src/lib/swarmSkills.ts` (both PM skills, under keeping work moving)
+- Modify: `cli/src/lib/swarmTools.ts` (task and group commands)
+- Test: `cli/src/lib/swarmSkills.spec.ts`
+
+- [ ] Write a failing spec: the PM text names `work.queue` with `after` and `notBefore`, and the tools text documents
+ the command's JSON.
+- [ ] Run `cd cli && npx vitest run src/lib/swarmSkills.spec.ts`: FAIL.
+- [ ] Add the text:
+ - PM: "Keep the project's Next up in the order work should start: `work.queue` with `after` (null for the top) moves
+ a task, and `notBefore` (YYYY-MM-DD) marks a promise such as removing a route after a date."
+ - Tools: the JSON and who may send it.
+- [ ] Run: PASS. Commit.
+
+## Task 5: Desktop: one function places a task
+
+**Files:**
+
+- Modify: `desktop/lib/super_tabs/task_groups.dart`. It replaces `SuperTabTaskGroup` and `superTabGroupTasks`; the
+ sidebar's groups go.
+- Modify: `desktop/lib/super_tabs/model.dart`:
+ - `SuperTabConversation.queueRank`, `notBefore`
+ - `SuperTabProposal`; `SuperTabController.proposalsOf` and `readProposals`, which read again only once the project chat
+ has moved
+- Modify: `desktop/lib/super_tabs/backlog.dart` (make #2872's shipped test public: `superTabTaskShipped`)
+- Test: `desktop/test/super_tab_task_groups_test.dart` (rewritten for columns)
+
+**Interfaces:**
+
+- Produces:
+ ```dart
+ enum SuperTabTaskColumn { proposals('Proposals'), nextUp('Next up'), working('Working'), waiting('Waiting'), shipped('Shipped') }
+ typedef SuperTabTaskPlace = ({SuperTabTaskColumn column, bool needsYou, String? state});
+ SuperTabTaskPlace? superTabTaskPlaceOf(SuperTabConversation task, {required String readerId, required DateTime now,
+ int mentions = 0, int needsHuman = 0, String? Function(String personId)? personName});
+ List<SuperTabConversation> superTabNextUpOrder(Iterable<SuperTabConversation> tasks); // queueRank ?? number, then number
+ ```
+- What `state` says, in the chat tag's and live card's words:
+ - Working: `PR #N` once a pull request is linked
+ - Waiting, by cause:
+ - review: `in review`
+ - revision: `changes requested`
+ - person or `needs_human`: `<Name> to decide`
+ - blocked: `blocked`
+ - queued, or no agent: `waiting for a machine`
+ - orphaned: `agent lost`
+ - quiet: `quiet`
+ - done with an unmerged pull request: `ready to merge`
+ - Shipped: `PR #N`, or `Done`
+ - Next up: `not before Dec 4`
+
+- [ ] Write failing tests. They place each state:
+ - no assignment, then Next up
+ - working or planned, then Working
+ - `waiting/starting`, then Working
+ - `waiting/review`, then Waiting "in review"
+ - `waiting/revision`, then Waiting "changes requested"
+ - `waiting/person` naming Ken, then Waiting "Ken to decide", and Needs you when Ken is the reader
+ - `needs_human`, then Needs you
+ - `quiet` with a question, then Waiting with Needs you
+ - `quiet` with none, then Waiting "quiet"
+ - `orphaned/lost`, then Waiting "agent lost"
+ - `waiting/queued`, then Waiting "waiting for a machine"
+ - blocked, then Waiting
+ - cancelled, then null
+ - stopped, then null
+ - done with no pull request, then Shipped "Done"
+ - merged 2 days ago, then Shipped "PR #12"
+ - merged 8 days ago, then null
+ - done with an unmerged pull request, then Waiting "ready to merge"
+ - tagged in a Shipped task, then Shipped with Needs you
+
+ `superTabNextUpOrder` puts ranked tasks in rank order, and an unranked new task last.
+- [ ] Run `cd desktop && flutter test test/super_tab_task_groups_test.dart`: FAIL.
+- [ ] Implement. Run: PASS. Commit.
+
+## Task 6: Desktop: the sidebar lists no tasks
+
+**Files:**
+
+- Modify: `desktop/lib/super_tabs/project_sidebar.dart`:
+ - remove `_workgroups`, `_taskGroupHeading` and `_closed`
+ - `superTabSidebarOrder` lists no tasks
+ - the project row's badge adds Needs-you tasks
+- Modify: `desktop/lib/super_tabs/controller.dart` (remove `taskGroupFolded`, `toggleTaskGroup`, `closedOpenProjects`,
+ and the expansion that showed only them)
+- Test: `desktop/test/super_tab_task_groups_test.dart` (sidebar and next-unread parts)
+
+**Interfaces:**
+
+- Produces: `int superTabTasksNeedingYou(SuperTabController c, SuperTabProject p, {int Function(SuperTabConversation)? needsHuman})`.
+
+- [ ] Write failing tests:
+ - the grouped fixture shows no `super-group-<task>` row and no `super-task-group-*` heading
+ - the project row's badge reads the chat's mentions plus the Needs-you tasks
+ - ⌥⇧↓ goes from one project chat to the next, past an unread task
+- [ ] Run: FAIL. Implement. Run: PASS. Commit.
+
+## Task 7: Desktop: the Tasks view, Board and List
+
+**Files:**
+
+- Create: `desktop/lib/super_tabs/tasks_view.dart` (bar, Board, List, empty state, saved choice)
+- Create: `desktop/lib/super_tabs/task_card.dart` (card and list row: title, caption, Needs-you mark, unread dot)
+- Modify: `desktop/lib/shared/theme/app_icons.dart` (`squareKanban`), then run `scripts/audit-icons.py`
+- Test: `desktop/test/super_tab_tasks_view_test.dart`
+
+**Interfaces:**
+
+- Produces:
+ - `SuperTabTasksView(controller:, project:, storage:, needsHuman:, onOpenTask:, onOpenProposal:, now:)`
+ - the saved choice is under `super-tab-tasks-view/<accountId>` as `{"layout":"board"|"list","mine":bool}`
+ - keys: `super-tasks-column-<column>`, `super-task-card-<id>`, `super-tasks-layout`, `super-tasks-mine`,
+ `super-tasks-search`
+
+- [ ] Write failing tests:
+ - Board shows five columns in order, with counts, and 0 on an empty one
+ - "No tasks yet" for a project with none
+ - a Needs-you card sorts first and reads "Needs you"
+ - the caption reads `dee · Finch2 · PR #2867`, with no number, machine or model
+ - Proposals lists the read's proposals oldest first, as `scholes · 3m`. A new one shows once the project chat moves,
+ and nothing is read while the chat stays still
+ - Shipped includes an archived task from the closed read
+ - List shows the same sections, with Shipped folded
+ - Mine keeps the reader's asks; Search filters by title
+ - the layout and Mine survive a rebuild with the same memory store
+ - a server change moves a card with no reload
+- [ ] Run: FAIL. Implement. Run: PASS. Commit.
+
+## Task 8: Desktop: reorder Next up by drag and keyboard
+
+**Files:**
+
+- Modify: `desktop/lib/super_tabs/tasks_view.dart`:
+ - Next up is a `ReorderableListView` with drag handles
+ - other columns are plain lists, so they offer no drop target
+- Modify: `desktop/lib/super_tabs/controller.dart`:
+ `Future<String?> queueTask(String taskId, {required String? after})`. It shows the new order until the server
+ answers, and returns the refusal's message or null.
+- Modify: `test/support/super_tab_fixture.dart` (the fake server applies `work.queue`)
+- Test: `desktop/test/super_tab_tasks_view_test.dart`
+
+- [ ] Write failing tests:
+ - dragging the third Next-up card to the top sends `work.queue` with `after: null`, and the order holds after a new
+ controller reads the same server (a reload)
+ - dropping a Next-up card on Working sends nothing and leaves both columns as they were
+ - a Working card has no drag handle
+ - ⌥↑ on a focused card moves it up one, and ⌥↓ down one, each sending `after`
+ - a refused move puts the card back and shows the refusal
+- [ ] Run: FAIL. Implement. Run: PASS. Commit.
+
+## Task 9: Desktop: the header's Tasks icon
+
+**Files:**
+
+- Modify: `desktop/lib/super_tabs/view.dart`:
+ - `_showTasks`, which switches like `_showPullRequests`
+ - the Tasks button `super-tasks`, between Terminals and People, with `SuperTabCountBadge` when the count is above 0
+ - a task's header shows the Tasks button, selected, to go back to its project's board
+ - the pane index for the view
+- Test: `desktop/test/super_tab_tasks_header_test.dart`
+
+- [ ] Write failing tests:
+ - the project header lists Chat, Terminals, Tasks and Members in that order
+ - Tasks shows a red badge "3" for three Needs-you tasks, and none at 0
+ - Tasks opens the Board, as Board is the default
+ - a card click opens the task's chat with Tasks selected, and Tasks brings the board back
+ - Chat closes the view
+- [ ] Run: FAIL. Implement. Run: PASS. Commit.
+
+## Task 10: Screenshots and guards
+
+**Files:**
+
+- Create: `desktop/test/super_tab_tasks_shots_test.dart` (Board and List, light and dark, with a Needs-you card and the
+ badge)
+
+- [ ] Write the shots test, modelled on `super_tab_backlog_shots_test.dart`, and run it on the Mac.
+- [ ] Run Desktop's guards: `python3 scripts/check-ui-style.py`, `flutter test test/laid_out_list_test.dart`, and
+ `flutter analyze`.
+- [ ] Run the backend unit suite (`cd backend && npm test`) and the CLI spec. Post red/green evidence in a PR comment.
+ Mark the PR ready.
diff --git a/docs/pr-shots-2569/tasks-board-dark.png b/docs/pr-shots-2569/tasks-board-dark.png
new file mode 100644
index 000000000..bf1b6aedf
Binary files /dev/null and b/docs/pr-shots-2569/tasks-board-dark.png differ
diff --git a/docs/pr-shots-2569/tasks-board-light.png b/docs/pr-shots-2569/tasks-board-light.png
new file mode 100644
index 000000000..f91d9701e
Binary files /dev/null and b/docs/pr-shots-2569/tasks-board-light.png differ
diff --git a/docs/pr-shots-2569/tasks-list-dark.png b/docs/pr-shots-2569/tasks-list-dark.png
new file mode 100644
index 000000000..797fb540e
Binary files /dev/null and b/docs/pr-shots-2569/tasks-list-dark.png differ
diff --git a/docs/pr-shots-2569/tasks-list-light.png b/docs/pr-shots-2569/tasks-list-light.png
new file mode 100644
index 000000000..fe2473d78
Binary files /dev/null and b/docs/pr-shots-2569/tasks-list-light.png differ
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index a048fea7a..0ba8581b4 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -384,6 +384,8 @@ class SuperTabConversation {
(row['shippedAt'] as num).toInt(),
)
: null,
+ queueRank = (row['queueRank'] as num?)?.toDouble(),
+ notBefore = DateTime.tryParse(row['notBefore'] as String? ?? ''),
lastMainSequence = (row['lastMainSequence'] as num?)?.toInt(),
lastPersonSequence = (row['lastPersonSequence'] as num?)?.toInt() ?? 0,
reactionSeq = (row['reactionSeq'] as num?)?.toInt() ?? 0,
@@ -437,6 +439,12 @@ class SuperTabConversation {
/// When it shipped (its first Done); null until it has, and from a server
/// that does not say.
final DateTime? shippedAt;
+
+ /// Its place in its project's shared Next up and the day before which it
+ /// may not start, as Desktop's Tasks view reads them (task #2569); read here
+ /// for the phone's Tasks view to come.
+ final double? queueRank;
+ final DateTime? notBefore;
String get label => number == null ? title : '#$number $title';
final String? leadId;
final List<String> agentIds;
diff --git a/mobile/lib/swarm/swarm_attachment.dart b/mobile/lib/swarm/swarm_attachment.dart
index cf5a448cf..5b5c0ef1d 100644
--- a/mobile/lib/swarm/swarm_attachment.dart
+++ b/mobile/lib/swarm/swarm_attachment.dart
@@ -13,6 +13,7 @@ import 'package:harness_mobile/shared/widgets/skeleton.dart';
import 'model.dart';
import 'swarm_attachment_store.dart';
+import 'swarm_file_download.dart';
import 'swarm_file_links.dart';
import 'swarm_outgoing_files.dart' show swarmFormAttachmentMaxBytes;
import 'swarm_style.dart';
@@ -64,6 +65,29 @@ class SwarmAttachment extends StatelessWidget {
}
}
+/// [file] as [store] keeps it: by the link at hand ([at]), else a fresh one
+/// of [ref]; a signed link that fails (it may have ended) is asked for once
+/// more, then the failure stands.
+Future<File> swarmKeptFile(
+ SwarmAttachmentStore store,
+ SuperTabAttachment file, {
+ Uri? at,
+ SwarmFileRef? ref,
+}) async {
+ // A signed link changes every few minutes; the file it reaches does not,
+ // so it is kept by the file's id.
+ String keyOf(Uri url) =>
+ url.host == swarmFilesHost ? 'swarm-file:${file.id}' : url.toString();
+ var url = at ?? await (ref ?? (throw StateError('No link'))).link();
+ try {
+ return await store.file(url, key: keyOf(url));
+ } catch (_) {
+ if (ref == null || url.host != swarmFilesHost) rethrow;
+ url = await ref.link(stale: true);
+ return store.file(url, key: keyOf(url));
+ }
+}
+
/// The most a picture shows in a message, each way (Dee, 10-29: Slack's 360).
const _maxSide = 360.0;
@@ -132,34 +156,15 @@ class _PreviewState extends State<_Preview> {
void _ask() {
_turn = widget.store.turns.value;
- _local = _fetch(widget.store, widget.url, widget.fileRef);
+ _local = swarmKeptFile(
+ widget.store,
+ widget.file,
+ at: widget.url,
+ ref: widget.fileRef,
+ );
_failed = false;
}
- /// The picture's file: by the link at hand, else a fresh one; a signed
- /// link that fails (it may have ended) is asked for once more, then the
- /// failure stands.
- Future<File> _fetch(
- SwarmAttachmentStore store,
- Uri? at,
- SwarmFileRef? ref,
- ) async {
- var url = at ?? await (ref ?? (throw StateError('No link'))).link();
- try {
- return await store.file(url, key: _keyOf(url));
- } catch (_) {
- if (ref == null || url.host != swarmFilesHost) rethrow;
- url = await ref.link(stale: true);
- return store.file(url, key: _keyOf(url));
- }
- }
-
- /// A signed link changes every few minutes; the file it reaches does not,
- /// so it is kept by the file's id.
- String _keyOf(Uri url) => url.host == swarmFilesHost
- ? 'swarm-file:${widget.file.id}'
- : url.toString();
-
/// The files kept changed hands: the picture is asked for again, for
/// whoever they are kept for now.
void _turned() {
@@ -273,7 +278,8 @@ class _PreviewState extends State<_Preview> {
}
}
-/// A picture full screen, to pinch and zoom; its name and a close at the top.
+/// A picture full screen, to pinch and zoom; its name, a close and Download
+/// ([SwarmDownloadButton]) at the top.
///
/// It shows a file [store] keeps for one account, so it goes when that
/// changes ([SwarmAttachmentStore.turns]: another account, sign-out, Swarm
@@ -361,6 +367,11 @@ class _ViewerState extends State<SwarmAttachmentViewer> {
onPressed: () => Navigator.of(context).maybePop(),
),
title: _gone ? '' : widget.name,
+ trailing: SwarmDownloadButton(
+ name: widget.name,
+ file: _gone ? null : widget.file,
+ store: widget.store,
+ ),
),
Expanded(
child: _gone
diff --git a/mobile/lib/swarm/swarm_attachment_store.dart b/mobile/lib/swarm/swarm_attachment_store.dart
index 8290ad114..1d9c6aae5 100644
--- a/mobile/lib/swarm/swarm_attachment_store.dart
+++ b/mobile/lib/swarm/swarm_attachment_store.dart
@@ -21,7 +21,7 @@ const swarmAttachmentStale = Duration(days: 7);
const swarmAttachmentCap = 200;
/// The phone's copies of Swarm's files, for the pictures shown in a chat
-/// ([SwarmAttachment]).
+/// ([SwarmAttachment]) and the text files read in one (`SwarmFileViewer`).
///
/// Fetched exactly as the chip opens them: the public link on Harness's file
/// storage, with no credential of the app's. Kept in the app's private
@@ -96,6 +96,58 @@ class SwarmAttachmentStore {
account,
))).getSingleFile(url.toString(), key: key);
+ /// Hands [use] a copy of [kept], one of the account's files ([file]), named
+ /// [name]: the share sheet names what it hands on by its path, and a kept
+ /// file's path is the cache's own. The copy lies in the account's folder, so
+ /// it goes with the rest, and goes itself once [use] ends. Throws for a
+ /// file that is not the account's.
+ Future<void> named(
+ File kept,
+ String name,
+ Future<void> Function(File copy) use,
+ ) async {
+ await _changing;
+ final account = _account;
+ if (account == null) throw StateError('No account to keep files for.');
+ // Waited for like a fetch, so no emptying runs under it: counted from
+ // here, before the first wait, as an emptying asked for meanwhile would
+ // otherwise run under the copy.
+ final copying = () async {
+ final folder = await _folderOf(account);
+ final inside = '${folder.absolute.path}/';
+ if (!File(kept.path).absolute.path.startsWith(inside)) {
+ throw StateError('Not a file kept for this account.');
+ }
+ final shared = Directory('${folder.path}/shared');
+ await shared.create(recursive: true);
+ final into = await shared.createTemp();
+ return kept.copy('${into.path}/${swarmFileName(name)}');
+ }();
+ final done = copying.then<void>((_) {}, onError: (Object _) {});
+ _fetching.add(done);
+ final File copy;
+ try {
+ copy = await copying;
+ } finally {
+ _fetching.remove(done);
+ }
+ try {
+ await use(copy);
+ } finally {
+ try {
+ await _delete(copy.parent);
+ } catch (error) {
+ // Left for the account's emptying. Its kind only: the error's path
+ // carries the file's name.
+ appLog.failure(
+ 'swarm',
+ 'A shared copy of a Swarm file could not be deleted: '
+ '${error.runtimeType}',
+ );
+ }
+ }
+ }
+
/// Keeps [accountId]'s files and empties every other account's; with null
/// (nobody signed in, or Swarm off) empties everything. A file that could
/// not go throws, after the rest went; the next call tries again.
@@ -206,6 +258,31 @@ class SwarmAttachmentStore {
}
}
+/// [name], a message's file name, as one a phone's file system takes: no
+/// folder or control character in it, never empty, at most 255 bytes, the
+/// extension kept when it has to be shortened.
+@visibleForTesting
+String swarmFileName(String name) {
+ var safe = name.replaceAll(RegExp(r'[/\\\x00-\x1f\x7f]'), '_').trim();
+ if (safe.isEmpty || safe == '.' || safe == '..') return 'file';
+ const most = 255;
+ if (utf8.encode(safe).length <= most) return safe;
+ final dot = safe.lastIndexOf('.');
+ final extension = dot > 0 && safe.length - dot <= 16
+ ? safe.substring(dot)
+ : '';
+ final room = most - utf8.encode(extension).length;
+ final stem = StringBuffer();
+ var bytes = 0;
+ for (final rune in safe.substring(0, safe.length - extension.length).runes) {
+ final size = utf8.encode(String.fromCharCode(rune)).length;
+ if (bytes + size > room) break;
+ stem.writeCharCode(rune);
+ bytes += size;
+ }
+ return '$stem$extension';
+}
+
/// The app's one store of Swarm's files; review screenshots put in one
/// that serves made-up pictures.
SwarmAttachmentStore swarmAttachments = SwarmAttachmentStore();
diff --git a/mobile/lib/swarm/swarm_chat_agents.dart b/mobile/lib/swarm/swarm_chat_agents.dart
new file mode 100644
index 000000000..7d6689ce5
--- /dev/null
+++ b/mobile/lib/swarm/swarm_chat_agents.dart
@@ -0,0 +1,553 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/logging/app_log.dart';
+import 'package:harness_mobile/phone/phone_sheet.dart';
+import 'package:harness_mobile/widgets/engine_identity.dart';
+
+import 'model.dart';
+import 'swarm_buddy.dart' show swarmCanWrite;
+import 'swarm_reader.dart';
+import 'swarm_request.dart';
+import 'swarm_session.dart' show SwarmScope;
+import 'swarm_start.dart' show SwarmComputers;
+
+/// A session running on one of the person's computers, as Add agent lists
+/// it: the computer's id and name, the session's id there ([harnessId]), its
+/// name and its engine.
+typedef SwarmRunningSession = ({
+ String machineId,
+ String machine,
+ String harnessId,
+ String name,
+ String engine,
+});
+
+/// The sessions running on the person's computers that may join a Swarm, as
+/// Desktop's Add agent lists those of the computers it reaches: the app's own
+/// (`AppSwarmComputers`), a stand-in in a test. Apart from [SwarmComputers],
+/// so a stand-in of those need not list any: none listed is none to attach.
+abstract interface class SwarmRunningSessions {
+ List<SwarmRunningSession> get running;
+}
+
+/// One row of Add agent: an agent already in the Swarm ([agentId]), or a
+/// session running on one of the person's computers ([session]).
+class SwarmAgentChoice {
+ SwarmAgentChoice.agent(SuperTabAgent agent, this.name)
+ : key = 'agent:${agent.id}',
+ agentId = agent.id,
+ engine = agent.engine,
+ session = null;
+
+ SwarmAgentChoice.session(SwarmRunningSession this.session)
+ : key = 'session:${session.machineId}/${session.harnessId}',
+ agentId = null,
+ name = session.name,
+ engine = session.engine;
+
+ /// Which row it is, the same at every read.
+ final String key;
+ final String name, engine;
+ final String? agentId;
+ final SwarmRunningSession? session;
+}
+
+/// What Add agent and Remove from Swarm sent to one Swarm and the server has
+/// not answered yet: an agent being removed leaves the Team at once and comes
+/// back if the server refuses; a row being added says so and is not sent
+/// twice. One per [SwarmReader], for as long as it lasts.
+class SwarmAgentWrites extends ChangeNotifier {
+ SwarmAgentWrites._();
+
+ static final _byReader = Expando<SwarmAgentWrites>('SwarmAgentWrites');
+
+ static SwarmAgentWrites of(SwarmReader reader) =>
+ _byReader[reader] ??= SwarmAgentWrites._();
+
+ final _removing = <String>{};
+ final _adding = <(String, String)>{};
+
+ /// Agent [agentId]'s removal is on its way.
+ bool removing(String agentId) => _removing.contains(agentId);
+
+ /// The row keyed [key] ([SwarmAgentChoice.key]) is on its way into chat
+ /// [chatId].
+ bool adding(String chatId, String key) => _adding.contains((chatId, key));
+
+ void _changed() => notifyListeners();
+}
+
+/// Whether the reader may add an agent to chat [chatId], as Desktop's Members
+/// offers Add agent (`roster.dart`, `_addAgent`): someone who may write, to a
+/// chat that is open and shared with its project; never a private chat or a
+/// Buddy chat, which stays its owner's and their Buddy's (backend
+/// `BUDDY_CHAT_FIXED`). The project chat is one: a session shared there joins
+/// the project, for its tasks (#2207).
+bool swarmCanAddAgent(SwarmReader reader, String chatId) {
+ final snapshot = reader.snapshot;
+ if (reader.accessRevoked || snapshot == null) return false;
+ final chat = snapshot.conversation(chatId);
+ return chat != null &&
+ !chat.archived &&
+ chat.audience == null &&
+ !chat.isBuddyChat &&
+ !reader.buddies.chatOwners.containsKey(chatId) &&
+ swarmCanWrite(reader);
+}
+
+/// Add agent's rows for chat [chatId], as Desktop's picker offers them
+/// (`swarm_screen.dart` `_openSearch`): the Swarm's agents of the chat's
+/// project not in it yet, by name — never a Buddy — then the sessions
+/// [running] on the person's computers that are not in the Swarm. The project
+/// chat holds only its coordinator among agents (#2207), so an agent of the
+/// Swarm, which the server would refuse there, is not offered in it; a
+/// session shared there joins the project. Empty when the reader may not add
+/// one ([swarmCanAddAgent]).
+List<SwarmAgentChoice> swarmAgentChoices(
+ SwarmReader reader,
+ String chatId,
+ List<SwarmRunningSession> running,
+) {
+ if (!swarmCanAddAgent(reader, chatId)) return const [];
+ final snapshot = reader.snapshot!;
+ final chat = snapshot.conversation(chatId)!;
+ final members = [
+ if (!snapshot.isProjectLead(chatId))
+ for (final agent in snapshot.agents)
+ if (!agent.isBuddy &&
+ agent.projectId == chat.projectId &&
+ !chat.agentIds.contains(agent.id))
+ SwarmAgentChoice.agent(agent, snapshot.agentName(agent.id)),
+ ];
+ String sortName(SwarmAgentChoice c) => c.name.toLowerCase();
+ members.sort((a, b) {
+ final byName = sortName(a).compareTo(sortName(b));
+ return byName != 0 ? byName : a.key.compareTo(b.key);
+ });
+ return [
+ ...members,
+ // One already in the Swarm is its agent's row, or none: a Buddy, or an
+ // agent of another project or already here.
+ for (final session in running)
+ if (!snapshot.agents.any(
+ (a) =>
+ a.machineId == session.machineId &&
+ a.harnessId == session.harnessId,
+ ))
+ SwarmAgentChoice.session(session),
+ ];
+}
+
+/// The longest name the backend takes (commands.ts `title`).
+const _maxName = 160;
+
+/// [name] as `agent.add` takes it: trimmed, at most [_maxName] characters,
+/// never half a character.
+String _nameToSend(String name) {
+ var trimmed = name.trim();
+ if (trimmed.isEmpty) return 'Agent';
+ if (trimmed.length <= _maxName) return trimmed;
+ trimmed = trimmed.substring(0, _maxName);
+ final last = trimmed.codeUnitAt(_maxName - 1);
+ // A lead surrogate cut from its pair.
+ if (last >= 0xD800 && last <= 0xDBFF) {
+ trimmed = trimmed.substring(0, _maxName - 1);
+ }
+ return trimmed.trimRight();
+}
+
+/// Adds [choice] to chat [chatId], as Desktop's `addSuperTabAgent` does: an
+/// agent of the Swarm joins it (`conversation.agent`); a running session is
+/// shared into it (`agent.add`), and its computer is woken to host it through
+/// [computers]. Null once the server kept it, the Swarm is read again and its
+/// computer answered, else the sentence to show. A row already on its way sends nothing again.
+Future<String?> swarmAddAgent(
+ SwarmReader reader,
+ String chatId,
+ SwarmAgentChoice choice, {
+ SwarmComputers? computers,
+}) async {
+ if (!swarmCanAddAgent(reader, chatId)) return _notAllowed;
+ final writes = SwarmAgentWrites.of(reader);
+ final pending = (chatId, choice.key);
+ if (!writes._adding.add(pending)) return null;
+ writes._changed();
+ try {
+ final session = choice.session;
+ // A session already in the Swarm joins as its agent (Desktop's
+ // addSuperTabAgent): it may have been added since the sheet was drawn.
+ final agentId =
+ choice.agentId ??
+ reader.snapshot?.agents
+ .where(
+ (a) =>
+ a.machineId == session?.machineId &&
+ a.harnessId == session?.harnessId,
+ )
+ .firstOrNull
+ ?.id;
+ if (agentId != null) {
+ return await _send(reader, {
+ 'type': 'conversation.agent',
+ 'conversationId': chatId,
+ 'agentId': agentId,
+ 'present': true,
+ 'lead': false,
+ });
+ }
+ if (session == null) return _notAllowed;
+ return await _send(
+ reader,
+ {
+ 'type': 'agent.add',
+ 'conversationId': chatId,
+ 'machineId': session.machineId,
+ 'harnessId': session.harnessId,
+ 'name': _nameToSend(session.name),
+ 'lead': false,
+ // What it runs is its host's to report (agent.configuration): the
+ // phone reads no model of a session.
+ 'configuration': {
+ 'engine': session.engine,
+ 'model': null,
+ 'effort': null,
+ 'contextWindow': null,
+ 'engineVersion': null,
+ },
+ },
+ // Its host reads the Swarm now, not at its next look. On a computer
+ // whose host never ran, nothing else starts it, so a wake not answered
+ // is said; the agent stays added.
+ kept: () async {
+ try {
+ await computers?.ask(session.machineId, {'action': 'wake'});
+ return null;
+ } catch (failure) {
+ appLog.warn(
+ 'swarm',
+ 'A computer did not answer a wake: ${failure.runtimeType}',
+ );
+ return "${session.machine} didn't answer, so it may not have picked "
+ 'up ${session.name} yet.';
+ }
+ },
+ );
+ } finally {
+ writes._adding.remove(pending);
+ writes._changed();
+ }
+}
+
+/// What the reader may do to agent [agentId] of a Swarm, as Desktop's Members
+/// row offers it (`roster.dart` `_canRemove`, `_removeReason`): remove it
+/// from the Swarm when they may write and it is theirs, or the Swarm is;
+/// never a project's coordinator while it is one ([removeReason], the
+/// desktop's words). The server checks both again (`agent.remove`
+/// FORBIDDEN). Null once the Swarm can no longer be read, or the agent is
+/// gone from it.
+typedef SwarmAgentRights = ({bool remove, String? removeReason});
+
+SwarmAgentRights? swarmAgentRights(SwarmReader reader, String agentId) {
+ final snapshot = reader.snapshot;
+ if (reader.accessRevoked || snapshot == null) return null;
+ final agent = snapshot.agent(agentId);
+ if (agent == null) return null;
+ return (
+ remove:
+ swarmCanWrite(reader) &&
+ (snapshot.ownerId == reader.accountId ||
+ agent.contributorId == reader.accountId),
+ removeReason: snapshot.leadProtectionReason(agentId),
+ );
+}
+
+/// Removes agent [agentId] from the Swarm (`agent.remove`): it leaves the
+/// Team at once ([SwarmAgentWrites.removing]) and comes back if the server
+/// refuses. Null once the server kept it and the Swarm is read again, else
+/// the sentence to show.
+Future<String?> swarmRemoveAgent(SwarmReader reader, String agentId) async {
+ final rights = swarmAgentRights(reader, agentId);
+ if (rights == null || !rights.remove) return _notAllowed;
+ if (rights.removeReason case final reason?) return reason;
+ final writes = SwarmAgentWrites.of(reader);
+ if (!writes._removing.add(agentId)) return null;
+ writes._changed();
+ try {
+ return await _send(reader, {'type': 'agent.remove', 'agentId': agentId});
+ } finally {
+ writes._removing.remove(agentId);
+ writes._changed();
+ }
+}
+
+const _notAllowed = 'This action is no longer available.';
+const _notSent = 'Could not reach this Swarm. Try again.';
+
+/// Sends [command]; once the server kept it, [kept], then a read begun after
+/// it, so what is drawn next is the server's.
+Future<String?> _send(
+ SwarmReader reader,
+ Map<String, dynamic> command, {
+ Future<String?> Function()? kept,
+}) async {
+ try {
+ await reader.request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',
+ body: {'operationId': superTabOperationId(), 'command': command},
+ );
+ } on SuperTabFailure catch (failure) {
+ return failure.message;
+ } catch (_) {
+ // A call lost on the way (a timeout, a socket dropped) is no answer.
+ return _notSent;
+ }
+ final after = kept?.call();
+ // A read under way began before the server kept it: one more after it.
+ if (reader.refreshing) await reader.refresh();
+ await reader.refresh();
+ return after;
+}
+
+/// Says [error] at the foot of the screen, unless the screen is gone or the
+/// Swarm can no longer be read.
+void _tell(
+ ScaffoldMessengerState? messenger,
+ SwarmReader reader,
+ String? error,
+) {
+ if (error == null ||
+ messenger == null ||
+ !messenger.mounted ||
+ reader.accessRevoked) {
+ return;
+ }
+ messenger.showSnackBar(
+ SnackBar(key: const ValueKey('swarm-agent-failed'), content: Text(error)),
+ );
+}
+
+/// Takes [route] down once [gone] says so, as the Swarm is read; not while
+/// the reader tells its listeners: once this frame is done.
+void _closeWhen(Route<void> route, SwarmReader reader, bool Function() gone) {
+ void check() {
+ if (!gone()) return;
+ reader.removeListener(check);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (route.isActive) route.navigator?.removeRoute(route);
+ });
+ }
+
+ reader.addListener(check);
+ unawaited(
+ (route is TransitionRoute<void> ? route.completed : route.popped)
+ .whenComplete(() => reader.removeListener(check)),
+ );
+}
+
+/// The chat ⋮ sheet's Add agent for chat [chatId], where the reader may add
+/// one ([swarmCanAddAgent]); none otherwise.
+List<PhoneSheetAction> swarmAddAgentActions(
+ BuildContext context,
+ SwarmReader reader,
+ String chatId,
+) => [
+ if (swarmCanAddAgent(reader, chatId))
+ PhoneSheetAction(
+ icon: LucideIcons.userPlus300,
+ label: 'Add agent',
+ chevron: true,
+ onTap: () => unawaited(showSwarmAddAgentSheet(context, reader, chatId)),
+ ),
+];
+
+/// Add agent for chat [chatId], titled as Desktop's picker is: the Swarm's
+/// agents that may join it, then the sessions running on each of the
+/// person's computers under its name ([swarmAgentChoices]), each with its
+/// engine. A tap closes the sheet and adds it ([swarmAddAgent]); the server's
+/// refusal shows at the foot of the screen. The rows follow the Swarm as it
+/// is read, a row on its way says so, and the sheet goes once the chat can no
+/// longer take an agent.
+Future<void> showSwarmAddAgentSheet(
+ BuildContext context,
+ SwarmReader reader,
+ String chatId,
+) {
+ if (!swarmCanAddAgent(reader, chatId) || !context.mounted) {
+ return Future.value();
+ }
+ final computers = SwarmScope.computersOf(context);
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ final writes = SwarmAgentWrites.of(reader);
+ List<SwarmRunningSession> running() => switch (computers) {
+ final SwarmRunningSessions sessions => sessions.running,
+ _ => const [],
+ };
+
+ PhoneSheetRows rows() {
+ final choices = swarmAgentChoices(reader, chatId, running());
+ PhoneSheetAction row(SwarmAgentChoice choice) {
+ final adding = writes.adding(chatId, choice.key);
+ return PhoneSheetAction(
+ icon: LucideIcons.bot300,
+ label: choice.name,
+ value: adding ? 'Adding…' : engineIdentity(choice.engine).label,
+ enabled: !adding,
+ onTap: () => unawaited(() async {
+ final error = await swarmAddAgent(
+ reader,
+ chatId,
+ choice,
+ computers: computers,
+ );
+ _tell(messenger, reader, error);
+ }()),
+ );
+ }
+
+ final machines = <String, ({String name, List<PhoneSheetAction> rows})>{};
+ for (final choice in choices) {
+ final session = choice.session;
+ if (session == null) continue;
+ (machines[session.machineId] ??= (
+ name: session.machine,
+ rows: [],
+ )).rows.add(row(choice));
+ }
+ return (
+ actions: [
+ if (choices.isEmpty)
+ PhoneSheetAction(
+ icon: LucideIcons.bot300,
+ label: 'No running agents',
+ enabled: false,
+ onTap: () {},
+ ),
+ ],
+ sections: [
+ PhoneSheetSection(
+ caption: 'Agents',
+ actions: [
+ for (final choice in choices)
+ if (choice.agentId != null) row(choice),
+ ],
+ ),
+ for (final machine in machines.values)
+ PhoneSheetSection(caption: machine.name, actions: machine.rows),
+ ],
+ );
+ }
+
+ return showPhoneSheet(
+ context,
+ title: 'Add agent to ${reader.snapshot?.name ?? 'Swarm'}',
+ rows: rows,
+ rebuildOn: Listenable.merge([reader, writes]),
+ onShown: (route) =>
+ _closeWhen(route, reader, () => !swarmCanAddAgent(reader, chatId)),
+ );
+}
+
+/// The long-press menu of an agent on a project's Team: Remove from Swarm,
+/// as Desktop's Members row menu offers it, for whoever may
+/// ([swarmAgentRights]); held back for a project's coordinator, which its
+/// row names in a word. The row follows the Swarm as it is read; the sheet
+/// goes once the agent, or the reader's right to remove it, is gone.
+Future<void> showSwarmAgentMenu(
+ BuildContext context,
+ SwarmReader reader,
+ String agentId,
+) {
+ final snapshot = reader.snapshot;
+ if (swarmAgentRights(reader, agentId)?.remove != true || snapshot == null) {
+ return Future.value();
+ }
+ PhoneSheetRows rows() {
+ final rights = swarmAgentRights(reader, agentId);
+ final project = reader.snapshot?.leadProjectForAgent(agentId);
+ return (
+ actions: [
+ if (rights != null && rights.remove)
+ PhoneSheetAction(
+ icon: LucideIcons.trash2300,
+ label: 'Remove from Swarm',
+ destructive: true,
+ enabled: rights.removeReason == null,
+ // The whole sentence is the desktop's line under the row; a
+ // sheet row has room for a word or two.
+ value: rights.removeReason == null || project == null
+ ? null
+ : reader.snapshot!.coordinatorNameOf(project.id),
+ onTap: () =>
+ unawaited(confirmSwarmRemoveAgent(context, reader, agentId)),
+ ),
+ ],
+ sections: const <PhoneSheetSection>[],
+ );
+ }
+
+ return showPhoneSheet(
+ context,
+ title: snapshot.agentName(agentId),
+ rows: rows,
+ rebuildOn: reader,
+ onShown: (route) => _closeWhen(
+ route,
+ reader,
+ () => swarmAgentRights(reader, agentId)?.remove != true,
+ ),
+ );
+}
+
+/// Asks before removing agent [agentId] from the Swarm, in the desktop's
+/// words (`roster.dart` `_remove`), then removes it ([swarmRemoveAgent]);
+/// the server's refusal shows at the foot of the screen. Nothing is asked or
+/// sent for someone who may not, an agent that changed meanwhile, or a Swarm
+/// the reader lost access to while it asked.
+Future<void> confirmSwarmRemoveAgent(
+ BuildContext context,
+ SwarmReader reader,
+ String agentId,
+) async {
+ bool allowed() {
+ final rights = swarmAgentRights(reader, agentId);
+ return rights != null && rights.remove && rights.removeReason == null;
+ }
+
+ final snapshot = reader.snapshot;
+ final agent = snapshot?.agent(agentId);
+ if (!allowed() || !context.mounted || snapshot == null || agent == null) {
+ return;
+ }
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ final generation = reader.generation;
+ final name = snapshot.agentName(agentId);
+ // The Mac, for an agent in that Mac's Harness Team account; named as the
+ // desktop names it: the person's own computer first, then the Swarm's
+ // record of it, which a computer used only for agents may not have.
+ final place = snapshot.placeOf(agent.machineId);
+ final own = SwarmScope.computersOf(context)?.own
+ .where((c) => c.id == place)
+ .firstOrNull
+ ?.name;
+ final pooled = snapshot.pool(place)?['name'];
+ final machine = switch ((own, pooled)) {
+ (final String own, _) when own.isNotEmpty => own,
+ (_, final String pooled) when pooled.isNotEmpty => pooled,
+ _ => 'its computer',
+ };
+ final confirmed = await confirmPhoneAction(
+ context,
+ icon: LucideIcons.trash2300,
+ title: 'Remove $name from this Swarm?',
+ message:
+ 'Any open task needs to be assigned again or closed. Its session on '
+ '$machine will stop.',
+ confirmLabel: 'Remove from Swarm',
+ );
+ if (!confirmed || reader.generation != generation || !allowed()) return;
+ _tell(messenger, reader, await swarmRemoveAgent(reader, agentId));
+}
diff --git a/mobile/lib/swarm/swarm_chat_menu.dart b/mobile/lib/swarm/swarm_chat_menu.dart
index 322098c26..c4af11666 100644
--- a/mobile/lib/swarm/swarm_chat_menu.dart
+++ b/mobile/lib/swarm/swarm_chat_menu.dart
@@ -9,6 +9,7 @@ import 'package:harness_mobile/shared/theme/app_icon_size.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/widgets/touch_target.dart';
+import 'swarm_chat_agents.dart';
import 'swarm_chat_manage.dart';
import 'swarm_chat_notify.dart';
import 'swarm_buddy.dart' show swarmIsOldBuddyChat;
@@ -122,8 +123,9 @@ Future<void> showSwarmNotifySheet(
}
}
-/// At the end of a chat's header: ⋮, whose sheet holds Rename and Archive
-/// where the person may ([swarmChatManage]) and the chat's Notifications
+/// At the end of a chat's header: ⋮, whose sheet holds Add agent
+/// ([swarmCanAddAgent]), Rename and Archive where the person may
+/// ([swarmChatManage]) and the chat's Notifications
/// ([swarmNotifySection]), as the desktop's chat menu does for every chat a
/// person reads, a viewer's too. Nothing while the chat is not
/// known. The sheet goes once the chat can no longer be read — access lost,
@@ -193,7 +195,7 @@ class _SwarmChatMenuButtonState extends State<SwarmChatMenuButton> {
widget.chatId,
onShown: (route) => _sheet = route,
// Work details, Rename and Archive where the desktop's chat menu has
- // them.
+ // them; Add agent where its Members does.
actions: () => [
if (swarmHasWorkDetails(widget.reader, widget.chatId))
PhoneSheetAction(
@@ -205,6 +207,7 @@ class _SwarmChatMenuButtonState extends State<SwarmChatMenuButton> {
chatId: widget.chatId,
),
),
+ ...swarmAddAgentActions(context, widget.reader, widget.chatId),
...swarmChatManageActions(context, widget.reader, widget.chatId),
],
).whenComplete(() => _sheet = null);
diff --git a/mobile/lib/swarm/swarm_computers.dart b/mobile/lib/swarm/swarm_computers.dart
index b4155ecd1..9e07f069e 100644
--- a/mobile/lib/swarm/swarm_computers.dart
+++ b/mobile/lib/swarm/swarm_computers.dart
@@ -11,6 +11,7 @@ import '../phone/phone_status.dart';
import '../phone/welcome/your_computer.dart';
import '../state/app_state.dart';
import 'swarm_agents.dart';
+import 'swarm_chat_agents.dart';
import 'swarm_start.dart';
/// The account's computers for Swarm's start screens, from the app's own
@@ -21,8 +22,10 @@ import 'swarm_start.dart';
/// a Swarm read waiting for a computer needs, `SwarmInbox.computerUp`) — not
/// at every change of the app's state, which moves with every frame a
/// terminal sends.
+///
+/// It also lists the sessions running on them, for Add agent ([running]).
class AppSwarmComputers extends ChangeNotifier
- implements SwarmComputers, SwarmAgentsSource {
+ implements SwarmComputers, SwarmAgentsSource, SwarmRunningSessions {
AppSwarmComputers(this.notifier) {
notifier.addListener(_changed);
_changed();
@@ -97,6 +100,12 @@ class AppSwarmComputers extends ChangeNotifier
Map<String, dynamic> payload,
) => notifier.swarmAskComputer(machineId, payload);
+ /// What runs on the computers now ([swarmRunningSessions]), read when
+ /// asked: told of by nothing here, since it moves with the app's state.
+ @override
+ List<SwarmRunningSession> get running =>
+ swarmRunningSessions(notifier.machineStates.values);
+
/// The machines tab's Try again: the account's list read again.
@override
Future<void> recheck() => notifier.retryMachines();
@@ -182,3 +191,40 @@ class AppSwarmAgents extends ChangeNotifier implements SwarmAgents {
super.dispose();
}
}
+
+/// The sessions running on [machines] that may join a Swarm, as Desktop's Add
+/// agent offers them (`swarm_screen.dart` `unavailable`): Claude Code or
+/// Codex, its terminal there and not stopped, the last used first; never one
+/// whose id the Swarm would refuse. Only on a computer answering now with a
+/// list of its own: one kept from the last run may name a session long gone.
+List<SwarmRunningSession> swarmRunningSessions(
+ Iterable<MachineState> machines,
+) => [
+ for (final machine in machines)
+ if (phoneMachineStatusOf(machine) == PhoneMachineStatus.ready &&
+ !machine.agentsFromCache)
+ for (final agent in [...machine.agents]..sort(_lastUsedFirst))
+ if (agent.engine case final engine?
+ when (engine == 'claude' || engine == 'codex') &&
+ agent.terminalAvailable &&
+ !agent.isStopped &&
+ _sessionId.hasMatch(agent.id))
+ (
+ machineId: machine.machine.machineId,
+ machine: machine.machine.displayName,
+ harnessId: agent.id,
+ name: agent.displayName,
+ engine: engine,
+ ),
+];
+
+int _lastUsedFirst(Agent a, Agent b) {
+ final at = a.lastUsedAt, bt = b.lastUsedAt;
+ if (at == null || bt == null) {
+ return (at == null ? 1 : 0) - (bt == null ? 1 : 0);
+ }
+ return bt.compareTo(at);
+}
+
+/// An id the Swarm takes for a session (backend commands.ts `id`).
+final _sessionId = RegExp(r'^[A-Za-z0-9_-]{1,160}$');
diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dart
index b6bff2a4d..ecc5cd71d 100644
--- a/mobile/lib/swarm/swarm_conversation_page.dart
+++ b/mobile/lib/swarm/swarm_conversation_page.dart
@@ -41,6 +41,7 @@ import 'swarm_outgoing_files.dart';
import 'swarm_inbox.dart';
import 'swarm_reader.dart';
import 'swarm_live_card.dart';
+import 'swarm_link_previews.dart';
import 'swarm_message_link.dart';
import 'swarm_message_receipt.dart';
import 'swarm_message_row.dart';
@@ -1006,6 +1007,10 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
nameOf: (kind, id) => _reactorName(c, kind, id),
onReact: view.canPost ? (emoji) => unawaited(t.react(m, emoji)) : null,
),
+ links: switch (_session) {
+ final session? => _linkPreviews(session, c, m, inThread: true),
+ null => null,
+ },
onLongPress: () => unawaited(_pickThreadReaction(c, t, m.id)),
);
}
@@ -1765,6 +1770,82 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
messageId: id,
);
+ /// The quote of [replyTo] in [conversationId] when the chat has not read
+ /// it: the original read by itself ([SwarmReadQuote]).
+ Widget _readQuote(
+ SwarmSession session,
+ SwarmConversation c,
+ String conversationId,
+ String replyTo, {
+ Key? key,
+ VoidCallback? onTap,
+ }) => SwarmReadQuote(
+ key: key,
+ reads: session.messageReads,
+ reader: c.reader,
+ link: SwarmMessageLink(
+ tabId: c.reader.tabId,
+ conversationId: conversationId,
+ messageId: replyTo,
+ ),
+ author: (original) => _quoted(c, original),
+ onTap: onTap,
+ );
+
+ /// The previews of the message links [m] says, under it; null when it
+ /// says none. A link into another of the account's Swarms is read with
+ /// that Swarm's reader; one into a Swarm the account does not list is
+ /// unavailable.
+ Widget? _linkPreviews(
+ SwarmSession session,
+ SwarmConversation c,
+ SuperTabMessage m, {
+ bool inThread = false,
+ }) {
+ final links = SwarmMessageLink.allIn(m.text);
+ if (links.isEmpty) return null;
+ final tabId = c.reader.tabId;
+ return SwarmLinkPreviews(
+ key: ValueKey('swarm-link-previews-${m.id}'),
+ links: links,
+ reads: session.messageReads,
+ reread: c.reader.reads,
+ readerOf: (id) => id == tabId ? c.reader : session.inbox.reader(id),
+ tabId: tabId,
+ chatId: m.conversationId,
+ held: (link) => link.tabId == tabId && link.conversationId == c.id
+ ? c.messages.where((held) => held.id == link.messageId).firstOrNull
+ : null,
+ onOpen: (link) => _openLink(c, link, inThread: inThread),
+ );
+ }
+
+ /// Opens the message [link] points at: brought into view and lit when it
+ /// is in this chat, else its chat over this one, at it, which says what it
+ /// cannot show. From a thread it always opens its chat over the thread.
+ void _openLink(
+ SwarmConversation c,
+ SwarmMessageLink link, {
+ bool inThread = false,
+ }) {
+ if (!mounted) return;
+ if (!inThread &&
+ link.tabId == c.reader.tabId &&
+ link.conversationId == c.id) {
+ unawaited(_jumpTo(c, link.messageId));
+ return;
+ }
+ unawaited(
+ Navigator.of(context).push(
+ swarmChatRoute(
+ swarmId: link.tabId,
+ conversationId: link.conversationId,
+ messageId: link.messageId,
+ ),
+ ),
+ );
+ }
+
/// What [c]'s list draws, oldest first ([rows]): its main stream, a reply
/// only in its thread showing there alone, with a task's steps' rows merged
/// in by time (task steps design) ([stream]); less the prompt warnings
@@ -2000,10 +2081,19 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
)
: m.replyTo == null
? null
+ : reply == null
+ ? _readQuote(
+ session,
+ c,
+ m.conversationId,
+ m.replyTo!,
+ key: ValueKey('swarm-quote-${m.id}'),
+ onTap: () => unawaited(_jumpTo(c, m.replyTo!)),
+ )
: SwarmQuote(
key: ValueKey('swarm-quote-${m.id}'),
author: quoted,
- text: reply?.text,
+ text: reply.text,
onTap: () => unawaited(_jumpTo(c, m.replyTo!)),
),
actions: acting,
@@ -2023,6 +2113,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
key: ValueKey('swarm-card-${m.id}'),
facts: card,
),
+ links: _linkPreviews(session, c, m),
thread: line == null || line.replies == 0
? null
: SwarmThreadLine(
@@ -2139,10 +2230,9 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
state: post.state,
quote: post.replyTo == null
? null
- : SwarmQuote(
- author: reply == null ? null : _quoted(c, reply),
- text: reply?.text,
- ),
+ : reply == null
+ ? _readQuote(session, c, c.id, post.replyTo!)
+ : SwarmQuote(author: _quoted(c, reply), text: reply.text),
onSendAgain: () => unawaited(_retry(c, post)),
onDelete: () => c.deletePost(post),
);
diff --git a/mobile/lib/swarm/swarm_file_download.dart b/mobile/lib/swarm/swarm_file_download.dart
new file mode 100644
index 000000000..815e2949d
--- /dev/null
+++ b/mobile/lib/swarm/swarm_file_download.dart
@@ -0,0 +1,96 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:share_plus/share_plus.dart';
+
+import 'package:harness_mobile/logging/app_log.dart';
+
+import 'swarm_attachment_store.dart';
+import 'swarm_style.dart';
+
+/// The system's share sheet; tests stand in for it.
+@visibleForTesting
+Future<void> Function(ShareParams params) swarmShareSheet = (params) async {
+ await SharePlus.instance.share(params);
+};
+
+/// Said when a file could not be handed on (the desktop's words for a
+/// Download that failed).
+const swarmFileNotSaved = 'Couldn’t save this file.';
+
+/// A chat file viewer's Download (the desktop's): the file the phone keeps
+/// handed to the system's share sheet under its own name — Save to Files,
+/// Save Image and AirDrop on iOS, the chooser on Android — as an app on a
+/// phone has no folder of its own to save into. Off until [file] is there;
+/// one sheet at a time.
+class SwarmDownloadButton extends StatefulWidget {
+ const SwarmDownloadButton({
+ super.key,
+ required this.name,
+ required this.file,
+ required this.store,
+ });
+
+ /// The file's name in its message: what it is saved as.
+ final String name;
+
+ /// The copy [store] keeps; null while it is on its way, or when it could
+ /// not be had.
+ final File? file;
+ final SwarmAttachmentStore store;
+
+ @override
+ State<SwarmDownloadButton> createState() => _SwarmDownloadButtonState();
+}
+
+class _SwarmDownloadButtonState extends State<SwarmDownloadButton> {
+ /// A sheet asked for is still up: iOS refuses a second over it, and Android
+ /// stacks two choosers.
+ bool _sharing = false;
+
+ Future<void> _download(Rect? origin) async {
+ final kept = widget.file;
+ if (kept == null || _sharing) return;
+ setState(() => _sharing = true);
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ try {
+ await widget.store.named(
+ kept,
+ widget.name,
+ (copy) => swarmShareSheet(
+ ShareParams(files: [XFile(copy.path)], sharePositionOrigin: origin),
+ ),
+ );
+ } catch (error) {
+ // Its kind only: the error's path carries the file's name.
+ appLog.failure(
+ 'swarm',
+ 'A Swarm file could not be shared: ${error.runtimeType}',
+ );
+ messenger?.showSnackBar(const SnackBar(content: Text(swarmFileNotSaved)));
+ } finally {
+ if (mounted) setState(() => _sharing = false);
+ }
+ }
+
+ /// The button's own rectangle on screen: the sheet's anchor on an iPad,
+ /// where it is a popover.
+ Rect? _origin() {
+ final box = context.findRenderObject() as RenderBox?;
+ return box == null || !box.attached
+ ? null
+ : box.localToGlobal(Offset.zero) & box.size;
+ }
+
+ @override
+ Widget build(BuildContext context) => SwarmIconButton(
+ key: const ValueKey('swarm-file-download'),
+ icon: LucideIcons.download300,
+ label: 'Download',
+ onPressed: widget.file == null || _sharing
+ ? null
+ : () => unawaited(_download(_origin())),
+ );
+}
diff --git a/mobile/lib/swarm/swarm_file_kind.dart b/mobile/lib/swarm/swarm_file_kind.dart
new file mode 100644
index 000000000..16fbc5083
--- /dev/null
+++ b/mobile/lib/swarm/swarm_file_kind.dart
@@ -0,0 +1,153 @@
+import 'dart:typed_data';
+
+import 'package:flutter/widgets.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'model.dart';
+
+/// The largest chat file read into the text viewer (the desktop's
+/// `kAttachmentTextMaxBytes`); a bigger one opens in the browser. Specs and
+/// logs sit well under it, though a message's file may weigh up to 256 MB.
+const swarmTextMaxBytes = 2 * 1024 * 1024;
+
+/// What a chat file is, as far as which view opens it is concerned.
+enum SwarmFileKind { text, markdown, other }
+
+/// [name]'s kind, told by its extension, or by the whole name for the few
+/// text files that have none (`Makefile`, `LICENSE`): the desktop's
+/// `finderFileKind`, less the pictures, which a chat shows in place.
+SwarmFileKind swarmFileKind(String name) {
+ final lower = _base(name);
+ final dot = lower.lastIndexOf('.');
+ final extension = dot < 0 ? '' : lower.substring(dot + 1);
+ if (_markdown.contains(extension)) return SwarmFileKind.markdown;
+ if (_binary.contains(extension)) return SwarmFileKind.other;
+ if (_text.contains(extension) || _textNames.contains(lower)) {
+ return SwarmFileKind.text;
+ }
+ return SwarmFileKind.other;
+}
+
+/// Whether [file] opens in the text viewer: text by its name and small enough
+/// to read in place (the desktop's `opensAsText`). Every other file opens in
+/// the browser.
+bool swarmOpensAsText(SuperTabAttachment file) =>
+ file.size <= swarmTextMaxBytes &&
+ swarmFileKind(file.name) != SwarmFileKind.other;
+
+/// Whether [bytes] read as text: no NUL byte, and few enough control
+/// characters that it is not a binary format (the desktop's `looksLikeText`).
+bool swarmLooksLikeText(Uint8List bytes) {
+ if (bytes.isEmpty) return true;
+ var control = 0;
+ for (final byte in bytes) {
+ if (byte == 0) return false;
+ if (byte < 0x09 || (byte > 0x0d && byte < 0x20)) control++;
+ }
+ return control * 100 < bytes.length * 2;
+}
+
+/// The mark for a file named [name], told by its extension, or for the few
+/// build files that have none by the name itself; a kind this does not know
+/// gets the plain file. The desktop's `fileTypeIcon`, mark for mark.
+IconData swarmFileIcon(String name) {
+ final lower = _base(name);
+ final dot = lower.lastIndexOf('.');
+ final key = dot < 0 ? lower : lower.substring(dot + 1);
+ return _icons[key] ?? LucideIcons.file;
+}
+
+/// [name] without any folder a sender's row put before it, in lower case.
+String _base(String name) {
+ final lower = name.toLowerCase();
+ final slash = lower.lastIndexOf(RegExp(r'[/\\]'));
+ return slash < 0 ? lower : lower.substring(slash + 1);
+}
+
+const _markdown = {'md', 'markdown', 'mdx'};
+
+/// Extensions never worth reading as text: they are binary even when their
+/// first bytes happen to look like text.
+const _binary = {
+ 'pdf', 'zip', 'gz', 'tgz', 'tar', 'bz2', 'xz', 'zst', '7z', 'rar', //
+ 'dmg', 'iso', 'jar', 'apk', 'ipa', 'exe', 'dll', 'so', 'dylib', 'o', 'a',
+ 'class', 'wasm', 'mp3', 'mp4', 'mov', 'm4a', 'wav', 'flac', 'ogg', 'webm',
+ 'mkv', 'avi', 'heic', 'heif', 'avif', 'tif', 'tiff', 'psd', 'sketch',
+ 'fig', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'key', 'numbers',
+ 'pages', 'sqlite', 'sqlite3', 'db', 'ttf', 'otf', 'woff', 'woff2', //
+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'wbmp', 'svg',
+};
+
+const _text = {
+ 'txt', 'log', 'rst', 'csv', 'tsv', 'diff', 'patch', //
+ 'json', 'jsonl', 'json5', 'yaml', 'yml', 'toml', 'xml', 'plist', 'ini',
+ 'env', 'lock', 'conf', 'cfg', 'properties', 'gradle', 'cmake',
+ 'dart', 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'py', 'go', 'rs', 'java',
+ 'kt', 'kts', 'swift', 'c', 'cc', 'cpp', 'h', 'hpp', 'm', 'mm', 'cs', 'rb',
+ 'php', 'lua', 'r', 'html', 'htm', 'css', 'scss', 'sass', 'less', 'vue',
+ 'svelte', 'sql', 'graphql', 'gql', 'proto', 'ipynb', 'sh', 'bash', 'zsh',
+ 'fish', 'ps1', 'bat', 'command', 'tf', 'hcl', 'nix', 'ex', 'exs', 'erl',
+ 'hs', 'ml', 'clj', 'scala', 'zig', 'v', 'sv', 'vhd', 'ino', 'gitignore',
+ 'gitattributes', 'editorconfig', 'npmrc', 'nvmrc', 'prettierrc',
+ 'eslintrc', 'babelrc', 'dockerignore', 'srt', 'vtt', 'tex', 'bib',
+};
+
+const _textNames = {
+ 'makefile', 'dockerfile', 'license', 'licence', 'readme', 'changelog', //
+ 'procfile', 'gemfile', 'rakefile', 'podfile', 'brewfile', 'justfile',
+ 'codeowners', 'authors', 'notice',
+};
+
+/// Each kind's mark, and the extensions that are of that kind.
+const _kinds = <(IconData, List<String>)>[
+ (
+ LucideIcons.fileImage,
+ [
+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'tif', 'tiff', //
+ 'heic', 'heif', 'avif', 'ico', 'svg', 'psd', 'fig', 'sketch',
+ ],
+ ),
+ (LucideIcons.filePlay, ['mp4', 'mov', 'm4v', 'webm', 'mkv', 'avi']),
+ (LucideIcons.fileMusic, ['mp3', 'wav', 'm4a', 'aac', 'flac', 'ogg', 'opus']),
+ (
+ LucideIcons.fileArchive,
+ [
+ 'zip', 'tar', 'gz', 'tgz', 'bz2', 'xz', 'zst', '7z', 'rar', //
+ 'dmg', 'iso', 'jar', 'apk', 'ipa',
+ ],
+ ),
+ (LucideIcons.fileText, ['pdf', 'doc', 'docx', 'rtf', 'odt', 'pages', 'epub']),
+ (LucideIcons.fileType, ['txt', 'md', 'markdown', 'mdx', 'rst', 'log']),
+ (
+ LucideIcons.fileSpreadsheet,
+ ['csv', 'tsv', 'xls', 'xlsx', 'numbers', 'ods'],
+ ),
+ (LucideIcons.presentation, ['ppt', 'pptx', 'key', 'odp']),
+ (
+ LucideIcons.fileCode,
+ [
+ 'dart', 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'py', 'go', 'rs', //
+ 'java', 'kt', 'swift', 'c', 'cc', 'cpp', 'h', 'hpp', 'm', 'mm', //
+ 'cs', 'rb', 'php', 'lua', 'r', 'html', 'css', 'scss', 'vue', //
+ 'svelte', 'sql', 'ipynb', 'makefile', 'dockerfile',
+ ],
+ ),
+ (
+ LucideIcons.fileBraces,
+ [
+ 'json', 'jsonl', 'yaml', 'yml', 'toml', 'xml', 'plist', 'ini', //
+ 'env', 'lock', 'conf',
+ ],
+ ),
+ (
+ LucideIcons.fileTerminal,
+ ['sh', 'bash', 'zsh', 'fish', 'ps1', 'bat', 'command'],
+ ),
+ (LucideIcons.fileDiff, ['diff', 'patch']),
+ (LucideIcons.database, ['db', 'sqlite', 'sqlite3']),
+];
+
+final _icons = <String, IconData>{
+ for (final (icon, extensions) in _kinds)
+ for (final extension in extensions) extension: icon,
+};
diff --git a/mobile/lib/swarm/swarm_file_viewer.dart b/mobile/lib/swarm/swarm_file_viewer.dart
new file mode 100644
index 000000000..9298803f4
--- /dev/null
+++ b/mobile/lib/swarm/swarm_file_viewer.dart
@@ -0,0 +1,340 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:markdown/markdown.dart' as md;
+import 'package:url_launcher/url_launcher.dart';
+
+import 'package:harness_mobile/logging/app_log.dart';
+import 'package:harness_mobile/phone/tty.dart';
+import 'package:harness_mobile/shared/theme/app_space.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/app_type.dart';
+import 'package:harness_mobile/shared/widgets/empty_state.dart';
+import 'package:harness_mobile/shared/widgets/skeleton.dart';
+
+import 'model.dart';
+import 'swarm_attachment.dart' show swarmKeptFile;
+import 'swarm_attachment_store.dart';
+import 'swarm_file_download.dart';
+import 'swarm_file_kind.dart';
+import 'swarm_file_links.dart';
+import 'swarm_message_text.dart';
+import 'swarm_style.dart';
+
+/// A text file from a chat, read only, full screen (the desktop's
+/// `AttachmentTextViewer`): Markdown rendered with its source a tap away,
+/// anything else as it is written, in the terminal's face. Fetched into
+/// [store] when this opens, by [url], and with [fileRef] by a fresh link once
+/// that one ends. Close and Download at the top; Open in browser
+/// ([openInBrowser]) when it cannot be shown. A file larger than its message
+/// said opens in the browser instead, as a large one does.
+///
+/// It shows a file [store] keeps for one account, so it goes when that
+/// changes ([SwarmAttachmentStore.turns]), as the picture viewer does: blank
+/// at once, its text let go, and closed.
+class SwarmFileViewer extends StatefulWidget {
+ const SwarmFileViewer({
+ super.key,
+ required this.file,
+ required this.url,
+ required this.store,
+ required this.turn,
+ required this.openInBrowser,
+ this.fileRef,
+ });
+
+ final SuperTabAttachment file;
+ final Uri url;
+ final SwarmFileRef? fileRef;
+ final SwarmAttachmentStore store;
+
+ /// The store's turn as the file was opened: shown only while it holds.
+ final int turn;
+
+ /// How the chat opens a file in the browser.
+ final Future<bool> Function(Uri url) openInBrowser;
+
+ @override
+ State<SwarmFileViewer> createState() => _SwarmFileViewerState();
+}
+
+class _SwarmFileViewerState extends State<SwarmFileViewer> {
+ /// The copy [SwarmFileViewer.store] keeps, once fetched.
+ File? _kept;
+
+ /// The file's text in lines, once read and found to be text.
+ List<String>? _lines;
+
+ /// A Markdown file's text whole, to render.
+ String? _text;
+
+ bool _failed = false;
+ bool _notText = false;
+ bool _source = false;
+ bool _gone = false;
+
+ /// A link for the browser is being asked for: another tap waits for it.
+ bool _browsing = false;
+
+ bool get _markdown =>
+ swarmFileKind(widget.file.name) == SwarmFileKind.markdown;
+
+ @override
+ void initState() {
+ super.initState();
+ widget.store.turns.addListener(_turned);
+ if (widget.store.turns.value != widget.turn) {
+ _gone = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) => _close());
+ } else {
+ unawaited(_read());
+ }
+ }
+
+ @override
+ void dispose() {
+ widget.store.turns.removeListener(_turned);
+ super.dispose();
+ }
+
+ void _turned() {
+ if (_gone || widget.store.turns.value == widget.turn) return;
+ setState(() {
+ _gone = true;
+ _kept = null;
+ _lines = null;
+ _text = null;
+ });
+ _close();
+ }
+
+ void _close() {
+ if (!mounted) return;
+ final route = ModalRoute.of(context);
+ if (route != null && route.isActive) {
+ Navigator.of(context).removeRoute(route);
+ }
+ }
+
+ Future<void> _read() async {
+ try {
+ final kept = await swarmKeptFile(
+ widget.store,
+ widget.file,
+ at: widget.url,
+ ref: widget.fileRef,
+ );
+ // Larger than its message said: read in the browser, as a large file is.
+ if (await kept.length() > swarmTextMaxBytes) {
+ if (!mounted || _gone) return;
+ if (!await _openInBrowser(close: true) && mounted && !_gone) {
+ setState(() => _failed = true);
+ }
+ return;
+ }
+ final bytes = await kept.readAsBytes();
+ if (!mounted || _gone) return;
+ final text = swarmLooksLikeText(bytes)
+ ? utf8.decode(bytes, allowMalformed: true)
+ : null;
+ setState(() {
+ _kept = kept;
+ _text = _markdown ? text : null;
+ _lines = text == null ? null : swarmTextLines(text);
+ _notText = text == null;
+ });
+ } catch (error) {
+ // Its kind only: the error carries the file's signed link.
+ appLog.failure(
+ 'swarm',
+ 'A Swarm file could not be read: ${error.runtimeType}',
+ );
+ if (mounted && !_gone) setState(() => _failed = true);
+ }
+ }
+
+ /// The file in the browser, by a link that opens now; with [close], this
+ /// viewer goes as it opens. False when no link could be had.
+ Future<bool> _openInBrowser({bool close = false}) async {
+ if (_browsing) return false;
+ final ref = widget.fileRef;
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ final Uri? url;
+ _browsing = true;
+ try {
+ url = ref == null
+ ? widget.url
+ : await swarmOpenableLink(
+ context,
+ ref,
+ onProblem: (text) =>
+ messenger?.showSnackBar(SnackBar(content: Text(text))),
+ );
+ } finally {
+ _browsing = false;
+ }
+ if (url == null || !mounted || _gone) return false;
+ if (close) _close();
+ unawaited(widget.openInBrowser(url));
+ return true;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ final shown = !_gone && _lines != null;
+ return Scaffold(
+ key: const ValueKey('swarm-file-viewer'),
+ backgroundColor: tty.ground,
+ body: SafeArea(
+ bottom: false,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SwarmTopBar(
+ leading: SwarmIconButton(
+ key: const ValueKey('swarm-file-close'),
+ icon: LucideIcons.x300,
+ label: 'Close',
+ onPressed: () => Navigator.of(context).maybePop(),
+ ),
+ title: _gone ? '' : widget.file.name,
+ trailing: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (_markdown && shown)
+ SwarmIconButton(
+ key: const ValueKey('swarm-file-source'),
+ icon: _source ? LucideIcons.eye300 : LucideIcons.code300,
+ label: _source ? 'Show preview' : 'Show source',
+ onPressed: () => setState(() => _source = !_source),
+ ),
+ SwarmDownloadButton(
+ name: widget.file.name,
+ file: _gone ? null : _kept,
+ store: widget.store,
+ ),
+ ],
+ ),
+ ),
+ Expanded(child: _body(tty)),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _body(Tty tty) {
+ if (_gone) return const SizedBox.expand();
+ final browse = SwarmButton(
+ key: const ValueKey('swarm-file-browser'),
+ label: 'Open in browser',
+ onPressed: () => unawaited(_openInBrowser()),
+ );
+ if (_failed) {
+ return EmptyState(
+ icon: LucideIcons.circleAlert300,
+ title: 'Can’t open this file',
+ message: 'It couldn’t be downloaded. Try again in the browser.',
+ compact: true,
+ action: browse,
+ );
+ }
+ if (_notText) {
+ return EmptyState(
+ icon: LucideIcons.file300,
+ title: 'No preview',
+ message: 'This file isn’t text that can be shown here.',
+ compact: true,
+ action: browse,
+ );
+ }
+ final padding = EdgeInsets.fromLTRB(
+ AppSpace.m,
+ AppSpace.xs,
+ AppSpace.m,
+ MediaQuery.paddingOf(context).bottom + AppSpace.xl,
+ );
+ final lines = _lines;
+ if (lines == null) {
+ return SkeletonList(
+ key: const ValueKey('swarm-file-loading'),
+ rows: 12,
+ padding: padding,
+ itemBuilder: (_, i) => Padding(
+ padding: const EdgeInsets.symmetric(vertical: AppSpace.xs + 2),
+ child: FractionallySizedBox(
+ alignment: Alignment.centerLeft,
+ widthFactor: const [.9, .7, .8, .5][i % 4],
+ child: const Skeleton.text(),
+ ),
+ ),
+ );
+ }
+ if (_text case final text? when !_source) {
+ return SelectionArea(
+ child: SingleChildScrollView(
+ key: const ValueKey('swarm-file-markdown'),
+ padding: padding,
+ child: MarkdownBody(
+ data: text,
+ extensionSet: md.ExtensionSet.gitHubFlavored,
+ styleSheet: swarmMarkdownStyle(context),
+ // A file's pictures stay labels: nothing it points at is fetched.
+ imageBuilder: (_, _, alt) => Text(
+ alt?.isNotEmpty == true ? 'Image: $alt' : 'Image',
+ style: AppType.caption(color: AppPalette.textSecondary),
+ ),
+ onTapLink: (_, href, _) {
+ final uri = swarmWebLink(href);
+ if (uri != null) {
+ unawaited(launchUrl(uri, mode: LaunchMode.inAppBrowserView));
+ }
+ },
+ ),
+ ),
+ );
+ }
+ final style = tty.style();
+ // A line at a time, built as it scrolls in: a file may run to 2 MB.
+ return SelectionArea(
+ child: ListView.builder(
+ key: const ValueKey('swarm-file-text'),
+ padding: padding,
+ itemCount: lines.length,
+ itemBuilder: (_, i) => Text(lines[i], style: style),
+ ),
+ );
+ }
+}
+
+/// The most of one line drawn as one piece: a minified file is a single
+/// line, and laying out megabytes as one paragraph stalls a phone.
+const _linePiece = 2000;
+
+/// [text] as the lines the viewer draws: its own lines, a tab as four
+/// spaces, a line past [_linePiece] cut into pieces of that length, never
+/// between the two halves of a character outside the Basic Multilingual Plane.
+@visibleForTesting
+List<String> swarmTextLines(String text) {
+ final lines = <String>[];
+ for (var line in text.split('\n')) {
+ if (line.endsWith('\r')) line = line.substring(0, line.length - 1);
+ line = line.replaceAll('\t', ' ');
+ var from = 0;
+ while (line.length - from > _linePiece) {
+ var to = from + _linePiece;
+ final unit = line.codeUnitAt(to - 1);
+ if (unit >= 0xD800 && unit <= 0xDBFF) to--;
+ lines.add(line.substring(from, to));
+ from = to;
+ }
+ lines.add(line.substring(from));
+ }
+ return lines;
+}
diff --git a/mobile/lib/swarm/swarm_link_previews.dart b/mobile/lib/swarm/swarm_link_previews.dart
new file mode 100644
index 000000000..ba546a2e1
--- /dev/null
+++ b/mobile/lib/swarm/swarm_link_previews.dart
@@ -0,0 +1,150 @@
+import 'package:flutter/material.dart';
+
+import 'identity.dart';
+import 'model.dart';
+import 'swarm_message_link.dart';
+import 'swarm_message_reads.dart';
+import 'swarm_message_row.dart';
+import 'swarm_reader.dart';
+
+/// [message]'s author as a link's preview names them: "You" for the reader's
+/// own, else as its Swarm's roster names them, or the name the message was
+/// written under while that Swarm is not read.
+String swarmLinkAuthor(SwarmReader reader, SuperTabMessage message) {
+ if (!message.fromAgent && message.authorId == reader.accountId) return 'You';
+ return reader.snapshot?.authorName(message) ??
+ (message.fromAgent
+ ? message.authorName
+ : superTabPersonName(message.authorName));
+}
+
+/// The messages [links] point at, each a small quote under the message that
+/// says them (the desktop's `SuperTabMessageLinkPreviews`): who wrote it, the
+/// chat it is in when that is not [chatId] of [tabId], and the start of its
+/// text. A tap opens it. One the reader may not read, or that is gone, or
+/// that could not be read, is only "Message unavailable", and opens nothing.
+class SwarmLinkPreviews extends StatelessWidget {
+ const SwarmLinkPreviews({
+ super.key,
+ required this.links,
+ required this.reads,
+ required this.reread,
+ required this.readerOf,
+ required this.tabId,
+ required this.chatId,
+ required this.onOpen,
+ this.held,
+ });
+
+ final List<SwarmMessageLink> links;
+ final SwarmMessageReads reads;
+
+ /// Ticks as the chat's Swarm is read ([SwarmReader.reads]): a read that
+ /// failed is asked again then, once [SwarmMessageReads.retryAfter] passed.
+ final Listenable reread;
+
+ /// The reader of the Swarm a link names, while the account lists it; null
+ /// for any other Swarm, whose links are unavailable.
+ final SwarmReader? Function(String tabId) readerOf;
+
+ /// Where the message saying [links] is.
+ final String tabId, chatId;
+
+ /// A linked message the chat already holds, which needs no read.
+ final SuperTabMessage? Function(SwarmMessageLink link)? held;
+ final ValueChanged<SwarmMessageLink> onOpen;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: Listenable.merge([reads, reread]),
+ builder: (context, _) => Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [for (final link in links) _preview(link)],
+ ),
+ );
+
+ Widget _preview(SwarmMessageLink link) {
+ // By the whole link: a message may name two messages of one id in two
+ // chats, and keys of one column must differ.
+ final key = ValueKey(
+ 'swarm-link-preview-'
+ '${link.tabId}/${link.conversationId}/${link.messageId}',
+ );
+ final reader = readerOf(link.tabId);
+ final kept = held?.call(link);
+ final read = reader == null
+ ? SwarmMessageRead.gone
+ : kept != null
+ ? (swarmShowsRead(kept)
+ ? SwarmMessageRead.found(kept)
+ : SwarmMessageRead.gone)
+ : reads.read(reader, link);
+ final message = read.message;
+ if (reader == null || message == null) {
+ return SwarmQuote(
+ key: key,
+ text: read.state == SwarmReadState.loading
+ ? 'Loading message…'
+ : 'Message unavailable',
+ );
+ }
+ final here = link.tabId == tabId && link.conversationId == chatId;
+ return SwarmQuote(
+ key: key,
+ author: swarmLinkAuthor(reader, message),
+ chat: here
+ ? null
+ : reader.snapshot?.conversation(link.conversationId)?.label,
+ text: message.text.trim().isEmpty
+ ? 'Attachment'
+ : message.text.trim().replaceAll(RegExp(r'\s+'), ' '),
+ label: 'Go to message',
+ onTap: () => onOpen(link),
+ );
+ }
+}
+
+/// A reply's quote whose original is not among the messages its chat read:
+/// the original read by itself (the desktop's `quoted`). It names its author
+/// and text once read; until then, and when it could not be read, the
+/// original "isn't loaded"; gone, or not the reader's, it is "no longer in
+/// this chat". A read that failed is asked again as the chat's Swarm is read
+/// ([SwarmReader.reads]), once [SwarmMessageReads.retryAfter] passed.
+class SwarmReadQuote extends StatelessWidget {
+ const SwarmReadQuote({
+ super.key,
+ required this.reads,
+ required this.reader,
+ required this.link,
+ required this.author,
+ this.onTap,
+ });
+
+ final SwarmMessageReads reads;
+ final SwarmReader reader;
+
+ /// The original.
+ final SwarmMessageLink link;
+
+ /// How the quote names the original's author.
+ final String Function(SuperTabMessage original) author;
+ final VoidCallback? onTap;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: Listenable.merge([reads, reader.reads]),
+ builder: (context, _) {
+ final read = reads.read(reader, link);
+ final original = read.message;
+ return SwarmQuote(
+ author: original == null ? null : author(original),
+ text:
+ original?.text ??
+ (read.state == SwarmReadState.gone
+ ? 'The original message is no longer in this chat.'
+ : null),
+ onTap: onTap,
+ );
+ },
+ );
+}
diff --git a/mobile/lib/swarm/swarm_message_link.dart b/mobile/lib/swarm/swarm_message_link.dart
index ca9f9007a..f415808e8 100644
--- a/mobile/lib/swarm/swarm_message_link.dart
+++ b/mobile/lib/swarm/swarm_message_link.dart
@@ -19,6 +19,24 @@ class SwarmMessageLink {
String get url => 'harness://swarm/$tabId/$conversationId/$messageId';
static final _id = RegExp(r'^[A-Za-z0-9_-]{1,160}$');
+ static final _candidate = RegExp(
+ r'harness://swarm/[A-Za-z0-9_/-]+(?![A-Za-z0-9_/?#%.-])',
+ );
+ static final _code = RegExp(r'```[\s\S]*?(?:```|$)|`[^`\n]*`');
+
+ /// Links a message previews; the rest stay text.
+ static const previewLimit = 4;
+
+ /// The message links [text] says outside code, each once, in order, as
+ /// Desktop finds them.
+ static List<SwarmMessageLink> allIn(String text) {
+ if (!text.contains('harness://swarm/')) return const [];
+ final seen = <String>{};
+ return [
+ for (final match in _candidate.allMatches(text.replaceAll(_code, ' ')))
+ if (parse(match[0]!) case final link? when seen.add(link.url)) link,
+ ].take(previewLimit).toList();
+ }
/// The link [value] is, read as Desktop reads it; null for anything else.
static SwarmMessageLink? parse(String value) {
diff --git a/mobile/lib/swarm/swarm_message_reads.dart b/mobile/lib/swarm/swarm_message_reads.dart
new file mode 100644
index 000000000..b26a83c83
--- /dev/null
+++ b/mobile/lib/swarm/swarm_message_reads.dart
@@ -0,0 +1,175 @@
+import 'dart:async';
+
+import 'package:clock/clock.dart';
+import 'package:flutter/foundation.dart';
+
+import 'package:harness_mobile/logging/app_log.dart';
+
+import 'model.dart';
+import 'swarm_message_link.dart';
+import 'swarm_reader.dart';
+import 'swarm_request.dart';
+
+/// Where a read of one message by itself stands ([SwarmMessageReads]).
+enum SwarmReadState {
+ /// Asked for, not answered yet.
+ loading,
+
+ /// Read: [SwarmMessageRead.message] holds it.
+ found,
+
+ /// Gone, or not the reader's to read: the backend tells the two apart for
+ /// no one, so neither does this.
+ gone,
+
+ /// Not answered: offline, a server error, or a server too old to read one
+ /// message.
+ failed,
+}
+
+/// What a read of one message by itself answered.
+@immutable
+class SwarmMessageRead {
+ const SwarmMessageRead._(this.state) : message = null;
+ const SwarmMessageRead.found(SuperTabMessage this.message)
+ : state = SwarmReadState.found;
+
+ static const loading = SwarmMessageRead._(SwarmReadState.loading);
+ static const gone = SwarmMessageRead._(SwarmReadState.gone);
+ static const failed = SwarmMessageRead._(SwarmReadState.failed);
+
+ final SwarmReadState state;
+
+ /// The message, once [SwarmReadState.found]; null otherwise.
+ final SuperTabMessage? message;
+}
+
+/// Whether a message read by itself is one to show: a waiting notice is
+/// never announced, and an update request is no chat row (the desktop's
+/// `AppLinkSwarms.read`).
+bool swarmShowsRead(SuperTabMessage message) =>
+ !const {'delivery-hold', 'update-request'}.contains(message.source['kind']);
+
+/// Messages read one at a time, outside the pages a chat holds: the original
+/// of a quote whose page is not read, and what a message link points at (the
+/// desktop's `quoted` and `AppLinkSwarms.read`), each read with the Swarm's
+/// own request so the backend decides what the reader may see.
+///
+/// In memory only, for the account's session ([SwarmSession]), and at most
+/// [kept]: the one drawn longest ago goes first. Any answer is asked for again
+/// only when it is drawn again [retryAfter] later, so nothing reads in a loop;
+/// a message found shows meanwhile, as the reader may since have lost its chat,
+/// and stays when the later read is not answered.
+class SwarmMessageReads extends ChangeNotifier {
+ SwarmMessageReads({
+ this.retryAfter = const Duration(minutes: 1),
+ this.kept = 100,
+ });
+
+ final Duration retryAfter;
+ final int kept;
+
+ /// By link, the one asked for longest ago first.
+ final _reads = <String, _Read>{};
+ bool _disposed = false;
+
+ /// What [link] points at, as [reader] (its Swarm's) may read it: asked for
+ /// the first time it is wanted, [SwarmMessageRead.loading] until then.
+ /// Asked again while an earlier answer shows, never twice at once.
+ SwarmMessageRead read(SwarmReader reader, SwarmMessageLink link) {
+ if (_disposed || reader.tabId != link.tabId) return SwarmMessageRead.gone;
+ if (reader.accessRevoked) {
+ // What it read goes with it.
+ _reads.removeWhere((_, read) => identical(read.reader, reader));
+ return SwarmMessageRead.gone;
+ }
+ final url = link.url;
+ final known = _reads.remove(url);
+ // A read for another reader, or before access was read again from
+ // nothing, may show what the reader can no longer see.
+ final current =
+ known != null &&
+ identical(known.reader, reader) &&
+ known.generation == reader.generation;
+ if (current &&
+ (known.reading || clock.now().difference(known.at) < retryAfter)) {
+ _reads[url] = known;
+ return known.value;
+ }
+ final read = _Read(reader, reader.generation)
+ ..value = current ? known.value : SwarmMessageRead.loading;
+ _reads[url] = read;
+ while (_reads.length > kept) {
+ _reads.remove(_reads.keys.first);
+ }
+ // Asked for while a screen is drawn: answered after it.
+ scheduleMicrotask(() => _read(link, read));
+ return read.value;
+ }
+
+ Future<void> _read(SwarmMessageLink link, _Read read) async {
+ bool stale() =>
+ _disposed ||
+ !identical(_reads[link.url], read) ||
+ read.generation != read.reader.generation;
+ if (stale()) return;
+ var value = SwarmMessageRead.failed;
+ try {
+ final answer = superTabMap(
+ await read.reader.request(
+ 'GET',
+ '/api/super-tabs/${Uri.encodeComponent(link.tabId)}'
+ '/conversations/${Uri.encodeComponent(link.conversationId)}'
+ '/messages?messageId=${Uri.encodeQueryComponent(link.messageId)}',
+ ),
+ );
+ final rows = [
+ for (final row in answer['messages'] as List)
+ SuperTabMessage.fromJson(superTabMap(row)),
+ ];
+ if (rows.isEmpty) {
+ value = SwarmMessageRead.gone;
+ } else if (rows.length == 1 &&
+ rows.single.id == link.messageId &&
+ rows.single.conversationId == link.conversationId) {
+ value = swarmShowsRead(rows.single)
+ ? SwarmMessageRead.found(rows.single)
+ : SwarmMessageRead.gone;
+ } else {
+ appLog.warn('swarm', 'One message read: not the message asked for');
+ }
+ } on SuperTabFailure catch (failure) {
+ if (const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {
+ value = SwarmMessageRead.gone;
+ } else {
+ appLog.warn('swarm', 'One message not read: ${failure.code}');
+ }
+ } catch (failure) {
+ appLog.warn('swarm', 'One message not read: ${failure.runtimeType}');
+ }
+ if (stale()) return;
+ final kept =
+ value.state == SwarmReadState.failed && read.value.message != null;
+ read
+ ..reading = false
+ ..at = clock.now()
+ ..value = kept ? read.value : value;
+ notifyListeners();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _reads.clear();
+ super.dispose();
+ }
+}
+
+class _Read {
+ _Read(this.reader, this.generation);
+ final SwarmReader reader;
+ final int generation;
+ bool reading = true;
+ DateTime at = DateTime.fromMillisecondsSinceEpoch(0);
+ SwarmMessageRead value = SwarmMessageRead.loading;
+}
diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dart
index 9495f8671..0bd43f56e 100644
--- a/mobile/lib/swarm/swarm_message_row.dart
+++ b/mobile/lib/swarm/swarm_message_row.dart
@@ -5,6 +5,7 @@ import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:url_launcher/url_launcher.dart';
+import 'package:harness_mobile/phone/phone_navigation.dart';
import 'package:harness_mobile/phone/tty.dart';
import 'package:harness_mobile/phone/tty_controls.dart';
import 'package:harness_mobile/shared/theme/app_ink.dart';
@@ -17,8 +18,11 @@ export 'swarm_message_style.dart'
import 'model.dart';
import 'swarm_attachment.dart';
+import 'swarm_attachment_store.dart';
import 'swarm_code_block.dart';
+import 'swarm_file_kind.dart';
import 'swarm_file_links.dart';
+import 'swarm_file_viewer.dart';
import 'swarm_message_text.dart';
import 'swarm_message_style.dart';
import 'swarm_face.dart';
@@ -275,6 +279,7 @@ class SwarmMessageRow extends StatelessWidget {
this.below,
this.receipt,
this.card,
+ this.links,
this.onLongPress,
this.references = const {},
this.onOpenConversation,
@@ -338,6 +343,10 @@ class SwarmMessageRow extends StatelessWidget {
/// (swarm_live_card.dart); null for a plain message.
final Widget? card;
+ /// Under its text, files and card: the messages its links point at
+ /// (swarm_link_previews.dart); null when it links to none.
+ final Widget? links;
+
/// Drawn under its text and files: its reaction counts.
final Widget? reactions;
@@ -452,6 +461,7 @@ class SwarmMessageRow extends StatelessWidget {
?swarmCutShort(message),
for (final file in message.attachments) _attachment(context, file),
?card,
+ ?links,
?reactions,
?thread,
?below,
@@ -680,14 +690,28 @@ class SwarmChatAvatar extends StatelessWidget {
}
/// What a reply answers: its author and the start of its text, or that it
-/// is not loaded. A tap leads to it.
+/// is not loaded. A tap leads to it. A message link's preview wears it too,
+/// naming the [chat] its message is in.
class SwarmQuote extends StatelessWidget {
- const SwarmQuote({super.key, this.author, this.text, this.onTap});
+ const SwarmQuote({
+ super.key,
+ this.author,
+ this.chat,
+ this.text,
+ this.onTap,
+ this.label = 'Go to the quoted message',
+ });
/// Null while the original is not loaded.
final String? author, text;
+
+ /// After [author]: the chat the message is in, when it is another one.
+ final String? chat;
final VoidCallback? onTap;
+ /// What a tap does, read aloud.
+ final String label;
+
@override
Widget build(BuildContext context) {
final tty = Tty.of(context);
@@ -710,8 +734,20 @@ class SwarmQuote extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (author case final author?)
- Text(
- author,
+ Text.rich(
+ TextSpan(
+ text: author,
+ children: [
+ if (chat case final chat?)
+ TextSpan(
+ text: ' · $chat',
+ style: swarmChatText(
+ 13.5,
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ ],
+ ),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: swarmChatText(13.5, weight: FontWeight.w600),
@@ -728,7 +764,7 @@ class SwarmQuote extends StatelessWidget {
if (onTap == null) return quote;
return Semantics(
button: true,
- label: 'Go to the quoted message',
+ label: label,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: onTap,
@@ -847,22 +883,28 @@ String swarmFileSize(int bytes) {
Future<bool> Function(Uri url) swarmOpenFile = (url) =>
launchUrl(url, mode: LaunchMode.inAppBrowserView);
-/// A message's file: opened in the browser when its link is the backend's.
-/// With [fileRef], a link about to end is asked for again first
-/// (swarm_file_links.dart); a reader who lost access is told so, and a
-/// failed ask can be tapped again.
+/// A message's file, marked by its kind ([swarmFileIcon]), opened when its
+/// link is the backend's: a text or Markdown file in the app
+/// ([SwarmFileViewer]), any other in the browser. With [fileRef], a link
+/// about to end is asked for again first (swarm_file_links.dart); a reader
+/// who lost access is told so, and a failed ask can be tapped again.
class SwarmFileChip extends StatefulWidget {
const SwarmFileChip({
super.key,
required this.file,
required this.link,
this.fileRef,
+ this.store,
});
final SuperTabAttachment file;
final Uri? link;
final SwarmFileRef? fileRef;
+ /// Where a text file read in the app is kept; the app's own
+ /// ([swarmAttachments]) by default.
+ final SwarmAttachmentStore? store;
+
@override
State<SwarmFileChip> createState() => _SwarmFileChipState();
}
@@ -877,7 +919,7 @@ class _SwarmFileChipState extends State<SwarmFileChip> {
Future<void> _open() async {
final ref = widget.fileRef;
if (ref == null) {
- if (widget.link case final url?) unawaited(swarmOpenFile(url));
+ if (widget.link case final url?) _show(url);
return;
}
if (_opening) return;
@@ -895,7 +937,34 @@ class _SwarmFileChipState extends State<SwarmFileChip> {
if (mounted) setState(() => _opening = false);
}
final url = found;
- if (url != null && mounted) unawaited(swarmOpenFile(url));
+ if (url != null && mounted) _show(url);
+ }
+
+ /// Opens the file at [url]: a text file in the app, any other in the
+ /// browser, as the desktop does.
+ void _show(Uri url) {
+ final file = widget.file;
+ if (!swarmOpensAsText(file)) {
+ unawaited(swarmOpenFile(url));
+ return;
+ }
+ final store = widget.store ?? swarmAttachments;
+ final turn = store.turns.value, ref = widget.fileRef;
+ unawaited(
+ Navigator.of(context).push(
+ phoneRoute(
+ (_) => SwarmFileViewer(
+ file: file,
+ url: url,
+ fileRef: ref,
+ store: store,
+ turn: turn,
+ openInBrowser: (url) => swarmOpenFile(url),
+ ),
+ listensForItself: true,
+ ),
+ ),
+ );
}
@override
@@ -926,7 +995,7 @@ class _SwarmFileChipState extends State<SwarmFileChip> {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
- Icon(LucideIcons.file, size: 16, color: color),
+ Icon(swarmFileIcon(file.name), size: 16, color: color),
const SizedBox(width: 8),
Flexible(
child: Text(
diff --git a/mobile/lib/swarm/swarm_message_text.dart b/mobile/lib/swarm/swarm_message_text.dart
index d22572c29..4d2605f07 100644
--- a/mobile/lib/swarm/swarm_message_text.dart
+++ b/mobile/lib/swarm/swarm_message_text.dart
@@ -40,9 +40,6 @@ class SwarmMessageText extends StatelessWidget {
@override
Widget build(BuildContext context) {
- final tty = Tty.of(context);
- final body = swarmChatText(16, height: 1.42);
- final heading = body.copyWith(fontWeight: FontWeight.w600);
final names = [...mentionNames, ...tagged];
return Semantics(
button: onTap != null,
@@ -69,45 +66,7 @@ class SwarmMessageText extends StatelessWidget {
_SwarmMention(names, addresses, labels),
],
builders: {'mention': _SwarmMentionBuilder()},
- styleSheet: MarkdownStyleSheet.fromTheme(Theme.of(context))
- .copyWith(
- p: body,
- a: TextStyle(
- color: AppPalette.accentOnSurface,
- decoration: TextDecoration.underline,
- ),
- h1: AppType.title(),
- h2: AppType.heading(),
- h3: heading,
- h4: heading,
- h5: heading,
- h6: heading,
- strong: const TextStyle(fontWeight: FontWeight.w600),
- code: tty
- .style(size: 14)
- .copyWith(backgroundColor: swarmChatCard(tty)),
- blockSpacing: 8,
- listIndent: 20,
- listBullet: body,
- blockquote: body.copyWith(color: AppPalette.textSecondary),
- blockquotePadding: const EdgeInsets.symmetric(
- horizontal: AppSpace.m,
- vertical: AppSpace.xs,
- ),
- blockquoteDecoration: BoxDecoration(
- border: Border(
- left: BorderSide(color: AppPalette.divider, width: 2),
- ),
- ),
- tableHead: heading,
- tableColumnWidth: const FlexColumnWidth(),
- tableBody: body,
- tableBorder: TableBorder.all(color: AppPalette.divider),
- tableCellsPadding: const EdgeInsets.symmetric(
- horizontal: AppSpace.s,
- vertical: AppSpace.xs,
- ),
- ),
+ styleSheet: swarmMarkdownStyle(context),
imageBuilder: (uri, title, alt) => Text(
alt?.isNotEmpty == true ? 'Image: $alt' : 'Image',
style: AppType.caption(color: AppPalette.textSecondary),
@@ -121,7 +80,7 @@ class SwarmMessageText extends StatelessWidget {
onOpenConversation?.call(conversation);
return;
}
- final uri = _webLink(href);
+ final uri = swarmWebLink(href);
if (uri != null) {
unawaited(launchUrl(uri, mode: LaunchMode.inAppBrowserView));
}
@@ -133,7 +92,51 @@ class SwarmMessageText extends StatelessWidget {
}
}
-Uri? _webLink(String? href) {
+/// The chat's Markdown look, for a message and a Markdown file read in the
+/// app (`SwarmFileViewer`) alike.
+MarkdownStyleSheet swarmMarkdownStyle(BuildContext context) {
+ final tty = Tty.of(context);
+ final body = swarmChatText(16, height: 1.42);
+ final heading = body.copyWith(fontWeight: FontWeight.w600);
+ return MarkdownStyleSheet.fromTheme(Theme.of(context)).copyWith(
+ p: body,
+ a: TextStyle(
+ color: AppPalette.accentOnSurface,
+ decoration: TextDecoration.underline,
+ ),
+ h1: AppType.title(),
+ h2: AppType.heading(),
+ h3: heading,
+ h4: heading,
+ h5: heading,
+ h6: heading,
+ strong: const TextStyle(fontWeight: FontWeight.w600),
+ code: tty.style(size: 14).copyWith(backgroundColor: swarmChatCard(tty)),
+ blockSpacing: 8,
+ listIndent: 20,
+ listBullet: body,
+ blockquote: body.copyWith(color: AppPalette.textSecondary),
+ blockquotePadding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.m,
+ vertical: AppSpace.xs,
+ ),
+ blockquoteDecoration: BoxDecoration(
+ border: Border(left: BorderSide(color: AppPalette.divider, width: 2)),
+ ),
+ tableHead: heading,
+ tableColumnWidth: const FlexColumnWidth(),
+ tableBody: body,
+ tableBorder: TableBorder.all(color: AppPalette.divider),
+ tableCellsPadding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.s,
+ vertical: AppSpace.xs,
+ ),
+ );
+}
+
+/// [href] as a web link to open, or null unless it is http or https with a
+/// host.
+Uri? swarmWebLink(String? href) {
final uri = href == null ? null : Uri.tryParse(href);
return uri != null &&
(uri.scheme == 'https' || uri.scheme == 'http') &&
@@ -157,7 +160,7 @@ class _WebAutolink extends md.AutolinkExtensionSyntax {
final anchor = nodes.firstOrNull;
if (anchor is! md.Element ||
anchor.tag != 'a' ||
- _webLink(anchor.textContent) == null) {
+ swarmWebLink(anchor.textContent) == null) {
return super.onMatch(parser, match);
}
anchor.attributes['href'] = anchor.textContent;
diff --git a/mobile/lib/swarm/swarm_project_team.dart b/mobile/lib/swarm/swarm_project_team.dart
index f05e40d72..f4574ee32 100644
--- a/mobile/lib/swarm/swarm_project_team.dart
+++ b/mobile/lib/swarm/swarm_project_team.dart
@@ -11,6 +11,7 @@ import 'package:harness_mobile/shared/widgets/touch_target.dart';
import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
import 'model.dart';
+import 'swarm_chat_agents.dart';
import 'swarm_instructions_page.dart';
import 'swarm_leaderboard.dart';
import 'swarm_project_tasks.dart';
@@ -244,8 +245,10 @@ class SwarmProjectTeamSheet extends StatelessWidget {
/// first ([swarmProjectAgents]), with what needs a look counted beside their
/// caption, each opening the task it holds ([onOpen]), its time since its
/// last progress kept true by a tick a minute ([tick]) and on coming back to
-/// the app. Its humans are on the project's leaderboard. A pull reads the
-/// Swarm again.
+/// the app. As Desktop's Members, a long press offers Remove from Swarm to
+/// whoever may ([showSwarmAgentMenu]), and Add agent ends the list
+/// ([showSwarmAddAgentSheet], into the project's chat). Its humans are on the
+/// project's leaderboard. A pull reads the Swarm again.
class SwarmProjectTeam extends StatefulWidget {
const SwarmProjectTeam({
super.key,
@@ -317,8 +320,13 @@ class _SwarmProjectTeamState extends State<SwarmProjectTeam> {
final reader = widget.reader;
return ListenableBuilder(
// Needs and held answers move with the session and its inbox; the
- // work and the team with the read.
- listenable: Listenable.merge([session, session.inbox, reader]),
+ // work and the team with the read, and with a removal on its way.
+ listenable: Listenable.merge([
+ session,
+ session.inbox,
+ reader,
+ SwarmAgentWrites.of(reader),
+ ]),
builder: (context, _) {
final snapshot = reader.snapshot;
final project = snapshot?.projects
@@ -330,12 +338,18 @@ class _SwarmProjectTeamState extends State<SwarmProjectTeam> {
final now = clock.now();
final tasks = swarmProjectTasks(session.inbox, reader, project.id, now);
final personName = swarmTaskPersonName(snapshot);
- final agents = swarmProjectAgents(
- snapshot,
- project.id,
- now: now,
- viewerId: reader.accountId,
- );
+ // One being removed is gone at once, and back if the server refuses.
+ final removing = SwarmAgentWrites.of(reader);
+ final agents = [
+ for (final a in swarmProjectAgents(
+ snapshot,
+ project.id,
+ now: now,
+ viewerId: reader.accountId,
+ ))
+ if (!removing.removing(a.agent.id)) a,
+ ];
+ final addsAgent = swarmCanAddAgent(reader, project.leadConversationId);
final working = tasks.working;
final folds = working.length > SwarmProjectTeam.workShown;
final work = folds && !_allWork
@@ -424,8 +438,8 @@ class _SwarmProjectTeamState extends State<SwarmProjectTeam> {
'No agents yet.',
key: const ValueKey('swarm-team-no-agents'),
),
- )
- else
+ ),
+ if (agents.isNotEmpty || addsAgent)
SwarmGroup(
children: [
for (final a in agents)
@@ -444,6 +458,24 @@ class _SwarmProjectTeamState extends State<SwarmProjectTeam> {
final task? => () => widget.onOpen(task.id),
null => null,
},
+ onLongPress:
+ swarmAgentRights(reader, a.agent.id)?.remove == true
+ ? () => unawaited(
+ showSwarmAgentMenu(context, reader, a.agent.id),
+ )
+ : null,
+ ),
+ if (addsAgent)
+ SwarmRow(
+ key: const ValueKey('swarm-team-add-agent'),
+ title: 'Add agent',
+ onTap: () => unawaited(
+ showSwarmAddAgentSheet(
+ context,
+ reader,
+ project.leadConversationId,
+ ),
+ ),
),
],
),
@@ -483,8 +515,8 @@ class _SwarmProjectTeamState extends State<SwarmProjectTeam> {
/// One agent on a project's Team (Dee, 2026-10-29): the face in one column,
/// with its state's [dot], the name and a quiet [detail] line beneath, ending
/// in its [age], which a narrow phone never cuts: the line's words give way
-/// first. The same height with or without the line; a tap does [onTap], when
-/// there is one.
+/// first. The same height with or without the line; a tap does [onTap], and
+/// a long press [onLongPress], when there is one.
class SwarmMemberRow extends StatelessWidget {
const SwarmMemberRow({
super.key,
@@ -494,6 +526,7 @@ class SwarmMemberRow extends StatelessWidget {
this.detail,
this.age,
this.onTap,
+ this.onLongPress,
});
final Widget face;
@@ -505,7 +538,7 @@ class SwarmMemberRow extends StatelessWidget {
/// How long since the agent's last progress: "4m".
final String? age;
- final VoidCallback? onTap;
+ final VoidCallback? onTap, onLongPress;
static const double _face = 36, _dot = 11;
@@ -527,8 +560,10 @@ class SwarmMemberRow extends StatelessWidget {
button: onTap != null,
label: [name, if (line.isNotEmpty) line].join(', '),
excludeSemantics: true,
+ onLongPress: onLongPress,
child: InkWell(
onTap: onTap,
+ onLongPress: onLongPress,
child: ConstrainedBox(
// A name over its line, with or without the line: every row of the
// Team one height.
diff --git a/mobile/lib/swarm/swarm_session.dart b/mobile/lib/swarm/swarm_session.dart
index ee14977ed..780a661e4 100644
--- a/mobile/lib/swarm/swarm_session.dart
+++ b/mobile/lib/swarm/swarm_session.dart
@@ -17,6 +17,7 @@ import 'swarm_home_prefs.dart';
import 'swarm_inbox.dart';
import 'swarm_kept.dart';
import 'swarm_mark_all.dart';
+import 'swarm_message_reads.dart';
import 'swarm_notices.dart';
import 'swarm_profile.dart';
import 'swarm_request.dart';
@@ -69,6 +70,10 @@ class SwarmSession extends ChangeNotifier {
/// The project chats read for Activity, a few at a time ([SwarmChatPeeks]).
final peeks = SwarmChatPeeks();
+ /// Messages read one at a time: quoted originals and what message links
+ /// point at ([SwarmMessageReads]), dropped with the session.
+ final messageReads = SwarmMessageReads();
+
/// Activity, in place of Needs you: its filters, counts and handled rows.
/// Made when a screen first asks for it.
SwarmActivity get activity => _activity ??= SwarmActivity(this);
@@ -320,6 +325,7 @@ class SwarmSession extends ChangeNotifier {
_held.clear();
_activity?.dispose();
peeks.dispose();
+ messageReads.dispose();
inbox.removeListener(_needsChanged);
_announcer.clear();
inbox.dispose();
diff --git a/mobile/test/swarm/swarm_attachment_fakes.dart b/mobile/test/swarm/swarm_attachment_fakes.dart
index 1a04582b5..d38164b3f 100644
--- a/mobile/test/swarm/swarm_attachment_fakes.dart
+++ b/mobile/test/swarm/swarm_attachment_fakes.dart
@@ -80,13 +80,20 @@ class _Folder implements FileSystem {
}
/// A store over [root] and [storage], as the app's is over its temporary
-/// folder and the network.
-SwarmAttachmentStore storeIn(io.Directory root, FileService storage) =>
- SwarmAttachmentStore(
- root: () async => root,
- fileService: storage,
- files: (folder) => _Folder(folder),
- );
+/// folder and the network. [reaching], when given, runs each time the store
+/// asks for [root], as the app's asks the platform for its folder.
+SwarmAttachmentStore storeIn(
+ io.Directory root,
+ FileService storage, {
+ Future<void> Function()? reaching,
+}) => SwarmAttachmentStore(
+ root: () async {
+ await reaching?.call();
+ return root;
+ },
+ fileService: storage,
+ files: (folder) => _Folder(folder),
+);
/// The files kept under [root], by their path below it.
List<String> keptUnder(io.Directory root) {
diff --git a/mobile/test/swarm/swarm_attachment_store_test.dart b/mobile/test/swarm/swarm_attachment_store_test.dart
index 4c8ccf139..593e9975e 100644
--- a/mobile/test/swarm/swarm_attachment_store_test.dart
+++ b/mobile/test/swarm/swarm_attachment_store_test.dart
@@ -1,4 +1,5 @@
import 'dart:async';
+import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
@@ -224,4 +225,167 @@ void main() {
await expectLater(store.file(picture), throwsA(anything));
});
+
+ group('a copy named for the share sheet', () {
+ test('is the kept file under its own name, in the account folder, and '
+ 'goes once used', () async {
+ await store.keepOnly('person-a');
+ final kept = await store.file(picture);
+ late String path;
+ late List<int> bytes;
+
+ await store.named(kept, 'plan.md', (copy) async {
+ path = copy.path;
+ bytes = await copy.readAsBytes();
+ });
+
+ expect(path.split(Platform.pathSeparator).last, 'plan.md');
+ expect(path, startsWith(root.path));
+ expect(bytes, pixelPng);
+ expect(File(path).existsSync(), isFalse);
+ expect(File(path).parent.existsSync(), isFalse);
+ expect(kept.existsSync(), isTrue, reason: 'the kept file stays');
+ });
+
+ test('goes when the share fails too, and the failure stands', () async {
+ await store.keepOnly('person-a');
+ final kept = await store.file(picture);
+ String? path;
+
+ await expectLater(
+ store.named(kept, 'plan.md', (copy) async {
+ path = copy.path;
+ throw StateError('No sheet');
+ }),
+ throwsStateError,
+ );
+
+ expect(path, isNotNull);
+ expect(File(path!).existsSync(), isFalse);
+ });
+
+ test('two at once do not share a folder', () async {
+ await store.keepOnly('person-a');
+ final kept = await store.file(picture);
+ final paths = <String>[];
+ final first = Completer<void>();
+
+ final one = store.named(kept, 'a.txt', (copy) async {
+ paths.add(copy.path);
+ await first.future;
+ });
+ await store.named(kept, 'a.txt', (copy) async {
+ paths.add(copy.path);
+ expect(File(paths.first).existsSync(), isTrue);
+ });
+ first.complete();
+ await one;
+
+ expect(paths.toSet(), hasLength(2));
+ });
+
+ test('is refused for a file another account kept, or nobody', () async {
+ await store.keepOnly('person-a');
+ final kept = await store.file(picture);
+ await store.keepOnly('person-b');
+ var used = false;
+
+ await expectLater(
+ store.named(kept, 'a.png', (_) async => used = true),
+ throwsStateError,
+ );
+ await store.keepOnly(null);
+ await expectLater(
+ store.named(kept, 'a.png', (_) async => used = true),
+ throwsStateError,
+ );
+ expect(used, isFalse);
+ });
+
+ test('started just before another account, is made before the emptying '
+ 'runs', () async {
+ // The app's folder comes from the platform, a wait of its own: the
+ // copy is held there, and the emptying must wait for it.
+ final reached = Completer<void>(), release = Completer<void>();
+ var holding = false;
+ final store = storeIn(
+ root,
+ storage,
+ reaching: () async {
+ if (!holding) return;
+ holding = false;
+ reached.complete();
+ await release.future;
+ },
+ );
+ await store.keepOnly('person-a');
+ final kept = await store.file(picture);
+ holding = true;
+ List<int>? bytes;
+ late final Future<void> changing;
+
+ final sharing = store.named(kept, 'a.png', (copy) async {
+ bytes = copy.readAsBytesSync();
+ await changing;
+ });
+ changing = store.keepOnly('person-b');
+ await reached.future;
+ final emptied = await Future.any([
+ changing.then((_) => true),
+ Future<bool>.delayed(const Duration(milliseconds: 300), () => false),
+ ]);
+ release.complete();
+ await sharing;
+ await changing;
+
+ expect(emptied, isFalse, reason: 'the emptying waited for the copy');
+ expect(bytes, pixelPng);
+ expect(keptUnder(root), isEmpty);
+ });
+
+ test('goes with the account on sign-out', () async {
+ await store.keepOnly('person-a');
+ final kept = await store.file(picture);
+ final shown = Completer<String>(), held = Completer<void>();
+ final sharing = store.named(kept, 'a.png', (copy) async {
+ shown.complete(copy.path);
+ await held.future;
+ });
+ final path = await shown.future;
+
+ await store.keepOnly(null);
+
+ expect(File(path).existsSync(), isFalse);
+ held.complete();
+ await sharing;
+ expect(keptUnder(root), isEmpty);
+ });
+ });
+
+ group('a file name the phone writes', () {
+ test('keeps an ordinary name as it is', () {
+ expect(swarmFileName('Plan v2 (final).md'), 'Plan v2 (final).md');
+ expect(swarmFileName('.env'), '.env');
+ expect(swarmFileName('Tiếng Việt.txt'), 'Tiếng Việt.txt');
+ });
+
+ test('never holds a folder or a control character', () {
+ expect(swarmFileName('../../etc/passwd'), '.._.._etc_passwd');
+ expect(swarmFileName(r'a\b.txt'), 'a_b.txt');
+ expect(swarmFileName('a\nb\u0000.txt'), 'a_b_.txt');
+ });
+
+ test('is never empty, nor a folder of its own', () {
+ for (final name in ['', ' ', '.', '..']) {
+ expect(swarmFileName(name), 'file', reason: '"$name"');
+ }
+ });
+
+ test('is at most 255 bytes, its extension kept', () {
+ final long = swarmFileName('${'é' * 300}.md');
+ expect(utf8.encode(long).length, lessThanOrEqualTo(255));
+ expect(long, endsWith('.md'));
+ expect(long, startsWith('éé'));
+ });
+ });
}
diff --git a/mobile/test/swarm/swarm_attachment_test.dart b/mobile/test/swarm/swarm_attachment_test.dart
index 0063c5d94..24fda860c 100644
--- a/mobile/test/swarm/swarm_attachment_test.dart
+++ b/mobile/test/swarm/swarm_attachment_test.dart
@@ -8,6 +8,7 @@ import 'package:harness_mobile/shared/widgets/skeleton.dart';
import 'package:harness_mobile/swarm/model.dart';
import 'package:harness_mobile/swarm/swarm_attachment.dart';
import 'package:harness_mobile/swarm/swarm_attachment_store.dart';
+import 'package:harness_mobile/swarm/swarm_file_download.dart';
import 'swarm_attachment_fakes.dart';
@@ -337,6 +338,31 @@ void main() {
await closed(tester);
});
+ testWidgets('Download hands the picture to the share sheet under its own '
+ 'name', (tester) async {
+ final shareSheet = swarmShareSheet;
+ addTearDown(() => swarmShareSheet = shareSheet);
+ final shared = <({String name, List<int> bytes})>[];
+ swarmShareSheet = (params) async {
+ final copy = File(params.files!.single.path);
+ shared.add((
+ name: copy.uri.pathSegments.last,
+ bytes: copy.readAsBytesSync(),
+ ));
+ };
+ await pump(tester);
+ await until(tester, () => drawn(tester));
+ await tester.tap(preview);
+ await tester.pumpAndSettle();
+
+ await tester.tap(key('swarm-file-download'));
+ await until(tester, () => shared.isNotEmpty);
+
+ expect(shared.single.name, 'screen.png');
+ expect(shared.single.bytes, storage.bytes);
+ await closed(tester);
+ });
+
group('open full screen, the picture goes with its account', () {
final viewer = key('swarm-attachment-viewer');
diff --git a/mobile/test/swarm/swarm_chat_agents_test.dart b/mobile/test/swarm/swarm_chat_agents_test.dart
new file mode 100644
index 000000000..d73be8062
--- /dev/null
+++ b/mobile/test/swarm/swarm_chat_agents_test.dart
@@ -0,0 +1,790 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
+import 'package:harness_mobile/swarm/swarm_chat_agents.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_project_page.dart';
+import 'package:harness_mobile/swarm/swarm_project_tabs.dart';
+import 'package:harness_mobile/swarm/swarm_reader.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_computers_fake.dart';
+import 'swarm_fixture.dart';
+
+/// The person's computers with the sessions running on them, as a test
+/// scripts them.
+class _Computers extends FakeComputers implements SwarmRunningSessions {
+ _Computers() : super(const [(name: 'Studio', away: false)]);
+
+ @override
+ List<SwarmRunningSession> running = const [];
+}
+
+SwarmRunningSession session(
+ String harnessId,
+ String name, {
+ String machineId = 'mac-1',
+ String machine = 'Studio',
+ String engine = 'claude',
+}) => (
+ machineId: machineId,
+ machine: machine,
+ harnessId: harnessId,
+ name: name,
+ engine: engine,
+);
+
+/// Add agent and Remove from Swarm on the phone (task 14), as Desktop's
+/// Members offers them: Add agent in a chat's ⋮ and at the end of a
+/// project's Team, with the Swarm's agents of the project and the sessions
+/// running on the person's computers; Remove from Swarm on a long press of a
+/// Team row, asked first in the desktop's words.
+void main() {
+ const chat = 'g1';
+ const board = '/api/super-tabs/$tab/leaderboard?projectId=$project';
+ late FakeSwarm swarm;
+ late SwarmHost host;
+ late _Computers computers;
+ late List<Map<String, dynamic>> agents;
+ late Set<String> removed;
+ late List<String> chatAgents;
+ late bool chatArchived;
+ var version = 2;
+
+ /// What the next command answers instead of the server, once.
+ FutureOr<Object?> Function()? answer;
+
+ Map<String, dynamic> groups(String id) => switch (id) {
+ chat => {
+ ...groupData(
+ chat,
+ title: 'Fix login flake',
+ number: 7,
+ agentIds: chatAgents,
+ ),
+ 'archived': chatArchived,
+ },
+ 'g-archived' => {
+ ...groupData('g-archived', title: 'Old'),
+ 'archived': true,
+ },
+ 'g-private' => groupData('g-private', title: 'Private', audience: [me]),
+ _ => buddyChatData('g-buddy', agentIds: ['agent-buddy']),
+ };
+ const groupIds = [chat, 'g-archived', 'g-private', 'g-buddy'];
+
+ Future<void> pump(
+ WidgetTester tester, {
+ String role = 'owner',
+ String owner = me,
+ Widget? home,
+ }) async {
+ version = 2;
+ answer = null;
+ removed = {};
+ chatAgents = ['agent-lead', 'agent-builder'];
+ chatArchived = false;
+ agents = [
+ agent('agent-lead', name: 'Lead', displayName: 'River'),
+ agent('agent-builder', displayName: 'Nova'),
+ agent('agent-ash', displayName: 'Ash'),
+ {
+ ...agent('agent-bea', displayName: 'Bea'),
+ 'contributorId': 'person-dee',
+ },
+ {...agent('agent-far', displayName: 'Far'), 'projectId': 'project-2'},
+ buddyData('agent-buddy', displayName: 'Wren'),
+ ];
+ computers = _Computers();
+ swarm = FakeSwarm();
+ swarm.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': owner},
+ ],
+ 'next': null,
+ };
+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ head: headData(ownerId: owner),
+ agents: agents,
+ groups: [for (final id in groupIds) groups(id)],
+ machines: [
+ {
+ 'machineId': 'mac-1',
+ 'name': 'Tony’s Mac',
+ 'contributorId': me,
+ 'engines': ['claude', 'codex'],
+ },
+ ],
+ ),
+ 'members': [
+ part(me, 1, person(me, role: role)),
+ part('person-dee', 1, person('person-dee', role: 'collaborator')),
+ ],
+ };
+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) {
+ version++;
+ return {
+ ...changes(
+ cursor: 'c$version',
+ groups: [for (final id in groupIds) part(id, version, groups(id))],
+ ),
+ 'agents': [
+ for (final a in agents) part(a['id'] as String, version, a),
+ for (final id in removed)
+ {
+ 'key': id,
+ 'version': version,
+ 'changedAt': version,
+ 'deleted': true,
+ },
+ ],
+ };
+ };
+ swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ swarm.routes[board] = (_) => leaderboardData(people: const []);
+ for (final id in [chat, leadChat]) {
+ swarm.routes['/api/super-tabs/$tab/conversations/$id/messages'] = (_) => {
+ 'messages': <Object>[],
+ 'next': null,
+ };
+ }
+ swarm.routes['/api/super-tabs/$tab/commands'] = (body) async {
+ final command = body!['command'] as Map<String, dynamic>;
+ if (answer case final once?) {
+ answer = null;
+ return await once();
+ }
+ switch (command['type']) {
+ case 'agent.remove':
+ final id = command['agentId'] as String;
+ agents.removeWhere((a) => a['id'] == id);
+ removed.add(id);
+ chatAgents = [...chatAgents]..remove(id);
+ case 'conversation.agent' when command['conversationId'] == chat:
+ chatAgents = [...chatAgents, command['agentId'] as String];
+ }
+ return {'ok': true};
+ };
+ final account = ValueNotifier<String?>(me);
+ host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: swarm.request,
+ upload: refuseSwarmUpload,
+ notices: SilentSystemNotices(),
+ computers: computers,
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => SwarmScope(notifier: host, child: child!),
+ home: Scaffold(
+ body:
+ home ??
+ const SwarmConversationPage(swarmId: tab, conversationId: chat),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ SwarmReader reader() => host.session!.inbox.reader(tab)!;
+ Finder key(String value) => find.byKey(ValueKey(value));
+ double y(WidgetTester tester, Finder finder) => tester.getTopLeft(finder).dy;
+
+ Future<void> addSheet(WidgetTester tester) async {
+ await tester.tap(key('swarm-chat-menu'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Add agent'));
+ await tester.pumpAndSettle();
+ }
+
+ const title = 'Add agent to Phone Swarm';
+
+ /// Two sessions on the Studio, one of them already the Swarm's Ash, and
+ /// one on the Mini.
+ void runSessions() => computers.running = [
+ session('h-new', 'Fix flaky test'),
+ session('harness-agent-ash', 'Ash session'),
+ session(
+ 'h-codex',
+ 'Docs',
+ machineId: 'mac-2',
+ machine: 'Mini',
+ engine: 'codex',
+ ),
+ ];
+
+ /// The commands sent, in order.
+ List<Map<String, dynamic>> sent() => swarm.commands;
+
+ group('who may add an agent', () {
+ testWidgets('an owner gets Add agent in an ordinary chat\'s ⋮, above '
+ 'Rename', (tester) async {
+ await pump(tester);
+ await tester.tap(key('swarm-chat-menu'));
+ await tester.pumpAndSettle();
+ expect(find.text('Add agent'), findsOneWidget);
+ expect(
+ y(tester, find.text('Add agent')),
+ lessThan(y(tester, find.text('Rename'))),
+ );
+ });
+
+ testWidgets('a viewer gets none', (tester) async {
+ await pump(tester, role: 'viewer');
+ await tester.tap(key('swarm-chat-menu'));
+ await tester.pumpAndSettle();
+ expect(find.text('Add agent'), findsNothing);
+ expect(find.text('All new messages'), findsOneWidget);
+ });
+
+ testWidgets('never to an archived, a private or a Buddy chat; the '
+ 'project chat takes one', (tester) async {
+ await pump(tester);
+ expect(swarmCanAddAgent(reader(), chat), isTrue);
+ expect(swarmCanAddAgent(reader(), leadChat), isTrue);
+ expect(swarmCanAddAgent(reader(), 'g-archived'), isFalse);
+ expect(swarmCanAddAgent(reader(), 'g-private'), isFalse);
+ expect(swarmCanAddAgent(reader(), 'g-buddy'), isFalse);
+ expect(swarmCanAddAgent(reader(), 'no-such-chat'), isFalse);
+ });
+ });
+
+ group('the choices', () {
+ testWidgets('an ordinary chat offers the project\'s agents not in it, by '
+ 'name, then each computer\'s sessions not in the Swarm under its '
+ 'name, each with its engine', (tester) async {
+ await pump(tester);
+ runSessions();
+ await addSheet(tester);
+
+ expect(find.text(title), findsOneWidget);
+ for (final shown in ['Ash', 'Bea', 'Fix flaky test', 'Docs']) {
+ expect(find.text(shown), findsOneWidget, reason: shown);
+ }
+ // In the chat already, a Buddy, another project's, and Ash's own
+ // session, which is Ash.
+ for (final hidden in ['River', 'Nova', 'Wren', 'Far', 'Ash session']) {
+ expect(find.text(hidden), findsNothing, reason: hidden);
+ }
+ expect(find.text('agents'), findsOneWidget);
+ expect(find.text('studio'), findsOneWidget);
+ expect(find.text('mini'), findsOneWidget);
+ expect(find.text('Claude'), findsNWidgets(3));
+ expect(find.text('Codex'), findsOneWidget);
+ final order = [
+ for (final name in ['Ash', 'Bea', 'Fix flaky test', 'Docs'])
+ y(tester, find.text(name)),
+ ];
+ expect(order, [...order]..sort());
+ expect(sent(), isEmpty);
+ });
+
+ testWidgets('the project chat offers only sessions not in the Swarm: it '
+ 'holds no agent but its coordinator (#2207)', (tester) async {
+ await pump(tester);
+ runSessions();
+ expect(
+ [
+ for (final c in swarmAgentChoices(
+ reader(),
+ leadChat,
+ computers.running,
+ ))
+ c.name,
+ ],
+ ['Fix flaky test', 'Docs'],
+ );
+ expect(
+ swarmAgentChoices(reader(), 'g-private', computers.running),
+ isEmpty,
+ );
+ });
+ });
+
+ group('adding', () {
+ testWidgets('an agent of the Swarm joins the chat with '
+ 'conversation.agent, and the Swarm is read again', (tester) async {
+ await pump(tester);
+ await addSheet(tester);
+ final before = swarm.paths.length;
+ await tester.tap(find.text('Ash'));
+ await tester.pumpAndSettle();
+
+ expect(find.text(title), findsNothing, reason: 'the sheet closes');
+ expect(sent(), [
+ {
+ 'type': 'conversation.agent',
+ 'conversationId': chat,
+ 'agentId': 'agent-ash',
+ 'present': true,
+ 'lead': false,
+ },
+ ]);
+ final after = swarm.paths.sublist(before);
+ final command = after.indexWhere((p) => p.endsWith('/commands'));
+ expect(
+ after.skip(command).where((p) => p.contains('/changes')),
+ isNotEmpty,
+ );
+ expect(reader().snapshot!.conversation(chat)!.agentIds, [
+ 'agent-lead',
+ 'agent-builder',
+ 'agent-ash',
+ ]);
+ expect(computers.asked, isEmpty, reason: 'it runs in the Swarm already');
+ expect(key('swarm-agent-failed'), findsNothing);
+ });
+
+ testWidgets('a running session is shared into the chat with agent.add, '
+ 'and its computer is woken to host it', (tester) async {
+ await pump(tester);
+ runSessions();
+ await addSheet(tester);
+ await tester.tap(find.text('Fix flaky test'));
+ await tester.pumpAndSettle();
+
+ expect(sent(), [
+ {
+ 'type': 'agent.add',
+ 'conversationId': chat,
+ 'machineId': 'mac-1',
+ 'harnessId': 'h-new',
+ 'name': 'Fix flaky test',
+ 'lead': false,
+ 'configuration': {
+ 'engine': 'claude',
+ 'model': null,
+ 'effort': null,
+ 'contextWindow': null,
+ 'engineVersion': null,
+ },
+ },
+ ]);
+ expect([for (final a in computers.asked) a.$1], ['mac-1']);
+ expect(computers.asked.single.$2, {'action': 'wake'});
+ });
+
+ testWidgets('a computer that does not answer the wake is named: the agent '
+ 'stays added, as nothing else may start its host', (tester) async {
+ await pump(tester);
+ runSessions();
+ await addSheet(tester);
+ computers.answer = (_, _) =>
+ throw const SuperTabFailure('OFFLINE', 'Could not reach it.');
+ await tester.tap(find.text('Fix flaky test'));
+ await tester.pumpAndSettle();
+
+ expect(sent().single['type'], 'agent.add');
+ expect(computers.asked.single.$2, {'action': 'wake'});
+ expect(
+ find.text(
+ "Studio didn't answer, so it may not have picked up Fix flaky test "
+ 'yet.',
+ ),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('the server\'s refusal is said at the foot of the screen, '
+ 'and wakes nothing', (tester) async {
+ await pump(tester);
+ runSessions();
+ await addSheet(tester);
+ answer = () => throw const SuperTabFailure(
+ 'TEAM_ACCOUNT_HELD',
+ 'This machine takes only that project\'s work for now.',
+ statusCode: 403,
+ );
+ await tester.tap(find.text('Fix flaky test'));
+ await tester.pumpAndSettle();
+
+ expect(key('swarm-agent-failed'), findsOneWidget);
+ expect(
+ find.text('This machine takes only that project\'s work for now.'),
+ findsOneWidget,
+ );
+ expect(computers.asked, isEmpty);
+ });
+
+ testWidgets('a call lost on the way says so', (tester) async {
+ await pump(tester);
+ await addSheet(tester);
+ answer = () => throw const SocketException('reset');
+ await tester.tap(find.text('Ash'));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Could not reach this Swarm. Try again.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('a row on its way says Adding… and is not sent twice', (
+ tester,
+ ) async {
+ await pump(tester);
+ final gate = Completer<void>();
+ answer = () async {
+ await gate.future;
+ return {'ok': true};
+ };
+ await addSheet(tester);
+ await tester.tap(find.text('Ash'));
+ await tester.pumpAndSettle();
+ await addSheet(tester);
+
+ expect(find.text('Adding…'), findsOneWidget);
+ await tester.tap(find.text('Ash'));
+ await tester.pumpAndSettle();
+ expect(find.text(title), findsOneWidget, reason: 'a dim row stays');
+ expect(sent(), hasLength(1));
+
+ gate.complete();
+ await tester.pumpAndSettle();
+ expect(find.text('Adding…'), findsNothing);
+ expect(sent(), hasLength(1));
+ });
+
+ testWidgets('a session that joined the Swarm since the sheet was drawn '
+ 'joins as its agent; a long name is cut to what the backend '
+ 'takes', (tester) async {
+ await pump(tester);
+ expect(
+ await swarmAddAgent(
+ reader(),
+ chat,
+ SwarmAgentChoice.session(session('harness-agent-ash', 'Ash')),
+ computers: computers,
+ ),
+ isNull,
+ );
+ expect(sent().single, {
+ 'type': 'conversation.agent',
+ 'conversationId': chat,
+ 'agentId': 'agent-ash',
+ 'present': true,
+ 'lead': false,
+ });
+
+ final long = ' ${'a' * 159}😀 and more ';
+ await swarmAddAgent(
+ reader(),
+ chat,
+ SwarmAgentChoice.session(session('h-long', long)),
+ );
+ final name = sent().last['name'] as String;
+ expect(name, 'a' * 159, reason: 'never half an emoji');
+ });
+
+ testWidgets('the sheet goes once the chat can no longer take an agent: '
+ 'archived elsewhere', (tester) async {
+ await pump(tester);
+ await addSheet(tester);
+ expect(find.text(title), findsOneWidget);
+ chatArchived = true;
+ await reader().refresh();
+ await tester.pumpAndSettle();
+ expect(find.text(title), findsNothing);
+ expect(sent(), isEmpty);
+ });
+
+ testWidgets('nothing is sent where the reader may not add one', (
+ tester,
+ ) async {
+ await pump(tester, role: 'viewer');
+ expect(
+ await swarmAddAgent(
+ reader(),
+ chat,
+ SwarmAgentChoice.session(session('h-new', 'Fix flaky test')),
+ ),
+ 'This action is no longer available.',
+ );
+ expect(sent(), isEmpty);
+ });
+ });
+
+ group('Team: Remove from Swarm', () {
+ const page = SwarmProjectPage(
+ swarmId: tab,
+ projectId: project,
+ tabs: SwarmProjectTab.homeC,
+ );
+
+ Future<void> team(
+ WidgetTester tester, {
+ String role = 'owner',
+ String owner = me,
+ }) async {
+ await pump(tester, role: role, owner: owner, home: page);
+ await tester.tap(key('swarm-project-menu'));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-project-menu-team'));
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> press(WidgetTester tester, String agentId) async {
+ await tester.longPress(key('swarm-member-$agentId'));
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> askToRemove(WidgetTester tester, String agentId) async {
+ await press(tester, agentId);
+ await tester.tap(find.text('Remove from Swarm'));
+ await tester.pumpAndSettle();
+ }
+
+ Finder confirm() => find.widgetWithText(FilledButton, 'Remove from Swarm');
+
+ testWidgets('a long press asks in the desktop\'s words, then sends '
+ 'agent.remove; the agent is gone from the Team', (tester) async {
+ await team(tester);
+ await askToRemove(tester, 'agent-ash');
+
+ expect(find.text('Remove Ash from this Swarm?'), findsOneWidget);
+ expect(
+ find.text(
+ 'Any open task needs to be assigned again or closed. Its session '
+ 'on Tony’s Mac will stop.',
+ ),
+ findsOneWidget,
+ );
+ expect(sent(), isEmpty);
+ await tester.tap(confirm());
+ await tester.pumpAndSettle();
+
+ expect(sent(), [
+ {'type': 'agent.remove', 'agentId': 'agent-ash'},
+ ]);
+ expect(key('swarm-member-agent-ash'), findsNothing);
+ expect(reader().snapshot!.agent('agent-ash'), isNull);
+ expect(key('swarm-agent-failed'), findsNothing);
+ });
+
+ testWidgets('its computer is named as the desktop names it: the '
+ 'person\'s own computer first, then the Swarm\'s record of it, '
+ 'else "its computer"', (tester) async {
+ await team(tester);
+ // On a computer used only for agents: the Swarm lists no pool for it.
+ agents.add(agent('agent-cy', displayName: 'Cy', machineId: 'mac-9'));
+ computers.own = const [
+ (id: 'mac-9', name: 'Studio Mac', away: false),
+ (id: 'mac-1', name: 'Tony’s MacBook', away: false),
+ ];
+ await reader().refresh();
+ await tester.pumpAndSettle();
+ String line(String machine) =>
+ 'Any open task needs to be assigned again or closed. Its session '
+ 'on $machine will stop.';
+
+ Future<void> ask(String agentId) async {
+ await tester.ensureVisible(key('swarm-member-$agentId'));
+ await tester.pumpAndSettle();
+ await askToRemove(tester, agentId);
+ }
+
+ Future<void> cancel() async {
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ }
+
+ await ask('agent-cy');
+ expect(find.text(line('Studio Mac')), findsOneWidget);
+ await cancel();
+
+ // The person's own name for it stands over the Swarm's record.
+ await ask('agent-ash');
+ expect(find.text(line('Tony’s MacBook')), findsOneWidget);
+ await cancel();
+
+ computers.own = const [];
+ await ask('agent-cy');
+ expect(find.text(line('its computer')), findsOneWidget);
+ await cancel();
+ expect(sent(), isEmpty);
+ });
+
+ testWidgets('the agent leaves the Team at once, and comes back with the '
+ 'server\'s words when it refuses', (tester) async {
+ await team(tester);
+ final gate = Completer<void>();
+ answer = () async {
+ await gate.future;
+ throw const SuperTabFailure(
+ 'WORK_ACTIVE',
+ 'Finish active work before stopping this worker.',
+ statusCode: 409,
+ );
+ };
+ await askToRemove(tester, 'agent-ash');
+ await tester.tap(confirm());
+ await tester.pumpAndSettle();
+ expect(key('swarm-member-agent-ash'), findsNothing);
+ expect(SwarmAgentWrites.of(reader()).removing('agent-ash'), isTrue);
+
+ gate.complete();
+ await tester.pumpAndSettle();
+ expect(key('swarm-member-agent-ash'), findsOneWidget);
+ expect(
+ find.text('Finish active work before stopping this worker.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('Cancel sends nothing', (tester) async {
+ await team(tester);
+ await askToRemove(tester, 'agent-ash');
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ expect(sent(), isEmpty);
+ expect(key('swarm-member-agent-ash'), findsOneWidget);
+ });
+
+ testWidgets('a project\'s coordinator is held back, its row naming the '
+ 'role in a word', (tester) async {
+ await team(tester);
+ await press(tester, 'agent-lead');
+ expect(find.text('Product Manager'), findsOneWidget);
+ await tester.tap(find.text('Remove from Swarm'));
+ await tester.pumpAndSettle();
+ expect(find.text('Remove River from this Swarm?'), findsNothing);
+ expect(sent(), isEmpty);
+ expect(
+ await swarmRemoveAgent(reader(), 'agent-lead'),
+ 'River is the Product Manager of project Mobile. Delete the project '
+ 'first.',
+ );
+ expect(sent(), isEmpty);
+ });
+
+ testWidgets('a collaborator removes only their own agents; the Swarm\'s '
+ 'owner removes any', (tester) async {
+ await team(tester, role: 'collaborator', owner: 'person-dee');
+ await press(tester, 'agent-bea');
+ expect(find.text('Remove from Swarm'), findsNothing);
+ expect(swarmAgentRights(reader(), 'agent-bea')?.remove, isFalse);
+ expect(swarmAgentRights(reader(), 'agent-ash')?.remove, isTrue);
+ expect(
+ await swarmRemoveAgent(reader(), 'agent-bea'),
+ 'This action is no longer available.',
+ );
+ expect(sent(), isEmpty);
+ await press(tester, 'agent-ash');
+ expect(find.text('Remove from Swarm'), findsOneWidget);
+ });
+
+ testWidgets('the owner may remove another person\'s agent', (tester) async {
+ await team(tester);
+ expect(swarmAgentRights(reader(), 'agent-bea')?.remove, isTrue);
+ });
+
+ testWidgets('a viewer gets no menu', (tester) async {
+ await team(tester, role: 'viewer');
+ await press(tester, 'agent-ash');
+ expect(find.text('Remove from Swarm'), findsNothing);
+ expect(key('swarm-team-add-agent'), findsNothing);
+ });
+ });
+
+ group('Team: Add agent', () {
+ const page = SwarmProjectPage(
+ swarmId: tab,
+ projectId: project,
+ tabs: SwarmProjectTab.homeC,
+ );
+
+ Future<void> team(WidgetTester tester) async {
+ await pump(tester, home: page);
+ await tester.tap(key('swarm-project-menu'));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-project-menu-team'));
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets('Add agent ends the Team\'s agents and shares a running '
+ 'session into the project\'s chat', (tester) async {
+ await team(tester);
+ runSessions();
+ await tester.ensureVisible(key('swarm-team-add-agent'));
+ expect(
+ y(tester, key('swarm-member-agent-ash')),
+ lessThan(y(tester, key('swarm-team-add-agent'))),
+ );
+ await tester.tap(key('swarm-team-add-agent'));
+ await tester.pumpAndSettle();
+
+ expect(find.text(title), findsOneWidget);
+ expect(find.text('agents'), findsNothing, reason: '#2207');
+ await tester.tap(find.text('Docs'));
+ await tester.pumpAndSettle();
+ expect(sent().single, {
+ 'type': 'agent.add',
+ 'conversationId': leadChat,
+ 'machineId': 'mac-2',
+ 'harnessId': 'h-codex',
+ 'name': 'Docs',
+ 'lead': false,
+ 'configuration': {
+ 'engine': 'codex',
+ 'model': null,
+ 'effort': null,
+ 'contextWindow': null,
+ 'engineVersion': null,
+ },
+ });
+ expect([for (final a in computers.asked) a.$1], ['mac-2']);
+ expect(computers.asked.single.$2, {'action': 'wake'});
+ });
+
+ testWidgets('with no session running it says so, and does nothing', (
+ tester,
+ ) async {
+ await team(tester);
+ await tester.ensureVisible(key('swarm-team-add-agent'));
+ await tester.tap(key('swarm-team-add-agent'));
+ await tester.pumpAndSettle();
+ expect(find.text('No running agents'), findsOneWidget);
+ await tester.tap(find.text('No running agents'));
+ await tester.pumpAndSettle();
+ expect(find.text(title), findsOneWidget);
+ expect(sent(), isEmpty);
+ });
+ });
+
+ test('the words are the desktop\'s', () {
+ final roster = File('../desktop/lib/super_tabs/roster.dart')
+ .readAsStringSync();
+ final screen = File('../desktop/lib/screens/swarm_screen.dart')
+ .readAsStringSync();
+ expect(roster, contains("addTooltip: 'Add agent'"));
+ expect(roster, contains("'Remove \$name from this Swarm?'"));
+ expect(
+ roster,
+ contains(
+ "'Any open task needs to be assigned again or closed. Its session on "
+ "\$machine will stop.'",
+ ),
+ );
+ expect(roster, contains("Text(checking ? 'Retry' : 'Remove from Swarm')"));
+ expect(roster, contains("'its computer'"));
+ expect(screen, contains("'Add agent to \${"));
+ });
+}
diff --git a/mobile/test/swarm/swarm_chat_test.dart b/mobile/test/swarm/swarm_chat_test.dart
index 54c8c2a3e..a53c9fbd6 100644
--- a/mobile/test/swarm/swarm_chat_test.dart
+++ b/mobile/test/swarm/swarm_chat_test.dart
@@ -454,25 +454,27 @@ void main() {
'm1',
1,
text: 'Here is the plan',
+ // A file the app does not read itself opens in the browser; a text
+ // file opens in the app (swarm_file_viewer_test.dart).
attachments: [
{
'id': 'f1',
- 'name': 'plan.md',
- 'mime': 'text/markdown',
+ 'name': 'plan.pdf',
+ 'mime': 'application/pdf',
'size': 2048,
- 'url': 'https://cdn.harness.autonomous.ai/f1/plan.md',
+ 'url': 'https://cdn.harness.autonomous.ai/f1/plan.pdf',
},
],
),
]),
);
- expect(find.textContaining('plan.md'), findsOneWidget);
+ expect(find.textContaining('plan.pdf'), findsOneWidget);
- await tester.tap(find.textContaining('plan.md'));
+ await tester.tap(find.textContaining('plan.pdf'));
await tester.pump();
- expect(opened, ['https://cdn.harness.autonomous.ai/f1/plan.md']);
+ expect(opened, ['https://cdn.harness.autonomous.ai/f1/plan.pdf']);
});
testWidgets('a numbered task message opens that task conversation', (
diff --git a/mobile/test/swarm/swarm_computers_test.dart b/mobile/test/swarm/swarm_computers_test.dart
index a785329cc..5950bc25e 100644
--- a/mobile/test/swarm/swarm_computers_test.dart
+++ b/mobile/test/swarm/swarm_computers_test.dart
@@ -179,6 +179,68 @@ void main() {
expect(computers.own, isEmpty);
});
+ test('the sessions running on them, for Add agent: Claude Code and Codex '
+ 'with their terminal there, not stopped, the last used first, only on '
+ 'a computer answering now', () async {
+ final rig = viewerApp();
+ addTearDown(rig.app.dispose);
+ final computers = AppSwarmComputers(rig.app);
+ addTearDown(computers.dispose);
+ rig.api.onMachines = () async => [
+ remoteMachine('a', name: 'Studio Mac'),
+ remoteMachine('b', name: 'Mac mini'),
+ ];
+ for (final id in ['a', 'b']) {
+ rig.conn(id).answers['agents_list'] = (_) => {
+ 'agents': [
+ agentJson(
+ '$id-older',
+ name: 'Fix login',
+ updatedAt: '2026-11-01T09:00:00.000Z',
+ ),
+ agentJson(
+ '$id-newer',
+ name: 'Write docs',
+ engine: 'codex',
+ updatedAt: '2026-11-02T09:00:00.000Z',
+ ),
+ agentJson('$id-cursor', name: 'Cursor work', engine: 'cursor'),
+ agentJson('$id-shell', name: 'Shell', engine: 'terminal'),
+ agentJson('$id-no-tty', name: 'No terminal', terminal: false),
+ agentJson('$id-stopped', name: 'Stopped', status: 'stopped'),
+ agentJson('$id bad id', name: 'Bad id'),
+ ],
+ };
+ rig.conn(id).answers['terminal_capabilities'] = (_) => capabilities();
+ }
+ await rig.app.bootstrap();
+ await settle();
+ rig.app.connectionStatusForTest('a', ConnectionStatus.connected);
+ rig.app.connectionStatusForTest('b', ConnectionStatus.disconnected);
+ await settle();
+
+ expect(computers.running, [
+ (
+ machineId: 'a',
+ machine: 'Studio Mac',
+ harnessId: 'a-newer',
+ name: 'Write docs',
+ engine: 'codex',
+ ),
+ (
+ machineId: 'a',
+ machine: 'Studio Mac',
+ harnessId: 'a-older',
+ name: 'Fix login',
+ engine: 'claude',
+ ),
+ ]);
+
+ // A list kept from the last run may name a session long gone.
+ rig.app.machineStates['a']!.agentsFromCache = true;
+ expect(computers.running, isEmpty);
+ });
+
test('Try again reads the list again', () async {
final rig = await signedInWith({'a': []});
addTearDown(rig.app.dispose);
diff --git a/mobile/test/swarm/swarm_file_kind_test.dart b/mobile/test/swarm/swarm_file_kind_test.dart
new file mode 100644
index 000000000..8a504a67c
--- /dev/null
+++ b/mobile/test/swarm/swarm_file_kind_test.dart
@@ -0,0 +1,106 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_file_kind.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+/// A chat file's kind, as the desktop tells it: the mark its chip wears, and
+/// whether it opens in the app's text viewer or in the browser.
+void main() {
+ SuperTabAttachment file(String name, {int size = 2048}) =>
+ SuperTabAttachment.fromJson({
+ 'id': 'f1',
+ 'name': name,
+ 'mime': 'application/octet-stream',
+ 'size': size,
+ 'url': '',
+ });
+
+ test('each kind wears the desktop mark', () {
+ final marks = {
+ 'shot.PNG': LucideIcons.fileImage,
+ 'clip.mov': LucideIcons.filePlay,
+ 'note.m4a': LucideIcons.fileMusic,
+ 'build.tar.gz': LucideIcons.fileArchive,
+ 'plan.pdf': LucideIcons.fileText,
+ 'notes.txt': LucideIcons.fileType,
+ 'README.md': LucideIcons.fileType,
+ 'numbers.csv': LucideIcons.fileSpreadsheet,
+ 'deck.pptx': LucideIcons.presentation,
+ 'main.dart': LucideIcons.fileCode,
+ 'Makefile': LucideIcons.fileCode,
+ 'Dockerfile': LucideIcons.fileCode,
+ 'package.json': LucideIcons.fileBraces,
+ 'run.sh': LucideIcons.fileTerminal,
+ 'fix.patch': LucideIcons.fileDiff,
+ 'app.sqlite': LucideIcons.database,
+ };
+ for (final MapEntry(key: name, value: mark) in marks.entries) {
+ expect(swarmFileIcon(name), mark, reason: name);
+ }
+ });
+
+ test('a kind it does not know, or no name, is the plain file', () {
+ for (final name in ['thing.xyz', 'LICENSE', '', 'archive.', '.']) {
+ expect(swarmFileIcon(name), LucideIcons.file, reason: '"$name"');
+ }
+ });
+
+ test('a folder in the name is not its kind', () {
+ expect(swarmFileIcon('docs.md/plan.pdf'), LucideIcons.fileText);
+ expect(swarmFileKind(r'logs\run.log'), SwarmFileKind.text);
+ });
+
+ test('text and Markdown by name, everything else not', () {
+ expect(swarmFileKind('spec.md'), SwarmFileKind.markdown);
+ expect(swarmFileKind('SPEC.MARKDOWN'), SwarmFileKind.markdown);
+ expect(swarmFileKind('page.mdx'), SwarmFileKind.markdown);
+ for (final name in [
+ 'notes.txt',
+ 'server.log',
+ 'data.csv',
+ 'config.yaml',
+ 'main.dart',
+ 'LICENSE',
+ 'Makefile',
+ '.gitignore',
+ ]) {
+ expect(swarmFileKind(name), SwarmFileKind.text, reason: name);
+ }
+ for (final name in [
+ 'plan.pdf',
+ 'shot.png',
+ 'logo.svg',
+ 'build.zip',
+ 'deck.pptx',
+ 'thing.xyz',
+ 'noextension',
+ ]) {
+ expect(swarmFileKind(name), SwarmFileKind.other, reason: name);
+ }
+ });
+
+ test('only text up to 2 MB opens in the viewer', () {
+ expect(swarmOpensAsText(file('notes.txt')), isTrue);
+ expect(swarmOpensAsText(file('spec.md', size: swarmTextMaxBytes)), isTrue);
+ expect(
+ swarmOpensAsText(file('spec.md', size: swarmTextMaxBytes + 1)),
+ isFalse,
+ );
+ expect(swarmOpensAsText(file('plan.pdf')), isFalse);
+ expect(swarmOpensAsText(file('shot.png')), isFalse);
+ expect(swarmTextMaxBytes, 2 * 1024 * 1024, reason: "the desktop's limit");
+ });
+
+ test('reads as text: no NUL, and few control characters', () {
+ Uint8List bytes(List<int> list) => Uint8List.fromList(list);
+ expect(swarmLooksLikeText(bytes([])), isTrue);
+ expect(swarmLooksLikeText(utf8.encode('# Plan\n\tTiếng Việt\r\n')), isTrue);
+ expect(swarmLooksLikeText(bytes([0x50, 0x4b, 0x03, 0x04, 0])), isFalse);
+ // One control character in a hundred passes; one in ten does not.
+ expect(swarmLooksLikeText(bytes([...List.filled(99, 0x41), 1])), isTrue);
+ expect(swarmLooksLikeText(bytes([...List.filled(9, 0x41), 1])), isFalse);
+ });
+}
diff --git a/mobile/test/swarm/swarm_file_viewer_test.dart b/mobile/test/swarm/swarm_file_viewer_test.dart
new file mode 100644
index 000000000..d1ff3d2b9
--- /dev/null
+++ b/mobile/test/swarm/swarm_file_viewer_test.dart
@@ -0,0 +1,454 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/phone/tty.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_attachment_store.dart';
+import 'package:harness_mobile/swarm/swarm_file_download.dart';
+import 'package:harness_mobile/swarm/swarm_file_kind.dart';
+import 'package:harness_mobile/swarm/swarm_file_links.dart';
+import 'package:harness_mobile/swarm/swarm_file_viewer.dart';
+import 'package:harness_mobile/swarm/swarm_message_row.dart';
+import 'package:harness_mobile/swarm/swarm_reader.dart';
+import 'package:harness_mobile/swarm/swarm_style.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:share_plus/share_plus.dart';
+
+import 'swarm_attachment_fakes.dart';
+
+/// A chat's text and Markdown files open in the app, as on the desktop: the
+/// chip wears the file's kind, a tap reads the file into a viewer (Markdown
+/// rendered, its source a tap away), Download hands it to the share sheet
+/// under its own name, and a file that cannot be shown offers the browser.
+/// Every other file still opens in the browser.
+void main() {
+ late Directory root;
+ late FakeFileStorage storage;
+ late SwarmAttachmentStore store;
+ late List<Uri> opened;
+ late List<({String name, String text})> shared;
+ late Future<bool> Function(Uri) openFile;
+ late Future<void> Function(ShareParams) shareSheet;
+
+ final link = Uri.parse('https://cdn.example/swarm/notes.txt');
+
+ SuperTabAttachment attachment(String name, {int size = 2048}) =>
+ SuperTabAttachment.fromJson({
+ 'id': 'file-1',
+ 'name': name,
+ 'mime': 'text/plain',
+ 'size': size,
+ 'url': link.toString(),
+ });
+
+ setUp(() {
+ root = Directory.systemTemp.createTempSync('swarm-file-viewer-');
+ storage = FakeFileStorage()..bytes = utf8.encode('line one\nline two\n');
+ store = storeIn(root, storage);
+ opened = [];
+ shared = [];
+ openFile = swarmOpenFile;
+ swarmOpenFile = (url) async {
+ opened.add(url);
+ return true;
+ };
+ shareSheet = swarmShareSheet;
+ swarmShareSheet = (params) async {
+ // Read as the sheet would, while it is up.
+ final copy = File(params.files!.single.path);
+ shared.add((
+ name: copy.uri.pathSegments.last,
+ text: copy.readAsStringSync(),
+ ));
+ };
+ });
+ tearDown(() {
+ swarmOpenFile = openFile;
+ swarmShareSheet = shareSheet;
+ if (root.existsSync()) root.deleteSync(recursive: true);
+ });
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+ final chip = key('swarm-file-chip-file-1');
+ final viewer = key('swarm-file-viewer');
+ final download = key('swarm-file-download');
+
+ Future<void> pump(WidgetTester tester, SuperTabAttachment file) async {
+ // Real folders: outside the test's fake clock.
+ await tester.runAsync(() => store.keepOnly('person-me'));
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Center(
+ child: SwarmFileChip(file: file, link: link, store: store),
+ ),
+ ),
+ ),
+ );
+ }
+
+ /// Real time for the file to be fetched and read, a frame after each step,
+ /// until [done] holds.
+ Future<void> until(WidgetTester tester, bool Function() done) async {
+ for (var i = 0; i < 100 && !done(); i++) {
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 10)),
+ );
+ await tester.pump();
+ }
+ expect(done(), isTrue);
+ }
+
+ /// The file open in the viewer and read.
+ Future<void> open(WidgetTester tester, SuperTabAttachment file) async {
+ await pump(tester, file);
+ await tester.tap(chip);
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 400));
+ await until(
+ tester,
+ () => find
+ .descendant(of: viewer, matching: find.byType(SelectionArea))
+ .evaluate()
+ .isNotEmpty,
+ );
+ }
+
+ /// Ends a test that fetched: the screen closed, and the cache's own
+ /// cleanup, which it runs every few seconds, let run.
+ Future<void> closed(WidgetTester tester) async {
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(minutes: 1));
+ }
+
+ VoidCallback? downloadTap(WidgetTester tester) =>
+ tester.widget<SwarmIconButton>(download).onPressed;
+
+ testWidgets('the chip wears its kind, as the desktop marks it', (
+ tester,
+ ) async {
+ for (final (name, mark) in [
+ ('notes.txt', LucideIcons.fileType),
+ ('plan.pdf', LucideIcons.fileText),
+ ('main.dart', LucideIcons.fileCode),
+ ('thing.xyz', LucideIcons.file),
+ ]) {
+ await pump(tester, attachment(name));
+ final icon = tester.widget<Icon>(
+ find.descendant(of: chip, matching: find.byType(Icon)),
+ );
+ expect(icon.icon, mark, reason: name);
+ }
+ });
+
+ testWidgets('a text file opens in the app, as it is written', (tester) async {
+ storage.bytes = utf8.encode('line one\r\n\tline two\n');
+ await open(tester, attachment('notes.txt'));
+
+ expect(viewer, findsOneWidget);
+ expect(find.text('notes.txt'), findsWidgets, reason: 'its name on top');
+ expect(find.text('line one'), findsOneWidget);
+ expect(find.text(' line two'), findsOneWidget);
+ expect(key('swarm-file-source'), findsNothing, reason: 'not Markdown');
+ expect(storage.asked.single.url, link.toString());
+ expect(opened, isEmpty, reason: 'not the browser');
+
+ await tester.tap(key('swarm-file-close'));
+ await tester.pumpAndSettle();
+ expect(viewer, findsNothing);
+ expect(chip, findsOneWidget);
+ await closed(tester);
+ });
+
+ testWidgets('source text follows the terminal setting, with no size of its '
+ 'own', (tester) async {
+ storage.bytes = utf8.encode('fn main() {}\n');
+ await open(tester, attachment('main.txt'));
+
+ final context = tester.element(key('swarm-file-text'));
+ expect(
+ tester.widget<Text>(find.text('fn main() {}')).style,
+ Tty.of(context).style(),
+ );
+ await closed(tester);
+ });
+
+ testWidgets('a Markdown file is rendered, and Show source shows it as '
+ 'written', (tester) async {
+ storage.bytes = utf8.encode('# Plan\n\nShip **today**.\n');
+ await open(tester, attachment('plan.md'));
+
+ expect(key('swarm-file-markdown'), findsOneWidget);
+ expect(find.text('Plan'), findsOneWidget);
+ expect(find.text('# Plan'), findsNothing);
+
+ await tester.tap(key('swarm-file-source'));
+ await tester.pump();
+ expect(key('swarm-file-text'), findsOneWidget);
+ expect(find.text('# Plan'), findsOneWidget);
+ expect(find.text('Ship **today**.'), findsOneWidget);
+ expect(
+ tester.widget<SwarmIconButton>(key('swarm-file-source')).label,
+ 'Show preview',
+ );
+
+ await tester.tap(key('swarm-file-source'));
+ await tester.pump();
+ expect(key('swarm-file-markdown'), findsOneWidget);
+ await closed(tester);
+ });
+
+ testWidgets('every other file opens in the browser, as before', (
+ tester,
+ ) async {
+ await pump(tester, attachment('plan.pdf'));
+ await tester.tap(chip);
+ await tester.pumpAndSettle();
+
+ expect(opened, [link]);
+ expect(viewer, findsNothing);
+ expect(storage.asked, isEmpty);
+ });
+
+ testWidgets('a text file over 2 MB by its message opens in the browser', (
+ tester,
+ ) async {
+ await pump(tester, attachment('big.log', size: swarmTextMaxBytes + 1));
+ await tester.tap(chip);
+ await tester.pumpAndSettle();
+
+ expect(opened, [link]);
+ expect(viewer, findsNothing);
+ expect(storage.asked, isEmpty);
+ });
+
+ testWidgets('a file larger than its message said opens in the browser '
+ 'instead', (tester) async {
+ storage.bytes = List.filled(swarmTextMaxBytes + 1, 0x61);
+ await pump(tester, attachment('notes.txt'));
+ await tester.tap(chip);
+ await tester.pump();
+
+ await until(tester, () => opened.isNotEmpty);
+ await tester.pumpAndSettle();
+ expect(opened, [link]);
+ expect(viewer, findsNothing);
+ await closed(tester);
+ });
+
+ testWidgets('a file that cannot be fetched says so, with Open in browser', (
+ tester,
+ ) async {
+ storage.status = 404;
+ await pump(tester, attachment('notes.txt'));
+ await tester.tap(chip);
+ await tester.pump();
+
+ await until(
+ tester,
+ () => find.text('Can’t open this file').evaluate().isNotEmpty,
+ );
+ expect(
+ find.text('It couldn’t be downloaded. Try again in the browser.'),
+ findsOneWidget,
+ );
+ expect(downloadTap(tester), isNull, reason: 'nothing to download');
+
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-file-browser'));
+ await tester.pump();
+ expect(opened, [link]);
+ await closed(tester);
+ });
+
+ testWidgets('a file that is not text after all has no preview', (
+ tester,
+ ) async {
+ storage.bytes = [0x50, 0x4b, 0x03, 0x04, 0, 0, 0];
+ await pump(tester, attachment('notes.txt'));
+ await tester.tap(chip);
+ await tester.pump();
+
+ await until(tester, () => find.text('No preview').evaluate().isNotEmpty);
+ expect(
+ find.text('This file isn’t text that can be shown here.'),
+ findsOneWidget,
+ );
+ expect(downloadTap(tester), isNotNull, reason: 'it can still be saved');
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-file-browser'));
+ await tester.pump();
+ expect(opened, [link]);
+ await closed(tester);
+ });
+
+ testWidgets('Download is off while the file is on its way', (tester) async {
+ storage.hold = Completer();
+ await pump(tester, attachment('notes.txt'));
+ await tester.tap(chip);
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 400));
+
+ expect(key('swarm-file-loading'), findsOneWidget);
+ expect(downloadTap(tester), isNull);
+
+ storage.hold!.complete();
+ await until(tester, () => downloadTap(tester) != null);
+ expect(find.text('line two'), findsOneWidget);
+ await closed(tester);
+ });
+
+ testWidgets('Download hands the file to the share sheet under its own '
+ 'name, then lets the copy go', (tester) async {
+ await open(tester, attachment('Release notes.md'));
+
+ await tester.tap(download);
+ await until(tester, () => shared.isNotEmpty);
+
+ expect(shared.single.name, 'Release notes.md');
+ expect(shared.single.text, 'line one\nline two\n');
+ await until(tester, () => downloadTap(tester) != null);
+ expect(
+ keptUnder(root).where((path) => path.contains('shared')),
+ isEmpty,
+ reason: 'the copy went',
+ );
+ await closed(tester);
+ });
+
+ testWidgets('a Download that fails says so', (tester) async {
+ swarmShareSheet = (_) async => throw StateError('No sheet');
+ await open(tester, attachment('notes.txt'));
+
+ await tester.tap(download);
+ await until(
+ tester,
+ () => find.text(swarmFileNotSaved).evaluate().isNotEmpty,
+ );
+ expect(viewer, findsOneWidget);
+ await closed(tester);
+ });
+
+ testWidgets('another account closes it at once, its text let go', (
+ tester,
+ ) async {
+ await open(tester, attachment('notes.txt'));
+
+ var changed = false;
+ unawaited(store.keepOnly('person-b').whenComplete(() => changed = true));
+ await tester.pump();
+
+ expect(find.text('line one'), findsNothing, reason: 'blank at once');
+ expect(
+ find.descendant(of: viewer, matching: find.text('notes.txt')),
+ findsNothing,
+ );
+ await tester.pumpAndSettle();
+ expect(viewer, findsNothing);
+
+ await until(tester, () => changed);
+ await closed(tester);
+ });
+
+ group('with a signed link', () {
+ final now = DateTime.utc(2026, 11, 3, 9);
+ final ms = now.millisecondsSinceEpoch;
+ String signed(String sig) =>
+ 'https://storage.googleapis.com/bucket/super-tabs/tab/f1/notes.txt'
+ '?X-Goog-Signature=$sig';
+
+ setUp(() => swarmFileClock = () => now);
+ tearDown(() => swarmFileClock = DateTime.now);
+
+ testWidgets('one about to end is asked for again before the file is '
+ 'fetched', (tester) async {
+ final reads = <String>[];
+ final reader = SwarmReader(
+ tabId: 'tab',
+ accountId: 'me',
+ request: (method, path, {body}) async {
+ reads.add(path);
+ return {
+ 'attachment': {
+ 'id': 'file-1',
+ 'name': 'notes.txt',
+ 'mime': 'text/plain',
+ 'size': 2048,
+ 'url': '',
+ 'link': signed('fresh'),
+ 'expiresAt': ms + 600000,
+ },
+ };
+ },
+ );
+ addTearDown(reader.dispose);
+ final file = SuperTabAttachment.fromJson({
+ 'id': 'file-1',
+ 'name': 'notes.txt',
+ 'mime': 'text/plain',
+ 'size': 2048,
+ 'url': '',
+ 'link': signed('old'),
+ 'expiresAt': ms + 30000,
+ });
+ final ref = SwarmFileRef(
+ file,
+ conversationId: 'lead',
+ messageId: 'm1',
+ reader: reader,
+ );
+ await tester.runAsync(() => store.keepOnly('person-me'));
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SwarmFiles(
+ reader: reader,
+ child: SwarmFileChip(
+ file: file,
+ link: ref.current,
+ fileRef: ref,
+ store: store,
+ ),
+ ),
+ ),
+ ),
+ );
+
+ await tester.tap(chip);
+ await until(tester, () => find.text('line two').evaluate().isNotEmpty);
+
+ expect(reads, [
+ '/api/super-tabs/tab/conversations/lead/messages/m1/attachments/file-1',
+ ]);
+ expect(storage.asked.map((a) => a.url), [signed('fresh')]);
+ expect(opened, isEmpty);
+ await closed(tester);
+ });
+ });
+
+ group('lines as drawn', () {
+ test('a file\'s own lines, CRLF or LF, a tab as four spaces', () {
+ expect(swarmTextLines('a\r\n\tb\nc'), ['a', ' b', 'c']);
+ expect(swarmTextLines(''), ['']);
+ expect(swarmTextLines('end\n'), ['end', '']);
+ });
+
+ test('a very long line is cut into pieces, the text kept whole', () {
+ final line = 'x' * 4500;
+ final pieces = swarmTextLines(line);
+ expect(pieces.map((p) => p.length), [2000, 2000, 500]);
+ expect(pieces.join(), line);
+ });
+
+ test('a cut never splits a character in two', () {
+ final line = '${'x' * 1999}😀${'y' * 10}';
+ final pieces = swarmTextLines(line);
+ expect(pieces.first, 'x' * 1999);
+ expect(pieces.join(), line);
+ expect(pieces[1], startsWith('😀'));
+ });
+ });
+}
diff --git a/mobile/test/swarm/swarm_link_previews_shots_test.dart b/mobile/test/swarm/swarm_link_previews_shots_test.dart
new file mode 100644
index 000000000..e92b956ec
--- /dev/null
+++ b/mobile/test/swarm/swarm_link_previews_shots_test.dart
@@ -0,0 +1,190 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Review screenshots of message link previews and a fetched quote in the real
+/// chat, 390 points wide in both phone themes, from made-up data, to the folder
+/// `SWARM_LINK_PREVIEW_SHOTS` names: a message this chat holds, one in another
+/// chat, one the reader may not read, and a reply whose original is not loaded.
+final shots = Platform.environment['SWARM_LINK_PREVIEW_SHOTS'];
+
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ Map<String, dynamic> message(
+ String id,
+ int sequence,
+ String text, {
+ String conversation = 'g1',
+ String? replyTo,
+ }) => {
+ 'id': id,
+ 'conversationId': conversation,
+ 'text': text,
+ 'sequence': sequence,
+ 'replyTo': ?replyTo,
+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},
+ 'attachments': <Object>[],
+ 'reactions': <Object>[],
+ 'createdAt': DateTime.now()
+ .subtract(Duration(minutes: 30 - sequence))
+ .toUtc()
+ .toIso8601String(),
+ };
+
+ testWidgets('Link previews and a fetched quote, in both phone themes', (
+ tester,
+ ) async {
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ String one(String chat, String id) =>
+ '/api/super-tabs/$tab/conversations/$chat/messages?messageId=$id';
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ await tester.binding.setSurfaceSize(const Size(390, 640));
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'OpenHarness', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(
+ groups: [
+ groupData(
+ 'g1',
+ title: 'Fix login',
+ agentIds: ['agent-lead', 'agent-builder'],
+ status: 'working',
+ lastMessageSequence: 3,
+ ),
+ groupData('g2', title: 'Release notes', agentIds: ['agent-builder']),
+ ],
+ );
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/conversations/g1/messages'] = (_) => {
+ 'messages': [
+ message(
+ 'm3',
+ 3,
+ 'Thanks, that matches what I saw.',
+ replyTo: 'older',
+ ),
+ message(
+ 'm2',
+ 2,
+ 'Three places to read before we ship:\n'
+ 'harness://swarm/$tab/g1/m1\n'
+ 'harness://swarm/$tab/g2/notes\n'
+ 'harness://swarm/$tab/g2/secret',
+ ),
+ message('m1', 1, 'Sign-in fails when the token has just expired.'),
+ ],
+ 'next': null,
+ 'threads': <Object>[],
+ };
+ fake.routes[one('g2', 'notes')] = (_) => {
+ 'messages': [
+ message(
+ 'notes',
+ 1,
+ 'Drafted the release notes.\nThe sign-in fix goes first.',
+ conversation: 'g2',
+ ),
+ ],
+ };
+ fake.routes[one('g2', 'secret')] = (_) =>
+ throw const SuperTabFailure('FORBIDDEN', 'No access.');
+ fake.routes[one('g1', 'older')] = (_) => {
+ 'messages': [message('older', 0, 'It only happens after a restart.')],
+ };
+ final host = SwarmHost(
+ accountId: () => me,
+ account: ValueNotifier<String?>(me),
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmConversationPage(
+ swarmId: tab,
+ conversationId: 'g1',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Message unavailable'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/phone-link-previews-${brightness.name}-390.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ await tester.pumpWidget(const SizedBox());
+ host.dispose();
+ await tester.pump(const Duration(minutes: 1));
+ }
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_link_previews_test.dart b/mobile/test/swarm/swarm_link_previews_test.dart
new file mode 100644
index 000000000..9ff6b8889
--- /dev/null
+++ b/mobile/test/swarm/swarm_link_previews_test.dart
@@ -0,0 +1,496 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_project_page.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// A message that links to another Swarm message shows a small preview of
+/// it under its text, as Desktop does: who wrote it, the chat it is in when
+/// that is another, and the start of its text; a tap opens it. A reply whose
+/// original is outside the pages read reads that one message by itself to
+/// quote it, and says it "isn't loaded" only when that read fails.
+void main() {
+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';
+ String one(String conversation, String id, {String swarm = tab}) =>
+ '/api/super-tabs/$swarm/conversations/$conversation/messages'
+ '?messageId=$id';
+
+ Map<String, dynamic> message(
+ String id,
+ int sequence, {
+ String conversation = 'g1',
+ String text = 'hello',
+ String author = 'agent-builder',
+ String? replyTo,
+ int minute = 0,
+ }) => {
+ 'id': id,
+ 'conversationId': conversation,
+ 'text': text,
+ 'sequence': sequence,
+ 'replyTo': ?replyTo,
+ 'author': author == me
+ ? {'kind': 'person', 'id': me, 'name': 'tony'}
+ : {
+ 'kind': 'agent',
+ 'id': author,
+ 'name': author == 'agent-lead' ? 'River' : 'Nova',
+ },
+ 'attachments': <Object>[],
+ 'reactions': <Object>[],
+ 'createdAt': DateTime.utc(2026, 10, 27, 1, minute).toIso8601String(),
+ };
+
+ /// Swarm [tab] with chat g1 reading [page] as its latest messages, and
+ /// chat g2, "Release notes"; with [other], the account also has Swarm
+ /// tab-2, whose chat h1 is "Billing". [members] join the reader in [tab].
+ FakeSwarm backend(
+ List<Map<String, dynamic>> page, {
+ Object? next,
+ bool other = false,
+ List<Map<String, dynamic>> members = const [],
+ }) {
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ if (other) {'id': 'tab-2', 'name': 'Ops Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) {
+ final load = firstLoad(
+ groups: [
+ groupData(
+ 'g1',
+ title: 'Fix login',
+ agentIds: ['agent-lead', 'agent-builder'],
+ status: 'working',
+ lastMessageSequence: page.isEmpty
+ ? 0
+ : page.last['sequence'] as int,
+ ),
+ groupData('g2', title: 'Release notes', agentIds: ['agent-builder']),
+ ],
+ );
+ for (final member in members) {
+ (load['members'] as List).add(part(member['id'] as String, 1, member));
+ }
+ return load;
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/tab-2/parts'] = (_) => firstLoad(
+ tabId: 'tab-2',
+ groups: [
+ groupData('h1', title: 'Billing', agentIds: ['agent-builder']),
+ ],
+ );
+ fake.routes['/api/super-tabs/tab-2/changes'] = (_) => changes(cursor: 'c2');
+ for (final swarm in [tab, 'tab-2']) {
+ fake.routes['/api/super-tabs/$swarm/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$swarm/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ }
+ fake.routes[messages] = (_) => {
+ 'messages': page.reversed.toList(),
+ 'next': next,
+ 'threads': <Object>[],
+ };
+ return fake;
+ }
+
+ late SwarmHost host;
+
+ /// The chat on screen. [inFront]: Harness is in front, so the chat's Swarm
+ /// is read every few seconds.
+ Future<void> pump(
+ WidgetTester tester,
+ FakeSwarm fake, {
+ bool inFront = false,
+ }) async {
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
+ final account = ValueNotifier<String?>(me);
+ host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: features,
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = inFront;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ /// Leaves the chat, so nothing it reads is still waiting.
+ Future<void> leave(WidgetTester tester) async {
+ host.foreground = false;
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 30));
+ }
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+
+ /// [text] in the preview of the link to [path], "<swarm>/<chat>/<message>".
+ Finder inPreview(String path, String text) => find.descendant(
+ of: key('swarm-link-preview-$path'),
+ matching: find.text(text),
+ );
+ int asked(FakeSwarm fake, String path) =>
+ fake.paths.where((p) => p == path).length;
+
+ testWidgets('a link to a message the chat holds shows who wrote it and its '
+ 'text; a tap brings it into view and lights it', (tester) async {
+ final fake = backend([
+ message('m1', 1, author: 'agent-lead', text: 'The very first plan'),
+ for (var i = 2; i < 40; i++)
+ message('m$i', i, text: 'Line $i\nof the log', minute: i),
+ message(
+ 'm40',
+ 40,
+ author: me,
+ text: 'Read this: harness://swarm/$tab/g1/m1',
+ minute: 50,
+ ),
+ ]);
+ await pump(tester, fake);
+
+ expect(inPreview('$tab/g1/m1', 'River'), findsOneWidget);
+ expect(inPreview('$tab/g1/m1', 'The very first plan'), findsOneWidget);
+ expect(
+ fake.paths.where((p) => p.contains('messageId=')),
+ isEmpty,
+ reason: 'a message the chat holds is not read again',
+ );
+
+ await tester.tap(key('swarm-link-preview-$tab/g1/m1'));
+ await tester.pumpAndSettle();
+
+ final row = find.descendant(
+ of: key('swarm-message-m1'),
+ matching: find.text('The very first plan'),
+ );
+ expect(row, findsOneWidget);
+ expect(key('swarm-lit-m1'), findsOneWidget);
+ await leave(tester);
+ });
+
+ testWidgets('a link to a message the chat has not read reads that one '
+ 'message once, says Loading meanwhile, then shows it', (tester) async {
+ final answer = Completer<Object?>();
+ final fake = backend([
+ message('m40', 40, author: me, text: 'See harness://swarm/$tab/g1/m-old'),
+ ]);
+ fake.routes[one('g1', 'm-old')] = (_) => answer.future;
+ await pump(tester, fake, inFront: true);
+
+ expect(inPreview('$tab/g1/m-old', 'Loading message…'), findsOneWidget);
+
+ answer.complete({
+ 'messages': [
+ message(
+ 'm-old',
+ 3,
+ author: 'agent-lead',
+ text: ' Ship it\n\n behind a flag ',
+ ),
+ ],
+ });
+ await tester.pumpAndSettle();
+ expect(inPreview('$tab/g1/m-old', 'River'), findsOneWidget);
+ expect(inPreview('$tab/g1/m-old', 'Ship it behind a flag'), findsOneWidget);
+
+ // The chat's Swarm is read again and again: the message is not.
+ await tester.pump(const Duration(seconds: 20));
+ await tester.pumpAndSettle();
+ expect(asked(fake, one('g1', 'm-old')), 1);
+ await leave(tester);
+ });
+
+ testWidgets('a link to another chat names that chat; a tap opens it at the '
+ 'message', (tester) async {
+ final fake = backend([
+ message('m1', 1, author: me, text: 'Notes: harness://swarm/$tab/g2/x1'),
+ ]);
+ fake.routes[one('g2', 'x1')] = (_) => {
+ 'messages': [message('x1', 7, conversation: 'g2', text: 'v2.4 is out')],
+ };
+ await pump(tester, fake);
+
+ expect(inPreview('$tab/g2/x1', 'Nova · Release notes'), findsOneWidget);
+ expect(inPreview('$tab/g2/x1', 'v2.4 is out'), findsOneWidget);
+
+ await tester.tap(key('swarm-link-preview-$tab/g2/x1'));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 500));
+
+ expect(
+ find.byWidgetPredicate(
+ (w) =>
+ w is SwarmOpenedChat &&
+ w.swarmId == tab &&
+ w.conversationId == 'g2' &&
+ w.messageId == 'x1',
+ ),
+ findsOneWidget,
+ );
+ await leave(tester);
+ });
+
+ testWidgets('a link into another of the account\'s Swarms is read with that '
+ 'Swarm; one the account does not have is unavailable, unread', (
+ tester,
+ ) async {
+ final fake = backend([
+ message(
+ 'm1',
+ 1,
+ author: me,
+ text:
+ 'Billing: harness://swarm/tab-2/h1/b1\n'
+ 'Old: harness://swarm/tab-9/z1/z2',
+ ),
+ ], other: true);
+ fake.routes[one('h1', 'b1', swarm: 'tab-2')] = (_) => {
+ 'messages': [
+ message('b1', 2, conversation: 'h1', author: me, text: 'Invoice sent'),
+ ],
+ };
+ await pump(tester, fake);
+
+ expect(inPreview('tab-2/h1/b1', 'You · Billing'), findsOneWidget);
+ expect(inPreview('tab-2/h1/b1', 'Invoice sent'), findsOneWidget);
+ expect(inPreview('tab-9/z1/z2', 'Message unavailable'), findsOneWidget);
+ expect(fake.paths.where((p) => p.contains('tab-9')), isEmpty);
+ await leave(tester);
+ });
+
+ testWidgets('a link the reader may not read, or to a message gone, says '
+ 'only Message unavailable and opens nothing', (tester) async {
+ final fake = backend([
+ message(
+ 'm1',
+ 1,
+ author: me,
+ text:
+ 'harness://swarm/$tab/g9/secret\n'
+ 'harness://swarm/$tab/g2/gone',
+ ),
+ ]);
+ fake.routes[one('g9', 'secret')] = (_) =>
+ throw const SuperTabFailure('FORBIDDEN', 'No access.', statusCode: 403);
+ fake.routes[one('g2', 'gone')] = (_) => {'messages': <Object>[]};
+ await pump(tester, fake);
+
+ expect(inPreview('$tab/g9/secret', 'Message unavailable'), findsOneWidget);
+ expect(inPreview('$tab/g2/gone', 'Message unavailable'), findsOneWidget);
+ expect(find.textContaining('No access'), findsNothing);
+
+ await tester.tap(key('swarm-link-preview-$tab/g9/secret'));
+ await tester.pumpAndSettle();
+ expect(find.byType(SwarmOpenedChat), findsNothing);
+ await leave(tester);
+ });
+
+ testWidgets('a link in code is no preview', (tester) async {
+ final fake = backend([
+ message('m1', 1, text: 'Run `open harness://swarm/$tab/g1/m1`'),
+ ]);
+ await pump(tester, fake);
+
+ expect(key('swarm-link-previews-m1'), findsNothing);
+ expect(fake.paths.where((p) => p.contains('messageId=')), isEmpty);
+ await leave(tester);
+ });
+
+ testWidgets('links to messages of the same id in two chats each show '
+ 'their own preview', (tester) async {
+ final fake = backend([
+ message(
+ 'm1',
+ 1,
+ author: me,
+ text: 'harness://swarm/$tab/g1/x1 and harness://swarm/$tab/g2/x1',
+ ),
+ ]);
+ fake.routes[one('g1', 'x1')] = (_) => {
+ 'messages': [message('x1', 7, text: 'Here')],
+ };
+ fake.routes[one('g2', 'x1')] = (_) => {
+ 'messages': [message('x1', 7, conversation: 'g2', text: 'There')],
+ };
+ await pump(tester, fake);
+
+ expect(tester.takeException(), isNull);
+ expect(inPreview('$tab/g1/x1', 'Here'), findsOneWidget);
+ expect(inPreview('$tab/g2/x1', 'Nova · Release notes'), findsOneWidget);
+ expect(inPreview('$tab/g2/x1', 'There'), findsOneWidget);
+ await leave(tester);
+ });
+
+ testWidgets('a person who set a name is shown by it, as the chat shows '
+ 'them', (tester) async {
+ final fake = backend(
+ [message('m1', 1, author: me, text: 'See harness://swarm/$tab/g2/k1')],
+ members: [
+ {
+ ...person('ken', role: 'collaborator'),
+ 'username': 'kenji',
+ 'name': 'Minh Nguyen',
+ },
+ ],
+ );
+ fake.routes[one('g2', 'k1')] = (_) => {
+ 'messages': [
+ {
+ ...message('k1', 7, conversation: 'g2', text: 'Shipped'),
+ 'author': {'kind': 'person', 'id': 'ken', 'name': 'kenji'},
+ },
+ ],
+ };
+ await pump(tester, fake);
+
+ expect(
+ inPreview('$tab/g2/k1', 'Minh Nguyen · Release notes'),
+ findsOneWidget,
+ );
+ expect(find.textContaining('kenji'), findsNothing);
+ await leave(tester);
+ });
+
+ group('a reply whose original is not loaded', () {
+ List<Map<String, dynamic>> page() => [
+ for (var i = 10; i < 40; i++)
+ message('m$i', i, text: 'Line $i\nof the log', minute: i),
+ message('m40', 40, author: me, text: 'Yes', replyTo: 'm1', minute: 50),
+ ];
+ const older = {'sequence': 10, 'id': 'm10'};
+
+ testWidgets('reads the original by itself, once, and quotes it', (
+ tester,
+ ) async {
+ final fake = backend(page(), next: older);
+ fake.routes[one('g1', 'm1')] = (_) => {
+ 'messages': [
+ message('m1', 1, author: 'agent-lead', text: 'The very first plan'),
+ ],
+ };
+ await pump(tester, fake, inFront: true);
+
+ final quote = key('swarm-quote-m40');
+ expect(
+ find.descendant(of: quote, matching: find.text('River')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: quote, matching: find.text('The very first plan')),
+ findsOneWidget,
+ );
+ expect(find.text("The original message isn't loaded."), findsNothing);
+
+ await tester.pump(const Duration(seconds: 20));
+ await tester.pumpAndSettle();
+ expect(asked(fake, one('g1', 'm1')), 1);
+ expect(
+ fake.paths,
+ isNot(contains('$messages?before=10&beforeId=m10')),
+ reason: 'no earlier page is read for a quote',
+ );
+ await leave(tester);
+ });
+
+ testWidgets('names a person who set a name by it', (tester) async {
+ final fake = backend(
+ page(),
+ next: older,
+ members: [
+ {
+ ...person('ken', role: 'collaborator'),
+ 'username': 'kenji',
+ 'name': 'Minh Nguyen',
+ },
+ ],
+ );
+ fake.routes[one('g1', 'm1')] = (_) => {
+ 'messages': [
+ {
+ ...message('m1', 1, text: 'The very first plan'),
+ 'author': {'kind': 'person', 'id': 'ken', 'name': 'kenji'},
+ },
+ ],
+ };
+ await pump(tester, fake);
+
+ expect(
+ find.descendant(
+ of: key('swarm-quote-m40'),
+ matching: find.text('Minh Nguyen'),
+ ),
+ findsOneWidget,
+ );
+ await leave(tester);
+ });
+
+ testWidgets('says it isn\'t loaded when that read fails, and asks again '
+ 'only a minute later', (tester) async {
+ final fake = backend(page(), next: older);
+ fake.routes[one('g1', 'm1')] = (_) =>
+ throw const SuperTabFailure('UNAVAILABLE', 'Down.', statusCode: 503);
+ await pump(tester, fake, inFront: true);
+
+ expect(find.text("The original message isn't loaded."), findsOneWidget);
+ await tester.pump(const Duration(seconds: 20));
+ await tester.pumpAndSettle();
+ expect(asked(fake, one('g1', 'm1')), 1);
+
+ await tester.pump(const Duration(seconds: 45));
+ await tester.pumpAndSettle();
+ expect(asked(fake, one('g1', 'm1')), 2);
+ expect(find.text("The original message isn't loaded."), findsOneWidget);
+ await leave(tester);
+ });
+
+ testWidgets('says it is no longer in the chat when it is gone or not the '
+ 'reader\'s', (tester) async {
+ for (final answer in <Object? Function()>[
+ () => {'messages': <Object>[]},
+ () => throw const SuperTabFailure('NOT_FOUND', 'Gone.'),
+ ]) {
+ final fake = backend(page(), next: older);
+ fake.routes[one('g1', 'm1')] = (_) => answer();
+ await pump(tester, fake);
+
+ expect(
+ find.descendant(
+ of: key('swarm-quote-m40'),
+ matching: find.text(
+ 'The original message is no longer in this chat.',
+ ),
+ ),
+ findsOneWidget,
+ );
+ await leave(tester);
+ }
+ });
+ });
+}
diff --git a/mobile/test/swarm/swarm_message_link_test.dart b/mobile/test/swarm/swarm_message_link_test.dart
index 93fd084c3..79c0fefb0 100644
--- a/mobile/test/swarm/swarm_message_link_test.dart
+++ b/mobile/test/swarm/swarm_message_link_test.dart
@@ -33,4 +33,46 @@ void main() {
expect(SwarmMessageLink.parse(value), isNull, reason: value);
}
});
+
+ group('allIn finds the links a message previews, as Desktop does', () {
+ List<String> urls(String text) => [
+ for (final link in SwarmMessageLink.allIn(text)) link.url,
+ ];
+
+ test('each link once, in order', () {
+ expect(
+ urls(
+ 'See harness://swarm/t/g1/m1 and harness://swarm/t/g2/m2\n'
+ 'again harness://swarm/t/g1/m1',
+ ),
+ ['harness://swarm/t/g1/m1', 'harness://swarm/t/g2/m2'],
+ );
+ });
+
+ test('none in code spans or fenced code', () {
+ expect(
+ urls(
+ 'Run `open harness://swarm/t/g1/m1`\n'
+ '```\nharness://swarm/t/g2/m2\n```\n'
+ 'but harness://swarm/t/g3/m3',
+ ),
+ ['harness://swarm/t/g3/m3'],
+ );
+ });
+
+ test('at most four', () {
+ expect(
+ urls([for (var i = 0; i < 6; i++) 'harness://swarm/t/g/m$i'].join(' ')),
+ hasLength(SwarmMessageLink.previewLimit),
+ );
+ expect(SwarmMessageLink.previewLimit, 4);
+ });
+
+ test('nothing that is not a message link', () {
+ expect(urls('No links here'), isEmpty);
+ expect(urls('harness://swarm/join/abc#token'), isEmpty);
+ expect(urls('harness://swarm/t/g1'), isEmpty);
+ expect(urls('harness://swarm/t/g1/m1?x=1'), isEmpty);
+ });
+ });
}
diff --git a/mobile/test/swarm/swarm_message_reads_test.dart b/mobile/test/swarm/swarm_message_reads_test.dart
new file mode 100644
index 000000000..4af73dd15
--- /dev/null
+++ b/mobile/test/swarm/swarm_message_reads_test.dart
@@ -0,0 +1,339 @@
+import 'dart:async';
+
+import 'package:clock/clock.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/swarm/swarm_message_link.dart';
+import 'package:harness_mobile/swarm/swarm_message_reads.dart';
+import 'package:harness_mobile/swarm/swarm_reader.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+
+import 'swarm_fixture.dart';
+
+/// One message read by itself, for a quote whose original is not loaded and
+/// for a message link's preview: read once, kept in memory, never in a loop,
+/// and a refusal reads as gone (the desktop's `quoted` and
+/// `AppLinkSwarms.read`).
+void main() {
+ const path = '/api/super-tabs/$tab/conversations/g1/messages?messageId=m1';
+ const link = SwarmMessageLink(
+ tabId: tab,
+ conversationId: 'g1',
+ messageId: 'm1',
+ );
+
+ Map<String, dynamic> row(
+ String id, {
+ String conversationId = 'g1',
+ String text = 'The plan',
+ Map<String, dynamic>? source,
+ }) => {
+ 'id': id,
+ 'conversationId': conversationId,
+ 'text': text,
+ 'sequence': 1,
+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},
+ 'source': ?source,
+ 'createdAt': DateTime.utc(2026, 10, 27).toIso8601String(),
+ };
+
+ late FakeSwarm fake;
+ late SwarmReader reader;
+ late SwarmMessageReads reads;
+ late int told;
+ var now = DateTime.utc(2026, 11, 3, 9);
+
+ setUp(() {
+ now = DateTime.utc(2026, 11, 3, 9);
+ fake = FakeSwarm();
+ reader = SwarmReader(tabId: tab, accountId: me, request: fake.request);
+ reads = SwarmMessageReads(kept: 3);
+ told = 0;
+ reads.addListener(() => told++);
+ });
+
+ tearDown(() {
+ reads.dispose();
+ reader.dispose();
+ });
+
+ /// [body] with the clock at [now], which a test moves.
+ Future<void> at(Future<void> Function() body) =>
+ withClock(Clock(() => now), body);
+
+ /// Lets a read asked for answer.
+ Future<void> answered() => Future<void>.delayed(Duration.zero);
+
+ int asked([String of = path]) => fake.paths.where((p) => p == of).length;
+
+ test('a message is read once, then kept within the minute', () async {
+ fake.routes[path] = (_) => {
+ 'messages': [row('m1')],
+ };
+ await at(() async {
+ expect(reads.read(reader, link).state, SwarmReadState.loading);
+ expect(reads.read(reader, link).state, SwarmReadState.loading);
+ await answered();
+ final read = reads.read(reader, link);
+ expect(read.state, SwarmReadState.found);
+ expect(read.message!.text, 'The plan');
+ now = now.add(const Duration(seconds: 59));
+ expect(reads.read(reader, link).state, SwarmReadState.found);
+ await answered();
+ });
+ expect(asked(), 1, reason: 'asked once while it was read, kept after');
+ expect(told, 1);
+ });
+
+ group('a message found', () {
+ Future<void> found() async {
+ fake.routes[path] = (_) => {
+ 'messages': [row('m1')],
+ };
+ reads.read(reader, link);
+ await answered();
+ }
+
+ test('is asked again a minute later, and shows until answered', () async {
+ await at(() async {
+ await found();
+ now = now.add(const Duration(seconds: 59));
+ reads.read(reader, link);
+ await answered();
+ expect(asked(), 1, reason: 'not within the minute');
+
+ now = now.add(const Duration(seconds: 1));
+ fake.routes[path] = (_) => {
+ 'messages': [row('m1', text: 'Edited')],
+ };
+ expect(reads.read(reader, link).message?.text, 'The plan');
+ await answered();
+ expect(asked(), 2);
+ expect(reads.read(reader, link).message?.text, 'Edited');
+ });
+ });
+
+ test('goes once a later read is refused or finds nothing', () async {
+ final answers = <Map<String, dynamic> Function(dynamic)>[
+ (_) => throw const SuperTabFailure('FORBIDDEN', 'No'),
+ (_) => {'messages': <Object>[]},
+ ];
+ await at(() async {
+ for (final answer in answers) {
+ await found();
+ now = now.add(const Duration(minutes: 1));
+ fake.routes[path] = answer;
+ reads.read(reader, link);
+ await answered();
+ expect(reads.read(reader, link).state, SwarmReadState.gone);
+ now = now.add(const Duration(minutes: 1));
+ }
+ });
+ });
+
+ test('stays when a later read is not answered', () async {
+ await at(() async {
+ await found();
+ now = now.add(const Duration(minutes: 1));
+ fake.routes[path] = (_) => throw const SuperTabFailure('OFFLINE', 'No');
+ reads.read(reader, link);
+ await answered();
+ expect(reads.read(reader, link).message?.text, 'The plan');
+ });
+ });
+ });
+
+ test('none read, or refused, is gone: asked again only a minute later, '
+ 'gone meanwhile', () async {
+ var refuse = false;
+ fake.routes[path] = (_) {
+ if (refuse) throw const SuperTabFailure('FORBIDDEN', 'No access.');
+ return {'messages': <Object>[]};
+ };
+ await at(() async {
+ reads.read(reader, link);
+ await answered();
+ expect(reads.read(reader, link).state, SwarmReadState.gone);
+ now = now.add(const Duration(seconds: 59));
+ expect(reads.read(reader, link).state, SwarmReadState.gone);
+ await answered();
+ expect(asked(), 1);
+
+ refuse = true;
+ now = now.add(const Duration(seconds: 2));
+ expect(
+ reads.read(reader, link).state,
+ SwarmReadState.gone,
+ reason: 'what was answered shows while it is asked again',
+ );
+ await answered();
+ expect(asked(), 2);
+ expect(reads.read(reader, link).state, SwarmReadState.gone);
+ });
+ });
+
+ test('a read that failed is failed, asked again a minute later, and found '
+ 'then', () async {
+ var down = true;
+ fake.routes[path] = (_) {
+ if (down) {
+ throw const SuperTabFailure('UNAVAILABLE', 'Down.', statusCode: 503);
+ }
+ return {
+ 'messages': [row('m1')],
+ };
+ };
+ await at(() async {
+ reads.read(reader, link);
+ await answered();
+ expect(reads.read(reader, link).state, SwarmReadState.failed);
+ for (var i = 0; i < 5; i++) {
+ reads.read(reader, link);
+ await answered();
+ }
+ expect(asked(), 1, reason: 'drawn again and again, asked once');
+
+ down = false;
+ now = now.add(const Duration(minutes: 1));
+ expect(reads.read(reader, link).state, SwarmReadState.failed);
+ await answered();
+ expect(reads.read(reader, link).state, SwarmReadState.found);
+ expect(asked(), 2);
+ });
+ });
+
+ test('anything thrown is failed', () async {
+ fake.routes[path] = (_) => throw StateError('offline');
+ reads.read(reader, link);
+ await answered();
+ expect(reads.read(reader, link).state, SwarmReadState.failed);
+ });
+
+ test('an answer that is not the message asked for is not taken', () async {
+ fake.routes[path] = (_) => {
+ 'messages': [row('m2'), row('m1')],
+ };
+ reads.read(reader, link);
+ await answered();
+ expect(reads.read(reader, link).state, SwarmReadState.failed);
+
+ fake.routes[path] = (_) => {
+ 'messages': [row('m1', conversationId: 'g2')],
+ };
+ final other = SwarmMessageReads();
+ addTearDown(other.dispose);
+ other.read(reader, link);
+ await answered();
+ expect(other.read(reader, link).state, SwarmReadState.failed);
+ });
+
+ test('a waiting notice or an update request is never shown', () async {
+ for (final kind in ['delivery-hold', 'update-request']) {
+ fake.routes[path] = (_) => {
+ 'messages': [
+ row('m1', source: {'kind': kind}),
+ ],
+ };
+ final once = SwarmMessageReads();
+ addTearDown(once.dispose);
+ once.read(reader, link);
+ await answered();
+ expect(once.read(reader, link).state, SwarmReadState.gone, reason: kind);
+ }
+ });
+
+ test('a reader that lost the Swarm, or of another Swarm, reads nothing', () {
+ final elsewhere = SwarmReader(
+ tabId: 'tab-2',
+ accountId: me,
+ request: fake.request,
+ );
+ addTearDown(elsewhere.dispose);
+ expect(reads.read(elsewhere, link).state, SwarmReadState.gone);
+ reader.accessRevoked = true;
+ expect(reads.read(reader, link).state, SwarmReadState.gone);
+ expect(fake.paths, isEmpty);
+ });
+
+ test('what a Swarm the reader lost had read is not kept', () async {
+ fake.routes[path] = (_) => {
+ 'messages': [row('m1')],
+ };
+ reads.read(reader, link);
+ await answered();
+ expect(reads.read(reader, link).state, SwarmReadState.found);
+
+ reader.accessRevoked = true;
+ expect(reads.read(reader, link).state, SwarmReadState.gone);
+ reader.accessRevoked = false;
+ expect(reads.read(reader, link).state, SwarmReadState.loading);
+ await answered();
+ });
+
+ test('access read again from nothing reads the message again', () async {
+ fake.routes[path] = (_) => {
+ 'messages': [row('m1')],
+ };
+ reads.read(reader, link);
+ await answered();
+ expect(reads.read(reader, link).state, SwarmReadState.found);
+
+ reader.generation++;
+ expect(reads.read(reader, link).state, SwarmReadState.loading);
+ await answered();
+ expect(reads.read(reader, link).state, SwarmReadState.found);
+ expect(asked(), 2);
+ });
+
+ test(
+ 'an answer to a read asked before access was read again is dropped',
+ () async {
+ final answer = Completer<Object?>();
+ fake.routes[path] = (_) => answer.future;
+ reads.read(reader, link);
+ await answered();
+ reader.generation++;
+ answer.complete({
+ 'messages': [row('m1')],
+ });
+ await answered();
+ expect(told, 0);
+ },
+ );
+
+ test('at most [kept] are held: the one asked for longest ago goes first', () async {
+ for (final id in ['m1', 'm2', 'm3', 'm4']) {
+ fake.routes['/api/super-tabs/$tab/conversations/g1/messages?messageId=$id'] =
+ (_) => {
+ 'messages': [row(id)],
+ };
+ }
+ SwarmMessageLink to(String id) =>
+ SwarmMessageLink(tabId: tab, conversationId: 'g1', messageId: id);
+ for (final id in ['m1', 'm2', 'm3']) {
+ reads.read(reader, to(id));
+ }
+ await answered();
+ // m1 asked for again: m2 is now the oldest.
+ expect(reads.read(reader, to('m1')).state, SwarmReadState.found);
+ reads.read(reader, to('m4'));
+ await answered();
+ expect(reads.read(reader, to('m1')).state, SwarmReadState.found);
+ expect(reads.read(reader, to('m2')).state, SwarmReadState.loading);
+ await answered();
+ });
+
+ test('an answer after the session ends tells no one', () async {
+ final answer = Completer<Object?>();
+ fake.routes[path] = (_) => answer.future;
+ final ended = SwarmMessageReads()..addListener(() => told++);
+ ended.read(reader, link);
+ await answered();
+ ended.dispose();
+ answer.complete({
+ 'messages': [row('m1')],
+ });
+ await answered();
+ expect(told, 0);
+ expect(ended.read(reader, link).state, SwarmReadState.gone);
+ });
+}
diff --git a/scripts/ui-style-allowlist/desktop.json b/scripts/ui-style-allowlist/desktop.json
index e5c86f4e5..9962a4c63 100644
--- a/scripts/ui-style-allowlist/desktop.json
+++ b/scripts/ui-style-allowlist/desktop.json
@@ -45,7 +45,7 @@
"font-size": 1
},
"desktop/lib/super_tabs/project_sidebar.dart": {
- "edge-insets": 8
+ "edge-insets": 5
},
"desktop/lib/super_tabs/pull_requests.dart": {
"edge-insets": 12,