The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-05 i1615: #3126 #3103 #3132 #3124 #3115 #3097 (#3139)
0xken15eaa970429f87
diff --git a/backend/integration/superTabProposals.test.ts b/backend/integration/superTabProposals.test.tsindex 1d59b56fc..690044f75 100644--- a/backend/integration/superTabProposals.test.ts+++ b/backend/integration/superTabProposals.test.ts@@ -65,9 +65,9 @@ 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) },+ { messageId: 'open', title: 'Sync edits', personId: 'peer', priority: 'P2', at: T0 + 1000 },+ { messageId: 'old', title: 'Old proposal', personId: 'peer', priority: 'P2', at: T0 + 9000 },+ { messageId: 'newest', title: 'Newest', personId: 'peer', priority: 'P2', at: expect.any(Number) },])})diff --git a/backend/src/superTabs/buddies.test.ts b/backend/src/superTabs/buddies.test.tsindex d2b69ec77..66a79247a 100644--- a/backend/src/superTabs/buddies.test.ts+++ b/backend/src/superTabs/buddies.test.ts@@ -750,6 +750,20 @@ describe('a Buddy\'s proposal to the PM', () => {expect(open('Desktop keeps drafts offline.').brief).toBe('Desktop keeps drafts offline.')})+ it('gives a task opened from it the proposal\'s priority on the one P0-P3 scale, unless the PM gives one (task #3117)', () => {+ const { f, propose } = asked()+ const root = propose().messages[0]!+ const context = { proposal: { id: root.id, conversationId: f.app.conversationId, author: root.author, source: root.source as Record<string, unknown> } }+ const open = (fields: Record<string, unknown> = {}) => f.run({ type: 'conversation.create', projectId: f.app.projectId, title: 'Offline drafts',+ brief: '', checks: [], proposalMessageId: root.id, ...fields } as Command, agentActor(f.pm), context).result+ // Its Buddy said high: a P1, with no warning that none was given.+ const opened = open()+ expect(opened).toMatchObject({ priority: 'P1' })+ expect(opened.warnings ?? []).not.toContainEqual(expect.stringContaining('No priority given'))+ expect(group(f, opened.conversationId as string).priority).toBe('P1')+ expect(group(f, open({ priority: 'P0' }).conversationId as string).priority).toBe('P0')+ })+it('counts as shown only the Buddy\'s own lines in the ask\'s lane, since its owner\'s previous message', () => {const me = { kind: 'agent' as const, id: 'buddy' }, owner = { kind: 'person' as const, id: 'peer' }const row = (id: string, author: { kind: 'person' | 'agent'; id: string }, text: string, extra: Record<string, unknown> = {}) =>diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex b7392054a..374e99a22 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -5815,6 +5815,106 @@ describe('the Next-up queue (work.queue)', () => {})})+// A task's priority, P0-P3 (task #3117): a hotfix for a broken release must not wait behind ordinary work.+describe('a task\'s priority (conversation.create and work.priority)', () => {+ function prioritized() {+ const f = routed()+ const task = (id: string) => f.state.conversations.find(g => g.id === id)!+ const create = (fields: Record<string, unknown> = {}, actor: Actor = f.leadActor) =>+ f.run(commandSchema.parse({ type: 'conversation.create', title: 'Sign-in broken', brief: 'Fix it.', checks: [], ...fields }), actor)+ const set = (conversationId: string, priority: string) => commandSchema.parse({ type: 'work.priority', conversationId, priority })+ return { f, task, create, set }+ }++ it('takes the PM\'s priority when it creates a task', () => {+ const { task, create } = prioritized()+ const created = create({ priority: 'P0' })+ expect(created.result).toMatchObject({ priority: 'P0' })+ expect(created.result.warnings ?? []).not.toContainEqual(expect.stringContaining('No priority given'))+ expect(task(created.result.conversationId as string).priority).toBe('P0')+ expect(groupView(task(created.result.conversationId as string), new Set())).toMatchObject({ priority: 'P0' })+ })++ it('gives a task created without one P2, and the reply says so', () => {+ const { task, create } = prioritized()+ const created = create()+ expect(task(created.result.conversationId as string).priority).toBe('P2')+ expect(created.result).toMatchObject({ priority: 'P2',+ warnings: expect.arrayContaining(['No priority given: this task is P2. Set P0-P3 with work.priority.']) })+ })++ it('gives no priority to a step, and refuses one there', () => {+ const { f, task, create } = prioritized()+ const parent = create().result.conversationId as string+ const step = create({ title: 'Review', reviewOf: parent, step: 'Review' }).result.conversationId as string+ expect(task(step)).not.toHaveProperty('priority')+ expect(() => create({ title: 'Test', reviewOf: parent, step: 'Test', priority: 'P1' }))+ .toThrow(expect.objectContaining({ code: 'PRIORITY_TASK_ONLY', status: 400 }))+ expect(f.state.conversations.filter(c => c.step === 'Test')).toEqual([])+ })++ it('lets only the PM or a person create a P0, while any agent may open a P1-P3 task', () => {+ const { f, task, create } = prioritized()+ expect(() => create({ priority: 'P0' }, f.workerActor)).toThrow(expect.objectContaining({ code: 'PRIORITY_P0', status: 403 }))+ expect(task(create({ priority: 'P1' }, f.workerActor).result.conversationId as string).priority).toBe('P1')+ expect(task(create({ priority: 'P0' }, owner).result.conversationId as string).priority).toBe('P0')+ })++ it('changes it for a person or the PM, and records each change in the task as a line', () => {+ const { f, task, create, set } = prioritized()+ const id = create().result.conversationId as string+ const changed = f.run(set(id, 'P0'), owner)+ expect(task(id).priority).toBe('P0')+ expect(changed.messages).toEqual([expect.objectContaining({ conversationId: id, recipients: [], source: { kind: 'system' },+ text: 'owner changed the priority to P0, hotfix: something shipped is broken (was P2).' })])+ const byPm = f.run(set(id, 'P1'), f.leadActor)+ expect(task(id).priority).toBe('P1')+ // The PM by the name the Swarm shows for it.+ const pm = f.state.agents.find(a => a.id === f.lead)!+ expect(byPm.messages[0]!.text).toBe(`${pm.displayName ?? pm.name} changed the priority to P1, needed by users soon (was P0).`)+ })++ it('reads a task from before priorities as P2 when it changes', () => {+ const { f, task, create, set } = prioritized()+ const id = create().result.conversationId as string+ delete task(id).priority+ expect(f.run(set(id, 'P3'), owner).messages[0]!.text).toBe('owner changed the priority to P3, tools, docs or process (was P2).')+ })++ it('reads a task from before priorities by its title\'s urgent or high marker, as every client shows it', () => {+ const { f, task, create, set } = prioritized()+ const urgent = create({ title: 'Sign-in broken (urgent)' }).result.conversationId as string+ const high = create({ title: 'Faster sync (Ken, high)' }).result.conversationId as string+ for (const id of [urgent, high]) delete task(id).priority+ expect(f.run(set(urgent, 'P2'), owner).messages[0]!.text).toBe('owner changed the priority to P2, planned goal (was P0).')+ expect(f.run(set(high, 'P2'), owner).messages[0]!.text).toBe('owner changed the priority to P2, planned goal (was P1).')+ })++ it('posts nothing when the priority is already that one', () => {+ const { f, task, create, set } = prioritized()+ const id = create({ priority: 'P1' }).result.conversationId as string+ expect(f.run(set(id, 'P1'), owner).messages).toEqual([])+ expect(task(id).priority).toBe('P1')+ })++ it('is refused to any other agent of the project, and on what is not an open task', () => {+ const { f, create, set } = prioritized()+ const id = create().result.conversationId as string+ const step = create({ title: 'Review', reviewOf: id, step: 'Review' }).result.conversationId as string+ const before = structuredClone(f.state)+ expect(() => f.run(set(id, 'P0'), f.workerActor)).toThrow(expect.objectContaining({ code: 'COORDINATOR_REQUIRED' }))+ for (const other of ['lead', step]) expect(() => f.run(set(other, 'P0'), owner), other).toThrow(expect.objectContaining({ code: 'PRIORITY_TASK_ONLY', status: 400 }))+ expect(f.state).toEqual(before)+ })++ it('takes only P0 to P3', () => {+ const parse = (priority: unknown) => commandSchema.safeParse({ type: 'work.priority', conversationId: 'task', priority }).success+ for (const priority of ['P0', 'P1', 'P2', 'P3']) expect(parse(priority)).toBe(true)+ for (const priority of ['P4', 'p0', 'high', 0, null, undefined]) expect(parse(priority), String(priority)).toBe(false)+ expect(commandSchema.safeParse({ type: 'conversation.create', title: 'T', brief: 'B', checks: [], priority: 'urgent' }).success).toBe(false)+ })+})+// 11-04 13:57 VN on the Mac Studio: the CLI's idle cleanup closed Tern, its machine's next reading listed the session// stopped, and six seconds after the close the PM assigned Tern a task, which was lost at once (task #2744).describe('assigning an agent whose session was closed', () => {diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 104ddcd00..82d880905 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -5,7 +5,7 @@ import { movableEntry } from './computerMoves.js'import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'import { addedAgentName, renameAgentTo } from './agentRename.js'import { keepUsernames, setUsername, swarmUsernames, usernameOf } from './usernames.js'-import { agentWrittenNameOf, setName } from './personNames.js'+import { agentWrittenNameOf, setName, shownNameOf } from './personNames.js'import { z } from 'zod'import { tokensByModelSchema } from './costs/tokens.js'import {@@ -60,6 +60,7 @@ import { launchRefusedLine, leadArrived, LEAD_CLAIM_MS, leadEffort, leadJoined,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 { BUILT_IN_HEADING } from './pmSchedule.js'+import { DEFAULT_PRIORITY, PRIORITY_DEFAULTED, TASK_PRIORITIES, priorityLine, proposalPriority, titlePriority, type TaskPriority } from './taskPriority.js'import { placeAfter, queueSiblings } from './taskQueue.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)@@ -239,6 +240,8 @@ export const commandSchema = z.discriminatedUnion('type', [// `audience`: a private conversation that only these people and the project's Lead read (projects.ts canReadGroup).z.object({ type: z.literal('work.teamWritten'), conversationId: id }).strict(),z.object({ type: z.literal('conversation.create'), projectId: id.optional(), title, brief: z.string().trim().max(8000).optional(), task: task.optional(), reviewOf: id.optional(),+ // How urgent the task is (taskPriority.ts); without one it is P2, and the reply says so.+ priority: z.enum(TASK_PRIORITIES).optional(),// A step of the task `reviewOf` names (task steps design): its name as the instructions give it, free text in any language.// No line break or control character: the name is printed in agents' terminals (final review, minor 10).step: z.string().trim().min(1).max(40).regex(/^[^\u0000-\u001f\u007f]+$/, 'A step name is one line of text.').optional(), checks: z.array(check).max(40),@@ -251,6 +254,8 @@ export const commandSchema = z.discriminatedUnion('type', [.refine(c => !c.task || renderWorkTask(c.task).length <= 8000, 'Keep the rendered task within 8,000 characters.'),z.object({ type: z.literal('conversation.rename'), conversationId: id, title }).strict(),z.object({ type: z.literal('conversation.archive'), conversationId: id, archived: z.boolean() }).strict(),+ // A task's priority, changed by the PM or a person (taskPriority.ts); each change writes a line into the task.+ z.object({ type: z.literal('work.priority'), conversationId: id, priority: z.enum(TASK_PRIORITIES) }).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.@@ -2205,6 +2210,13 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (command.audience) pmChatClosed()const leadId = conversation(state, project.leadConversationId).leadIdif (command.step && !command.reviewOf) fail('INVALID_REQUEST', 'A step belongs to a task: name the task with reviewOf.', 400)+ // A step and a private chat are no tasks of their own, so they carry no priority (taskPriority.ts).+ const prioritized = !command.step && !command.audience+ if (command.priority && !prioritized) fail('PRIORITY_TASK_ONLY', 'Only a task has a priority: leave it out of a step or a private chat.', 400)+ // A hotfix jumps every queue, so of the agents only the PM marks one (River, task #3117).+ if (command.priority === 'P0' && actor.kind === 'agent' && ledProject(state, actor.agentId)?.id !== project.id) {+ fail('PRIORITY_P0', 'Only the PM or a person sets P0. Give this task P1, P2 or P3.', 403)+ }if (command.reviewOf) {// A task links to another task of its own project, a linked one included, and to nothing else: the project chat, a// Buddy chat, a private chat, the Leads conversation and other projects' tasks read as missing, archived or not, so the@@ -2242,6 +2254,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// A Team agent's own task is Team-written from its first line, and a step keeps its task's mark (teamWritten.ts, audit H2)....((command.reviewOf ? teamWrittenTask(state, conversation(state, command.reviewOf)) : creator.some(id => onTeamAccount(state, agent(state, id)))) ? { teamWritten: true as const } : {}),...(command.step ? { step: command.step } : {}),+ ...(prioritized ? { priority: command.priority ?? (proposal ? proposalPriority(proposalNamed(context.proposal)?.source?.priority) : DEFAULT_PRIORITY) } : {}),assignment: null, lastMessageSequence: 0,checks: storedChecks(command.checks, operationId),})@@ -2256,6 +2269,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,result.requesterUnknown = trueresult.warnings = [REQUESTER_UNKNOWN]}+ if (prioritized) {+ result.priority = state.conversations.at(-1)!.priority+ if (!command.priority && !proposal) result.warnings = [...result.warnings as string[] ?? [], PRIORITY_DEFAULTED]+ }if (brief) {message(operationId, brief, [], null, SYSTEM_ROW)bindTaskCard(state.conversations.at(-1)!, effects.messages.at(-1)!)@@ -2314,6 +2331,23 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,else if (command.notBefore !== undefined) task.notBefore = command.notBeforebreak}+ case 'work.priority': {+ chatOnly(command.conversationId)+ coordinatorOrPerson(state, actor, command.conversationId)+ const task = open(state, command.conversationId)+ const project = groupProject(state, task)+ if (task.id === project.leadConversationId || task.kind || task.audience || task.step) {+ fail('PRIORITY_TASK_ONLY', 'Only a task has a priority: name a task, not a chat or a step.', 400)+ }+ // A task from before priorities reads as its title marks it, as every client shows it.+ const previous: TaskPriority = task.priority ?? titlePriority(task.title) ?? DEFAULT_PRIORITY+ task.priority = command.priority+ if (previous === command.priority) break+ const name = actor.kind === 'person' ? shownNameOf(state, actor.userId) ?? 'Someone'+ : agentDisplayName(state.agents, actor.agentId) ?? state.agents.find(a => a.id === actor.agentId)?.name ?? 'An agent'+ message(task.id, priorityLine(name, command.priority, previous), [], null, SYSTEM_ROW)+ break+ }case 'conversation.merged': {chatOnly(command.conversationId)projectChatWork(command.conversationId)diff --git a/backend/src/superTabs/leaderboard/record.test.ts b/backend/src/superTabs/leaderboard/record.test.tsindex c55c13d40..a90135503 100644--- a/backend/src/superTabs/leaderboard/record.test.ts+++ b/backend/src/superTabs/leaderboard/record.test.ts@@ -78,8 +78,9 @@ describe('who asked for a group', () => {it('tells a Lead that opens a build group for nobody to name who asked; never for a named requester, a person or a review', () => {const f = fixture(), lead = f.add('lead', 'lead', true)f.invitePeer()+ // Each gives a priority, so the only warning left is who asked (a task without one is told it is P2: task #3117).const open = (actor: Actor, extra: Record<string, unknown> = {}) =>- f.run(commandSchema.parse({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits.', checks, ...extra }), actor).result+ f.run(commandSchema.parse({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits.', checks, priority: 'P2', ...extra }), actor).resultconst unnamed = open(f.asAgent(lead))expect(unnamed).toMatchObject({ requesterUnknown: true, warnings: [expect.stringContaining('Name the person who asked')] })for (const result of [open(f.asAgent(lead), { requesterId: 'peer' }), open(owner),diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 16dab12b3..b961b4ef9 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -408,6 +408,9 @@ export interface Conversation {queueRank?: number/** The day (YYYY-MM-DD) its work should not start before, a promise the PM marks with work.queue. */notBefore?: string+ /** How urgent its task is (taskPriority.ts), set by conversation.create and work.priority. Absent on a step, a chat and a task+ * from before priorities, which reads as P2. */+ priority?: import('./taskPriority.js').TaskPriority}/** 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.tsindex 9c3aaa8c6..02a9b68b8 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, heardAt: 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: '' }, queueRank: 1.5, notBefore: '2026-12-04',+ stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' }, queueRank: 1.5, notBefore: '2026-12-04', priority: 'P0',}describe('the light conversation projection (parts/light.ts)', () => {diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex e9f36916d..3b69a2873 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', 'heardAt', 'pullRequestUrls', 'pullRequestEvents', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp', 'queueRank', 'notBefore',+ unread: ['number', 'brief', 'reviewOf', 'teamWritten', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'lastPersonSequence', 'heardAt', 'pullRequestUrls', 'pullRequestEvents', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp', 'queueRank', 'notBefore', 'priority','assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf', 'assignment.reviewFoundAt', 'assignment.changesRequestedAt', 'assignment.toldEngineerAt','assignment.handoffs', 'assignment.verdicts'],} as constdiff --git a/backend/src/superTabs/parts/touches.test.ts b/backend/src/superTabs/parts/touches.test.tsindex 542eb72dc..a5ceb562a 100644--- a/backend/src/superTabs/parts/touches.test.ts+++ b/backend/src/superTabs/parts/touches.test.ts@@ -106,6 +106,13 @@ describe('the parts a command touches (design section 1.2, column T)', () => {expect(has(named.touches, 'group', 'lead')).toBe(true)})+ it('makes a priority change meet a change of who is PM on the project\'s chat (task #3117)', () => {+ const f = swarm()+ const id = f.run({ type: 'conversation.create', title: 'R', brief: 'Do it', checks: [] }, f.agentActor(f.lead)).effects.result.conversationId as string+ const changed = f.run({ type: 'work.priority', conversationId: id, priority: 'P0' }, f.agentActor(f.lead))+ expect(has(changed.touches, 'group', 'lead')).toBe(true)+ })+it('makes an answer to waiting work meet a change to whom it waits on', () => {const f = swarm(), a = f.group('A')f.run({ type: 'conversation.requester', conversationId: a.id, personId: 'owner' })diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.tsindex d42ba8c87..ccc48f6cd 100644--- a/backend/src/superTabs/parts/touches.ts+++ b/backend/src/superTabs/parts/touches.ts@@ -115,6 +115,10 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabStatecase 'conversation.merged':leadCheck(projectOfGroup(command.conversationId)?.id)break+ // Whether an agent may change a priority is whether it is still its project's PM (commands.ts coordinatorOrPerson).+ case 'work.priority':+ leadCheck(projectOfGroup(command.conversationId)?.id)+ breakcase 'conversation.requester':leadCheck(projectOfGroup(command.conversationId)?.id)member(command.personId ?? undefined)diff --git a/backend/src/superTabs/proposals.test.ts b/backend/src/superTabs/proposals.test.tsindex 0f07ad926..2fe1a4677 100644--- a/backend/src/superTabs/proposals.test.ts+++ b/backend/src/superTabs/proposals.test.ts@@ -79,12 +79,20 @@ describe('a project\'s open proposals', () => {// 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, NOW)).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 },+ { messageId: 'old', title: 'Old proposal', personId: 'peer', priority: 'P2', at: 5 },+ { messageId: 'open', title: 'Sync edits', personId: 'peer', priority: 'P2', at: 10 },+ { messageId: 'personal', title: 'Offline drafts', personId: 'peer', priority: 'P2', at: 50 },])})+ it('carries each proposal\'s priority on the one P0-P3 scale: high is P1, low P3, anything else P2 (task #3117)', async () => {+ const s = swarm()+ const said = (id: string, at: number, priority?: string): ProposalRoot => ({ ...root(id, at), source: { ...root(id, at).source, ...priority ? { priority } : {} } })+ const { reads } = chatReads([said('high', 10, 'high'), said('low', 20, 'low'), said('normal', 30, 'normal'), said('none', 40)], [])+ expect((await openProposals(s.state, s.chat(), reads, NOW)).map(p => [p.messageId, p.priority]))+ .toEqual([['high', 'P1'], ['low', 'P3'], ['normal', 'P2'], ['none', 'P2']])+ })+it('reads a proposal as its owner\'s words in full, and one from before task #2926 without its "Let\'s build: "', async () => {const s = swarm()const words = 'Jumping a chat back a week (Jump to, Last week) freezes the app and then lags for a minute on Huy\'s Mac, every time'@@ -92,8 +100,8 @@ describe('a project\'s open proposals', () => {const owned: ProposalRoot = { ...root('owned', 20), text: words }const { reads } = chatReads([root('old', 10, 'Offline drafts'), owned], [...rows(root('old', 10, 'Offline drafts'), { author: agent('buddy') })])expect(await openProposals(s.state, s.chat(), reads, NOW)).toEqual([- { messageId: 'old', title: 'Offline drafts', personId: 'peer', at: 10 },- { messageId: 'owned', title: words, personId: 'peer', at: 20 },+ { messageId: 'old', title: 'Offline drafts', personId: 'peer', priority: 'P2', at: 10 },+ { messageId: 'owned', title: words, personId: 'peer', priority: 'P2', at: 20 },])})@@ -139,7 +147,7 @@ describe('a project\'s open proposals', () => {const [fresh, answered, onIt, gone] = [root('fresh', 60, 'New idea'), root('answered', 20), root('on-it', 30), root('gone', 40)]const chat = chatReads([fresh, answered, onIt], [...rows(fresh, { author: agent('buddy') }), ...rows(answered, { author: agent('buddy') }, { author: agent(s.pm) }),...rows(onIt, { author: agent('buddy') }, { author: person('owner'), ask: 'on-it' })], { seededAt: NOW - SEED_SETTLE_MS - 1, open: [fresh, answered, onIt, gone] })- expect(await openProposals(s.state, s.chat(), chat.reads, NOW)).toEqual([{ messageId: 'fresh', title: 'New idea', personId: 'peer', at: 60 }])+ expect(await openProposals(s.state, s.chat(), chat.reads, NOW)).toEqual([{ messageId: 'fresh', title: 'New idea', personId: 'peer', priority: 'P2', at: 60 }])expect(chat.forgotten.sort()).toEqual(['answered', 'gone', 'on-it'])expect([...chat.set.keys()]).toEqual(['fresh'])expect(chat.counts.scan).toBe(0)diff --git a/backend/src/superTabs/proposals.ts b/backend/src/superTabs/proposals.tsindex ea430b123..64b76b308 100644--- a/backend/src/superTabs/proposals.ts+++ b/backend/src/superTabs/proposals.ts@@ -13,6 +13,7 @@ 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 { proposalPriority, type TaskPriority } from './taskPriority.js'import { threadSummaries } from './threads.js'type Transaction = Prisma.TransactionClient@@ -24,7 +25,9 @@ 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 }+export interface OpenProposal { messageId: string; title: string; personId?: string+ /** Its Buddy's low, normal or high on the tasks' one scale (taskPriority.ts). */+ priority: TaskPriority; at: number }/** How long after a chat's seed its reads scan it again: a server still on the release before writes a proposal with no row* in the open set, and a rolling release replaces them within minutes. */export const SEED_SETTLE_MS = 30 * 60_000@@ -110,7 +113,7 @@ async function scanned(state: SuperTabState, chat: Conversation, reads: Proposalfunction shown(root: ProposalRoot): OpenProposal {const personId = root.source.personIdreturn { 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() }+ ...typeof personId === 'string' ? { personId } : {}, priority: proposalPriority(root.source.priority), at: root.createdAt.getTime() }}const date = (value: unknown): Date => new Date((value as { $date?: string } | null)?.$date ?? value as string)diff --git a/backend/src/superTabs/taskPriority.test.ts b/backend/src/superTabs/taskPriority.test.tsnew file mode 100644index 000000000..0a18306d1--- /dev/null+++ b/backend/src/superTabs/taskPriority.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest'+import { PRIORITY_MEANING, TASK_PRIORITIES, priorityLine, proposalPriority, titlePriority } from './taskPriority.js'++// A task's priority, P0-P3 (task #3117): one scale for the PM, people and Buddies' proposals.+describe('task priorities', () => {+ it('are P0 to P3, each with its meaning in plain words', () => {+ expect(TASK_PRIORITIES).toEqual(['P0', 'P1', 'P2', 'P3'])+ expect(PRIORITY_MEANING).toEqual({+ P0: 'Hotfix: something shipped is broken',+ P1: 'Needed by users soon',+ P2: 'Planned goal',+ P3: 'Tools, docs or process',+ })+ })++ it('maps a Buddy proposal\'s high, normal and low onto P1, P2 and P3, and never onto P0', () => {+ expect(proposalPriority('high')).toBe('P1')+ expect(proposalPriority('normal')).toBe('P2')+ expect(proposalPriority('low')).toBe('P3')+ for (const other of [undefined, null, '', 'urgent', 'P0', 3]) expect(proposalPriority(other), String(other)).toBe('P2')+ })++ it('reads a title\'s old urgent or high marker as P0 or P1, as the apps read it', () => {+ expect(titlePriority('URGENT: Sign-in broken')).toBe('P0')+ expect(titlePriority('Sign-in broken (urgent)')).toBe('P0')+ expect(titlePriority('Faster sync (Ken, high)')).toBe('P1')+ expect(titlePriority('Faster sync (high priority)')).toBe('P1')+ for (const plain of ['Faster sync', 'URGENT', '(urgent)', 'Fix the (urgent) path']) expect(titlePriority(plain), plain).toBeNull()+ })++ it('says a change in one line, naming who changed it and what it was', () => {+ expect(priorityLine('Ken', 'P0', 'P2')).toBe('Ken changed the priority to P0, hotfix: something shipped is broken (was P2).')+ expect(priorityLine('River', 'P3', 'P1')).toBe('River changed the priority to P3, tools, docs or process (was P1).')+ })+})diff --git a/backend/src/superTabs/taskPriority.ts b/backend/src/superTabs/taskPriority.tsnew file mode 100644index 000000000..0ef1a8f65--- /dev/null+++ b/backend/src/superTabs/taskPriority.ts@@ -0,0 +1,42 @@+/**+ * A task's priority (task #3117): one scale, P0 to P3, for the PM, people and Buddies' proposals, so a hotfix for a broken+ * release no longer waits behind ordinary work until someone says "urgent". A task created without one is P2.+ */+export const TASK_PRIORITIES = ['P0', 'P1', 'P2', 'P3'] as const+export type TaskPriority = typeof TASK_PRIORITIES[number]++/** What each priority means, as people read it. */+export const PRIORITY_MEANING: Record<TaskPriority, string> = {+ P0: 'Hotfix: something shipped is broken',+ P1: 'Needed by users soon',+ P2: 'Planned goal',+ P3: 'Tools, docs or process',+}++export const DEFAULT_PRIORITY: TaskPriority = 'P2'+export const PRIORITY_DEFAULTED = 'No priority given: this task is P2. Set P0-P3 with work.priority.'++/** A Buddy proposal's low, normal or high on the same scale. A proposal never reaches P0: only the PM or a person sets that. */+export function proposalPriority(value: unknown): TaskPriority {+ return value === 'high' ? 'P1' : value === 'low' ? 'P3' : 'P2'+}++const LEADING = /^\s*URGENT\b\s*:?\s*/i+const TRAILING = /\s*\((?:[^()]*,\s*)?(urgent|high)(?:\s+priority)?\)\s*$/i++/** A task from before priorities by its title, as every client reads it (Desktop backlog.dart superTabTitlePriority): a+ * leading URGENT or a closing "(urgent)" is P0, a closing "(high)" or "(Name, high)" P1. A marker with no title beside it+ * marks nothing. */+export function titlePriority(title: string): TaskPriority | null {+ const leading = LEADING.exec(title)+ if (leading && title.length > leading[0].length) return 'P0'+ const trailing = TRAILING.exec(title)+ if (trailing && trailing.index > 0) return trailing[1]!.toLowerCase() === 'urgent' ? 'P0' : 'P1'+ return null+}++/** The line a change writes into its task: who changed it, to what and from what. */+export function priorityLine(actorName: string, next: TaskPriority, previous: TaskPriority): string {+ const meaning = PRIORITY_MEANING[next]+ return `${actorName} changed the priority to ${next}, ${meaning[0]!.toLowerCase()}${meaning.slice(1)} (was ${previous}).`+}diff --git a/cli/src/lib/swarmTools.spec.ts b/cli/src/lib/swarmTools.spec.tsindex c30916077..de19cc1a1 100644--- a/cli/src/lib/swarmTools.spec.ts+++ b/cli/src/lib/swarmTools.spec.ts@@ -91,6 +91,12 @@ describe('SWARM_TOOLS_SKILL', () => {expect(SWARM_TOOLS_SKILL).toContain('- \`task GROUP\`:')expect(SWARM_TOOLS_SKILL).toContain('messages GROUP --thread ROOT')})+ // Task #3117: the tools say how a task gets its priority and who changes it, as the help does.+ it('says how a task gets its priority, what P0 to P3 mean, and who changes it', () => {+ expect(SWARM_TOOLS_SKILL).toContain('- `mine`: what you work on, one line per task, P0 first: its number, priority, title,')+ expect(SWARM_TOOLS_SKILL).toContain('`"priority":"P0|P1|P2|P3"` (P0 hotfix: something shipped is broken, loses data, or stops people\'s or agents\' work; P1 needed by users soon; P2 planned goal; P3 tools, docs or process; without one the task is P2)')+ expect(SWARM_TOOLS_SKILL).toContain('- `{"type":"work.priority","conversationId":"GROUP","priority":"P0"}` changes a task\'s priority. Only a person or the project\'s coordinator may send it, and only they set P0.\n')+ })// River, 11-04 (task #2926): proposals answered before threads, or built without the task's link, closed by hand.it('says how to close a proposal with a reason, posting nothing', () => {expect(SWARM_TOOLS_SKILL).toContain('`{"type":"proposal.close","projectId":"PROJECT","messageId":"PROPOSAL","reason":"built in #N, declined or duplicate"}`')diff --git a/cli/src/lib/swarmTools.ts b/cli/src/lib/swarmTools.tsindex a51eca621..9b8b06635 100644--- a/cli/src/lib/swarmTools.ts+++ b/cli/src/lib/swarmTools.ts@@ -15,7 +15,7 @@ Every command starts \`harness super-tab --tab TAB\` (your tab id is in your lau## Read- \`status [--archived [PAGE]]\`: the shared roster and work: people, projects, agents (id, name, machine, state), conversations, tasks. Agent ids for \`--to\` come from here.-- \`mine\`: what you work on, one line per task: its number, title, conversation id, status, when it last changed, its last result and pull requests, and the open tasks linked to it. A project's coordinator gets every open task of its project instead.+- \`mine\`: what you work on, one line per task, P0 first: its number, priority, title, conversation id, status, when it last changed, its last result and pull requests, and the open tasks linked to it. A project's coordinator gets every open task of its project instead.- \`task GROUP\`: one task: its project, status, assignee, pull requests, brief, checks (passed, by whom, or failed with the evidence's first line), attempts newest first, and linked tasks. It reads a finished task too.- \`messages GROUP [--before SEQUENCE MESSAGE_ID]\`: recent messages of a conversation, thread replies included; each names the thread (the root message) it answers in. \`--before\` pages back from the cursor the last page named. \`messages GROUP --thread ROOT\` reads one thread whole: its root and every reply.- \`message GROUP MESSAGE_ID\`: one exact message, such as an earlier question or result a reply refers to.@@ -57,11 +57,12 @@ JSONPut OPERATION_ID before the JSON, on the same command line. A refusal says what to fix; change something before you resend.Task and group commands:-- \`{"type":"conversation.create","title":"Outcome","task":{"goal":"...","changes":"...","constraints":"...","owns":["paths or code areas"]},"checks":[{"description":"observable acceptance evidence","independent":false}]}\` opens a group. Optional: \`"reviewOf":"GROUP"\` (a group that reviews another), \`"requesterId":"PERSON"\` (who asked; records only that they asked), \`"requires":{"machines":["MACHINE"],"devices":["/dev/..."]}\` inside \`task\` (the route notes it; a start asks its machine to check the devices). Task sections take up to 8,000 characters; \`owns\` up to 40 paths; checks may be empty. A task is taken as written: one with every part (goal, changes, constraints, owns) goes as the task; one without them all goes as a brief of the parts you gave.+- \`{"type":"conversation.create","title":"Outcome","task":{"goal":"...","changes":"...","constraints":"...","owns":["paths or code areas"]},"checks":[{"description":"observable acceptance evidence","independent":false}]}\` opens a group. Optional: \`"priority":"P0|P1|P2|P3"\` (P0 hotfix: something shipped is broken, loses data, or stops people's or agents' work; P1 needed by users soon; P2 planned goal; P3 tools, docs or process; without one the task is P2), \`"reviewOf":"GROUP"\` (a group that reviews another), \`"requesterId":"PERSON"\` (who asked; records only that they asked), \`"requires":{"machines":["MACHINE"],"devices":["/dev/..."]}\` inside \`task\` (the route notes it; a start asks its machine to check the devices). Task sections take up to 8,000 characters; \`owns\` up to 40 paths; checks may be empty. A task is taken as written: one with every part (goal, changes, constraints, owns) goes as the task; one without them all goes as a brief of the parts you gave.- \`{"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.priority","conversationId":"GROUP","priority":"P0"}\` changes a task's priority. Only a person or the project's coordinator may send it, and only they set P0.- \`{"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/cli/src/superTabs/agentContext.spec.ts b/cli/src/superTabs/agentContext.spec.tsindex 27991d200..6386a88c9 100644--- a/cli/src/superTabs/agentContext.spec.ts+++ b/cli/src/superTabs/agentContext.spec.ts@@ -30,7 +30,7 @@ describe('mine', () => {assignment: { id: 'a', agentId: 'dev1', status: 'working', result: 'Tests pass on main\nmore detail' },pullRequestUrls: ['https://github.com/o/r/pull/7'] })])expect(mineText(state, changed({ g12: NOW - 5 * MIN }), 'dev1', NOW)).toBe(- '#12 Fix login (conversation g12) — working, updated 5 min ago; last result: Tests pass on main; PR https://github.com/o/r/pull/7')+ '#12 P2 Fix login (conversation g12) — working, updated 5 min ago; last result: Tests pass on main; PR https://github.com/o/r/pull/7')})it('leaves out a reused agent\'s finished task', () => {@@ -58,8 +58,8 @@ describe('mine', () => {{ ...task('g20', 20, 'Web work', 'pm-web', 'working'), projectId: 'web' }])expect(isCoordinator(state, 'pm')).toBe(true)const text = mineText(state, changed({}), 'pm', NOW)- expect(text).toContain('#12 Fix login (conversation g12) — Dev1, working')- expect(text).toContain('#14 Docs (conversation g14) — unassigned')+ expect(text).toContain('#12 P2 Fix login (conversation g12) — Dev1, working')+ expect(text).toContain('#14 P2 Docs (conversation g14) — unassigned')expect(text).not.toContain('#15')expect(text).not.toContain('Web work')// g12 and g14; g16 is a step of g12, shown under it.@@ -96,7 +96,7 @@ describe('task', () => {it('shows goal, checks, attempts and linked tasks', () => {const state = swarm([group, task('g13', 13, 'Review: Fix login', 'rev1', 'working', { reviewOf: 'g12' })])const text = taskText(group, state, attempts, changed({ g12: NOW - 2 * MIN }), NOW)- expect(text.split('\n')[0]).toBe('#12 Fix login (conversation g12)')+ expect(text.split('\n')[0]).toBe('#12 P2 Fix login (conversation g12)')expect(text).toContain('Project: App · Status: working · Assignee: Dev1 · Updated 2 min ago')expect(text).toContain('PR: https://github.com/o/r/pull/7')expect(text).toContain('Goal:\nSign in works offline.')@@ -147,12 +147,12 @@ describe('steps', () => {it('mine shows the owner its task\'s steps on one line', () => {expect(mineText(withSteps(), changed({}), 'dev1', NOW)).toBe(- '#1835 Fix login (conversation g1835) — working\n steps: Review (Rev1): working · Test (Dev1): done')+ '#1835 P2 Fix login (conversation g1835) — working\n steps: Review (Rev1): working · Test (Dev1): done')})it('the coordinator\'s open work counts tasks, not steps', () => {const text = mineText(withSteps(), changed({}), 'pm', NOW)- expect(text).toContain('#1835 Fix login (conversation g1835) — Dev1, working\n steps: Review (Rev1): working · Test (Dev1): done')+ expect(text).toContain('#1835 P2 Fix login (conversation g1835) — Dev1, working\n steps: Review (Rev1): working · Test (Dev1): done')expect(text).not.toContain('#1918')expect(text.endsWith('1 open task.')).toBe(true)})@@ -169,7 +169,7 @@ describe('steps', () => {const state = withSteps()const step = (state.conversations as Array<Record<string, unknown>>).find(c => c.id === 'g1918')!const text = taskText(step, state, [], changed({}), NOW)- expect(text.split('\n')[0]).toBe('#1835 Fix login (conversation g1835)')+ expect(text.split('\n')[0]).toBe('#1835 P2 Fix login (conversation g1835)')expect(text).toContain('▶ Review (Rev1): working')})})@@ -186,7 +186,7 @@ describe('the default project', () => {{ ...task('g1', 1, 'Fix login', 'dev1', 'review'), projectId: 'lead' },],}- expect(mineText(state, changed({}), 'pm', NOW)).toBe('#1 Fix login (conversation g1) — Dev1, review\n1 open task.')+ expect(mineText(state, changed({}), 'pm', NOW)).toBe('#1 P2 Fix login (conversation g1) — Dev1, review\n1 open task.')})})@@ -205,7 +205,7 @@ describe('a linked task with no step name', () => {it('is a step named by its title', () => {const state = swarm([task('g12', 12, 'Fix login', 'dev1', 'working'),task('g13', 13, 'Test: PR #7', 'rev1', 'working', { reviewOf: 'g12' })])- expect(mineText(state, changed({}), 'dev1', NOW)).toBe('#12 Fix login (conversation g12) — working\n steps: Test: PR #7 (Rev1): working')+ expect(mineText(state, changed({}), 'dev1', NOW)).toBe('#12 P2 Fix login (conversation g12) — working\n steps: Test: PR #7 (Rev1): working')expect(mineText(state, changed({}), 'rev1', NOW)).toBe('#12 Fix login · Test: PR #7 (conversation g13) — working')})})@@ -244,3 +244,38 @@ describe('a check with several checkers', () => {.toContain('✗ Signs in offline — failed by Plover: Crashes; passed by Rev1')})})++// Task #3117: every task line says its priority after its number, and mine lists P0 first, keeping the order within one.+describe('priority', () => {+ it('the coordinator\'s mine lists a P0 task before an older P2 one, each with its priority', () => {+ const state = swarm([task('g12', 12, 'Fix login', 'dev1', 'working', { priority: 'P2' }), task('g14', 14, 'Docs', null, null, { priority: 'P3' }),+ task('g15', 15, 'Checkout fails', null, null, { priority: 'P0' }), task('g16', 16, 'Search', null, null)])+ expect(mineText(state, changed({}), 'pm', NOW)).toBe([+ '#15 P0 Checkout fails (conversation g15) — unassigned',+ '#12 P2 Fix login (conversation g12) — Dev1, working',+ '#16 P2 Search (conversation g16) — unassigned',+ '#14 P3 Docs (conversation g14) — unassigned',+ '4 open tasks.',+ ].join('\n'))+ })++ it('reads a legacy "(urgent)" title with no field as P0', () => {+ const state = swarm([task('g12', 12, 'Docs', null, null), task('g13', 13, 'Fix login (urgent)', null, null)])+ expect(mineText(state, changed({}), 'pm', NOW).split('\n')[0]).toBe('#13 P0 Fix login (urgent) (conversation g13) — unassigned')+ })++ it('an agent\'s own lines show their priority, P0 first, and its step keeps its task\'s label', () => {+ const state = swarm([task('g12', 12, 'Fix login', 'dev1', 'working', { priority: 'P1' }), task('g14', 14, 'Hotfix', 'dev1', 'working', { priority: 'P0' }),+ task('g20', 20, 'Docs', 'rev1', 'working', { priority: 'P0' }), task('g21', 21, 'Review', 'dev1', 'working', { reviewOf: 'g20', step: 'Review' })])+ expect(mineText(state, changed({}), 'dev1', NOW).split('\n')).toEqual([+ '#14 P0 Hotfix (conversation g14) — working',+ '#20 Docs · Review (conversation g21) — working',+ '#12 P1 Fix login (conversation g12) — working',+ ])+ })++ it('task shows its priority on its first line', () => {+ const group = task('g12', 12, 'Fix login', 'dev1', 'working', { priority: 'P1' })+ expect(taskText(group, swarm([group]), [], changed({}), NOW).split('\n')[0]).toBe('#12 P1 Fix login (conversation g12)')+ })+})diff --git a/cli/src/superTabs/agentContext.ts b/cli/src/superTabs/agentContext.tsindex e603df8c6..85279cead 100644--- a/cli/src/superTabs/agentContext.ts+++ b/cli/src/superTabs/agentContext.ts@@ -6,6 +6,7 @@*/import { personName } from './personName.js'+import { effectivePriority, priorityRank, type TaskPriority } from './taskPriority.js'type Json = Record<string, unknown>const object = (value: unknown): Json => value && typeof value === 'object' && !Array.isArray(value) ? value as Json : {}@@ -29,6 +30,8 @@ export interface TaskLine {pullRequestUrls: string[]step: string | nulltaskId: string | null+ /** A task's priority; for a step, its task's, by which it is ordered but not labelled (a step carries none, #3117). */+ priority: TaskPriority/** For a step: its task's number and title, by which it is shown (task steps design). */taskNumber: number | nulltaskTitle: string | null@@ -68,7 +71,7 @@ function lineOf(state: Json, group: Json): TaskLine {status: text(assignment.status) ?? 'unassigned', agentName: agentName(state, assignment.agentId),updatedAt: null, result: text(assignment.result),pullRequestUrls: Array.isArray(group.pullRequestUrls) ? group.pullRequestUrls.filter((u): u is string => typeof u === 'string') : [],- step: isStep(group) ? stepName(group) : null, taskId: text(group.reviewOf),+ step: isStep(group) ? stepName(group) : null, taskId: text(group.reviewOf), priority: effectivePriority(task ?? group),}}@@ -111,7 +114,9 @@ const utc = (at: number): string => `${new Date(at).toISOString().slice(0, 16).rconst label = (line: TaskLine): string => line.step && line.taskTitle !== null? `${line.taskNumber !== null ? `#${line.taskNumber} ` : ''}${line.taskTitle} · ${line.step} (conversation ${line.id})`- : `${line.number !== null ? `#${line.number} ` : ''}${line.title} (conversation ${line.id})`+ : `${line.number !== null ? `#${line.number} ` : ''}${line.priority} ${line.title} (conversation ${line.id})`+/** [lines] P0 first, each priority in the order given (#3117). */+const byPriority = (lines: TaskLine[]): TaskLine[] => [...lines].sort((a, b) => priorityRank(a.priority) - priorityRank(b.priority))function ownLine(line: TaskLine, changedAt: number | undefined, now: number): string {return `${label(line)} — ${line.status}`@@ -146,11 +151,11 @@ function stepsLine(state: Json, taskId: string): string[] {export function mineText(state: Json, groupChangedAt: ReadonlyMap<string, number>, agentId: string, now: number): string {if (isCoordinator(state, agentId)) {- const open = projectOpenWork(state, agentId)+ const open = byPriority(projectOpenWork(state, agentId))if (!open.length) return 'Your project has no open task.'return [...open.flatMap(line => [otherLine(line), ...stepsLine(state, line.id)]), `${open.length} open task${open.length === 1 ? '' : 's'}.`].join('\n')}- const own = openWorkOf(state, agentId)+ const own = byPriority(openWorkOf(state, agentId))if (!own.length) return 'No task is assigned to you.'const groups = new Map(list(state.conversations).map(g => [String(g.id), g]))return own.map(line => [ownLine(line, groupChangedAt.get(line.id), now),diff --git a/cli/src/superTabs/buddyStatus.spec.ts b/cli/src/superTabs/buddyStatus.spec.tsindex a8b3ec93b..557921fc3 100644--- a/cli/src/superTabs/buddyStatus.spec.ts+++ b/cli/src/superTabs/buddyStatus.spec.ts@@ -52,7 +52,7 @@ describe('a Buddy\'s status', () => {expect(status).toEqual({project: { name: 'App', chat: 'app-chat' }, chat: 'buddy-chat', since: null, more: 0,archived: 'Archived tasks the PM has reported on are left out: read them with status --archived.',- tasks: [{ conversationId: 'offline', number: 12, title: 'Offline sync', status: 'needs_human', note: 'Ship it behind a flag?', owns: ['desktop/lib/sync'],+ tasks: [{ conversationId: 'offline', number: 12, title: 'Offline sync', priority: 'P2', status: 'needs_human', note: 'Ship it behind a flag?', owns: ['desktop/lib/sync'],agents: [{ name: 'Ada', role: 'Product Manager', state: 'present' }, { name: 'Echo', role: 'Engineer', state: 'needs_human' },{ name: 'Reviewer', role: 'Reviewer', state: 'down' }],checks: [{ description: 'Edits survive a restart', passed: false }, { description: 'Specs pass', passed: true }],@@ -64,6 +64,14 @@ describe('a Buddy\'s status', () => {expect(prs.asked).toEqual([[pr(12)]])})+ // Task #3117: its person asks what is urgent; a step carries no priority of its own.+ it('says each task\'s priority, a legacy title\'s marker as one, and none for a step', async () => {+ const groups = [{ ...offline, priority: 'P0', pullRequestUrls: [] }, { ...offline, id: 'legacy', number: 13, title: 'Fix login (high)', pullRequestUrls: [] },+ { ...offline, id: 'review', number: 14, title: 'Review', reviewOf: 'offline', step: 'Review', pullRequestUrls: [] }]+ const status = await buddyStatus(input(swarm(groups), { offline: 3, legacy: 2, review: 1 }), { pullRequests: reader().read, decisions: decisions() })+ expect((status.tasks as Array<Record<string, unknown>>).map(t => [t.conversationId, t.priority])).toEqual([['offline', 'P0'], ['legacy', 'P1'], ['review', undefined]])+ })+it('marks the tasks that changed since its last read, newest first; shows one archived until its report, and leaves out dormant ones', async () => {const groups = [{ ...offline, id: 'a', number: 1, pullRequestUrls: [] }, { ...offline, id: 'b', number: 2, pullRequestUrls: [] },{ ...offline, id: 'c', number: 3, archived: true, pullRequestUrls: [] }, { ...offline, id: 'd', number: 4, dormant: true, pullRequestUrls: [] }]diff --git a/cli/src/superTabs/buddyStatus.ts b/cli/src/superTabs/buddyStatus.tsindex 9f0ca13b4..c03f95a9b 100644--- a/cli/src/superTabs/buddyStatus.ts+++ b/cli/src/superTabs/buddyStatus.ts@@ -7,6 +7,7 @@*/import { PULL_REQUESTS_MAX, type PullRequestsResult } from '../lib/pullRequestsStatus.js'import { validPullRequestUrl } from '../lib/sessionWorkWire.js'+import { effectivePriority } from './taskPriority.js'type Json = Record<string, unknown>const object = (value: unknown): Json => value && typeof value === 'object' && !Array.isArray(value) ? value as Json : {}@@ -147,7 +148,8 @@ async function taskRows(groups: Json[], state: Json, deps: BuddyStatusDeps, acticonst assignment = object(group.assignment), status = typeof assignment.status === 'string' ? assignment.status : 'open'return {conversationId: group.id, number: group.number ?? null, title: group.title, ...(group.archived === true ? { archived: true } : {}),- ...(group.reviewOf ? { reviewOf: group.reviewOf } : {}),+ // A step carries no priority of its own (#3117).+ ...(group.reviewOf ? { reviewOf: group.reviewOf } : { priority: effectivePriority(group) }),status, ...(text(assignment.result, 500) ? { note: text(assignment.result, 500) } : {}),owns: Array.isArray(object(group.task).owns) ? (object(group.task).owns as unknown[]).filter(o => typeof o === 'string').slice(0, 40) : [],agents: (Array.isArray(group.agentIds) ? group.agentIds : []).flatMap(id => {diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex 214d1f4b5..3663d1f4b 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -383,6 +383,18 @@ it('tells how the instructions are changed, and how the Swarm\'s tidying is turnexpect(answer.help.commands).toContainEqual({ type: 'tab.tidy', enabled: false, askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } })expect(answer.help.command).toContain('tab.tidy turns off, or back on, the Swarm\'s tidying: finished groups archive once their pull requests are merged or closed. The Swarm owner does, or the PM passing on the owner\'s own chat message, with askedIn naming it.')})+// Task #3117: a task is created with its priority, and the PM or a person changes it.+it('asks for a task\'s priority on conversation.create, says what P0 to P3 mean, and how work.priority changes it', async () => {+ const t = setup()+ const answer = await t.ask({ action: 'help' }, owner) as { help: { command: string; mine: string; commands: Array<Record<string, unknown>> } }+ expect(answer.help.mine).toContain('one line per task, P0 first (number, priority, title,')+ const creates = answer.help.commands.filter(c => c.type === 'conversation.create')+ expect(creates.find(c => !('step' in c))).toMatchObject({ title: 'Outcome', priority: 'P0|P1|P2|P3' })+ // A step carries no priority.+ expect(creates.find(c => 'step' in c)).not.toHaveProperty('priority')+ expect(answer.help.commands).toContainEqual({ type: 'work.priority', conversationId: 'GROUP', priority: 'P0' })+ expect(answer.help.command).toContain('A task\'s priority is P0 (hotfix: something shipped is broken, loses data, or stops people\'s or agents\' work), P1 (needed by users soon), P2 (planned goal) or P3 (tools, docs or process): give one on conversation.create, or it gets P2; only the PM or a person sets P0, or changes a priority later with work.priority.')+})it('tells the Lead that start works only on a machine in the Swarm\'s Machines list', async () => {const t = setup()const answer = await t.ask({ action: 'help' }, owner) as { help: { start: string } }@@ -468,6 +480,15 @@ describe('other projects\' work in status', () => {expect(state).not.toHaveProperty('leadsConversationId')expect(list(state.conversations).map(c => c.id)).toEqual(['pilot'])})++ // Task #3117: a task's priority reaches the PM and every other agent as the backend sends it.+ it('keeps a task\'s priority, for a Lead and for any other agent', async () => {+ for (const leadId of ['self', 'another-lead']) {+ const t = setup()+ swarm(t, leadId === 'self' ? t.agentId : leadId, [{ id: 'hotfix', projectId: 'pilot', number: 7, title: 'Checkout fails', priority: 'P0', agentIds: [] }])+ expect(list((await status(t)).conversations).find(c => c.id === 'hotfix'), leadId).toMatchObject({ priority: 'P0' })+ }+ })})// Security review of #2087: a harness that names another agent with --agent spoke as it (a Buddy as its Builder). The CLI@@ -1677,14 +1698,14 @@ describe('mine and task', () => {const t = setup()withState(t, [{ id: 'g12', number: 12, title: 'Fix login', archived: false, checks: [], assignment: { agentId: t.agentId, status: 'working', result: null } }])const answer = await t.ask({ action: 'mine', tabId: 'tab', harnessId: 'native' }, owner) as { value: { text: string } }- expect(answer.value.text).toMatch(/^#12 Fix login \(conversation g12\) — working/)+ expect(answer.value.text).toMatch(/^#12 P2 Fix login \(conversation g12\) — working/)})it('task reads a dormant group from the group read', async () => {const t = setup()const dormant = { id: 'g9', number: 9, title: 'Old fix', archived: true, dormant: true, checks: [], brief: 'Goal:\nOld.', assignment: { agentId: t.agentId, status: 'done', result: 'Merged' } }withState(t, [], path => path.startsWith('/api/super-tabs/tab/groups/g9?') ? ok({ group: { key: 'g9', version: 1, changedAt: 1, data: dormant } }) : ok({}))const answer = await t.ask({ action: 'task', tabId: 'tab', harnessId: 'native', conversationId: 'g9' }, owner) as { value: { text: string } }- expect(answer.value.text.split('\n')[0]).toBe('#9 Old fix (conversation g9)')+ expect(answer.value.text.split('\n')[0]).toBe('#9 P2 Old fix (conversation g9)')expect(answer.value.text).toContain('- Dev1, done (current): Merged')})it('task names a stopped assignee from the task\'s messages', async () => {diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 302130283..723124fa2 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -53,7 +53,7 @@ const MENTION_HELP = ' --mention tags a person, by the username, display name or/** What the command entry says after how its JSON is passed, the same for everyone. A task's review plan (#2382) is said in* its brief (backend superTabs/model.ts renderWorkTask), for whoever opens its review (project instructions, phase 4). */const COMMAND_ABOUT = 'send one of the commands below.'-const COMMAND_RULES = 'Reuse exactly the same ID and JSON after an interrupted request. A task is taken as written: conversation.create and work.define send the parts you give (goal, changes, constraints, owns), and checks may be empty. A task\'s optional review ({"focus": what every review of it checks first, such as the most-likely-wrong list; "reviews": 2 for two independent reviews}) is written into its brief, where whoever opens its review reads it; the Swarm opens no review by itself. When your assignment needs a person to decide, set work.status needs_human; when you cannot go on, blocked. Set working again once it moves. To change how the project works or routes, change its instructions (instructions.save; read them with instructions). tab.tidy turns off, or back on, the Swarm\'s tidying: finished groups archive once their pull requests are merged or closed. The Swarm owner does, or the PM passing on the owner\'s own chat message, with askedIn naming it. Two failed starts in a row suspend an engine on a machine for up to 6 hours (the route says so); machine.engineResume offers it there again: the machine\'s owner does, or the PM passing on the owner\'s chat message, with askedIn naming it. machine.projects keeps a machine for some projects (projectIds null: every project); the route leaves it out for the others: the machine\'s owner sets it, or the PM passing on the owner\'s chat message, with askedIn naming it.'+const COMMAND_RULES = 'Reuse exactly the same ID and JSON after an interrupted request. A task is taken as written: conversation.create and work.define send the parts you give (goal, changes, constraints, owns), and checks may be empty. A task\'s priority is P0 (hotfix: something shipped is broken, loses data, or stops people\'s or agents\' work), P1 (needed by users soon), P2 (planned goal) or P3 (tools, docs or process): give one on conversation.create, or it gets P2; only the PM or a person sets P0, or changes a priority later with work.priority. A task\'s optional review ({"focus": what every review of it checks first, such as the most-likely-wrong list; "reviews": 2 for two independent reviews}) is written into its brief, where whoever opens its review reads it; the Swarm opens no review by itself. When your assignment needs a person to decide, set work.status needs_human; when you cannot go on, blocked. Set working again once it moves. To change how the project works or routes, change its instructions (instructions.save; read them with instructions). tab.tidy turns off, or back on, the Swarm\'s tidying: finished groups archive once their pull requests are merged or closed. The Swarm owner does, or the PM passing on the owner\'s own chat message, with askedIn naming it. Two failed starts in a row suspend an engine on a machine for up to 6 hours (the route says so); machine.engineResume offers it there again: the machine\'s owner does, or the PM passing on the owner\'s chat message, with askedIn naming it. machine.projects keeps a machine for some projects (projectIds null: every project); the route leaves it out for the others: the machine\'s owner sets it, or the PM passing on the owner\'s chat message, with askedIn naming it.'/** A Buddy's guard refuses `command` itself and every JSON read from stdin, so its help never offers - and stdin there either* (a Buddy that follows a stdin form is refused and tries again, #2360); it quotes the JSON, as its usage hints do. */const BUDDY_COMMAND_HELP = `command OPERATION_ID JSON: ${COMMAND_ABOUT} The JSON is one argument, in single quotes: command OPERATION_ID '{...}' (an apostrophe inside it as \\u0027). ${COMMAND_RULES}`@@ -71,7 +71,7 @@ async function finishingWith(core: CoreApi, command: Record<string, unknown>, ha* is the project's instructions', never this help's. */const HELP = {status: 'Read the shared tab roster and work: people, projects, agents, conversations and their tasks. How the project routes work is in its instructions (instructions). The PM\'s status also lists otherProjectsWork: the active work of the Swarm\'s other projects (group, project, title, owned code, status, agent, PR), read only.',- mine: 'mine: what you work on, one line per task (number, title, conversation id, status, when it changed, last result, pull requests) with the open tasks linked to it. A project\'s coordinator gets every open task of its project instead.',+ mine: 'mine: what you work on, one line per task, P0 first (number, priority, title, conversation id, status, when it changed, last result, pull requests) with the open tasks linked to it. A project\'s coordinator gets every open task of its project instead.',task: 'task GROUP: one task, active or finished: project, status, assignee, pull requests, brief, checks, attempts newest first, and linked tasks.',messages: 'messages GROUP: read recent messages in a conversation, thread replies included: each names its thread, the root message it answers there. A post with --reply-to lands in that message\'s thread. messages GROUP --thread ROOT reads one thread, its root and replies; a Buddy\'s thread session also gets there, as context, the main-chat messages it started from.',message: 'message GROUP MESSAGE_ID: read one exact message, including an earlier question or result referenced by a reply.',@@ -105,11 +105,12 @@ const HELP = {{ type: 'project.digest', projectId: 'PROJECT', time: '08:00', timeZone: 'Asia/Ho_Chi_Minh' },{ type: 'tab.tidy', enabled: false, askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },{ type: 'message.send', conversationId: 'GROUP', text: 'A message addressed to an agent', replyTo: null, recipientIds: ['AGENT'] },- { type: 'conversation.create', title: 'Outcome', task: { goal: 'An independently assignable result', changes: 'What changes', constraints: 'What must stay true', owns: ['Paths or code areas'],+ { type: 'conversation.create', title: 'Outcome', priority: 'P0|P1|P2|P3', task: { goal: 'An independently assignable result', changes: 'What changes', constraints: 'What must stay true', owns: ['Paths or code areas'],review: { focus: 'Optional: what every review of it checks first, such as the most-likely-wrong list (up to 2,000 characters)', reviews: 2 } }, checks: [{ description: 'Observable acceptance evidence', independent: false }] },// A step of a task (task steps design): its name is the one the project's instructions give.{ type: 'conversation.create', title: 'STEP_NAME', reviewOf: 'GROUP', step: 'STEP_NAME', task: { goal: 'What this step delivers for the task', changes: 'What it changes, or None', constraints: 'The task\'s constraints', owns: ['What it works on'] }, checks: [{ description: 'Its verdict, with evidence', independent: false }] },{ type: 'conversation.agent', conversationId: 'GROUP', agentId: 'AGENT', present: true, lead: false },+ { type: 'work.priority', conversationId: 'GROUP', priority: 'P0' },{ type: 'work.define', conversationId: 'GROUP', task: { goal: 'What to deliver', changes: 'What changes', constraints: 'What must stay true', owns: ['Paths or code areas'] }, checks: [{ description: 'Observable acceptance evidence', independent: false }] },{ type: 'work.cancel', conversationId: 'GROUP', assignmentId: 'current', reason: 'Why the task is cancelled, in one short sentence' },{ type: 'conversation.merged', conversationId: 'GROUP', pullRequestUrl: 'https://github.com/OWNER/REPOSITORY/pull/NUMBER', mergedAt: 'Optional ISO time of a merge recorded later' },diff --git a/cli/src/superTabs/taskPriority.spec.ts b/cli/src/superTabs/taskPriority.spec.tsnew file mode 100644index 000000000..7f8025c53--- /dev/null+++ b/cli/src/superTabs/taskPriority.spec.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest'+import { effectivePriority, priorityRank, type TaskPriority } from './taskPriority.js'++// Task #3117: a task's priority is its field, else the title marker the PM wrote before there was one (Desktop backlog.dart+// superTabTitlePriority), else P2.+describe('a task\'s priority', () => {+ it('is its field when it is one of P0 to P3, over any title marker', () => {+ for (const priority of ['P0', 'P1', 'P2', 'P3']) expect(effectivePriority({ priority, title: 'Fix login (urgent)' })).toBe(priority)+ })++ it('reads a legacy title marker when the field is missing or not a priority', () => {+ expect(effectivePriority({ title: 'Fix login (urgent)' })).toBe('P0')+ for (const priority of ['P4', 'p0', 'urgent', 0, null]) expect(effectivePriority({ priority, title: 'Fix login (urgent)' })).toBe('P0')+ })++ it('reads a leading URGENT word as P0', () => {+ for (const title of ['URGENT Fix login', 'URGENT: Fix login', 'urgent: fix login', ' Urgent fix login']) expect(effectivePriority({ title }), title).toBe('P0')+ // A word that only starts with it, or the word alone, marks nothing.+ for (const title of ['Urgently fix login', 'URGENT', 'URGENT: ']) expect(effectivePriority({ title }), title).toBe('P2')+ })++ it('reads a closing (urgent) as P0 and (high) as P1, with a name before it or "priority" after it', () => {+ for (const title of ['Fix login (urgent)', 'Fix login (Ken, urgent)', 'Fix login (URGENT)', 'Fix login (urgent priority)']) expect(effectivePriority({ title }), title).toBe('P0')+ for (const title of ['Fix login (high)', 'Fix login (Ken, high)', 'Fix login (high priority)', 'Fix login (Ken, High Priority) ']) expect(effectivePriority({ title }), title).toBe('P1')+ })++ it('is P2 with no marker', () => {+ for (const title of ['Fix login', 'Fix login (low)', 'Fix (urgent) login', 'Fix login (Ken)', '(urgent)', '']) expect(effectivePriority({ title }), title).toBe('P2')+ expect(effectivePriority({})).toBe('P2')+ expect(effectivePriority({ title: 7 })).toBe('P2')+ })++ it('ranks P0 first', () => {+ const shuffled: TaskPriority[] = ['P2', 'P0', 'P3', 'P1']+ expect(shuffled.sort((a, b) => priorityRank(a) - priorityRank(b))).toEqual(['P0', 'P1', 'P2', 'P3'])+ })+})diff --git a/cli/src/superTabs/taskPriority.ts b/cli/src/superTabs/taskPriority.tsnew file mode 100644index 000000000..9ceaee06a--- /dev/null+++ b/cli/src/superTabs/taskPriority.ts@@ -0,0 +1,30 @@+/**+ * A task's priority (task #3117): P0 hotfix, P1 needed by users soon, P2 planned goal, P3 tools, docs or process. The+ * backend stores it on the task's group; a task from before it carries none, and the PM marked urgency in its title+ * instead, which is read the way Desktop reads it (backlog.dart superTabTitlePriority), so every client agrees.+ */++export type TaskPriority = 'P0' | 'P1' | 'P2' | 'P3'+const PRIORITIES: readonly TaskPriority[] = ['P0', 'P1', 'P2', 'P3']++const LEADING = /^\s*URGENT\b\s*:?\s*/i+const TRAILING = /\s*\((?:[^()]*,\s*)?(urgent|high)(?:\s+priority)?\)\s*$/i++/** The title's marker: a leading URGENT, or a closing "(urgent)", "(Name, high)" or "(high priority)"; a marker with no+ * title left beside it marks nothing. */+function titlePriority(title: string): TaskPriority | null {+ const leading = LEADING.exec(title)+ if (leading && title.length > leading[0].length) return 'P0'+ const trailing = TRAILING.exec(title)+ if (trailing && trailing.index > 0) return trailing[1]!.toLowerCase() === 'urgent' ? 'P0' : 'P1'+ return null+}++/** [group]'s priority: its field, else its title's marker, else P2. */+export function effectivePriority(group: { priority?: unknown; title?: unknown }): TaskPriority {+ if (PRIORITIES.includes(group.priority as TaskPriority)) return group.priority as TaskPriority+ return (typeof group.title === 'string' ? titlePriority(group.title) : null) ?? 'P2'+}++/** Where [priority] sorts: P0 first. */+export const priorityRank = (priority: TaskPriority): number => PRIORITIES.indexOf(priority)diff --git a/cli/src/team/command.spec.ts b/cli/src/team/command.spec.tsindex 028c16049..04997ae06 100644--- a/cli/src/team/command.spec.ts+++ b/cli/src/team/command.spec.ts@@ -97,6 +97,17 @@ describe('harness team', () => {})describe('harness team setup', () => {+ it('copies the engines this Mac already has into the team account, instead of downloading them (#3169)', async () => {+ const codex = { packageName: '@openai/codex', dir: `${OWNER_HOME}/.local/lib/node_modules/@openai/codex`, bin: 'codex', binPath: 'bin/codex.js' }+ const f = fake({ statusAfter: reported })+ const installed = f.deps.installed()+ f.deps.installed = () => ({ ...installed, engineCopies: [codex] })+ expect(await teamCommand(['setup'], f.deps)).toBe(0)+ const { script } = f.built[0]!+ expect(script).toContain(`copy_engine '@openai/codex' '${OWNER_HOME}/.local/lib/node_modules/@openai/codex' 'codex' 'bin/codex.js'`)+ expect(script).toContain("[ -n \"$copied_claude\" ] || set -- \"$@\" '@anthropic-ai/claude-code'")+ })+it('says what it will make, runs one privileged script, and waits for the team daemon to sign in and pass its check', async () => {const f = fake({ statusAfter: reported, env: { BACKEND_WS_URL: 'wss://backend.example.test', HARNESS_AUTH_DIR: '/tmp/auth' } })expect(await teamCommand(['setup'], f.deps)).toBe(0)diff --git a/cli/src/team/command.ts b/cli/src/team/command.tsindex f33478c43..86a00d41e 100644--- a/cli/src/team/command.ts+++ b/cli/src/team/command.ts@@ -30,7 +30,7 @@ import {import type { PrivacyResult, TeamStatus } from './privacy.js'import {LINUX_NO_SYSTEMD, LINUX_NO_TMUX, REMOVE_REFUSED, buildLinuxRemoveScript, buildLinuxSetupScript, buildRemoveScript,- buildSetupScript, teamLaunchdPlist, teamSystemdUnit, type RemoveScriptInput, type SetupScriptInput, type TeamPlistInput,+ buildSetupScript, teamLaunchdPlist, teamSystemdUnit, type EngineCopy, type RemoveScriptInput, type SetupScriptInput, type TeamPlistInput,} from './script.js'import { windowsTeamPaths } from './windowsLayout.js'import { WINDOWS_STAGED, buildWindowsRemoveScript, buildWindowsSetupScript, teamTaskXml } from './windowsScript.js'@@ -115,6 +115,9 @@ export interface Installed {/** Windows: the owner's terminal host payload in use (`runtime\pty\<version>`), copied for the team account, which has no* installer of its own to lay one down; null without one. */ptyDir?: string | null+ /** A Mac: the owner's own installed Claude Code and Codex (./engines.ts `ownerEngineCopies`), copied for the team account+ * instead of downloaded again (#3169). */+ engineCopies?: EngineCopy[]}export interface JobState { loaded: boolean; pid: number | null; state: string | null }@@ -410,6 +413,7 @@ async function setup(deps: TeamCommandDeps, json: boolean, signInAgain: boolean)user: TEAM_USER, realName: TEAM_REAL_NAME, home: layout.home, owner, ownerHome, stageDir,nodeRuntimeDir: installed.nodeRuntimeDir!, tmuxRuntimeDir: installed.tmuxRuntimeDir, cliDir: installed.cliDir,ownerNode: installed.node, ownerCli: installed.cliJs, mintEnv, signIn: signInAgain ? 'always' : 'missing',+ ...mac && installed.engineCopies?.length ? { engineCopies: installed.engineCopies } : {},...windows ? { ownerSid, ptyDir: installed.ptyDir ?? null } : {},}),files: { 'team.json': teamConfigJson(config), [scripts.serviceFile]: service },diff --git a/cli/src/team/deps.ts b/cli/src/team/deps.tsindex f475487b3..9fbf48e5a 100644--- a/cli/src/team/deps.ts+++ b/cli/src/team/deps.ts@@ -26,7 +26,7 @@ import { readTeamConfig } from './config.js'import { agentTmpState } from '../lib/agentTmp.js'import { realPrivacyDeps, readTeamStatus, runPrivacyCheck, writeTeamStatus } from './privacy.js'import { takeHandoffFile } from './handoff.js'-import { checkTeamEngines, realEngineCheckDeps } from './engines.js'+import { checkTeamEngines, ownerEngineCopies, realEngineCheckDeps } from './engines.js'import { teamSetupDecisionFile, writeTeamSetupDecision } from './autoSetup.js'/** What `launchctl print system/<label>` says of a job; not loaded when launchd does not know it. Readable without root. */@@ -130,6 +130,7 @@ export function teamCommandDeps(options: {node: managedNodePath(),nodeRuntimeDir: managedNodeRuntimeDir(),tmuxRuntimeDir: tmux ? dirname(dirname(tmux)) : null,+ ...process.platform === 'darwin' ? { engineCopies: ownerEngineCopies({ home: homedir(), nodeRuntimeDir: managedNodeRuntimeDir() }) } : {},}},exists: existsSync,diff --git a/cli/src/team/engines.spec.ts b/cli/src/team/engines.spec.tsindex a39425ed9..e420f09c1 100644--- a/cli/src/team/engines.spec.ts+++ b/cli/src/team/engines.spec.ts@@ -1,9 +1,9 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'import { readTeamConfig, type TeamConfig } from './config.js'-import { checkTeamEngines, engineLines, realEngineCheckDeps, teamEngineBin, teamEngineReporter, TeamEngineReporter, type TeamEngines } from './engines.js'+import { checkTeamEngines, engineLines, ownerEngineCopies, realEngineCheckDeps, teamEngineBin, teamEngineReporter, TeamEngineReporter, type TeamEngines } from './engines.js'import { readTeamStatus, type TeamStatus } from './privacy.js'vi.mock('./config.js', async (original) => ({ ...await original<typeof import('./config.js')>(), readTeamConfig: vi.fn(() => null) }))@@ -163,3 +163,81 @@ describe('TeamEngineReporter', () => {}})})++describe('the owner\'s installed engines, for setup to copy (#3169)', () => {+ function home(): string {+ const dir = mkdtempSync(join(tmpdir(), 'owner-engines-'))+ cleanup.push(dir)+ return dir+ }+ function pkg(prefix: string, name: string, bin: unknown, binFile = typeof bin === 'string' ? bin : Object.values(bin as object)[0] as string) {+ const dir = join(prefix, 'lib', 'node_modules', name)+ mkdirSync(join(dir, 'bin'), { recursive: true })+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ name, version: '1.0.0', bin }))+ writeFileSync(join(dir, binFile.replace(/^\.\//, '')), '#!/bin/sh\n', { mode: 0o755 })+ return dir+ }++ it('finds each engine where Harness installs it, then in its Node, then in Homebrew\'s, with the command npm links', () => {+ const owner = home(), node = join(owner, '.harness', 'runtime', 'node-v1'), brew = join(owner, 'brew')+ const claude = pkg(join(owner, '.local'), '@anthropic-ai/claude-code', { claude: 'bin/claude.exe' })+ pkg(brew, '@anthropic-ai/claude-code', { claude: 'bin/claude.exe' })+ const codex = pkg(brew, '@openai/codex', { codex: './bin/codex.js' })+ expect(ownerEngineCopies({ home: owner, nodeRuntimeDir: node, prefixes: [brew] })).toEqual([+ { packageName: '@anthropic-ai/claude-code', dir: claude, bin: 'claude', binPath: 'bin/claude.exe' },+ { packageName: '@openai/codex', dir: codex, bin: 'codex', binPath: 'bin/codex.js' },+ ])+ const inNode = pkg(node, '@openai/codex', 'bin/codex.js')+ expect(ownerEngineCopies({ home: owner, nodeRuntimeDir: node, prefixes: [brew] })[1]).toEqual(+ { packageName: '@openai/codex', dir: inNode, bin: 'codex', binPath: 'bin/codex.js' })+ })++ it('leaves out what is not a plain install of that package: another name, no command, a command outside it, a link', () => {+ const owner = home(), local = join(owner, '.local')+ pkg(local, '@openai/codex', { codex: '../../../../../bin/sh' }, 'bin/x')+ const other = pkg(local, '@anthropic-ai/claude-code', { claude: 'bin/claude.exe' })+ writeFileSync(join(other, 'package.json'), JSON.stringify({ name: 'left-pad', bin: { claude: 'bin/claude.exe' } }))+ expect(ownerEngineCopies({ home: owner, nodeRuntimeDir: null, prefixes: [] })).toEqual([])+ // An `npm link` to a source checkout is the owner's work in progress, never copied.+ const checkout = pkg(join(owner, 'src'), '@openai/codex', 'bin/codex.js')+ rmSync(join(local, 'lib', 'node_modules', '@openai', 'codex'), { recursive: true })+ symlinkSync(checkout, join(local, 'lib', 'node_modules', '@openai', 'codex'))+ expect(ownerEngineCopies({ home: owner, nodeRuntimeDir: null, prefixes: [] })).toEqual([])+ // A command that is a link: where it points is not the package's to say.+ const linked = pkg(join(owner, 'linked'), '@openai/codex', { codex: 'bin/codex.js' })+ rmSync(join(linked, 'bin', 'codex.js'))+ symlinkSync('/bin/sh', join(linked, 'bin', 'codex.js'))+ expect(ownerEngineCopies({ home: owner, nodeRuntimeDir: null, prefixes: [join(owner, 'linked')] })).toEqual([])+ const noBin = pkg(join(owner, 'nobin'), '@openai/codex', { codex: 'bin/codex.js' })+ rmSync(join(noBin, 'bin', 'codex.js'))+ expect(ownerEngineCopies({ home: owner, nodeRuntimeDir: null, prefixes: [join(owner, 'nobin')] })).toEqual([])+ })++ // Security review 1 of #3124 (Dahlia): Homebrew's folders may belong to another person on this Mac, and a folder anyone+ // else can write decides what the Team account would run. Only a package whose every folder, from / down, and every+ // file is the owner's or root's and writable by no one else is copied; anything else goes to npm.+ it('copies nothing another person, or anyone in a group, could have changed', () => {+ const owner = home(), brew = join(owner, 'brew')+ const dir = pkg(brew, '@openai/codex', { codex: 'bin/codex.js' })+ const found = () => ownerEngineCopies({ home: join(owner, 'nobody'), nodeRuntimeDir: null, prefixes: [brew] })+ expect(found()).toHaveLength(1)+ // Another person's Homebrew: the same files, owned by someone who is not the owner and not root.+ expect(ownerEngineCopies({ home: join(owner, 'nobody'), nodeRuntimeDir: null, prefixes: [brew], uid: process.getuid!() + 12345 })).toEqual([])+ // A prefix folder others can write, and a file inside the package others can write.+ chmodSync(join(brew, 'lib'), 0o775)+ expect(found()).toEqual([])+ chmodSync(join(brew, 'lib'), 0o755)+ expect(found()).toHaveLength(1)+ writeFileSync(join(dir, 'index.js'), '// engine', { mode: 0o666 })+ chmodSync(join(dir, 'index.js'), 0o666)+ expect(found()).toEqual([])+ chmodSync(join(dir, 'index.js'), 0o644)+ // A folder anyone can write is fine only with the sticky bit (/tmp), where nobody else can swap what is in it.+ chmodSync(brew, 0o1777)+ expect(found()).toHaveLength(1)+ chmodSync(brew, 0o777)+ expect(found()).toEqual([])+ chmodSync(brew, 0o755)+ })+})+diff --git a/cli/src/team/engines.ts b/cli/src/team/engines.tsindex b9660d9ed..6c8970046 100644--- a/cli/src/team/engines.ts+++ b/cli/src/team/engines.ts@@ -10,14 +10,15 @@* The owner cannot look inside the team account's home, so the team daemon reports what it finds (installed, signed in)* in its status file, as it starts and every minute after, and `harness team status` reads it there.*/-import { accessSync, constants } from 'node:fs'+import { accessSync, constants, lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs'import { userInfo } from 'node:os'-import { join, win32 } from 'node:path'+import { dirname, join, posix, win32 } from 'node:path'import { engineAccount, type EngineAccount } from '../lib/engineAccount.js'import { env } from '../config/env.js'import { readTeamConfig, type TeamConfig } from './config.js'import { receiveTeamModel } from './modelHandoff.js'import { TEAM_USER } from './layout.js'+import type { EngineCopy } from './script.js'import { readTeamStatus, writeTeamStatus, type TeamStatus } from './privacy.js'import { teamRelayed } from './relay.js'@@ -37,6 +38,90 @@ export const TEAM_ENGINES: readonly TeamEngineInfo[] = [{ engine: 'codex', name: 'Codex', packageName: '@openai/codex', signIn: 'codex login --device-auth' },]+/** Where else an owner's npm puts global packages on a Mac: Homebrew's Node, on Apple silicon and on Intel. */+export const SYSTEM_NPM_PREFIXES = ['/opt/homebrew', '/usr/local'] as const++/**+ * The owner's own installed Claude Code and Codex, for setup to copy into the team account instead of downloading them+ * again (#3169: npm was 4 min 18 s of a 4 min 35 s setup on this Mac; the copy 2.3 s). Read as the owner, before the+ * password. Each engine from the first place that has it as npm leaves it: Harness's own prefix (`~/.local`,+ * lib/engineInstall.ts), the Harness Node's, then [prefixes] (Homebrew's). Only a real folder holding that package by name,+ * with its command where its package.json says: an `npm link` to a source checkout is the owner's work, not an install.+ * An engine found nowhere is left to npm.+ *+ * And only what nobody but the owner or root could have changed (security review 1 of #3124): Homebrew's folders may+ * belong to another person on this Mac, and whoever can write a package decides what the Team account runs. So every+ * folder from / down to the package, and everything in it, must be the owner's ([uid]) or root's and writable by no one+ * else; a folder anyone can write passes only with the sticky bit (/tmp), where nobody else can swap what is in it.+ */+export function ownerEngineCopies(input: { home: string; nodeRuntimeDir: string | null; prefixes?: readonly string[]; uid?: number }): EngineCopy[] {+ const uid = input.uid ?? process.getuid?.()+ if (uid === undefined) return []+ const prefixes = [join(input.home, '.local'), ...input.nodeRuntimeDir ? [input.nodeRuntimeDir] : [], ...input.prefixes ?? SYSTEM_NPM_PREFIXES]+ const copies: EngineCopy[] = []+ for (const { engine, packageName } of TEAM_ENGINES) {+ for (const prefix of prefixes) {+ const copy = installedPackage(join(prefix, 'lib', 'node_modules', packageName), packageName, engine, uid)+ if (copy) { copies.push(copy); break }+ }+ }+ return copies+}++/** More than any engine's package holds (Claude Code and Codex together were 77 entries on 2026-11-05): past it, npm. */+const MOST_ENTRIES = 20_000++const ownedBy = (uid: number, stat: { uid: number }) => stat.uid === uid || stat.uid === 0+/** Writable by its group or others, without the sticky bit that keeps them from swapping what is in a folder. */+const openToOthers = (mode: number, folder: boolean) => (mode & 0o022) !== 0 && !(folder && (mode & 0o1000) !== 0)++/** Every folder above [dir], through its real path to /, the owner's or root's and closed to others. */+function aboveTrusted(dir: string, uid: number): boolean {+ for (let at = dirname(realpathSync(dir)); ; at = dirname(at)) {+ const stat = lstatSync(at)+ if (!ownedBy(uid, stat) || openToOthers(stat.mode, true)) return false+ if (dirname(at) === at) return true+ }+}++/** [dir] and everything in it, links included and never followed, the owner's or root's and closed to others. */+function treeTrusted(dir: string, uid: number): boolean {+ const folders = [dir]+ let seen = 0+ while (folders.length) {+ const folder = folders.pop()!+ for (const name of ['', ...readdirSync(folder)]) {+ if (++seen > MOST_ENTRIES) return false+ const path = name ? join(folder, name) : folder+ const stat = lstatSync(path)+ if (!ownedBy(uid, stat)) return false+ // A link's own mode means nothing; where it points is checked as the team account reads it.+ if (stat.isSymbolicLink()) continue+ if (openToOthers(stat.mode, stat.isDirectory())) return false+ if (name && stat.isDirectory()) folders.push(path)+ }+ }+ return true+}++function installedPackage(dir: string, packageName: string, bin: string, uid: number): EngineCopy | null {+ try {+ if (!lstatSync(dir).isDirectory()) return null+ const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { name?: unknown; bin?: unknown }+ if (manifest.name !== packageName) return null+ const named = typeof manifest.bin === 'string' ? manifest.bin+ : manifest.bin && typeof manifest.bin === 'object' ? (manifest.bin as Record<string, unknown>)[bin] : undefined+ if (typeof named !== 'string') return null+ const binPath = posix.normalize(named)+ if (binPath.startsWith('../') || binPath.startsWith('/') || binPath === '..' || !/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/.test(binPath)) return null+ // The command itself, not a link: where a link points is not the package's to say.+ if (!lstatSync(join(dir, binPath)).isFile()) return null+ accessSync(join(dir, binPath), constants.X_OK)+ if (!aboveTrusted(dir, uid) || !treeTrusted(dir, uid)) return null+ return { packageName, dir, bin, binPath }+ } catch { return null }+}+/** [relayed]: not signed in itself, it spends the owner's subscription through the owner's relay (team/relay.ts). */export interface EngineReadiness { installed: boolean; signedIn: boolean | null; relayed?: boolean }export type TeamEngines = { checkedAt: number } & Record<TeamEngine, EngineReadiness>diff --git a/cli/src/team/script.spec.ts b/cli/src/team/script.spec.tsindex 235e823ea..94bf10e58 100644--- a/cli/src/team/script.spec.ts+++ b/cli/src/team/script.spec.ts@@ -4,12 +4,12 @@* osascript, launchctl, dscl or sudo: the whole scripts are only parsed (`sh -n`), never run.*/import { execFileSync, spawnSync } from 'node:child_process'-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'import {- REMOVE_REFUSED, SENTINEL_TEXT, TEAM_COPY, TEAM_ENGINES_INSTALL, TEAM_JOB_WRAPPER, TEAM_PASSWORD, WRITE_PRIVATE, WRITE_PUBLIC,+ REMOVE_REFUSED, SENTINEL_TEXT, TEAM_COPY, TEAM_ENGINE_COPY, TEAM_ENGINE_COPY_FN, TEAM_ENGINES_INSTALL, TEAM_JOB_WRAPPER, TEAM_PASSWORD, WRITE_PRIVATE, WRITE_PUBLIC,LINUX_NO_SYSTEMD, LINUX_NO_TMUX, LINUX_ROOT_CHECKS, TEAM_SYSTEM_PATH, buildLinuxRemoveScript, buildLinuxSetupScript, buildRemoveScript, buildSetupScript, sh, teamLaunchdPlist,teamSystemdUnit, type SetupScriptInput,} from './script.js'@@ -162,7 +162,7 @@ describe('setup script', () => {describe('the team account\'s own engines', () => {it('are installed by the team account itself, never by root, from the vendors\' packages, and never fail setup', () => {const script = buildSetupScript(input())- expect(script).toContain(`\nas_team /bin/sh -c ${sh(TEAM_ENGINES_INSTALL)} sh "$TEAM_HOME" "$NODE_NAME" '@anthropic-ai/claude-code' '@openai/codex' || true\n`)+ expect(script).toContain(`\n as_team /bin/sh -c ${sh(TEAM_ENGINES_INSTALL)} sh "$TEAM_HOME" "$NODE_NAME" "$@" || true\n`)parses(script)})@@ -193,6 +193,119 @@ describe('the team account\'s own engines', () => {})})+describe('the team account\'s engines, copied from the owner\'s', () => {+ // #3169 (this Mac, 2026-11-04): npm took 4 min 18 s of a 4 min 35 s setup; copying the two installed packages took 2.3 s.+ const copies = [+ { packageName: '@anthropic-ai/claude-code', dir: `${OWNER_HOME}/.local/lib/node_modules/@anthropic-ai/claude-code`, bin: 'claude', binPath: 'bin/claude.exe' },+ { packageName: '@openai/codex', dir: `${OWNER_HOME}/.local/lib/node_modules/@openai/codex`, bin: 'codex', binPath: 'bin/codex.js' },+ ]++ it('copies what the owner has, as the owner reading and the team account writing, and asks npm only for the rest', () => {+ const script = buildSetupScript(input({ engineCopies: [copies[1]!] }))+ parses(script)+ expect(script).toContain(TEAM_ENGINE_COPY_FN)+ expect(script).toContain(`copy_engine '@openai/codex' '${OWNER_HOME}/.local/lib/node_modules/@openai/codex' 'codex' 'bin/codex.js'`)+ expect(script).not.toContain("copy_engine '@anthropic-ai/claude-code'")+ // Said before it runs, and the npm step only when something is left for it.+ expect(at(script, '\nstep copy-engines\n')).toBeLessThan(at(script, "copy_engine '@openai/codex'"))+ expect(at(script, "copy_engine '@openai/codex'")).toBeLessThan(at(script, '\n step engines\n'))+ expect(at(script, '\n step engines\n')).toBeLessThan(at(script, `as_team /bin/sh -c ${sh(TEAM_ENGINES_INSTALL)} sh "$TEAM_HOME" "$NODE_NAME" "$@"`))+ // Root reads nothing of the owner's and writes nothing of the team account's: the owner's tar into the team account's.+ expect(TEAM_ENGINE_COPY_FN).toContain('as_owner /usr/bin/tar -C "$2" -cf - .')+ expect(TEAM_ENGINE_COPY_FN).toContain(`| as_team /bin/sh -c ${sh(TEAM_ENGINE_COPY)} sh unpack "$TEAM_HOME" "$1" "$3" "$4"`)+ })++ it('installs both from npm, as before, on a Mac that has neither', () => {+ const script = buildSetupScript(input())+ parses(script)+ expect(script).not.toContain('\nstep copy-engines\n')+ expect(script).not.toMatch(/\ncopy_engine '/)+ expect(script).toContain("[ -n \"$copied_claude\" ] || set -- \"$@\" '@anthropic-ai/claude-code'")+ expect(script).toContain("[ -n \"$copied_codex\" ] || set -- \"$@\" '@openai/codex'")+ })++ it('refuses a copy it cannot name plainly, before anything is written', () => {+ for (const bad of [+ { ...copies[0]!, packageName: 'left-pad' },+ { ...copies[0]!, bin: 'claude; id' },+ { ...copies[0]!, binPath: '../../../etc/passwd' },+ { ...copies[0]!, binPath: '/bin/sh' },+ { ...copies[0]!, dir: 'relative/claude-code' },+ { ...copies[0]!, dir: `${OWNER_HOME}/x'y` },+ ]) expect(() => buildSetupScript(input({ engineCopies: [bad] })), JSON.stringify(bad)).toThrow()+ })++ /** A package as npm leaves one: package.json, its bin executable, a nested dependency and a relative link. */+ function ownerPackage(root: string, name = '@openai/codex', binPath = 'bin/codex.js'): string {+ const dir = join(root, 'owner', 'lib', 'node_modules', name)+ mkdirSync(join(dir, 'bin'), { recursive: true })+ mkdirSync(join(dir, 'node_modules', 'dep'), { recursive: true })+ writeFileSync(join(dir, 'package.json'), `{\n "name": "${name}",\n "version": "1.2.3"\n}\n`)+ writeFileSync(join(dir, binPath), '#!/bin/sh\necho engine\n', { mode: 0o755 })+ writeFileSync(join(dir, 'node_modules', 'dep', 'index.js'), '// dep')+ return dir+ }+ /** TEAM_ENGINE_COPY_FN with as_owner and as_team as this account, so it runs here without sudo. */+ const runCopy = (root: string, home: string, args: string[], owner = '"$@"') => spawnSync('/bin/sh', ['-c', [+ 'set -eu', `RT=${sh(join(root, 'rt'))}`, `TEAM_HOME=${sh(home)}`, 'mkdir -p "$RT"',+ `as_owner() { ${owner}; }`, 'as_team() { "$@"; }', `say() { printf 'harness: %s\\n' "$1"; }`,+ TEAM_ENGINE_COPY_FN, `if copy_engine ${args.map(sh).join(' ')}; then echo copied; else echo not-copied; fi`,+ ].join('\n')], { encoding: 'utf8' })++ it('lays the package into the team account\'s npm prefix and links its command as npm does', () => {+ const root = temp(), home = join(root, 'home')+ mkdirSync(home)+ const dir = ownerPackage(root)+ // Twice: a repair run replaces the copy the first one laid down.+ for (let i = 0; i < 2; i++) {+ const run = runCopy(root, home, ['@openai/codex', dir, 'codex', 'bin/codex.js'])+ expect(run.stdout).toContain('copied\n')+ expect(run.stdout).not.toContain('not-copied')+ }+ const dest = join(home, '.local', 'lib', 'node_modules', '@openai', 'codex')+ expect(readFileSync(join(dest, 'node_modules', 'dep', 'index.js'), 'utf8')).toBe('// dep')+ expect(existsSync(`${dest}.next`)).toBe(false)+ const link = join(home, '.local', 'bin', 'codex')+ expect(readlinkSync(link)).toBe('../lib/node_modules/@openai/codex/bin/codex.js')+ expect(execFileSync(link, { encoding: 'utf8' })).toBe('engine\n')+ })++ it('keeps nothing of a copy that is not the package, has no command, or whose reading failed, so npm installs it', () => {+ const cases: [string, (root: string) => string[], string?][] = [+ ['another package', (root) => ['@openai/codex', ownerPackage(root, '@anthropic-ai/claude-code', 'bin/codex.js'), 'codex', 'bin/codex.js']],+ ['no command', (root) => ['@openai/codex', ownerPackage(root), 'codex', 'bin/missing.js']],+ // Security review 1 of #3124: a command that is a link points wherever it was made to, outside the package too.+ ['a command that is a link', (root) => {+ const dir = ownerPackage(root)+ rmSync(join(dir, 'bin', 'codex.js'))+ symlinkSync('/bin/sh', join(dir, 'bin', 'codex.js'))+ return ['@openai/codex', dir, 'codex', 'bin/codex.js']+ }],+ ['no folder', (root) => ['@openai/codex', join(root, 'nothing-here'), 'codex', 'bin/codex.js']],+ // The owner's tar sends a whole package, then fails (a file it could not read): the copy is not kept.+ ['reading failed', (root) => ['@openai/codex', ownerPackage(root), 'codex', 'bin/codex.js'], '"$@"; return 1'],+ ]+ for (const [what, args, owner] of cases) {+ const root = temp(), home = join(root, 'home')+ mkdirSync(home)+ const run = runCopy(root, home, args(root), owner)+ expect(run.stdout, what).toContain('not-copied')+ expect(existsSync(join(home, '.local', 'lib', 'node_modules', '@openai', 'codex')), what).toBe(false)+ expect(existsSync(join(home, '.local', 'lib', 'node_modules', '@openai', 'codex.next')), what).toBe(false)+ expect(existsSync(join(home, '.local', 'bin', 'codex')), what).toBe(false)+ }+ })++ it('leaves an engine the team account already has in place when a new copy is refused', () => {+ const root = temp(), home = join(root, 'home')+ mkdirSync(home)+ expect(runCopy(root, home, ['@openai/codex', ownerPackage(root), 'codex', 'bin/codex.js']).stdout).toContain('copied\n')+ const broken = temp()+ expect(runCopy(root, home, ['@openai/codex', ownerPackage(broken), 'codex', 'bin/gone.js']).stdout).toContain('not-copied')+ expect(execFileSync(join(home, '.local', 'bin', 'codex'), { encoding: 'utf8' })).toBe('engine\n')+ })+})+describe('the team account\'s engines, on a slow network', () => {// Scholes, 2026-11-04: a new Mac waited about 7 minutes after the password, nothing on screen saying why. Claude// Code and Codex are ~320 MB from npm with an empty cache, and nothing bounded it.@@ -231,7 +344,8 @@ describe('the team account\'s engines, on a slow network', () => {it('says each step, as the owner, in the stage the owner\'s Harness reads, before the step runs', () => {const script = buildSetupScript(input())expect(script).toContain(`step() { printf '%s\\n' "$1" | as_owner /bin/sh -c ${sh(WRITE_PRIVATE)} sh "$STAGE/progress" >/dev/null 2>&1 || true; }`)- const order = ['account', 'home', 'privacy', 'runtime', 'engines', 'sign-in', 'daemon'].map((name) => script.indexOf(`\nstep ${name}\n`))+ // The npm step is said only when an engine is left for it, inside its own `if`.+ const order = ['account', 'home', 'privacy', 'runtime', ' engines', 'sign-in', 'daemon'].map((name) => script.indexOf(`\nstep ${name.trim()}\n`.replace('\nstep', name.startsWith(' ') ? '\n step' : '\nstep')))for (const at of order) expect(at).toBeGreaterThan(0)expect([...order].sort((a, b) => a - b)).toEqual(order)expect(order[4]).toBeLessThan(script.indexOf(`as_team /bin/sh -c ${sh(TEAM_ENGINES_INSTALL)}`))diff --git a/cli/src/team/script.ts b/cli/src/team/script.tsindex 7fe548589..06734984c 100644--- a/cli/src/team/script.ts+++ b/cli/src/team/script.ts@@ -148,6 +148,30 @@ export interface SetupScriptInput {mintEnv: Record<string, string>/** `missing`: hand over a sign-in only when the team account has none. `always`: a new one regardless. */signIn: 'missing' | 'always'+ /** The owner's own installed Claude Code and Codex (./engines.ts `ownerEngineCopies`), copied in place of npm (#3169). */+ engineCopies?: readonly EngineCopy[]+}++/** One engine the owner has installed as npm leaves one: its package folder, and the command npm links to it. */+export interface EngineCopy {+ packageName: string+ dir: string+ bin: string+ /** The command's file inside the package, as its package.json `bin` names it, relative and plain. */+ binPath: string+}++const PLAIN_RELATIVE = /^[A-Za-z0-9_][A-Za-z0-9_.-]*(\/[A-Za-z0-9_][A-Za-z0-9_.-]*)*$/++/** A copy whose every value setup can quote plainly: one of the team's engines, by its own package and command. */+export function checkEngineCopy(copy: EngineCopy): EngineCopy {+ const engine = TEAM_ENGINES.find((e) => e.packageName === copy.packageName)+ if (!engine) throw new Error(`not an engine of the team account: ${JSON.stringify(copy.packageName)}`)+ if (copy.bin !== engine.engine) throw new Error(`not the command of ${engine.name}: ${JSON.stringify(copy.bin)}`)+ if (!PLAIN_RELATIVE.test(copy.binPath) || copy.binPath.split('/').some((part) => part === '..' || part === '.') || copy.binPath.length > 200) {+ throw new Error(`not a plain path inside the package: ${JSON.stringify(copy.binPath)}`)+ }+ return { packageName: engine.packageName, dir: checkPath(copy.dir, `${engine.name} folder`), bin: engine.engine, binPath: copy.binPath }}const basename = (path: string): string => path.slice(path.lastIndexOf('/') + 1)@@ -235,6 +259,59 @@ export const TEAM_ENGINES_INSTALL = ['done',].join('\n')+/**+ * The team account's side of copying one of the owner's installed engines (#3169: npm took 4 min 18 s of a 4 min 35 s+ * setup on this Mac; copying the two packages took 2.3 s). Run as the team account, never as root. Positional: the mode,+ * the home, the package, its command and the command's file inside it.+ * - `unpack` reads a tar of the package on its input into `<package>.next` in the team's npm prefix, and keeps it only when+ * it is that package with its command there, a file and not a link (security review 1 of #3124), executable to the+ * team account. tar refuses to write outside the folder or through a link, and as this account sets no owner or set-id bit.+ * - `commit` puts it in place of the one there, and links the command as npm does, relatively.+ * - `discard` removes what `unpack` left.+ */+export const TEAM_ENGINE_COPY = [+ 'set -eu',+ 'umask 022',+ 'mode=$1; home=$2; pkg=$3; name=$4; file=$5',+ 'dest="$home/.local/lib/node_modules/$pkg"; bin="$home/.local/bin"',+ 'case $mode in',+ 'unpack)',+ ' mkdir -p "${dest%/*}" "$bin"',+ ' rm -rf "$dest.next"; mkdir "$dest.next"',+ ' /usr/bin/tar -C "$dest.next" -xf - || { rm -rf "$dest.next"; exit 1; }',+ // The package's own name, as npm wrote it: what the owner has there is that engine, not something else by its folder.+ ' grep -Eq "\\"name\\"[[:space:]]*:[[:space:]]*\\"$pkg\\"" "$dest.next/package.json" 2>/dev/null \\',+ ' && [ ! -L "$dest.next/$file" ] && [ -f "$dest.next/$file" ] && [ -x "$dest.next/$file" ] || { rm -rf "$dest.next"; exit 1; } ;;',+ 'commit)',+ ' [ -d "$dest.next" ] || exit 1',+ ' rm -rf "$dest"; mv "$dest.next" "$dest"',+ ' ln -sfn "../lib/node_modules/$pkg/$file" "$bin/$name" ;;',+ 'discard)',+ ' rm -rf "$dest.next" ;;',+ '*) exit 2 ;;',+ 'esac',+].join('\n')++/**+ * `copy_engine PACKAGE FOLDER COMMAND FILE`, inside the setup script, with as_owner, as_team, $RT and $TEAM_HOME: the+ * owner's tar of their package piped into the team account's (TEAM_ENGINE_COPY), so root reads nothing of the owner's and+ * writes nothing of the team account's. The owner's tar failing part-way (a file it could not read) is noted in root's own+ * $RT, where neither account can write, and the copy is discarded rather than kept short of a file. False when not copied:+ * npm installs it then.+ */+export const TEAM_ENGINE_COPY_FN = [+ 'copy_engine() {',+ ' : > "$RT/engine-copy"',+ ` if { as_owner /usr/bin/tar -C "$2" -cf - . 2>/dev/null || echo failed > "$RT/engine-copy"; } \\`,+ ` | as_team /bin/sh -c ${sh(TEAM_ENGINE_COPY)} sh unpack "$TEAM_HOME" "$1" "$3" "$4" && [ ! -s "$RT/engine-copy" ]; then`,+ ` as_team /bin/sh -c ${sh(TEAM_ENGINE_COPY)} sh commit "$TEAM_HOME" "$1" "$3" "$4" && say "copied $1 for the team account" && return 0`,+ ' fi',+ ` as_team /bin/sh -c ${sh(TEAM_ENGINE_COPY)} sh discard "$TEAM_HOME" "$1" "$3" "$4" || true`,+ ' say "could not copy $1 for the team account; npm installs it"',+ ' return 1',+ '}',+].join('\n')+/*** The team account's password. macOS lists only an account with one: macOS 26 hides an account whose password is `*`* from Users & Groups. A random one, made here and forgotten: never printed, logged or stored, and never a process's@@ -301,11 +378,44 @@ function checkedSetup(input: SetupScriptInput) {ownerCli: checkPath(input.ownerCli, 'owner CLI'),mintEnv: Object.entries(checkEnv(input.mintEnv)).map(([name, value]) => sh(`${name}=${value}`)).join(' '),paths: teamPaths(home),+ engineCopies: (input.engineCopies ?? []).map(checkEngineCopy),}}+/**+ * Steps 5a and 5b of the Mac's setup: the owner's installed engines copied, then npm for each one not copied. Each engine+ * is named once in the script, quoted, from ./engines.ts.+ */+function engineSteps(copies: readonly EngineCopy[]): string[] {+ const lines = TEAM_ENGINES.map(({ engine }) => `copied_${engine}=`)+ if (copies.length) {+ lines.push(+ 'step copy-engines',+ '# 5a. Claude Code and Codex as this Mac already has them (#3169): the owner\'s own install, copied in seconds instead of',+ '# downloaded again. None of the owner\'s sign-ins is in it: those live outside the package folders.',+ TEAM_ENGINE_COPY_FN,+ ...copies.map((copy) => {+ const { engine } = TEAM_ENGINES.find((e) => e.packageName === copy.packageName)!+ return `if copy_engine ${[copy.packageName, copy.dir, copy.bin, copy.binPath].map(sh).join(' ')}; then copied_${engine}=1; fi`+ }),+ )+ }+ lines.push(+ '# 5b. What was not copied, installed by the team account itself into its own home: the owner\'s copies are inside the',+ '# owner\'s private home. None of the owner\'s sign-ins is copied; the owner signs them in once (harness team status).',+ 'set --',+ ...TEAM_ENGINES.map(({ engine, packageName }) => `[ -n "$copied_${engine}" ] || set -- "$@" ${sh(packageName)}`),+ 'if [ $# -gt 0 ]; then',+ ' step engines',+ ` as_team /bin/sh -c ${sh(TEAM_ENGINES_INSTALL)} sh "$TEAM_HOME" "$NODE_NAME" "$@" || true`,+ 'fi',+ )+ return lines+}+export function buildSetupScript(input: SetupScriptInput): string {- const { user, owner, home, ownerHome, stage, nodeDir, nodeName, tmuxDir, tmuxName, cliDir, ownerNode, ownerCli, mintEnv, paths } = checkedSetup(input)+ const { user, owner, home, ownerHome, stage, nodeDir, nodeName, tmuxDir, tmuxName, cliDir, ownerNode, ownerCli, mintEnv, paths, engineCopies } =+ checkedSetup(input)const lines = ['#!/bin/sh','# Harness Team account setup (cli/src/team/script.ts), run once as root behind the macOS administrator prompt.',@@ -431,10 +541,7 @@ export function buildSetupScript(input: SetupScriptInput): string {'chmod 755 "$RT"',`as_team /bin/sh -c ${sh(TEAM_COPY)} sh "$RT" "$TEAM_HOME" "$NODE_NAME" "$TMUX_NAME"`,'',- 'step engines',- '# 5b. Claude Code and Codex, installed by the team account itself into its own home: the owner\'s copies are inside the',- '# owner\'s private home. None of the owner\'s sign-ins is copied; the owner signs them in once (harness team status).',- `as_team /bin/sh -c ${sh(TEAM_ENGINES_INSTALL)} sh "$TEAM_HOME" "$NODE_NAME" ${TEAM_ENGINES.map((e) => sh(e.packageName)).join(' ')} || true`,+ ...engineSteps(engineCopies),'','# 6. What setup made (root\'s), and the team account\'s status folder, which the owner can read.',// A folder setup made says so, so that removal takes it away again once it is empty, and never one made by anything else.diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex f2935a033..f5238c09d 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -107,6 +107,7 @@ import '../super_tabs/backend_transport.dart';import '../super_tabs/client.dart';import '../super_tabs/controller.dart';import '../super_tabs/join_machine.dart';+import '../super_tabs/join_seen.dart';import '../super_tabs/identity.dart' show superTabMachineName;import '../super_tabs/view_store.dart';import '../super_tabs/notifications.dart'@@ -1952,6 +1953,12 @@ class AppNotifier extends ChangeNotifier {currentUser?.id == null) {return;}+ // However the person joined, this computer is added once to each Swarm+ // new here (task #3160).+ _addMachineWhereNew(+ [for (final tab in tabs) tab.id],+ {for (final swarm in swarms) ?swarm.superTabId, ...hidden},+ );var changed = false;// Membership and names for the closed list: a tab hidden before a// restart has no open view to take its name from.@@ -2705,6 +2712,29 @@ class AppNotifier extends ChangeNotifier {Stream<SwarmJoinedMachine> get joinedMachines => _joinedMachines.stream;final _joinAdding = <String>{};+ /// The Swarms the join's add already ran or was decided for, per account on+ /// this computer (super_tabs/join_seen.dart). Null without a local store:+ /// nothing is added that could not be remembered.+ SwarmJoinSeen? get _joinRecord {+ final store = localStore;+ if (store == null) return null;+ if (!identical(store, _joinSeen?.store)) _joinSeen = SwarmJoinSeen(store);+ return _joinSeen;+ }++ SwarmJoinSeen? _joinSeen;+ Future<void>? _joinPass;++ /// Swarms tried in this run where the person is not known to be a+ /// collaborator or owner (a viewer, not listed yet, or a Swarm that could+ /// not be read): tried again at the next launch, never on every discovery+ /// (review of #3115).+ final _joinPassed = <String>{};++ /// The pass discovery started last, for tests to wait on.+ @visibleForTesting+ Future<void> get joinAddPassForTest => _joinPass ?? Future.value();+/// A Swarm [tabId] just joined at this computer, as [role]: adds this/// computer to it with Add machine's defaults (super_tabs/join_machine.dart),/// then offers the Harness Team account, the one step macOS asks a password@@ -2716,6 +2746,49 @@ class AppNotifier extends ChangeNotifier {bool alreadyMember = false,}) async {if (alreadyMember || role != 'collaborator') return;+ await _addMachineToSwarm(tabId, joined: true);+ }++ /// Swarm discovery's list ([listed]), however each was joined: a domain+ /// auto-join, a Workspace-open join, a join on the phone or the web+ /// (Scholes, 2026-11-05, task #3160). The join's add runs once for each+ /// Swarm new here; [knownHere], the Swarms open or hidden on this computer,+ /// are taken as seen the first time, even by a pass that cannot add yet+ /// (this computer's own row not known). One pass at a time: a discovery+ /// while one runs leaves its list to the next.+ void _addMachineWhereNew(List<String> listed, Set<String> knownHere) {+ final record = _joinRecord;+ final account = currentUser?.id;+ if (_joinPass != null || record == null || account == null) return;+ _joinPass = () async {+ try {+ final fresh = await record.fresh(account, listed, knownHere: knownHere);+ for (final tabId in fresh) {+ if (_disposed ||+ currentUser?.id != account ||+ _teamAccountHere() == null) {+ return;+ }+ if (_joinPassed.contains('$account/$tabId')) continue;+ await _addMachineToSwarm(tabId, joined: false);+ }+ } catch (error) {+ appLog.info('super-tabs', 'joined Swarms not checked: $error');+ } finally {+ _joinPass = null;+ }+ }();+ }++ /// The join's add for one Swarm this account is in. The person's role is+ /// read from the Swarm itself: a viewer's Swarm is neither added nor+ /// recorded, so it is asked about again; an owner's is recorded and left.+ /// A step that fails for a collaborator shows them a note saying what to do+ /// (task #3160). [joined]: they joined it at this computer just now, so+ /// they are known to be one before the Swarm is read; a Swarm only listed+ /// that cannot be read says nothing yet, since they may be a viewer, and is+ /// asked about again on the next discovery.+ Future<void> _addMachineToSwarm(String tabId, {required bool joined}) async {final here = _teamAccountHere();final accountId = currentUser?.id;if (here == null || accountId == null || !_joinAdding.add(tabId)) return;@@ -2723,30 +2796,72 @@ class AppNotifier extends ChangeNotifier {!_disposed &&status == AppStatus.authenticated &¤tUser?.id == accountId;+ final machineName = stateOf(here)?.machine.displayName ?? 'This computer';+ // Opened only for this add: let go after it, unless the person went to it+ // meanwhile, so it does not keep polling unseen (review of #3115).+ final openedHere = superTabs.peek(tabId) == null;+ var collaborator = joined;+ void failed(String problem) {+ if (!collaborator || !current()) return;+ _joinedMachines.add(+ SwarmJoinedMachine(+ tabId: tabId,+ swarmName: superTabName(tabId) ?? 'the Swarm',+ machineId: here,+ machineName: machineName,+ problem: problem,+ ),+ );+ }+try {final c = await superTabs.open(tabId);if (!current()) return;await c.refresh();- final note =- await SwarmJoinMachine(- machineRequest: superTabMachineRequest,- readResources: readMachineResources,- wake: wakeSuperTabHost,- ).add(- c,- machineId: here,- machineName: stateOf(here)?.machine.displayName ?? 'This computer',- current: current,- );+ if (!current()) return;+ final snapshot = c.snapshot;+ if (snapshot == null) {+ appLog.info('super-tabs', 'machine not added on join: unread Swarm');+ if (!collaborator) _joinPassed.add('$accountId/$tabId');+ failed('Could not reach the Swarm. Add this computer from Machines.');+ return;+ }+ final role = snapshot.people+ .where((p) => p.id == accountId)+ .firstOrNull+ ?.role;+ if (role == null || role == 'viewer') {+ _joinPassed.add('$accountId/$tabId');+ return;+ }+ collaborator = role == 'collaborator';+ await _joinRecord?.mark(accountId, tabId);+ if (!collaborator) return;+ final note = await SwarmJoinMachine(+ machineRequest: superTabMachineRequest,+ readResources: readMachineResources,+ wake: wakeSuperTabHost,+ ).add(c, machineId: here, machineName: machineName, current: current);if (note == null || !current()) return;_joinedMachines.add(note);// Joined by the person at this computer: the system asks once for the// Harness Team account (cli/src/team/autoSetup.ts).- if (note.added) await offerTeamAccount('join', tabId: tabId);+ if (!note.added) return;+ if (!await offerTeamAccount('join', tabId: tabId) && current()) {+ _joinedMachines.add(note.withoutTeamOffer());+ }} catch (error) {appLog.info('super-tabs', 'machine not added on join: $error');+ if (!collaborator) _joinPassed.add('$accountId/$tabId');+ failed('Could not add this computer. Add it from Machines.');} finally {_joinAdding.remove(tabId);+ if (openedHere &&+ !_disposed &&+ activeSwarm.superTabId != tabId &&+ superTabs.peek(tabId) != null) {+ superTabs.release(tabId);+ }}}diff --git a/desktop/lib/super_tabs/backlog.dart b/desktop/lib/super_tabs/backlog.dartindex bc2f9103d..5a571f9d9 100644--- a/desktop/lib/super_tabs/backlog.dart+++ b/desktop/lib/super_tabs/backlog.dart@@ -122,15 +122,36 @@ List<SuperTabConversation> superTabProjectTasks(];}-/// A task's priority as its title marks it (task #2774).+/// A task's priority (task #3117): P0 goes first wherever work is ordered.enum SuperTabTaskPriority {- urgent('URGENT'),- high('HIGH');+ p0('P0', 'Hotfix: something shipped is broken'),+ p1('P1', 'Needed by users soon'),+ p2('P2', 'Planned goal'),+ p3('P3', 'Tools, docs or process');- const SuperTabTaskPriority(this.badge);+ const SuperTabTaskPriority(this.badge, this.meaning);++ /// What its badge says, which is also its value on the wire: "P0".final String badge;+ final String meaning;++ /// The priority [value] names ("P0" to "P3"); null for anything else.+ static SuperTabTaskPriority? named(Object? value) =>+ values.where((p) => p.badge == value).firstOrNull;}+/// [task]'s effective priority: its field, else its title's marker (a task+/// from before the field: URGENT is P0, high is P1), else P2.+SuperTabTaskPriority superTabTaskPriority(SuperTabConversation task) =>+ SuperTabTaskPriority.named(task.priority) ??+ superTabTitlePriority(task.title).priority ??+ SuperTabTaskPriority.p2;++/// Whether [group] carries a priority: a task, not a step or a private chat+/// (a Buddy chat is one). The project's chat is the caller's to leave out.+bool superTabCarriesPriority(SuperTabConversation group) =>+ !superTabIsStep(group) && group.audience == null && !group.isBuddyChat;+final _leading = RegExp(r'^\s*URGENT\b\s*:?\s*', caseSensitive: false);final _trailing = RegExp(r'\s*\((?:[^()]*,\s*)?(urgent|high)(?:\s+priority)?\)\s*$',@@ -138,9 +159,9 @@ final _trailing = RegExp();/// [title]'s priority and the title without its marker (Scholes's mockup,-/// task #2774). Tasks carry no priority field: the PM writes it into the-/// title, as a leading URGENT or a closing "(Name, high)". Any other-/// parenthetical stays.+/// task #2774). Before the priority field (task #3117) the PM wrote it into+/// the title, as a leading URGENT (P0) or a closing "(Name, high)" (P1); the+/// shown title drops the marker either way. Any other parenthetical stays.({SuperTabTaskPriority? priority, String title}) superTabTitlePriority(String title,) {@@ -148,7 +169,7 @@ final _trailing = RegExp(final rest = title.substring(match.end);if (rest.isNotEmpty) {return (- priority: SuperTabTaskPriority.urgent,+ priority: SuperTabTaskPriority.p0,title: rest[0].toUpperCase() + rest.substring(1),);}@@ -158,8 +179,8 @@ final _trailing = RegExp(if (rest.isNotEmpty) {return (priority: match.group(1)!.toLowerCase() == 'urgent'- ? SuperTabTaskPriority.urgent- : SuperTabTaskPriority.high,+ ? SuperTabTaskPriority.p0+ : SuperTabTaskPriority.p1,title: rest,);}diff --git a/desktop/lib/super_tabs/backlog_view.dart b/desktop/lib/super_tabs/backlog_view.dartindex 610d641a7..1aa38e1f3 100644--- a/desktop/lib/super_tabs/backlog_view.dart+++ b/desktop/lib/super_tabs/backlog_view.dart@@ -12,6 +12,7 @@ import '../widgets/desktop_chrome.dart';import '../widgets/laid_out_list.dart';import '../widgets/swarm_search_field.dart';import 'backlog.dart';+import 'chip.dart';import 'controller.dart';import 'machine_status.dart';import 'model.dart';@@ -232,6 +233,16 @@ class _SuperTabBacklogViewState extends State<SuperTabBacklogView>compare: (a, b) =>(b.shippedAt ?? DateTime(0)).compareTo(a.shippedAt ?? DateTime(0)),);+ // P0 first in every group (task #3117); a stable sort keeps the order+ // above within a priority.+ for (final tasks in byGroup.values) {+ mergeSort(+ tasks,+ compare: (a, b) =>+ superTabTaskPriority(a).index+ .compareTo(superTabTaskPriority(b).index),+ );+ }final entries = <Object>[];for (final MapEntry(key: group, value: tasks) in byGroup.entries) {if (tasks.isEmpty) continue;@@ -579,7 +590,7 @@ class _HeadingRow extends StatelessWidget {style: _label(color: DesktopChrome.foreground),),const SizedBox(width: grid.AppDesktop.controlGap),- _Chip(text: '${heading.count}'),+ SuperTabChip(text: '${heading.count}'),const SizedBox(width: grid.AppDesktop.controlGap),Expanded(child: Text(@@ -598,64 +609,6 @@ class _HeadingRow extends StatelessWidget {}}-/// A small rounded label: a count, a project, a badge or a pull request.-class _Chip extends StatelessWidget {- const _Chip({- required this.text,- this.color,- this.fill,- this.outlined = false,- this.leading,- this.bold = false,- });- final String text;- final Color? color, fill;- final bool outlined, bold;- final Widget? leading;-- @override- Widget build(BuildContext context) {- final ink = color ?? DesktopChrome.muted;- return Container(- padding: const EdgeInsets.symmetric(- horizontal: grid.AppDesktop.menuInset,- vertical: grid.AppDesktop.listRowGap,- ),- decoration: BoxDecoration(- color: fill ?? (outlined ? null : grid.AppSurface.wellFill),- border: outlined ? Border.all(color: grid.AppPalette.divider) : null,- borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- if (leading case final leading?) ...[- leading,- const SizedBox(width: grid.AppDesktop.badgeInset),- ],- Text(- text,- style: DesktopChrome.metadata(color: ink).copyWith(- fontWeight: bold ? FontWeight.w600 : null,- letterSpacing: bold ? .6 : null,- ),- ),- ],- ),- );- }-}--/// A tinted chip: [color] ink on a wash of it.-_Chip _tinted(String text, Color color, {Widget? leading, bool bold = false}) =>- _Chip(- text: text,- color: color,- fill: color.withValues(alpha: .14),- leading: leading,- bold: bold,- );-/// One task as a card row (Scholes's mockup): its group's mark; its number,/// priority and title; then agent, machine, state and project; at the right/// how long since it changed, its pull request with its checks or merge, and@@ -708,7 +661,7 @@ class _Row extends StatelessWidget {};return KeyedSubtree(key: ValueKey('super-backlog-pr-${task.id}'),- child: _tinted(+ child: superTabTintedChip(['PR $number', if (words.isNotEmpty) words].join(' · '),color,leading: SvgPicture.asset(@@ -742,7 +695,7 @@ class _Row extends StatelessWidget {if (status != null) status.reason,].join(' · ');final project = snapshot.projectById(task.projectId)?.name;- final (:priority, :title) = superTabTitlePriority(task.title);+ final title = superTabTitlePriority(task.title).title;final url = _pullRequest(task);final approved = url != null && facts?.of(url)?.review == 'APPROVED';final pullRequest = _pullRequestChip();@@ -804,14 +757,7 @@ class _Row extends StatelessWidget {children: [if (task.number case final number?)Text('#$number', style: muted),- if (priority != null)- _tinted(- priority.badge,- priority == SuperTabTaskPriority.urgent- ? grid.AppPalette.usageCritical- : grid.AppPalette.warn,- bold: true,- ),+ SuperTabPriorityBadge(superTabTaskPriority(task)),Text(title,style: DesktopChrome.control(medium: true),@@ -826,9 +772,12 @@ class _Row extends StatelessWidget {children: [Text(details, style: muted),if (project != null)- _Chip(text: project, outlined: true),+ SuperTabChip(text: project, outlined: true),if (approved)- _tinted('Approved', grid.AppPalette.online),+ superTabTintedChip(+ 'Approved',+ grid.AppPalette.online,+ ),],),],diff --git a/desktop/lib/super_tabs/chip.dart b/desktop/lib/super_tabs/chip.dartnew file mode 100644index 000000000..f708d6f50--- /dev/null+++ b/desktop/lib/super_tabs/chip.dart@@ -0,0 +1,118 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_icons.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../widgets/desktop_chrome.dart';+import 'backlog.dart';++/// A small rounded label: a count, a project, a badge or a pull request.+class SuperTabChip extends StatelessWidget {+ const SuperTabChip({+ super.key,+ required this.text,+ this.color,+ this.fill,+ this.outlined = false,+ this.leading,+ this.trailing,+ this.bold = false,+ });+ final String text;+ final Color? color, fill;+ final bool outlined, bold;+ final Widget? leading, trailing;++ @override+ Widget build(BuildContext context) {+ final ink = color ?? DesktopChrome.muted;+ return Container(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.menuInset,+ vertical: grid.AppDesktop.listRowGap,+ ),+ decoration: BoxDecoration(+ color: fill ?? (outlined ? null : grid.AppSurface.wellFill),+ border: outlined ? Border.all(color: grid.AppPalette.divider) : null,+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (leading case final leading?) ...[+ leading,+ const SizedBox(width: grid.AppDesktop.badgeInset),+ ],+ Text(+ text,+ style: DesktopChrome.metadata(color: ink).copyWith(+ fontWeight: bold ? FontWeight.w600 : null,+ letterSpacing: bold ? .6 : null,+ ),+ ),+ if (trailing case final trailing?) ...[+ const SizedBox(width: grid.AppDesktop.listRowGap),+ trailing,+ ],+ ],+ ),+ );+ }+}++/// A tinted chip: [color] ink on a wash of it.+SuperTabChip superTabTintedChip(+ String text,+ Color color, {+ Key? key,+ Widget? leading,+ Widget? trailing,+ bool bold = false,+}) => SuperTabChip(+ key: key,+ text: text,+ color: color,+ fill: color.withValues(alpha: .14),+ leading: leading,+ trailing: trailing,+ bold: bold,+);++/// [priority]'s ink (task #3117): P0 critical, P1 a warning, P2 and P3 quiet.+Color superTabPriorityColor(SuperTabTaskPriority priority) =>+ switch (priority) {+ SuperTabTaskPriority.p0 => grid.AppPalette.usageCritical,+ SuperTabTaskPriority.p1 => grid.AppPalette.warn,+ SuperTabTaskPriority.p2 || SuperTabTaskPriority.p3 => DesktopChrome.muted,+ };++/// A task's priority as a tinted badge, "P0", leading a card's caption, a+/// Backlog row's title and the task header's title. With [menu] it carries a+/// ▾, for the header's button that opens the priority menu.+class SuperTabPriorityBadge extends StatelessWidget {+ const SuperTabPriorityBadge(this.priority, {super.key, this.menu = false});++ final SuperTabTaskPriority priority;+ final bool menu;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final color = superTabPriorityColor(priority);+ return Semantics(+ label: 'Priority ${priority.badge}, ${priority.meaning}',+ excludeSemantics: true,+ child: superTabTintedChip(+ priority.badge,+ color,+ bold: true,+ trailing: menu+ ? Icon(+ AppIcons.chevronDown,+ size: AppIcons.inlineSize,+ color: color,+ )+ : null,+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 6b6c08e8e..cfb087e63 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -13,6 +13,7 @@ import '../measurement/speed_marks.dart';import '../state/harness_attachments.dart';import 'attachment_upload.dart';import 'avatar_upload.dart';+import 'backlog.dart' show SuperTabTaskPriority;import 'message_link.dart';import 'identity.dart' show superTabMachineName;import 'machine_status.dart' show kSuperTabMachineOfflineAfter;@@ -3174,6 +3175,23 @@ class SuperTabController extends ChangeNotifier {: operationError ?? 'Another change is on its way. Try again.';}+ /// Sets task [taskId]'s priority for everyone (backend `work.priority`,+ /// task #3117): null once done, else why it was refused. Only a person or+ /// the project's PM may; an older server refuses the command as unknown.+ Future<String?> setTaskPriority(+ String taskId,+ SuperTabTaskPriority priority,+ ) async {+ final done = await command({+ 'type': 'work.priority',+ 'conversationId': taskId,+ 'priority': priority.badge,+ });+ 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`diff --git a/desktop/lib/super_tabs/join_machine.dart b/desktop/lib/super_tabs/join_machine.dartindex 1ac5424c4..0266752c2 100644--- a/desktop/lib/super_tabs/join_machine.dart+++ b/desktop/lib/super_tabs/join_machine.dart@@ -67,6 +67,8 @@ const _swarmEngines = {'claude', 'codex'};/// This computer, added to a Swarm by the join that just let its person in/// (Scholes, 2026-10-29): what [SwarmJoinMachine.add] did, for the note the/// person sees. [problem]: why it was not added, in a sentence for them.+/// [teamProblem]: it was added, but its Harness Team account could not be+/// offered, and where to set it up (task #3160).class SwarmJoinedMachine {const SwarmJoinedMachine({required this.tabId,@@ -74,11 +76,21 @@ class SwarmJoinedMachine {required this.machineId,required this.machineName,this.problem,+ this.teamProblem,});final String tabId, swarmName, machineId, machineName;- final String? problem;+ final String? problem, teamProblem;bool get added => problem == null;++ /// The same machine, added, whose Team account offer failed.+ SwarmJoinedMachine withoutTeamOffer() => SwarmJoinedMachine(+ tabId: tabId,+ swarmName: swarmName,+ machineId: machineId,+ machineName: machineName,+ teamProblem: 'Set it up from Machines.',+ );}/// Adds this computer to a Swarm its person just joined, with Add machine'sdiff --git a/desktop/lib/super_tabs/join_machine_note.dart b/desktop/lib/super_tabs/join_machine_note.dartindex 8046febd8..93250b813 100644--- a/desktop/lib/super_tabs/join_machine_note.dart+++ b/desktop/lib/super_tabs/join_machine_note.dart@@ -24,10 +24,18 @@ void showJoinedMachineNote(final here = (operatingSystem ?? RuntimePlatform.operatingSystem) == 'macos'? 'This Mac': 'This computer';- final text = note.added- ? '$here was added to ${note.swarmName}. Teammates\' agents run here '- 'only in Harness Team, never as you.'- : '$here was not added to ${note.swarmName}. ${note.problem}';+ final text = switch (note) {+ SwarmJoinedMachine(added: false) =>+ '$here was not added to ${note.swarmName}. ${note.problem}',+ SwarmJoinedMachine(teamProblem: final String problem) =>+ '$here was added to ${note.swarmName}, but Harness could not offer its '+ 'Harness Team account. $problem',+ _ =>+ '$here was added to ${note.swarmName}. Teammates\' agents run here '+ 'only in Harness Team, never as you.',+ };+ // Pause and Remove came with the note that it was added.+ final undo = note.added && note.teamProblem == null;messenger.showSnackBar(SnackBar(key: const Key('swarm-joined-machine-note'),@@ -36,7 +44,7 @@ void showJoinedMachineNote(content: Row(children: [Expanded(child: Text(text)),- if (note.added) ...[+ if (undo) ...[const SizedBox(width: 12),_NoteAction(key: const Key('swarm-joined-machine-pause'),diff --git a/desktop/lib/super_tabs/join_seen.dart b/desktop/lib/super_tabs/join_seen.dartnew file mode 100644index 000000000..d8da4292a--- /dev/null+++ b/desktop/lib/super_tabs/join_seen.dart@@ -0,0 +1,106 @@+import 'dart:async';+import 'dart:convert';++import '../core/local_key_value_store.dart';++/// The Swarms this computer already decided the join's add for+/// (`AppNotifier.addMachineOnJoin`), per account (Scholes, 2026-11-05, task+/// #3160): a domain auto-join, a Workspace-open join or a join on the phone or+/// web reached no Desktop join flow, so discovery asks here which of the Swarms+/// it lists are new on this computer, and the add runs once for each.+///+/// The first pass for an account takes the Swarms already open or hidden here+/// as seen, so an update never adds a long-time member's computer to Swarms+/// they chose not to add it to. Each pass drops the Swarms no longer listed:+/// joining one again is a new membership.+class SwarmJoinSeen {+ SwarmJoinSeen(this.store);++ final LocalKeyValueStore store;++ static String keyFor(String account) => 'swarm_join_seen.$account';++ final _records = <String, Future<_Record>>{};++ /// Recorded in this run, which a list read just before may not show yet.+ final _recent = <String, Set<String>>{};+ Future<void> _writes = Future.value();++ /// The Swarms of [listed] new for [account] on this computer, in their order.+ /// [knownHere]: the Swarms open or hidden here, taken as seen on the first+ /// pass.+ Future<List<String>> fresh(+ String account,+ List<String> listed, {+ required Set<String> knownHere,+ }) async {+ final record = await _load(account);+ final recent = _recent[account] ?? const {};+ var changed = false;+ if (!record.baseline) {+ record.baseline = true;+ record.seen.addAll(listed.where(knownHere.contains));+ changed = true;+ }+ final before = record.seen.length;+ record.seen.removeWhere(+ (id) => !listed.contains(id) && !recent.contains(id),+ );+ if (record.seen.length != before) changed = true;+ if (changed) await _save(account, record);+ return [+ for (final id in listed)+ if (!record.seen.contains(id)) id,+ ];+ }++ /// Records that the add was decided for [tabId]: it never runs there again+ /// for [account] on this computer.+ Future<void> mark(String account, String tabId) async {+ final record = await _load(account);+ (_recent[account] ??= {}).add(tabId);+ if (record.seen.add(tabId)) await _save(account, record);+ }++ Future<_Record> _load(String account) => _records[account] ??= _read(account);++ Future<_Record> _read(String account) async {+ try {+ final raw = await store.read(keyFor(account));+ if (raw == null) return _Record();+ final json = jsonDecode(raw) as Map<String, dynamic>;+ return _Record(+ baseline: json['baseline'] == true,+ seen: {+ for (final id in json['seen'] as List? ?? const [])+ if (id is String) id,+ },+ );+ } catch (_) {+ // Unreadable: taken as none, so the first pass sets it again.+ return _Record();+ }+ }++ /// One write at a time, each of the whole record as it is then. A write+ /// that fails is dropped: the record stays right in memory for this run and+ /// the next write carries it whole, and an add that runs again finds this+ /// computer already in the Swarm (review of #3115).+ Future<void> _save(String account, _Record record) => _writes = _writes+ .then(+ (_) => store.write(+ keyFor(account),+ jsonEncode({+ 'baseline': record.baseline,+ 'seen': [...record.seen],+ }),+ ),+ )+ .catchError((Object _) {});+}++class _Record {+ _Record({this.baseline = false, Set<String>? seen}) : seen = seen ?? {};+ bool baseline;+ final Set<String> seen;+}diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex 942911de3..ef39bb483 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -869,6 +869,27 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {/// or when it cannot say.({String state, String? detail})? _teamSetup;bool _teamSetupReading = false;++ /// This Mac's setup while it runs in the background (#3169), for its row's+ /// step and time left; null without the app's lock in the window.+ TeamSetupWatch? _setupWatch;++ void _followSetupWatch() {+ final app = widget.app;+ final watch = app == null ? null : TeamSetupWatch.of(app);+ if (identical(watch, _setupWatch)) return;+ _setupWatch?.removeListener(_setupMoved);+ _setupWatch = watch?..addListener(_setupMoved);+ }++ /// The row says the step as it moves, and what the daemon remembers once+ /// setup ends.+ void _setupMoved() {+ if (!mounted) return;+ _changed();+ if (_setupWatch?.running == false) unawaited(_readTeamSetup());+ }+SuperTabController get c => widget.controller;// Team agents only: a Buddy is listed nowhere, and its machine may be its// person's alone, outside the Swarm (backend buddyOnly).@@ -887,6 +908,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {void initState() {super.initState();c.machinesChanged.addListener(_machinesMoved);+ _followSetupWatch();unawaited(_readTeamSetup());if ((!kUnderTest || widget.readLocal != null) && widget.app != null) {_updateUsage();@@ -1008,6 +1030,10 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {final read = await app.teamSetupStatus();if (!mounted) return;_teamSetup = read;+ // Running and nobody following it (the app opened while it ran, or it+ // was started from a terminal): followed from here, so it ends in a+ // notice too.+ if (read?.state == 'running') TeamSetupWatch.of(app)?.follow();_changed();} finally {_teamSetupReading = false;@@ -1088,6 +1114,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {_timer?.cancel();_tick?.cancel();c.machinesChanged.removeListener(_machinesMoved);+ _setupWatch?.removeListener(_setupMoved);for (final beat in _rowBeats.values) {beat.dispose();}@@ -1364,6 +1391,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {/// Everything a machine's row, its tooltip and its details say of it, read once per build._MachineView _view(String id) {+ _followSetupWatch();final app = widget.app, snapshot = c.snapshot!;final shared = snapshot.pool(id);// The Mac's Harness Team account is part of its row: its agents are listed here, and everyone but the Mac's owner@@ -1545,8 +1573,13 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {app != null &&app.canSetUpTeamAccount &&app.stateOf(id)?.isLocalMachine == true;- // Its own person reads why: they cancelled, or setup failed and why.- final problem = setUpTeam+ // While setup runs, its step and the time left, and that the person may+ // go on working (#3169); otherwise its own person reads why: they+ // cancelled, or setup failed and why.+ final progress = setUpTeam ? _setupWatch?.line : null;+ final problem = progress != null+ ? '$progress\nKeep working. We\'ll tell you when it\'s ready.'+ : setUpTeam? superTabTeamSetupLine(_teamSetup) ?? line: line;return _MachineView(@@ -1556,7 +1589,8 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {name: name,problem: problem,history: superTabMachineHistory(shared, snapshot.people),- setUpTeam: setUpTeam,+ // Set up would ask for the password again while one setup runs.+ setUpTeam: setUpTeam && progress == null,setUpTeamLabel: superTabTeamSetupAction(_teamSetup),owner: person,contributor: contributor,diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 132ce6280..7a034bf8d 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -394,6 +394,7 @@ class SuperTabConversation {): null,queueRank = (row['queueRank'] as num?)?.toDouble(),+ priority = row['priority'] as String?,notBefore = DateTime.tryParse(row['notBefore'] as String? ?? ''),lastMessageSequence = (row['lastMessageSequence'] as num?)?.toInt() ?? 0,lastMainSequence = (row['lastMainSequence'] as num?)?.toInt(),@@ -497,6 +498,11 @@ class SuperTabConversation {/// places it (task_groups.dart).final double? queueRank;+ /// A task's priority as the server keeps it, `P0` to `P3` (backend+ /// taskPriority.ts); null on a step, a chat, and a task from before it,+ /// whose title may still mark one (`superTabTaskPriority`, backlog.dart).+ final String? priority;+/// 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;diff --git a/desktop/lib/super_tabs/task_card.dart b/desktop/lib/super_tabs/task_card.dartindex c2ff85372..2b20d4c3d 100644--- a/desktop/lib/super_tabs/task_card.dart+++ b/desktop/lib/super_tabs/task_card.dart@@ -7,9 +7,12 @@ import '../terminal/terminal_theme.dart';import '../terminal/terminal_theme_store.dart';import '../widgets/desktop_chrome.dart';import '../widgets/harness_activity_mark.dart';+import 'backlog.dart';+import 'chip.dart';/// One card of a project's Tasks view, on the Board and as a List row alike:-/// its title (up to [titleLines]), caption and shared activity mark.+/// its title (up to [titleLines]), its caption led by its [priority] badge+/// (task #3117), and its shared activity mark.////// On the Board it is a [tile] (task #2948): an inset tile set into its/// column's panel, one step less rounded than the panel, with no shadow.@@ -24,6 +27,7 @@ class SuperTabTaskCard extends StatelessWidget {required this.unread,required this.activity,required this.onOpen,+ this.priority,this.titleLines = 2,this.tile = false,this.selected = false,@@ -34,6 +38,7 @@ class SuperTabTaskCard extends StatelessWidget {final bool needsYou, unread;final HarnessActivity activity;final VoidCallback onOpen;+ final SuperTabTaskPriority? priority;final int titleLines;final bool tile, selected;final Widget? trailing;@@ -47,6 +52,7 @@ class SuperTabTaskCard extends StatelessWidget {selected: selected ? true : null,label: [title,+ if (priority case final priority?) 'Priority ${priority.badge}',caption,if (!needsYou)switch (activity) {@@ -86,12 +92,29 @@ class SuperTabTaskCard extends StatelessWidget {: FontWeight.w400,),),- if (caption.isNotEmpty)- Text(- caption,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: muted,+ if (priority != null || caption.isNotEmpty)+ Padding(+ padding: EdgeInsets.only(+ top: priority == null+ ? 0+ : grid.AppDesktop.listRowGap,+ ),+ child: Row(+ children: [+ if (priority case final priority?) ...[+ SuperTabPriorityBadge(priority),+ const SizedBox(width: grid.AppDesktop.menuInset),+ ],+ Flexible(+ child: Text(+ caption,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: muted,+ ),+ ),+ ],+ ),),],),diff --git a/desktop/lib/super_tabs/task_groups.dart b/desktop/lib/super_tabs/task_groups.dartindex f7bfa70fb..4dbf7a00f 100644--- a/desktop/lib/super_tabs/task_groups.dart+++ b/desktop/lib/super_tabs/task_groups.dart@@ -14,11 +14,18 @@ class SuperTabProposal {: messageId = answer['messageId'] as String,title = answer['title'] as String? ?? '',personId = answer['personId'] as String?,+ priority =+ SuperTabTaskPriority.named(answer['priority']) ??+ SuperTabTaskPriority.p2,at = DateTime.fromMillisecondsSinceEpoch((answer['at'] as num? ?? 0).toInt(),);final String messageId, title;final String? personId;++ /// What the task it asks for would be: the proposal's high, normal or low as+ /// P1, P2 or P3 (task #3117); P2 when an older server sends none.+ final SuperTabTaskPriority priority;final DateTime at;}@@ -150,6 +157,13 @@ typedef SuperTabTaskEntry = ({String? state,});+/// [entry]'s priority: its task's effective one, or its proposal's.+SuperTabTaskPriority superTabEntryPriority(SuperTabTaskEntry entry) =>+ switch (entry.task) {+ final task? => superTabTaskPriority(task),+ null => entry.proposal!.priority,+ };+/// 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) =>@@ -168,9 +182,10 @@ List<SuperTabConversation> superTabQueueOrder() => [...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.+/// column, in order and empty or not, each listing by priority, P0 first+/// (task #3117); within a priority 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 [],@@ -211,6 +226,9 @@ Map<SuperTabTaskColumn, List<SuperTabTaskEntry>> superTabTaskBoard(SuperTabTaskEntry a,SuperTabTaskEntry b,) {+ final priority = superTabEntryPriority(a).index+ .compareTo(superTabEntryPriority(b).index);+ if (priority != 0) return priority;if (a.needsYou != b.needsYou) return a.needsYou ? -1 : 1;final (x, y) = (a.task, b.task);if (x == null || y == null) return 0;diff --git a/desktop/lib/super_tabs/tasks_view.dart b/desktop/lib/super_tabs/tasks_view.dartindex 64858c7d7..c5c1e750e 100644--- a/desktop/lib/super_tabs/tasks_view.dart+++ b/desktop/lib/super_tabs/tasks_view.dart@@ -382,8 +382,12 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {final id = task?.id ?? entry.proposal!.messageId;return SuperTabTaskCard(key: ValueKey('super-task-card-$id'),- title: task?.title ?? entry.proposal!.title,+ // A legacy marker is the badge now: the title drops it.+ title: task == null+ ? entry.proposal!.title+ : superTabTitlePriority(task.title).title,caption: _caption(entry, now),+ priority: superTabEntryPriority(entry),needsYou: entry.needsYou,unread: task != null && widget.controller.unreadShown(task),activity: _activity(entry),@@ -512,8 +516,17 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {/// 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.+ /// A card moves only among those of its own priority (task #3117): one+ /// dropped past them stops at the edge of its band.Future<void> _move(List<SuperTabTaskEntry> ordered, int from, int to) async {- if (from == to || to < 0 || to >= ordered.length) return;+ if (to < 0 || to >= ordered.length) return;+ final priority = superTabEntryPriority(ordered[from]);+ final band = [+ for (final (i, e) in ordered.indexed)+ if (superTabEntryPriority(e) == priority) i,+ ];+ to = to.clamp(band.first, band.last);+ if (from == to) return;final ids = [for (final e in ordered) e.task!.id];final id = ids.removeAt(from);ids.insert(to, id);@@ -521,22 +534,31 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {_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).+ // The column lifts what needs the reader, and sorts by priority, so its+ // neighbours on screen are not its neighbours in the shared order: it+ // goes right before the first card of its priority under it that is not+ // lifted (reviews of #2883), or else right after the last of its priority+ // in the queue.+ final tasks = {for (final e in ordered) e.task!.id: e.task!};final queue = [- for (final task in superTabQueueOrder([for (final e in ordered) e.task!]))+ for (final task in superTabQueueOrder(tasks.values))if (task.id != id) task.id,];+ bool peer(String other) => superTabTaskPriority(tasks[other]!) == priority;final lifted = {for (final e in ordered)if (e.needsYou) e.task!.id,};final below = ids.skip(to + 1)- .where((other) => !lifted.contains(other))+ .where((other) => peer(other) && !lifted.contains(other)).firstOrNull;- final at = below == null ? queue.length : queue.indexOf(below);+ final at = below != null+ ? queue.indexOf(below)+ : switch (queue.lastIndexWhere(peer)) {+ -1 => queue.length,+ final last => last + 1,+ };final refused = await widget.controller.queueTask(id,after: at == 0 ? null : queue[at - 1],diff --git a/desktop/lib/super_tabs/team_account_setup.dart b/desktop/lib/super_tabs/team_account_setup.dartindex 3db79cea0..7a79677e5 100644--- a/desktop/lib/super_tabs/team_account_setup.dart+++ b/desktop/lib/super_tabs/team_account_setup.dart@@ -64,8 +64,9 @@ class _Words {account: _computerAccount,prompt: 'Your system asks for your password once.',started:- 'Your system is asking for your password. '- 'Setup then takes a minute or two. This computer\'s row updates when it is ready.',+ 'Your system is asking for your password. After that, setup goes on '+ 'in the background: this computer\'s row in Machines shows how far it is, '+ 'and Harness tells you when it is ready.',exists: _computerExists,update: _computerUpdate,cannot: _computerCannot,@@ -73,8 +74,8 @@ class _Words {noPrompt: 'Run harness team setup in a terminal on this computer.',lead: _computerLead,waiting:- 'Your system is asking for your password. '- 'Setup then takes a minute or two, and Harness opens when it is done.',+ 'Your system is asking for your password. After that, setup goes on '+ 'in the background and you can keep working.',rejected: 'Your system did not accept that password. Try again.',cancelled: 'The password window was closed before setup finished.',removeWhy:@@ -89,16 +90,17 @@ class _Words {account: _computerAccount,prompt: 'Windows asks for permission once (User Account Control).',started:- 'Windows is asking for permission. '- 'Setup then takes a minute or two. This computer\'s row updates when it is ready.',+ 'Windows is asking for permission. After that, setup goes on '+ 'in the background: this computer\'s row in Machines shows how far it is, '+ 'and Harness tells you when it is ready.',exists: _computerExists,update: _computerUpdate,cannot: _computerCannot,unreachable: _computerUnreachable,lead: _computerLead,waiting:- 'Windows is asking for permission. '- 'Setup then takes a minute or two, and Harness opens when it is done.',+ 'Windows is asking for permission. After that, setup goes on '+ 'in the background and you can keep working.',rejected: 'Windows did not give permission. Try again.',cancelled: 'The permission window was closed before setup finished.',removeWhy:@@ -119,7 +121,8 @@ class _Words {'That is the macOS tool Harness uses to ask.',started:'macOS is asking for your password in a window titled “osascript”. '- 'Setup then takes a minute or two. This Mac\'s row updates when it is ready.',+ 'After that, setup goes on in the background: this Mac\'s row in '+ 'Machines shows how far it is, and Harness tells you when it is ready.',exists: 'Harness Team is already set up on this Mac.',update:'This Mac\'s Harness is too old to set it up from here. Update Harness, '@@ -130,7 +133,7 @@ class _Words {'This Mac joined a Swarm, so it needs Harness Team before you go on.',waiting:'macOS is asking for your password in a window titled “osascript”. '- 'Setup then takes a minute or two, and Harness opens when it is done.',+ 'After that, setup goes on in the background and you can keep working.',rejected: 'macOS did not accept that password. Try again.',cancelled: 'The password window was closed before setup finished.',removeWhy:@@ -199,49 +202,19 @@ class _Words {/// "this Mac", or "this computer": what Remove takes out of the Swarms.final String here;- /// The steps setup says after the password, in order (cli/src/team/script.ts- /// `step`, then cli/src/team/command.ts `report`).- static const steps = [- 'account',- 'home',- 'privacy',- 'runtime',- 'engines',- 'sign-in',- 'daemon',- 'report',- ];-- /// What setup is doing at [step], or null for the password (or a step this- /// app does not know), which [waiting] says.- String? doing(String? step) => switch (step) {- 'account' => 'Making the Harness Team account.',- 'home' => 'Making the Harness Team account\'s home folder.',- 'privacy' => 'Making your home folder private.',- 'runtime' => 'Copying Harness into the Harness Team account.',- 'engines' =>- 'Installing Claude Code and Codex for Harness Team. '- 'On a new ${here.replaceFirst('this ', '')} this can take several minutes.',- 'sign-in' => 'Signing Harness Team in.',- 'daemon' => 'Starting Harness Team.',- 'report' => 'Checking that Harness Team cannot read your files.',- _ => null,- };-- /// The line under it: the step's number once one is said, and the time so- /// far.- static String sofar(String? step, Duration elapsed) {+ /// The line under the password wait: how long it has waited.+ static String sofar(Duration elapsed) {final seconds = elapsed.inSeconds;final time = seconds < 60? '$seconds s': '${seconds ~/ 60} min ${seconds % 60} s';- final at = steps.indexOf(step ?? '');- return at < 0- ? '$time so far.'- : 'Step ${at + 1} of ${steps.length} · $time so far. '- 'Harness opens when it is done.';+ return '$time so far.';}+ /// [cancelled] for a notice, which says first that setup did not finish:+ /// "The password window was closed."+ String get closed => cancelled.replaceFirst(' before setup finished', '');+/// What Remove asks before it removes anything (security review of #2779):/// it deletes this computer from each Swarm in [swarms], which it names.String confirmRemove(List<String> swarms) {@@ -295,9 +268,15 @@ class _TeamAccountSetupState extends State<_TeamAccountSetup> {final words = widget.words;String outcome;try {- outcome = switch (await widget.app.setUpTeamAccount(+ final state = await widget.app.setUpTeamAccount(signInAgain: widget.signInAgain,- )) {+ );+ // The row and the notice follow it from here (#3169): the dialog's OK+ // leaves the person free while it runs.+ if (state == 'started' || state == 'running') {+ TeamSetupWatch.of(widget.app)?.follow(restart: state == 'started');+ }+ outcome = switch (state) {'started' || 'running' => words.started,'exists' => words.exists,'update' => words.update,@@ -434,6 +413,261 @@ final _refusedPassword = RegExp(caseSensitive: false,);+String _sentence(String text) =>+ RegExp(r'[.!?]$').hasMatch(text) ? text : '$text.';++/// The four steps a person reads (#3169 mockup: "step 2 of 4"), from the+/// steps setup says (cli/src/team/script.ts `step`, ./command.ts `progress`):+/// the account, Harness and its engines, starting it, its privacy check. Null+/// for the password, and for a step this app does not know.+int? teamSetupPhase(String? step) => switch (step) {+ 'account' || 'home' || 'privacy' => 1,+ 'runtime' || 'copy-engines' || 'engines' => 2,+ 'sign-in' || 'daemon' => 3,+ 'report' => 4,+ _ => null,+};++/// What each step usually takes, from this Mac's real setup of 2026-11-04+/// (#3169): the account, homes and privacy about 8 s, Harness 3 s, the npm+/// download of Claude Code and Codex 4 min 18 s (`engines`), the start and+/// its check about 5 s. `copy-engines`, which took over from the download+/// where the Mac has both, took 1.4 to 9.9 s.+const _stepTimes = <String, Duration>{+ 'account': Duration(seconds: 4),+ 'home': Duration(seconds: 2),+ 'privacy': Duration(seconds: 2),+ 'runtime': Duration(seconds: 5),+ 'copy-engines': Duration(seconds: 10),+ 'engines': Duration(seconds: 240),+ 'sign-in': Duration(seconds: 2),+ 'daemon': Duration(seconds: 3),+ 'report': Duration(seconds: 5),+};++/// How long setup has left, at [step] after [inStep] on it; null for a step+/// this app does not know. A step past its usual time keeps a quarter of it+/// (at least 10 s), so a slow download never reads as done. The download is+/// counted only once it runs: a Mac that copies its engines never has one.+Duration? teamSetupLeft(String? step, Duration inStep) {+ final usual = _stepTimes[step];+ if (usual == null) return null;+ final floor = usual ~/ 4 > const Duration(seconds: 10)+ ? usual ~/ 4+ : const Duration(seconds: 10);+ var left = usual - inStep < floor ? floor : usual - inStep;+ final steps = _stepTimes.keys.toList();+ for (final later in steps.skip(steps.indexOf(step!) + 1)) {+ if (later != 'engines') left += _stepTimes[later]!;+ }+ return left;+}++/// This Mac's row while setup runs (#3169): "Harness Team: setting up · step+/// 2 of 4 · about 4 min left".+String teamSetupLine(String? step, Duration inStep) {+ final phase = teamSetupPhase(step);+ final left = teamSetupLeft(step, inStep);+ if (phase == null || left == null) return 'Harness Team: setting up';+ final time = left < const Duration(minutes: 1)+ ? 'less than a minute left'+ : 'about ${(left.inSeconds / 60).round()} min left';+ return 'Harness Team: setting up · step $phase of 4 · $time';+}++/// How a setup [TeamSetupWatch] followed ended.+enum TeamSetupEndKind { ready, failed, cancelled }++class TeamSetupEnd {+ const TeamSetupEnd(this.kind, {this.lock = '', this.notice = ''});++ final TeamSetupEndKind kind;++ /// What the lock says when it holds the app ([TeamAccountSetupLock]).+ final String lock;++ /// What the notice says otherwise.+ final String notice;+}++/// This computer's Harness Team setup, followed while it runs (#3169): one+/// per app, made and ended by [TeamAccountSetupLock], which sits above every+/// route for the app's whole life. It reads the daemon's status every 2 s,+/// only while setup runs, and ends with [ended]: ready (the lock is let go),+/// failed or cancelled, with words for the lock and for a notice. The machine+/// row draws [line].+class TeamSetupWatch extends ChangeNotifier {+ TeamSetupWatch._(this.app, this._words, this._now);++ static final _watches = Expando<TeamSetupWatch>('team setup watch');++ /// [app]'s watch, while its lock is in the window; null otherwise.+ static TeamSetupWatch? of(AppNotifier app) => _watches[app];++ final AppNotifier app;+ final _Words _words;+ final DateTime Function() _now;+ final _ended = StreamController<TeamSetupEnd>.broadcast();+ Timer? _read;+ int _generation = 0;+ bool _disposed = false;+ DateTime? _since, _stepSince;++ /// Each end of a setup it followed.+ Stream<TeamSetupEnd> get ended => _ended.stream;++ bool running = false;++ /// The step setup said last, and how long it has run.+ String? step;+ Duration? elapsed;++ /// Setup is past the password: the person may go on working.+ bool get afterPassword => running && step != null && step != 'password';++ /// The row's line while it runs after the password; null otherwise.+ String? get line {+ final since = _stepSince;+ if (!afterPassword || since == null) return null;+ return teamSetupLine(step, _now().difference(since));+ }++ /// Follows a setup started here or found running. One already followed is+ /// left as it is, unless [restart]: a setup just started again.+ void follow({bool restart = false}) {+ if (_disposed || (running && !restart)) return;+ _generation++;+ running = true;+ step = null;+ elapsed = Duration.zero;+ _since = _stepSince = _now();+ notifyListeners();+ _schedule();+ }++ void _schedule() {+ _read?.cancel();+ final generation = _generation;+ _read = Timer(_setupRead, () => unawaited(_readNow(generation)));+ }++ Future<void> _readNow(int generation) async {+ _read = null;+ final setup = await app.teamSetupProgress();+ if (_disposed || !running || generation != _generation) return;+ final words = _words;+ final detail = setup?.detail?.trim();+ switch (setup?.state) {+ case 'exists':+ return _end(const TeamSetupEnd(TeamSetupEndKind.ready));+ case 'failed' when detail != null && _refusedPassword.hasMatch(detail):+ return _end(+ TeamSetupEnd(+ TeamSetupEndKind.failed,+ lock: words.rejected,+ notice: _failed(words.rejected.replaceFirst(' Try again.', '')),+ ),+ );+ case 'failed':+ final said = detail == null || detail.isEmpty+ ? null+ : _sentence(detail);+ return _end(+ TeamSetupEnd(+ TeamSetupEndKind.failed,+ lock: said == null+ ? 'Setup did not finish. Try again.'+ : 'Setup did not finish: $said',+ notice: _failed(said),+ ),+ );+ case 'declined':+ return _end(+ TeamSetupEnd(+ TeamSetupEndKind.cancelled,+ lock: words.cancelled,+ notice: _failed(words.closed),+ ),+ );+ // It ended with the account there and a part not (#2765): said, and Try again repairs it.+ case 'incomplete':+ final missing = detail == null || detail.isEmpty+ ? null+ : _sentence(detail);+ return _end(+ TeamSetupEnd(+ TeamSetupEndKind.failed,+ lock: missing == null+ ? 'Setup ended, but Harness Team is not finished. Try again.'+ : 'Setup ended, but Harness Team is not finished: $missing Try again.',+ notice: missing == null+ ? 'Harness Team setup ended, but it is not finished.'+ : 'Harness Team setup ended, but it is not finished: $missing',+ ),+ );+ case 'running':+ final next = setup?.step;+ if (next != step) _stepSince = _now();+ step = next;+ final since = _since;+ elapsed =+ setup?.elapsed ?? (since == null ? null : _now().difference(since));+ notifyListeners();+ case null:+ // No answer (the daemon restarting): read again, until the limit.+ break;+ default:+ // Anything else once it stopped running ('none': it ended with no+ // account and nothing remembered, or the daemon restarted): the+ // wait is over, and it says so (Scholes, 2026-11-04).+ return _end(+ TeamSetupEnd(+ TeamSetupEndKind.failed,+ lock: 'Setup stopped before the Harness Team account was made. Try again.',+ notice: _failed('It stopped before the account was made.'),+ ),+ );+ }+ final since = _since;+ if (since != null && _now().difference(since) > _setupLimit) {+ return _end(+ TeamSetupEnd(+ TeamSetupEndKind.failed,+ lock: 'Setup did not finish. Try again.',+ notice: _failed('It ran out of time.'),+ ),+ );+ }+ _schedule();+ }++ static String _failed(String? why) => why == null+ ? 'Harness Team setup did not finish.'+ : 'Harness Team setup did not finish. $why';++ Future<void> _end(TeamSetupEnd end) async {+ _read?.cancel();+ _read = null;+ running = false;+ step = null;+ elapsed = null;+ notifyListeners();+ // Ready lets the lock go before anyone hears of it, so a notice never+ // sits under a lock that is about to end.+ if (end.kind == TeamSetupEndKind.ready) await app.teamAccountMade();+ if (!_disposed) _ended.add(end);+ }++ @override+ void dispose() {+ _disposed = true;+ _read?.cancel();+ unawaited(_ended.close());+ if (identical(_watches[app], this)) _watches[app] = null;+ super.dispose();+ }+}+class _TeamAccountSetupLockState extends State<TeamAccountSetupLock> {late final _Words _words = _Words.of(widget.operatingSystem ?? RuntimePlatform.operatingSystem,@@ -446,17 +680,29 @@ class _TeamAccountSetupLockState extends State<TeamAccountSetupLock> {/// these Swarms.bool _confirming = false;List<String> _confirmSwarms = const [];- Timer? _read;- DateTime? _since;- /// While it waits: the step setup said, and how long it has run.- String? _setupStep;- Duration? _elapsed;+ late TeamSetupWatch _watch;+ StreamSubscription<TeamSetupEnd>? _ends;@overridevoid initState() {super.initState();widget.app.addListener(_changed);+ _makeWatch();+ }++ void _makeWatch() {+ _watch = TeamSetupWatch._(widget.app, _words, DateTime.now)+ ..addListener(_changed);+ TeamSetupWatch._watches[widget.app] = _watch;+ _ends = _watch.ended.listen(_setupEnded);+ }++ void _dropWatch() {+ unawaited(_ends?.cancel());+ _watch+ ..removeListener(_changed)+ ..dispose();}@override@@ -465,13 +711,15 @@ class _TeamAccountSetupLockState extends State<TeamAccountSetupLock> {if (!identical(old.app, widget.app)) {old.app.removeListener(_changed);widget.app.addListener(_changed);+ _dropWatch();+ _makeWatch();}}@overridevoid dispose() {widget.app.removeListener(_changed);- _read?.cancel();+ _dropWatch();super.dispose();}@@ -483,14 +731,10 @@ class _TeamAccountSetupLockState extends State<TeamAccountSetupLock> {}void _reset() {- _read?.cancel();- _read = null;_step = _LockStep.intro;_outcome = _removeError = null;_busy = false;_confirming = false;- _setupStep = null;- _elapsed = null;}void _show(_LockStep step, String outcome) {@@ -502,6 +746,59 @@ class _TeamAccountSetupLockState extends State<TeamAccountSetupLock> {});}+ /// A setup the watch followed ended. Where the lock holds the app, it says+ /// why on the lock again, with Try again; otherwise a notice says it, with+ /// Retry on a failure (#3169).+ void _setupEnded(TeamSetupEnd end) {+ if (!mounted) return;+ if (end.kind != TeamSetupEndKind.ready && widget.app.teamSetupLocked) {+ _show(+ end.kind == TeamSetupEndKind.cancelled+ ? _LockStep.cancelled+ : _LockStep.retry,+ end.lock,+ );+ return;+ }+ final messenger = ScaffoldMessenger.maybeOf(context);+ if (messenger == null) return;+ final here = _words.here.replaceFirst('this ', '');+ final ready = end.kind == TeamSetupEndKind.ready;+ messenger.showSnackBar(+ SnackBar(+ key: const Key('team-setup-notice'),+ duration: Duration(seconds: ready ? 8 : 20),+ showCloseIcon: true,+ content: Text(+ ready+ ? 'Harness Team is ready on this $here. Teammates\' agents can run here now.'+ : end.notice,+ ),+ action: ready+ ? null+ : SnackBarAction(+ key: const Key('team-setup-notice-retry'),+ label: 'Retry',+ onPressed: () => unawaited(_retry()),+ ),+ ),+ );+ }++ /// The notice's Retry: the system's prompt again, followed as before.+ Future<void> _retry() async {+ try {+ final state = await widget.app.setUpTeamAccount();+ if (state == 'started' || state == 'running') {+ _watch.follow(restart: state == 'started');+ }+ } catch (_) {+ if (!mounted) return;+ ScaffoldMessenger.maybeOf(context)+ ?.showSnackBar(SnackBar(content: Text(_words.unreachable)));+ }+ }+Future<void> _start() async {setState(() {_busy = true;@@ -511,11 +808,8 @@ class _TeamAccountSetupLockState extends State<TeamAccountSetupLock> {try {switch (await widget.app.setUpTeamAccount()) {case 'started' || 'running':- _since = DateTime.now();- _setupStep = null;- _elapsed = Duration.zero;_show(_LockStep.waiting, words.waiting);- _scheduleRead();+ _watch.follow(restart: true);case 'exists':await widget.app.teamAccountMade();case 'update':@@ -536,78 +830,6 @@ class _TeamAccountSetupLockState extends State<TeamAccountSetupLock> {}}- /// The setup runs in this computer's daemon after the system's prompt;- /// nothing tells the app when it ends, so its status is read while the- /// prompt can still be open, and never after.- void _scheduleRead() {- _read?.cancel();- _read = Timer(_setupRead, () => unawaited(_readSetup()));- }-- Future<void> _readSetup() async {- _read = null;- final setup = await widget.app.teamSetupProgress();- if (!mounted || _step != _LockStep.waiting) return;- switch (setup?.state) {- case 'exists':- await widget.app.teamAccountMade();- return;- case 'failed':- final detail = setup?.detail?.trim();- if (detail != null && _refusedPassword.hasMatch(detail)) {- _show(_LockStep.retry, _words.rejected);- } else {- _show(- _LockStep.retry,- detail == null || detail.isEmpty- ? 'Setup did not finish. Try again.'- : 'Setup did not finish: ${_sentence(detail)}',- );- }- return;- case 'declined':- _show(_LockStep.cancelled, _words.cancelled);- return;- // It ended with the account there and a part not (#2765): said, and Try again repairs it.- case 'incomplete':- final missing = setup?.detail?.trim();- _show(- _LockStep.retry,- missing == null || missing.isEmpty- ? 'Setup ended, but Harness Team is not finished. Try again.'- : 'Setup ended, but Harness Team is not finished: ${_sentence(missing)} Try again.',- );- return;- case 'running':- final since = _since;- setState(() {- _setupStep = setup?.step;- _elapsed =- setup?.elapsed ??- (since == null ? null : DateTime.now().difference(since));- _outcome = _words.doing(_setupStep) ?? _words.waiting;- });- case null:- // No answer (the daemon restarting): read again, until the limit.- break;- default:- // Anything else once it stopped running ('none': it ended with no- // account and nothing remembered, or the daemon restarted): the- // wait is over, and it says so (Scholes, 2026-11-04).- _show(- _LockStep.retry,- 'Setup stopped before the Harness Team account was made. Try again.',- );- return;- }- final since = _since;- if (since != null && DateTime.now().difference(since) > _setupLimit) {- _show(_LockStep.retry, 'Setup did not finish. Try again.');- return;- }- _scheduleRead();- }-/// Try again while it waits: reads the status first, and starts setup/// again only when none is running.Future<void> _tryAgainWaiting() async {@@ -628,9 +850,6 @@ class _TeamAccountSetupLockState extends State<TeamAccountSetupLock> {}}- static String _sentence(String text) =>- RegExp(r'[.!?]$').hasMatch(text) ? text : '$text.';-Future<void> _askRemove() async {setState(() {_busy = true;@@ -667,7 +886,9 @@ class _TeamAccountSetupLockState extends State<TeamAccountSetupLock> {@overrideWidget build(BuildContext context) {- final locked = widget.app.teamSetupLocked;+ // Past the password, setup goes on behind the person's work (#3169): the+ // lock still holds, and comes back if setup fails.+ final locked = widget.app.teamSetupLocked && !_watch.afterPassword;// One tree shape locked or not, so the app below is never remounted.return Stack(fit: StackFit.expand,@@ -769,10 +990,10 @@ class _TeamAccountSetupLockState extends State<TeamAccountSetupLock> {),],),- if (_step == _LockStep.waiting && _elapsed != null) ...[+ if (_step == _LockStep.waiting && _watch.elapsed != null) ...[const SizedBox(height: 8),Text(- _Words.sofar(_setupStep, _elapsed!),+ _Words.sofar(_watch.elapsed!),key: const Key('team-account-lock-elapsed'),style: muted,),diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex b55990e6d..3e7769d47 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -64,6 +64,13 @@ import 'identity.dart' show superTabMachineName;import 'identity_card.dart';import 'prompt_alerts.dart';import 'workgroup_name.dart';+import 'backlog.dart'+ show+ SuperTabTaskPriority,+ superTabCarriesPriority,+ superTabTaskPriority,+ superTabTitlePriority;+import 'chip.dart' show SuperTabPriorityBadge;import 'message_link.dart';import 'message_link_swarms.dart';import 'message_link_preview.dart';@@ -190,6 +197,10 @@ class _SuperTabViewState extends State<SuperTabView>/// last opened from it, or the task whose chat the board was opened from.String? _tasksSelectedId;+ /// Why the last priority change was refused, and for which task: said+ /// beside that task's title (task #3117).+ ({String taskId, String error})? _priorityRefusal;+/// The Swarm's page holding the main pane, if one does: Decisions,/// Mentions or Threads (anh Dee, 11-05, task #2996).SwarmPage? _page;@@ -2768,7 +2779,11 @@ class _SuperTabViewState extends State<SuperTabView>? c.snapshot!.name: 'Choose a project': _groupName(group);- if (name == null) return SuperTabWorkgroupName(group!, style: style);+ if (name == null) {+ return superTabCarriesPriority(group!)+ ? _taskTitle(group, style)+ : SuperTabWorkgroupName(group, style: style);+ }if (group != null &&c.snapshot!.isProjectLead(group.id) &&!_devicesVisible &&@@ -2803,6 +2818,101 @@ class _SuperTabViewState extends State<SuperTabView>);}+ /// A task's name in its header (task #3117): its number, its priority as a+ /// button that opens the priority menu, then its title without a legacy+ /// marker, which the badge now says; a refused change is said after it.+ Widget _taskTitle(SuperTabConversation task, TextStyle style) {+ final refusal = _priorityRefusal;+ return Row(+ key: const ValueKey('super-task-title'),+ mainAxisSize: MainAxisSize.min,+ children: [+ if (task.number case final number?) ...[+ Text('$number', style: style.copyWith(color: DesktopChrome.muted)),+ const SizedBox(width: grid.AppDesktop.controlGap),+ ],+ _priorityMenu(task),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Flexible(+ child: Text(+ superTabTitlePriority(task.title).title,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: style,+ ),+ ),+ if (refusal != null && refusal.taskId == task.id) ...[+ const SizedBox(width: grid.AppDesktop.groupGap),+ Flexible(+ child: Text(+ refusal.error,+ key: const ValueKey('super-task-priority-error'),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(),+ ),+ ),+ ],+ ],+ );+ }++ /// The priority menu's widest: room for the longest meaning on one line.+ static const double _priorityMenuWidth = 340;++ /// [task]'s priority badge, `P1 ▾`, opening the four priorities with what+ /// each means, the current one checked.+ Widget _priorityMenu(SuperTabConversation task) {+ final current = superTabTaskPriority(task);+ final editable = c.canWrite && !c.saving && !c.hasPendingAction;+ return AppDropdown(+ width: _priorityMenuWidth,+ consumeOutsideTap: false,+ alignmentOffset: Offset.zero,+ children: [+ for (final priority in SuperTabTaskPriority.values)+ fingerTarget(+ enabled: _phone,+ AppMenuItem(+ key: ValueKey('super-task-priority-${priority.name}'),+ label: priority.badge,+ // A sentence, so the row's second line: beside the label it+ // would be cut ([AppMenuItem.detail]).+ detail: priority.meaning,+ selected: priority == current,+ onPressed: editable+ ? () => unawaited(_setPriority(task, priority))+ : null,+ ),+ ),+ ],+ builder: (context, menu, _) => Tooltip(+ message: 'Priority: ${current.meaning}',+ child: InkWell(+ key: const ValueKey('super-task-priority'),+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),+ onTap: () => menu.isOpen ? menu.close() : menu.open(),+ child: SuperTabPriorityBadge(current, menu: true),+ ),+ ),+ );+ }++ Future<void> _setPriority(+ SuperTabConversation task,+ SuperTabTaskPriority priority,+ ) async {+ if (priority == superTabTaskPriority(task)) return;+ setState(() => _priorityRefusal = null);+ final refused = await c.setTaskPriority(task.id, priority);+ if (!mounted) return;+ setState(+ () => _priorityRefusal = refused == null+ ? null+ : (taskId: task.id, error: refused),+ );+ }+/// [group]'s name as the sidebar names it: "# openharness", a Buddy chat's;/// null for a workgroup, named by [SuperTabWorkgroupName].String? _groupName(SuperTabConversation group) =>diff --git a/desktop/test/super_tab_backlog_test.dart b/desktop/test/super_tab_backlog_test.dartindex a9a02316f..acd1dde5a 100644--- a/desktop/test/super_tab_backlog_test.dart+++ b/desktop/test/super_tab_backlog_test.dart@@ -312,28 +312,29 @@ void main() {]);});- // Task #2774 (Scholes's mockup): tasks carry no priority field; the badge- // reads the title's own marker, which the row then drops.+ // Task #2774 (Scholes's mockup): a task from before the priority field+ // reads the title's own marker, which the row then drops; URGENT is P0 and+ // high is P1 (task #3117).test('a title\'s URGENT or "(Name, high)" marker is its priority badge', () {for (final (title, priority, shown) in [('URGENT: agents\' GitHub tokens also carry workflows',- SuperTabTaskPriority.urgent,+ SuperTabTaskPriority.p0,'Agents\' GitHub tokens also carry workflows',),('URGENT bug in #2608: the date pill crashes',- SuperTabTaskPriority.urgent,+ SuperTabTaskPriority.p0,'Bug in #2608: the date pill crashes',),('Manage Backlog tab redesigned (Scholes, high)',- SuperTabTaskPriority.high,+ SuperTabTaskPriority.p1,'Manage Backlog tab redesigned',),('Round dial fix (Huy, urgent)',- SuperTabTaskPriority.urgent,+ SuperTabTaskPriority.p0,'Round dial fix',),('Thread tags (Dee, 2026-11-04)', null, 'Thread tags (Dee, 2026-11-04)'),@@ -661,11 +662,11 @@ void main() {'shipped',]);expect(summary(tester), (working: 1, review: 1, shipped: 1));- // Scholes's mockup (#2774): number and title; then agent, machine and- // state with a project chip; the pull request's chip and how long ago- // at the right.+ // Scholes's mockup (#2774): number, priority (#3117) and title; then+ // agent, machine and state with a project chip; the pull request's+ // chip and how long ago at the right.final working = rowText(tester, 'working');- expect(working, contains('#11 | Sidebar task groups'));+ expect(working, contains('#11 | P2 | Sidebar task groups'));expect(working, contains('Kestrel · Mac Studio · Working'));expect(working, contains('web-project'));expect(working, contains('PR 2733'));@@ -872,11 +873,8 @@ void main() {conversations.firstWhere((g) => g['id'] == 'review')['title'] ='Thread reply bar (Scholes, high)';await show(tester, server);- expect(- rowText(tester, 'working'),- contains('URGENT | Sidebar task groups'),- );- expect(rowText(tester, 'review'), contains('HIGH | Thread reply bar'));+ expect(rowText(tester, 'working'), contains('P0 | Sidebar task groups'));+ expect(rowText(tester, 'review'), contains('P1 | Thread reply bar'));expect(rowText(tester, 'review'), isNot(contains('Scholes')));});diff --git a/desktop/test/super_tab_buddy_chat_counts_test.dart b/desktop/test/super_tab_buddy_chat_counts_test.dartindex 79b45d2b3..028e14b20 100644--- a/desktop/test/super_tab_buddy_chat_counts_test.dart+++ b/desktop/test/super_tab_buddy_chat_counts_test.dart@@ -549,12 +549,17 @@ void main() {await tester.pumpAndSettle();expect(find.text('#196 Offline editing'), findsNothing);- // The header's alone: the sidebar lists no tasks (task #2569).- final name = tester.widget<Text>(find.text('196 Offline editing'));+ // The header's alone: the sidebar lists no tasks (task #2569). Its+ // priority sits between number and title (task #3117).+ final title = find.byKey(const ValueKey('super-task-title'));expect(- (name.textSpan! as TextSpan).children!.first.style?.color,- DesktopChrome.muted,+ find.descendant(of: title, matching: find.text('Offline editing')),+ findsOneWidget,);+ final number = tester.widget<Text>(+ find.descendant(of: title, matching: find.text('196')),+ );+ expect(number.style?.color, DesktopChrome.muted);await close(tester, c);});diff --git a/desktop/test/super_tab_task_priority_shots_test.dart b/desktop/test/super_tab_task_priority_shots_test.dartnew file mode 100644index 000000000..7ef4ca80d--- /dev/null+++ b/desktop/test/super_tab_task_priority_shots_test.dart@@ -0,0 +1,104 @@+import 'dart:io';++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/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_PRIORITY_SHOTS'];++/// Task priorities as the PR shows them (task #3117): the Board with a badge+/// on every card, P0 first in its column, and a task's header with its+/// priority menu open, in both appearances.+void main() {+ setUpAll(() async {+ await loadCaptureFonts(shots);+ if (shots != null && Platform.isMacOS) {+ for (final (family, path) in [+ ('.AppleSystemUIFontMonospaced', '/System/Library/Fonts/SFNSMono.ttf'),+ ('Apple Symbols', '/System/Library/Fonts/Apple Symbols.ttf'),+ ]) {+ final bytes = ByteData.sublistView(await File(path).readAsBytes());+ await (FontLoader(family)..addFont(Future.value(bytes))).load();+ }+ }+ });++ for (final brightness in Brightness.values) {+ for (final view in ['board', 'header']) {+ testWidgets('screenshots for review ($view, ${brightness.name})', (+ tester,+ ) async {+ await tester.binding.setSurfaceSize(const Size(1900, 900));+ 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.proposals['lead']!.first['priority'] = 'P1';+ (server.state['conversations'] as List).addAll(<Map<String, dynamic>>[+ {+ ...taskFixture('hotfix', 'Sign-in loops forever', 30),+ 'priority': 'P0',+ },+ taskFixture('legacy', 'Round dial crashes (Ken, high)', 31),+ {+ ...taskFixture('docs', 'Docs for the round dial', 32),+ 'priority': 'P3',+ },+ {+ ...taskFixture(+ 'crash',+ 'Settings crash on open',+ 8,+ requester: 'ken',+ status: 'working',+ ),+ 'priority': 'P0',+ },+ ]);+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context).copyWith(disableAnimations: true),+ child: child!,+ ),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ if (view == 'board') {+ await tester.tap(find.byKey(const ValueKey('super-tasks')));+ await tester.pumpAndSettle();+ expect(find.text('P0'), findsNWidgets(2));+ } else {+ await c.select('preview');+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-task-priority')));+ await tester.pumpAndSettle();+ expect(find.text('Planned goal'), findsOneWidget);+ }+ expect(tester.takeException(), isNull);+ await captureWindow(tester, shots, 'priority-$view-${brightness.name}');+ });+ }+ }+}diff --git a/desktop/test/super_tab_task_priority_test.dart b/desktop/test/super_tab_task_priority_test.dartnew file mode 100644index 000000000..b3aa922ff--- /dev/null+++ b/desktop/test/super_tab_task_priority_test.dart@@ -0,0 +1,466 @@+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/backlog.dart';+import 'package:harness/super_tabs/backlog_view.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/model.dart';+import 'package:harness/super_tabs/tasks_view.dart';+import 'package:harness/super_tabs/view.dart';++import 'super_tab_tasks_view_test.dart' show tasksServer, taskFixture;+import 'support/memory_key_value_store.dart';+import 'support/super_tab_fixture.dart';++final _now = DateTime(2026, 11, 4, 9);++Finder _key(String key) => find.byKey(ValueKey(key));+Finder _column(String name) => _key('super-tasks-column-$name');+Finder _card(String id) => _key('super-task-card-$id');+Finder _row(String id) => _key('super-backlog-row-$id');+Finder _in(Finder of, String text) =>+ find.descendant(of: of, matching: find.text(text, findRichText: true));++List<Map<String, dynamic>> _groups(ConversationServer server) =>+ (server.state['conversations'] as List).cast<Map<String, dynamic>>();++Map<String, dynamic> _group(ConversationServer server, String id) =>+ _groups(server).firstWhere((g) => g['id'] == id);++/// The mockup's project with a hotfix asked after the P2 work: `hotfix` (#30,+/// P0) is the newest task in Next up, and `crash` (#8, P0) the oldest in+/// Working.+ConversationServer _server() {+ final server = tasksServer();+ _groups(server).addAll([+ taskFixture('third', 'Rename the round dial', 14),+ {...taskFixture('hotfix', 'Sign-in loops forever', 30), 'priority': 'P0'},+ {+ ...taskFixture('crash', 'Settings crash on open', 8, status: 'working'),+ 'priority': 'P0',+ },+ ]);+ // A task the server says is P2 reads as one with no field.+ _group(server, 'preview')['priority'] = 'P2';+ return server;+}++Widget _app(Widget body) => MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context).copyWith(disableAnimations: true),+ child: child!,+ ),+ home: Scaffold(body: body),+);++Future<SuperTabController> _board(+ 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(+ _app(+ SuperTabTasksView(+ controller: c,+ project: c.snapshot!.projects.single,+ storage: MemoryKeyValueStore(),+ needsHuman: (_) => 0,+ onOpenTask: (_) {},+ onOpenProposal: (_) {},+ now: () => _now,+ ),+ ),+ );+ await tester.pumpAndSettle();+ return c;+}++Future<SuperTabController> _view(+ WidgetTester tester,+ ConversationServer server,+ String open,+) 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(+ _app(+ SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ );+ await tester.pumpAndSettle();+ await c.select(open);+ await tester.pumpAndSettle();+ return c;+}++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];+}++Iterable<Map> _commands(ConversationServer server, String type) => [+ for (final post in server.posts)+ if ((post['command'] as Map?)?['type'] == type) post['command'] as Map,+];++/// Task priorities P0–P3 on Desktop (task #3117): a badge on every card, the+/// Backlog's rows and the task header; P0 first wherever work is ordered.+void main() {+ test('each priority says what it means, and a task reads its effective '+ 'one: the field, else the title marker, else P2', () {+ expect(+ [for (final p in SuperTabTaskPriority.values) (p.badge, p.meaning)],+ [+ ('P0', 'Hotfix: something shipped is broken'),+ ('P1', 'Needed by users soon'),+ ('P2', 'Planned goal'),+ ('P3', 'Tools, docs or process'),+ ],+ );+ SuperTabConversation task(String title, [String? priority]) =>+ SuperTabConversation.fromJson({+ ...conversationFixture('t', title),+ 'priority': ?priority,+ });+ expect(task('A', 'P3').priority, 'P3');+ expect(task('A').priority, isNull);+ for (final (built, expected) in [+ (task('Fix it (urgent)', 'P3'), SuperTabTaskPriority.p3),+ (task('Fix it (urgent)'), SuperTabTaskPriority.p0),+ (task('URGENT: fix it'), SuperTabTaskPriority.p0),+ (task('Polish it (Scholes, high)'), SuperTabTaskPriority.p1),+ (task('Polish it'), SuperTabTaskPriority.p2),+ (task('Polish it', 'P9'), SuperTabTaskPriority.p2),+ ]) {+ expect(superTabTaskPriority(built), expected, reason: built.title);+ }+ });++ group('Tasks board', () {+ testWidgets('a P0 task created after a P2 task shows P0 on its card and '+ 'leads Next up and Working', (tester) async {+ await _board(tester, _server());+ expect(_in(_card('hotfix'), 'P0'), findsOneWidget);+ expect(_in(_card('crash'), 'P0'), findsOneWidget);+ expect(_in(_card('preview'), 'P2'), findsOneWidget);+ expect(_in(_card('shipped-means'), 'P2'), findsOneWidget);+ // Today's order after the priority: the shared queue, newest first.+ expect(_cardsIn(tester, 'nextUp'), [+ 'hotfix',+ 'shipped-means',+ 'preview',+ 'third',+ ]);+ expect(_cardsIn(tester, 'working'), ['crash', 'tag']);+ // The badge leads the caption, which keeps its words.+ expect(+ tester.getTopLeft(_in(_card('crash'), 'P0')).dx,+ lessThan(tester.getTopLeft(_in(_card('crash'), 'Finch2')).dx),+ );+ });++ testWidgets('a legacy "(urgent)" title with no field shows P0, without '+ 'its marker', (tester) async {+ final server = _server();+ _groups(server)+ .add(taskFixture('legacy', 'Round dial crashes (urgent)', 31));+ await _board(tester, server);+ expect(_in(_card('legacy'), 'P0'), findsOneWidget);+ expect(_in(_card('legacy'), 'Round dial crashes'), findsOneWidget);+ expect(find.textContaining('(urgent)'), findsNothing);+ expect(_cardsIn(tester, 'nextUp').take(2), ['hotfix', 'legacy']);+ });++ testWidgets('a proposal card shows its mapped badge and sorts by it', (+ tester,+ ) async {+ final server = _server();+ server.proposals['lead']!.first['priority'] = 'P1';+ await _board(tester, server);+ expect(_in(_card('p-new'), 'P1'), findsOneWidget);+ // None sent reads P2.+ expect(_in(_card('p-old'), 'P2'), findsOneWidget);+ expect(_cardsIn(tester, 'proposals'), ['p-new', 'p-old']);+ });+ });++ group('Next up moves stay inside their priority', () {+ 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 P2 card dragged above a P0 card goes first among the P2s', (+ tester,+ ) async {+ final server = _server();+ await _board(tester, server);+ await dragTo(+ tester,+ 'third',+ tester.getTopLeft(_card('hotfix')) + const Offset(20, 2),+ );+ // Before `shipped-means`, the first P2 in the shared queue.+ expect(_commands(server, 'work.queue'), [+ {'type': 'work.queue', 'conversationId': 'third', 'after': null},+ ]);+ expect(_cardsIn(tester, 'nextUp'), [+ 'hotfix',+ 'third',+ 'shipped-means',+ 'preview',+ ]);+ });++ testWidgets('a P2 card dropped at the end of its band lands after the '+ 'last P2, not before a P3 ranked between them', (tester) async {+ final server = _server();+ _groups(server).add({+ ...taskFixture('docs', 'Docs for the dial', 12),+ 'priority': 'P3',+ 'queueRank': 10.5,+ });+ await _board(tester, server);+ expect(_cardsIn(tester, 'nextUp'), [+ 'hotfix',+ 'shipped-means',+ 'preview',+ 'third',+ 'docs',+ ]);+ Focus.of(tester.element(find.text('Shipped means merged')))+ .requestFocus();+ await tester.pump();+ for (var i = 0; i < 2; i++) {+ await tester.sendKeyDownEvent(LogicalKeyboardKey.alt);+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.alt);+ await tester.pumpAndSettle();+ Focus.of(tester.element(find.text('Shipped means merged')))+ .requestFocus();+ await tester.pump();+ }+ // A third ⌥↓ would leave the P2s: it does nothing.+ await tester.sendKeyDownEvent(LogicalKeyboardKey.alt);+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.alt);+ await tester.pumpAndSettle();+ expect(_commands(server, 'work.queue'), [+ {+ 'type': 'work.queue',+ 'conversationId': 'shipped-means',+ 'after': 'preview',+ },+ {+ 'type': 'work.queue',+ 'conversationId': 'shipped-means',+ 'after': 'third',+ },+ ]);+ expect(_cardsIn(tester, 'nextUp'), [+ 'hotfix',+ 'preview',+ 'third',+ 'shipped-means',+ 'docs',+ ]);+ });++ testWidgets('⌥↑ on the first P2 does not pass the P0 above it', (+ tester,+ ) async {+ final server = _server();+ await _board(tester, server);+ Focus.of(tester.element(find.text('Shipped means merged')))+ .requestFocus();+ await tester.pump();+ await tester.sendKeyDownEvent(LogicalKeyboardKey.alt);+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.alt);+ await tester.pumpAndSettle();+ expect(_commands(server, 'work.queue'), isEmpty);+ expect(_cardsIn(tester, 'nextUp').first, 'hotfix');+ });+ });++ group('Task header', () {+ final button = _key('super-task-priority');+ final header = _key('super-task-title');++ testWidgets('a task shows its badge between its number and title, and '+ 'its menu lists the four meanings with the current one checked', (+ tester,+ ) async {+ await _view(tester, _server(), 'preview');+ expect(_in(button, 'P2'), findsOneWidget);+ final number = _in(header, '11');+ final title = _in(header, 'Remove the old preview route');+ expect(+ tester.getCenter(button).dx,+ greaterThan(tester.getTopLeft(number).dx),+ );+ expect(+ tester.getCenter(button).dx,+ lessThan(tester.getTopLeft(title).dx),+ );+ await tester.tap(button);+ await tester.pumpAndSettle();+ for (final meaning in [+ 'Hotfix: something shipped is broken',+ 'Needed by users soon',+ 'Planned goal',+ 'Tools, docs or process',+ ]) {+ expect(find.text(meaning), findsOneWidget, reason: meaning);+ }+ for (final p in ['p0', 'p1', 'p2', 'p3']) {+ expect(_key('super-task-priority-$p'), findsOneWidget, reason: p);+ }+ });++ testWidgets('choosing P0 sends work.priority and the badge follows', (+ tester,+ ) async {+ final server = _server();+ await _view(tester, server, 'preview');+ await tester.tap(button);+ await tester.pumpAndSettle();+ await tester.tap(_key('super-task-priority-p0'));+ await tester.pumpAndSettle();+ expect(_commands(server, 'work.priority'), [+ {+ 'type': 'work.priority',+ 'conversationId': 'preview',+ 'priority': 'P0',+ },+ ]);+ expect(_in(button, 'P0'), findsOneWidget);+ expect(_key('super-task-priority-error'), findsNothing);+ });++ testWidgets('a refusal shows inline beside the title', (tester) async {+ final server = _server();+ await _view(tester, server, 'preview');+ server.refuse = {+ 'code': 'COORDINATOR_REQUIRED',+ 'message': 'Only a person or the PM can change a priority.',+ };+ await tester.tap(button);+ await tester.pumpAndSettle();+ await tester.tap(_key('super-task-priority-p1'));+ await tester.pumpAndSettle();+ expect(+ tester.widget<Text>(_key('super-task-priority-error')).data,+ 'Only a person or the PM can change a priority.',+ );+ expect(_in(button, 'P2'), findsOneWidget);+ });++ testWidgets('a legacy "(urgent)" title shows P0 without its marker', (+ tester,+ ) async {+ final server = _server();+ _groups(server)+ .add(taskFixture('legacy', 'Round dial crashes (urgent)', 31));+ await _view(tester, server, 'legacy');+ expect(_in(button, 'P0'), findsOneWidget);+ expect(_in(header, 'Round dial crashes'), findsOneWidget);+ expect(+ find.descendant(+ of: header,+ matching: find.textContaining('(urgent)', findRichText: true),+ ),+ findsNothing,+ );+ });++ testWidgets('the project chat and a step show no priority', (tester) async {+ final server = _server();+ _groups(server).add({+ ...taskFixture('review-step', 'Review', 32),+ 'reviewOf': 'preview',+ 'step': 'Review',+ });+ final c = await _view(tester, server, 'lead');+ expect(button, findsNothing);+ await c.select('review-step');+ await tester.pumpAndSettle();+ expect(button, findsNothing);+ });+ });++ group('Backlog', () {+ testWidgets('each row shows its Px badge, and P0 leads its group', (+ tester,+ ) async {+ final server = _server();+ // Waiting for a machine, newest first today: preview, shipped-means,+ // ask.+ _group(server, 'shipped-means')['priority'] = 'P0';+ _groups(server).add(taskFixture('ask', 'An old ask (Scholes, high)', 5));+ await tester.binding.setSurfaceSize(const Size(1100, 2000));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ await tester.pumpWidget(+ _app(+ SuperTabBacklogView(+ controller: c,+ onOpenConversation: (_) {},+ now: () => _now,+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(_in(_row('shipped-means'), 'P0'), findsOneWidget);+ expect(_in(_row('ask'), 'P1'), findsOneWidget);+ expect(_in(_row('ask'), 'An old ask'), findsOneWidget);+ expect(_in(_row('preview'), 'P2'), findsOneWidget);+ expect(find.text('URGENT'), findsNothing);+ expect(find.text('HIGH'), findsNothing);+ double top(String id) => tester.getTopLeft(_row(id)).dy;+ expect(top('shipped-means'), lessThan(top('ask')));+ expect(top('ask'), lessThan(top('preview')));+ });+ });+}diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex a4083363f..b10ce0759 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -1725,6 +1725,15 @@ class ConversationServer {: (key(siblings[i]) + key(next)) / 2;}revision++;+ } else if (command['type'] == 'work.priority') {+ // As backend taskPriority.ts sets it: the task's one field.+ (state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere(+ (g) => g['id'] == command['conversationId'],+ )['priority'] =+ command['priority'];+ revision++;} else if (command['type'] == 'conversation.archive') {(state['conversations'] as List).cast<Map<String, dynamic>>()diff --git a/desktop/test/swarm_join_any_test.dart b/desktop/test/swarm_join_any_test.dartnew file mode 100644index 000000000..8eea65d8f--- /dev/null+++ b/desktop/test/swarm_join_any_test.dart@@ -0,0 +1,203 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/join_machine.dart';+import 'package:harness/ws/ws_conn.dart';++import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;++// Task #3160 (Scholes, 11-05): about a dozen new members joined through a+// domain auto-join, a Workspace-open join or on the phone or web first, and+// were never offered the Harness Team account: the add ran only from+// Desktop's own join dialog. Discovery now runs it once for any Swarm new here.++/// This Mac's app, signed in, its Swarm list naming one Swarm the person is+/// in as [role], joined on the server (a domain auto-join) with no client+/// asking.+SuperTabLaunchFixture _computer({String role = 'collaborator'}) {+ final f = SuperTabLaunchFixture();+ f.app.status = AppStatus.authenticated;+ f.app.teamAccountHereForTest = true;+ f.connection.teamCheck = {'state': 'wanted'};+ f.connection.server.state+ ..['ownerId'] = 'boss'+ ..['people'] = <dynamic>[+ {'id': 'boss', 'email': '[email protected]', 'role': 'owner'},+ {+ 'id': 'owner',+ 'email': '[email protected]',+ 'role': role,+ 'joinedVia': 'domain',+ },+ ];+ return f;+}++/// One discovery, and the add it started run to its end.+Future<void> _discover(SuperTabLaunchFixture f) async {+ await f.app.superTabs.refreshTabs();+ await f.app.joinAddPassForTest;+ // The notes reach their listeners after it.+ await pumpEventQueue();+}++List<Map> _contributions(SuperTabLaunchFixture f) => [+ for (final post in f.connection.server.posts)+ if ((post['command'] as Map)['type'] == 'machine.contribute')+ post['command'] as Map,+];++List<Map> _teamOffers(SuperTabLaunchFixture f) => [+ for (final (type, payload) in f.connection.calls)+ if (type == 'super_tabs' && payload['action'] == 'teamSetupCheck') payload,+];++/// The Swarm's first loads: each is a read of its whole state.+int _firstLoads(SuperTabLaunchFixture f) => [+ for (final (type, payload) in f.connection.calls)+ if (type == 'super_tabs' &&+ payload['method'] == 'GET' &&+ payload['path'] == '/api/super-tabs/$tabId/parts')+ payload,+].length;++void main() {+ test('a Swarm first seen through a domain auto-join adds this Mac and offers the Team account, once', () async {+ final f = _computer();+ final notes = <SwarmJoinedMachine>[];+ final listening = f.app.joinedMachines.listen(notes.add);+ await _discover(f);+ expect(_contributions(f), [containsPair('teamAccountOnly', true)]);+ expect(_contributions(f).single['machineId'], 'm');+ expect(_teamOffers(f), [+ {'action': 'teamSetupCheck', 'reason': 'join', 'tabId': tabId},+ ]);+ expect(notes.map((n) => (n.tabId, n.added)), [(tabId, true)]);+ expect(f.app.teamSetupLocked, isTrue);++ // The person removed this Mac again: the next discovery leaves it so.+ f.connection.server.state['machines'] = <dynamic>[];+ await _discover(f);+ expect(_contributions(f), hasLength(1));+ expect(_teamOffers(f), hasLength(1));+ expect(notes, hasLength(1));+ await listening.cancel();+ });++ test(+ 'it never runs again for the same Swarm and person after a restart',+ () async {+ final first = _computer();+ await _discover(first);+ expect(_contributions(first), hasLength(1));++ final restarted = _computer();+ restarted.store.values.addAll(first.store.values);+ await _discover(restarted);+ expect(_contributions(restarted), isEmpty);+ expect(_teamOffers(restarted), isEmpty);+ },+ );++ test('a viewer is never added and never offered the Team account', () async {+ final f = _computer(role: 'viewer');+ final notes = <SwarmJoinedMachine>[];+ final listening = f.app.joinedMachines.listen(notes.add);+ await _discover(f);+ await _discover(f);+ expect(_contributions(f), isEmpty);+ expect(_teamOffers(f), isEmpty);+ expect(notes, isEmpty);+ await listening.cancel();+ });++ test(+ 'a Swarm already shown on this computer before the update is left as it is',+ () async {+ final f = _computer();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ await _discover(f);+ expect(_contributions(f), isEmpty);+ expect(_teamOffers(f), isEmpty);+ },+ );++ test(+ 'a join in Desktop and the discovery after it add this Mac once',+ () async {+ final f = _computer();+ await f.app.addMachineOnJoin(tabId, role: 'collaborator');+ expect(_contributions(f), hasLength(1));+ f.connection.server.state['machines'] = <dynamic>[];+ await _discover(f);+ expect(_contributions(f), hasLength(1));+ expect(_teamOffers(f), hasLength(1));+ },+ );++ // Review of #3115: a Swarm opened only for the add kept polling, and a+ // viewer's was read in full on every discovery.+ test('a Swarm opened only to add this Mac is let go, and a viewer\'s is read once', () async {+ final viewer = _computer(role: 'viewer');+ await _discover(viewer);+ await _discover(viewer);+ expect(_firstLoads(viewer), 1);+ expect(viewer.app.superTabs.peek(tabId), isNull);++ final collaborator = _computer();+ await _discover(collaborator);+ expect(_contributions(collaborator), hasLength(1));+ expect(collaborator.app.superTabs.peek(tabId), isNull);+ });++ test('a first discovery before this Mac\'s own row is known still takes the update\'s baseline', () async {+ final f = _computer();+ f.app.teamAccountHereForTest = false;+ await _discover(f);+ expect(_contributions(f), isEmpty);+ // Discovery showed the Swarm meanwhile; it is still new to the add.+ f.app.teamAccountHereForTest = true;+ await _discover(f);+ expect(_contributions(f), hasLength(1));+ });++ group('a failed step shows the person a note', () {+ test(+ 'a Team account this Mac could not be offered says where to set it up',+ () async {+ final f = _computer();+ // A daemon that cannot say whether the account is wanted.+ f.connection.teamCheck = null;+ final notes = <SwarmJoinedMachine>[];+ final listening = f.app.joinedMachines.listen(notes.add);+ await _discover(f);+ expect(notes.map((n) => (n.added, n.teamProblem)), [+ (true, null),+ (true, 'Set it up from Machines.'),+ ]);+ await listening.cancel();+ },+ );++ test('a Swarm joined here that cannot be read says to add this Mac from Machines', () async {+ final f = _computer();+ f.connection.backendFailure = const WsRequestFailure(+ responseType: 'super_tabs_result',+ code: 'UNAVAILABLE',+ detail: 'The Swarm service is unavailable.',+ payload: {'status': 503},+ );+ final notes = <SwarmJoinedMachine>[];+ final listening = f.app.joinedMachines.listen(notes.add);+ await f.app.addMachineOnJoin(tabId, role: 'collaborator');+ await pumpEventQueue();+ expect(notes.map((n) => (n.tabId, n.added, n.problem)), [+ (+ tabId,+ false,+ 'Could not reach the Swarm. Add this computer from Machines.',+ ),+ ]);+ await listening.cancel();+ });+ });+}diff --git a/desktop/test/swarm_join_machine_test.dart b/desktop/test/swarm_join_machine_test.dartindex 1612311c6..3c8449c76 100644--- a/desktop/test/swarm_join_machine_test.dart+++ b/desktop/test/swarm_join_machine_test.dart@@ -480,6 +480,32 @@ void noteTests() {c.dispose();});+ // Task #3160: a failed Team account offer was only a log line.+ testWidgets(+ 'a Team account that could not be offered says where to set it up',+ (tester) async {+ final c = await mount(+ tester,+ const SwarmJoinedMachine(+ tabId: 'tab',+ swarmName: 'Pilot',+ machineId: 'mate-mac',+ machineName: 'MacBook Air',+ teamProblem: 'Set it up from Machines.',+ ),+ );+ expect(+ find.text(+ 'This Mac was added to Pilot, but Harness could not offer its Harness '+ 'Team account. Set it up from Machines.',+ ),+ findsOneWidget,+ );+ expect(find.byKey(const Key('swarm-joined-machine-pause')), findsNothing);+ c.dispose();+ },+ );+testWidgets('a Swarm at its limit says so after joining', (tester) async {final c = await mount(tester,diff --git a/desktop/test/swarm_join_seen_test.dart b/desktop/test/swarm_join_seen_test.dartnew file mode 100644index 000000000..d0af33a18--- /dev/null+++ b/desktop/test/swarm_join_seen_test.dart@@ -0,0 +1,139 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/join_seen.dart';++import 'support/memory_key_value_store.dart';++// Task #3160 (Scholes, 11-05): a Swarm joined anywhere but Desktop's own join+// dialog never added this computer. Discovery now asks which listed Swarms+// are new here, so the join's add runs once for each.+void main() {+ late MemoryKeyValueStore store;+ setUp(() => store = MemoryKeyValueStore());++ test(+ 'the first pass takes the Swarms already here as seen and returns the rest',+ () async {+ final seen = SwarmJoinSeen(store);+ expect(+ await seen.fresh(+ 'mate',+ ['old', 'hidden', 'domain'],+ knownHere: {'old', 'hidden'},+ ),+ ['domain'],+ );+ },+ );++ test(+ 'a recorded Swarm is never returned again, also after a restart',+ () async {+ final seen = SwarmJoinSeen(store);+ expect(await seen.fresh('mate', ['old', 'domain'], knownHere: {'old'}), [+ 'domain',+ ]);+ await seen.mark('mate', 'domain');+ expect(+ await seen.fresh('mate', ['old', 'domain'], knownHere: const {}),+ isEmpty,+ );+ final restarted = SwarmJoinSeen(store);+ expect(+ await restarted.fresh('mate', ['old', 'domain'], knownHere: const {}),+ isEmpty,+ );+ // A Swarm joined later, on the web, is new even though nothing shows it here yet.+ expect(+ await restarted.fresh('mate', [+ 'old',+ 'domain',+ 'web',+ ], knownHere: const {}),+ ['web'],+ );+ },+ );++ test('a Swarm not recorded yet stays new until it is', () async {+ final seen = SwarmJoinSeen(store);+ await seen.fresh('mate', const [], knownHere: const {});+ // A viewer's Swarm is never recorded, so it is asked about again.+ expect(await seen.fresh('mate', ['viewed'], knownHere: const {}), [+ 'viewed',+ ]);+ expect(await seen.fresh('mate', ['viewed'], knownHere: const {}), [+ 'viewed',+ ]);+ });++ test('each account keeps its own record', () async {+ final seen = SwarmJoinSeen(store);+ await seen.fresh('mate', ['pilot'], knownHere: {'pilot'});+ expect(await seen.fresh('other', ['pilot'], knownHere: const {}), [+ 'pilot',+ ]);+ });++ test('a join recorded before the first pass still lets the first pass take what is here as seen', () async {+ final seen = SwarmJoinSeen(store);+ await seen.mark('mate', 'joined');+ expect(+ await seen.fresh('mate', ['old', 'joined', 'domain'], knownHere: {'old'}),+ ['domain'],+ );+ });++ test('a Swarm no longer listed is dropped from the record, unless recorded in this run', () async {+ final seen = SwarmJoinSeen(store);+ await seen.fresh('mate', ['a', 'b'], knownHere: {'a', 'b'});+ await seen.mark('mate', 'just-joined');+ await seen.fresh('mate', ['a'], knownHere: const {});+ final restarted = SwarmJoinSeen(store);+ // Left and joined again: a new membership, added again.+ expect(+ await restarted.fresh('mate', [+ 'a',+ 'b',+ 'just-joined',+ ], knownHere: const {}),+ ['b'],+ );+ });++ test('an unreadable record is taken as none', () async {+ store.values[SwarmJoinSeen.keyFor('mate')] = '{not json';+ final seen = SwarmJoinSeen(store);+ expect(await seen.fresh('mate', ['old', 'new'], knownHere: {'old'}), [+ 'new',+ ]);+ });++ test('a write that fails neither throws nor stops the next one', () async {+ final failing = _FailingOnce();+ final seen = SwarmJoinSeen(failing);+ await seen.fresh('mate', ['a', 'b'], knownHere: const {});+ await seen.mark('mate', 'a');+ await seen.mark('mate', 'b');+ final restarted = SwarmJoinSeen(failing);+ expect(+ await restarted.fresh('mate', ['a', 'b'], knownHere: const {}),+ isEmpty,+ );+ });+}++/// A store whose first write fails, as a full disk does once.+class _FailingOnce extends MemoryKeyValueStore {+ var _failed = false;++ @override+ Future<void> write(String key, String value) async {+ if (!_failed) {+ _failed = true;+ throw const FileSystemException('No space left on device');+ }+ await super.write(key, value);+ }+}diff --git a/desktop/test/team_account_lock_test.dart b/desktop/test/team_account_lock_test.dartindex 06bfe9e6e..9bae3b116 100644--- a/desktop/test/team_account_lock_test.dart+++ b/desktop/test/team_account_lock_test.dart@@ -319,7 +319,7 @@ void main() {expect(outcome(tester),'macOS is asking for your password in a window titled “osascript”. '- 'Setup then takes a minute or two, and Harness opens when it is done.',+ 'After that, setup goes on in the background and you can keep working.',);expect(find.byType(CircularProgressIndicator), findsOneWidget);await tester.pump(const Duration(seconds: 2));@@ -473,7 +473,7 @@ void main() {expect(outcome(tester),'macOS is asking for your password in a window titled “osascript”. '- 'Setup then takes a minute or two, and Harness opens when it is done.',+ 'After that, setup goes on in the background and you can keep working.',);expect(find.byType(CircularProgressIndicator), findsOneWidget);expect(find.byKey(const Key('team-account-lock-retry')), findsOneWidget);@@ -515,10 +515,11 @@ void main() {);// Scholes, 2026-11-04: the new member's setup did finish, after about 7- // minutes on a screen that showed no progress. It says the step and the- // time so far, and which step can take minutes.+ // minutes on a screen that showed no progress. While the password is asked+ // it says how long it has waited; past it, the lock steps aside and this+ // Mac's row says the step and the time left (#3169).testWidgets(- 'while it waits, it says the step setup is on and how long it has run',+ 'while it waits for the password it says how long, and past it the lock steps aside',(tester) async {daemon.statuses..clear()@@ -544,23 +545,17 @@ void main() {expect(outcome(tester),'macOS is asking for your password in a window titled “osascript”. '- 'Setup then takes a minute or two, and Harness opens when it is done.',+ 'After that, setup goes on in the background and you can keep working.',);expect(find.text('1 s so far.'), findsOneWidget);+ expect(find.byKey(const Key('team-account-lock-retry')), findsOneWidget);await tester.pump(const Duration(seconds: 2));+ expect(find.byKey(const Key('team-account-lock')), findsNothing);+ expect(app.teamSetupLocked, isTrue);expect(- outcome(tester),- 'Installing Claude Code and Codex for Harness Team. '- 'On a new Mac this can take several minutes.',+ TeamSetupWatch.of(app)!.line,+ 'Harness Team: setting up · step 2 of 4 · about 4 min left',);- expect(- find.text(- 'Step 5 of 8 · 2 min 5 s so far. Harness opens when it is done.',- ),- findsOneWidget,- );- expect(find.byType(CircularProgressIndicator), findsOneWidget);- expect(find.byKey(const Key('team-account-lock-retry')), findsOneWidget);},);diff --git a/desktop/test/team_account_offer_test.dart b/desktop/test/team_account_offer_test.dartindex 2a316e639..a67c23247 100644--- a/desktop/test/team_account_offer_test.dart+++ b/desktop/test/team_account_offer_test.dart@@ -559,7 +559,8 @@ void main() {expect(await outcome(tester, 'macos', {'ok': true, 'state': 'started'}),'macOS is asking for your password in a window titled “osascript”. '- 'Setup then takes a minute or two. This Mac\'s row updates when it is ready.',+ 'After that, setup goes on in the background: this Mac\'s row in '+ 'Machines shows how far it is, and Harness tells you when it is ready.',);expect(await outcome(tester, 'macos', {'ok': true, 'state': 'exists'}),@@ -592,8 +593,9 @@ void main() {await tester.pumpAndSettle();expect(await outcome(tester, 'linux', {'ok': true, 'state': 'started'}),- 'Your system is asking for your password. Setup then takes a minute or two. '- 'This computer\'s row updates when it is ready.',+ 'Your system is asking for your password. After that, setup goes on '+ 'in the background: this computer\'s row in Machines shows how far it is, '+ 'and Harness tells you when it is ready.',);// No desktop session to ask in (the owner's daemon under systemd --user, or SSH): the daemon answers `no-prompt` up// front (cli/src/team/autoSetup.ts) and nothing runs, so the terminal is the way.@@ -633,8 +635,9 @@ void main() {daemon.asked.clear();expect(await outcome(tester, 'windows', {'ok': true, 'state': 'started'}),- 'Windows is asking for permission. Setup then takes a minute or two. '- 'This computer\'s row updates when it is ready.',+ 'Windows is asking for permission. After that, setup goes on '+ 'in the background: this computer\'s row in Machines shows how far it is, '+ 'and Harness tells you when it is ready.',);expect(await outcome(tester, 'windows', {'ok': true, 'state': 'exists'}),diff --git a/desktop/test/team_setup_background_test.dart b/desktop/test/team_setup_background_test.dartnew file mode 100644index 000000000..f55b20f74--- /dev/null+++ b/desktop/test/team_setup_background_test.dart@@ -0,0 +1,404 @@+// #3169 (Scholes, 2026-11-05): after the password, Harness Team setup took 5 to 7 minutes and held the whole app. It now+// runs in the background: the lock steps aside once the password is accepted, this Mac's row in Machines says the step+// and the time left, and a notice says when it is ready or failed, with Retry. Nothing here opens a socket, signs the+// CLI in or out, or makes a macOS account: the daemon's answers are a fake's.+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/machines.dart';+import 'package:harness/super_tabs/team_account_setup.dart';++import 'support/capture.dart';+import 'support/rename_connection.dart';+import 'support/super_tab_fixture.dart';+import 'swarm_state_test.dart' show createApp;++/// This Mac's daemon for the Harness Team account's actions.+class _Daemon extends RenameConnection {+ final asked = <String>[];+ Map<String, dynamic> check = {'ok': true, 'state': 'wanted'};+ Map<String, dynamic> run = {'ok': true, 'state': 'started'};++ /// `teamSetupStatus`, in turn; the last one repeats.+ final statuses = <Map<String, dynamic>>[+ {'ok': true, 'state': 'running'},+ ];++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ final action = '${payload['action']}';+ if (type == 'super_tabs' && action.startsWith('teamSetup')) {+ asked.add(action);+ return switch (action) {+ 'teamSetupCheck' => check,+ 'teamSetup' => run,+ 'teamSetupStatus' =>+ statuses.length > 1 ? statuses.removeAt(0) : statuses.single,+ _ => {'ok': true},+ };+ }+ return super.request(type, payload: payload, timeout: timeout);+ }+}++Map<String, dynamic> _running(String step, {int elapsedMs = 20000}) => {+ 'ok': true,+ 'state': 'running',+ 'step': step,+ 'elapsedMs': elapsedMs,+};++/// Set to a folder to write the PR's pictures there.+final shots = Platform.environment['TEAM_SETUP_SHOTS'];++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ setUpAll(() => loadCaptureFonts(shots));+ late _Daemon daemon;+ late AppNotifier app;++ setUp(() {+ daemon = _Daemon();+ app = createApp(connectionForTest: (_) => daemon, connected: true);+ app.currentUser = const CurrentUserProfile(+ id: 'owner',+ email: '[email protected]',+ );+ app.machineStates['m']!.localOnly = true;+ app.teamAccountHereForTest = true;+ });+ tearDown(() => app.dispose());++ group('the time left', () {+ test('four steps, from the eight setup says', () {+ expect(+ [+ for (final step in [+ 'password',+ 'account',+ 'home',+ 'privacy',+ 'runtime',+ 'copy-engines',+ 'engines',+ 'sign-in',+ 'daemon',+ 'report',+ 'something-new',+ ])+ teamSetupPhase(step),+ ],+ [null, 1, 1, 1, 2, 2, 2, 3, 3, 4, null],+ );+ });++ test('from the measured step times, never nothing while it runs', () {+ // The npm download is the long one (4 min 18 s on 2026-11-04); the copy that replaced it takes seconds.+ expect(+ teamSetupLine('engines', Duration.zero),+ 'Harness Team: setting up · step 2 of 4 · about 4 min left',+ );+ expect(+ teamSetupLine('copy-engines', Duration.zero),+ 'Harness Team: setting up · step 2 of 4 · less than a minute left',+ );+ expect(+ teamSetupLine('account', Duration.zero),+ 'Harness Team: setting up · step 1 of 4 · less than a minute left',+ );+ expect(+ teamSetupLine('engines', const Duration(minutes: 2)),+ 'Harness Team: setting up · step 2 of 4 · about 2 min left',+ );+ // Past what it usually takes (a slow network), it still says a minute is left, never zero.+ expect(+ teamSetupLine('engines', const Duration(minutes: 9)),+ 'Harness Team: setting up · step 2 of 4 · about 1 min left',+ );+ expect(+ teamSetupLine('report', const Duration(minutes: 9)),+ 'Harness Team: setting up · step 4 of 4 · less than a minute left',+ );+ // A step this app does not know yet: setting up, without a number it cannot give.+ expect(+ teamSetupLine('something-new', Duration.zero),+ 'Harness Team: setting up',+ );+ });+ });++ group('in the background', () {+ final messenger = GlobalKey<ScaffoldMessengerState>();+ var taps = 0;++ /// The window as app_shell.dart builds it, the lock above the Navigator, with this Mac's row in Machines when+ /// [server] is given.+ /// Its Swarm's controller, for [unmount].+ dynamic shown;++ Future<void> window(+ WidgetTester tester, {+ ConversationServer? server,+ }) async {+ taps = 0;+ final c = server?.controller(account: 'owner');+ shown = c;+ if (c != null) await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ scaffoldMessengerKey: messenger,+ builder: (context, child) => TeamAccountSetupLock(+ app: app,+ operatingSystem: 'macos',+ child: child!,+ ),+ home: Scaffold(+ body: Column(+ children: [+ TextButton(+ key: const Key('behind-button'),+ onPressed: () => taps++,+ child: const Text('Behind'),+ ),+ if (c != null)+ Expanded(+ child: SuperTabMachines(+ controller: c,+ app: app,+ onAddAgent: (_) {},+ ),+ ),+ ],+ ),+ ),+ ),+ );+ await tester.pump();+ }++ ConversationServer swarm() {+ final server = ConversationServer();+ (server.state['people'] as List).add({+ 'id': 'peer',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ server.state['machines'] = [+ {+ 'machineId': 'm',+ 'name': 'MacBooks-MacBook-Pro-7',+ 'contributorId': 'owner',+ 'scope': 'swarm',+ 'cwd': '/swarm',+ 'engines': ['codex'],+ 'maxAgents': 4,+ 'paused': false,+ 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},+ 'teamWork': {+ 'allowed': false,+ 'code': 'TEAM_ACCOUNT_REQUIRED',+ 'reason': 'Refused.',+ },+ },+ ];+ return server;+ }++ Future<void> continueSetup(WidgetTester tester) async {+ await app.offerTeamAccount('join', tabId: 'tab-1');+ await tester.pump();+ await tester.tap(find.byKey(const Key('team-account-lock-continue')));+ await tester.pump();+ }++ testWidgets(+ 'once the password is accepted the lock steps aside and the app takes clicks, while setup still runs',+ (tester) async {+ daemon.statuses+ ..clear()+ ..addAll([_running('password'), _running('engines')]);+ await window(tester);+ await continueSetup(tester);+ // While macOS asks for the password, the lock waits with it.+ await tester.pump(const Duration(seconds: 2));+ expect(find.byKey(const Key('team-account-lock')), findsOneWidget);+ await tester.tap(+ find.byKey(const Key('behind-button')),+ warnIfMissed: false,+ );+ expect(taps, 0);+ // The password is in: setup goes on behind, and the app is the person's again.+ await tester.pump(const Duration(seconds: 2));+ expect(find.byKey(const Key('team-account-lock')), findsNothing);+ expect(app.teamSetupLocked, isTrue);+ await tester.tap(find.byKey(const Key('behind-button')));+ expect(taps, 1);+ expect(TeamSetupWatch.of(app)!.running, isTrue);+ },+ );++ testWidgets(+ 'this Mac\'s row says the step and the time left, and that the person can keep working',+ (tester) async {+ daemon.statuses+ ..clear()+ ..add(_running('engines'));+ await window(tester, server: swarm());+ await continueSetup(tester);+ await tester.pump(const Duration(seconds: 2));+ await tester.pump();+ expect(+ tester+ .widget<Text>(+ find.byKey(const ValueKey('super-machine-problem-m')),+ )+ .data,+ 'Harness Team: setting up · step 2 of 4 · about 4 min left\n'+ 'Keep working. We\'ll tell you when it\'s ready.',+ );+ // Nothing to press while it runs: Set up would ask for the password again.+ expect(+ find.byKey(const ValueKey('super-machine-team-setup-m')),+ findsNothing,+ );+ // Past the row's arrival fade, for the picture.+ await tester.pump(const Duration(milliseconds: 1500));+ await captureWindow(tester, shots, 'row-setting-up');+ await tester.pumpWidget(const SizedBox());+ await shown.flush();+ shown.dispose();+ },+ );++ testWidgets(+ 'a setup that finishes says so, and the lock is gone for good',+ (tester) async {+ daemon.statuses+ ..clear()+ ..addAll([+ _running('engines'),+ {'ok': true, 'state': 'exists'},+ ]);+ await window(tester);+ await continueSetup(tester);+ await tester.pump(const Duration(seconds: 2));+ expect(find.byKey(const Key('team-account-lock')), findsNothing);+ await tester.pump(const Duration(seconds: 2));+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 500));+ expect(+ find.text(+ 'Harness Team is ready on this Mac. Teammates\' agents can run here now.',+ ),+ findsOneWidget,+ );+ expect(app.teamSetupLocked, isFalse);+ expect(find.byKey(const Key('team-account-lock')), findsNothing);+ await captureWindow(tester, shots, 'notice-ready');+ // Nothing is read once it has ended.+ final reads = daemon.asked.where((a) => a == 'teamSetupStatus').length;+ await tester.pump(const Duration(seconds: 10));+ expect(+ daemon.asked.where((a) => a == 'teamSetupStatus'),+ hasLength(reads),+ );+ },+ );++ testWidgets(+ 'a setup that fails after the lock stepped aside brings it back, with the reason and Try again',+ (tester) async {+ daemon.statuses+ ..clear()+ ..addAll([+ _running('engines'),+ {+ 'ok': true,+ 'state': 'failed',+ 'detail': 'launchd would not start the team daemon',+ },+ ]);+ await window(tester);+ await continueSetup(tester);+ await tester.pump(const Duration(seconds: 2));+ expect(find.byKey(const Key('team-account-lock')), findsNothing);+ await tester.pump(const Duration(seconds: 2));+ await tester.pump();+ expect(find.byKey(const Key('team-account-lock')), findsOneWidget);+ expect(+ tester+ .widget<Text>(find.byKey(const Key('team-account-lock-outcome')))+ .data,+ 'Setup did not finish: launchd would not start the team daemon.',+ );+ expect(+ find.byKey(const Key('team-account-lock-retry')),+ findsOneWidget,+ );+ },+ );++ testWidgets(+ 'started from this Mac\'s row, a failure is a notice with the reason and Retry, and Retry starts it again',+ (tester) async {+ daemon.statuses+ ..clear()+ ..addAll([+ _running('runtime'),+ {'ok': true, 'state': 'failed', 'detail': 'dscl exited 64.'},+ ]);+ await window(tester);+ expect(app.teamSetupLocked, isFalse);+ // What the row's Set up does once its dialog's Continue has started setup.+ TeamSetupWatch.of(app)!.follow();+ await tester.pump(const Duration(seconds: 2));+ await tester.pump();+ await tester.pump(const Duration(seconds: 2));+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 500));+ expect(+ find.text('Harness Team setup did not finish. dscl exited 64.'),+ findsOneWidget,+ );+ await captureWindow(tester, shots, 'notice-failed');+ daemon.statuses+ ..clear()+ ..add(_running('password'));+ await tester.tap(find.byKey(const Key('team-setup-notice-retry')));+ await tester.pump();+ await tester.pump();+ expect(daemon.asked.where((a) => a == 'teamSetup'), hasLength(1));+ expect(TeamSetupWatch.of(app)!.running, isTrue);+ messenger.currentState?.clearSnackBars();+ },+ );++ testWidgets('a closed password window, from the row, says so with Retry', (+ tester,+ ) async {+ daemon.statuses+ ..clear()+ ..add({'ok': true, 'state': 'declined'});+ await window(tester);+ TeamSetupWatch.of(app)!.follow();+ await tester.pump(const Duration(seconds: 2));+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 500));+ expect(+ find.text(+ 'Harness Team setup did not finish. The password window was closed.',+ ),+ findsOneWidget,+ );+ expect(find.byKey(const Key('team-setup-notice-retry')), findsOneWidget);+ messenger.currentState?.clearSnackBars();+ });+ });+}diff --git a/docs/design/2026-11-05-phone-push.md b/docs/design/2026-11-05-phone-push.mdnew file mode 100644index 000000000..0a732db82--- /dev/null+++ b/docs/design/2026-11-05-phone-push.md@@ -0,0 +1,185 @@+# Phone push notifications: the phone's side, and the contract the backend builds to++Status: the server part merged first (#3071) with its own routes and payload, and the phone now+follows it. Where this contract and the merged server differ, the server wins: the gaps are listed+in [docs/plans/2026-11-05-phone-push-backend-plan.md](../plans/2026-11-05-phone-push-backend-plan.md#merged-server-11-05-what-differs-from-this-plan).++Phase 1 only: the push carries ids and the same short copy the app's own notices use, never what was+asked or said. Phase 2 (a payload sealed to the phone's device key, opened by a Notification Service+Extension) is not part of this.++## What the phone does++- While someone is signed in and the OS allows notices, the phone tells the backend its push address:+ the APNs device token on iOS, the FCM registration token on Android.+ (`mobile/lib/notify/push_tokens.dart`, `push_channel.dart`)+- It tells again when the token, its APNs gateway or the account changes, and otherwise every 7 days.+ It is told once the account is known, when notices are allowed, when the OS hands over a new token,+ and when the app comes back to the front. It is never told while signed out.+- Notices turned off in the phone's Settings: the phone asks the backend to forget the token.+- Sign-out: the phone asks the backend to forget the token. It also stops the OS delivering to it+ (iOS `unregisterForRemoteNotifications`, Android `deleteToken`), so a backend that missed the+ request still reaches nothing. On Android nothing is drawn after a sign-out in any case.+- A push that lands while Harness is in front is not shown: the app is up and posts its own notices,+ which know what the person is looking at.+- A tapped push opens what the same local notice opens: the Swarm conversation (at the message and+ thread, or the decision), or the agent.++## API (backend)++Both are signed with the phone's own sign-in (`Authorization: Bearer`). The account is always the+caller's, never a field of the body.++### `PUT /api/push-tokens`++```json+{ "token": "…", "platform": "ios", "environment": "production", "device": "…" }+```++| Field | |+| --- | --- |+| `token` | APNs device token (hex) or FCM registration token. |+| `platform` | `ios` or `android`. |+| `environment` | iOS only: `sandbox` (a build Xcode signed for development, or the simulator) or `production` (TestFlight, App Store). Absent on Android. |+| `device` | Optional. This phone's device key, base64, the same value the phone sends as `self` to `GET /api/device-keys`. Removing that device from the account removes its token. |++- Upsert by `token`. A token already stored for another account moves to the caller: the last+ sign-in on a phone owns it. Refresh `updatedAt`.+- Answers `{ "success": true, "data": {} }`. Any other answer counts as not stored: the phone tries+ again after an hour, or at the next launch.++### `DELETE /api/push-tokens`++```json+{ "token": "…" }+```++Removes the token if it belongs to the caller. Idempotent: an unknown token also answers success.+The token is in the body, not the path, so it stays out of access logs.++## What a push carries++Every value is a string, beside the platform's own fields:++| `kind` | Keys | Opens |+| --- | --- | --- |+| `swarm` | `swarm`, `conversation`, and `message` (with `thread` when the message is only in a thread) or `decision`; `key` | the conversation, at the message or the decision |+| `agent_question`, `agent_done` | `machine`, `agent` | that agent |++`key` is the need's key, as `SwarmNeed.key` makes it (`mobile/lib/swarm/swarm_inbox.dart`):+`decision:<id>`, `mention:<id>`, or `work:<swarm>:<conversation>:<assignment>:<status>`.++The copy is the app's own notices' (`swarmNotice` in `mobile/lib/swarm/swarm_notices.dart`). For+example, title `Ann asks you`, subtitle the project's name, body `Open Harness to answer.` Who asks+and where, never what. Send no `badge`: the app sets the count itself.++### iOS (APNs)++```json+{+ "aps": {+ "alert": { "title": "Ann asks you", "subtitle": "Website", "body": "Open Harness to answer." },+ "sound": "default",+ "thread-id": "swarm-needs-you"+ },+ "kind": "swarm", "swarm": "…", "conversation": "…", "decision": "…", "key": "decision:…"+}+```++- Headers: `apns-push-type: alert`, `apns-topic: ai.autonomous.harness.ios`, `apns-priority: 10`, and+ `apns-collapse-id` set to the notice id (below).+- `thread-id`: `swarm-needs-you`, `agent-question` or `agent-done`, the app's own threads.+- A token goes to its own gateway: `sandbox` to `api.sandbox.push.apple.com`, `production` to+ `api.push.apple.com`. The team has one APNs key per gateway, each limited to its own, so the+ sender signs a token's push with the key of that token's `environment`. Both keys are the+ backend's secrets, never in this repository.++### Android (FCM HTTP v1)++`POST https://fcm.googleapis.com/v1/projects/autonomous-harness/messages:send`. The message is+**data-only**, with no `notification` block. `PushService.kt` draws it on the app's own channel for+that kind, so one switch in Settings silences both.++```json+{ "message": {+ "token": "…",+ "data": { "kind": "swarm", "title": "Ann asks you", "subtitle": "Website",+ "body": "Open Harness to answer.", "swarm": "…", "conversation": "…",+ "decision": "…", "key": "decision:…" },+ "android": { "priority": "HIGH", "ttl": "86400s" } } }+```++Every high-priority message must end in a notice, or Android lowers the app's priority. The phone+drops one only when it is signed out or in front.++The phone registers FCM *registration tokens* (`getToken`). firebase-messaging deprecated them in+25.1.0 for Installation-ID registration (`register()`), but HTTP v1 still documents sending to tokens+only. Moving to Installation IDs is a new field, added beside `token`, not a change to it.++### The notice id, shared with the app's own notices++A push and the local notice the running app posts for the same news carry the same id, so one+replaces the other instead of two stacking. The id is FNV-1a over the text's UTF-16 code units, kept+to 31 bits:++```+hash = 0x811c9dc5+for each UTF-16 code unit u: hash = ((hash XOR u) * 0x01000193) AND 0x7fffffff+```++- Text: `swarm\n` + `key` for a Swarm need; `<machine>\n<agent>` for an agent.+- iOS: `apns-collapse-id` is the id in decimal. Android: the phone computes it from the data.++Test vectors, pinned in `mobile/test/notify/local_system_notices_test.dart`:++| Text | Id |+| --- | --- |+| `swarm\nmention:m1` | 1161357565 |+| `swarm\ndecision:d1` | 15921470 |+| `swarm\nwork:s1:c1:a1:needs_human` | 701122187 |+| `machine-1\nagent-7` | 1081005959 |++## Design++- **Growth.** One row per token. Rows are deleted by:+ - `DELETE` on sign-out or when notices are turned off;+ - a register by another account, which moves the row;+ - the provider saying the token is gone (APNs 410 `Unregistered`, FCM `UNREGISTERED`);+ - removal of the device whose key it carries;+ - 60 days without a renewal (the phone renews every 7).++ Limit: 20 tokens per account, the oldest dropped first.+- **Concurrency.** A unique index on `token`. A register is one atomic upsert and a delete one+ delete; nothing locks more than the row.+- **Read cost.** Sending reads one account's tokens by an index on the account. A phone writes at+ most once per 7 days unless its token, gateway or account changes.+- **Scale.** At 10x the phones, the rows stay small and the reads indexed. The first warning is the+ rate of failed sends per provider; log it with the provider's reason.+- **Compatibility.**+ - A phone from before this: no rows, no pushes; nothing else changes.+ - This phone against a backend from before this: 404, logged under `push`. The phone retries after+ an hour or at the next launch and shows nothing to the person.+ - The backend ships first.+- **Migration and rollback.** A new collection, no migration. Rollback removes the routes and the+ collection; the phone treats the missing route as above.+- **Audience.** The server binds each token to the caller's account, and `DELETE` removes only the+ caller's own rows. A push names ids only. Opening one shows only what the account may read, since+ Swarm reads check access as before.+- **Identity.** The signed-in person's account, from their own sign-in, never a machine owner's.+- **Failure.** The phone logs each failed register or delete under `push`, with the HTTP status,+ never the token. The backend logs each provider refusal with its reason.+- **Platforms.**+ - iOS 15+: the `aps-environment` entitlement, with an App Store export signed as `production`.+ - Android 7+ (API 24): `firebase-messaging` with its values in `res/values/firebase.xml`, with no+ google-services plugin.++## Not in this change++- **Backend:**+ - token store and routes;+ - the APNs and FCM senders and their keys;+ - the triggers (Swarm needs; agent questions and finished turns asked for by the CLI when no app is+ connected).+- **CLI:** asking the backend to push an agent's question or finished turn.+- **Measures:** the push measures need names in the backend's product-usage vocabulary first.+- **Phase 2:** the sealed payload and the Notification Service Extension.diff --git a/docs/plans/2026-11-05-join-add-any-join-plan.md b/docs/plans/2026-11-05-join-add-any-join-plan.mdnew file mode 100644index 000000000..5e3129d3d--- /dev/null+++ b/docs/plans/2026-11-05-join-add-any-join-plan.md@@ -0,0 +1,83 @@+# This Mac is added however its person joined: plan++> Way of working: test-driven, one Engineer, by the project instructions (Engineer role). No Execution Handoff.++**Goal:** a new collaborator's computer is added to the Swarm and offered the Harness Team account once, however they+joined: Desktop's join dialog, an invitation, a domain auto-join on the server, a Workspace-open join, or a join made on+the phone or the web first (task #3160, Scholes 11-05: about a dozen people had to add their machine by hand).++**Architecture:** the join auto-add (`AppNotifier.addMachineOnJoin`, `super_tabs/join_machine.dart`+`SwarmJoinMachine`) ran only from the two join paths in Desktop. Swarm discovery (`SuperTabs.refreshTabs` →+`onTabs`) already lists every Swarm the account is in, however it got there, so it becomes the second trigger. A new+`SwarmJoinSeen` (`super_tabs/join_seen.dart`) remembers, per account on this computer, the Swarms the add was already+decided for; discovery hands it the listed Swarms and gets back the ones new here. For each, the app reads the Swarm,+and when the person is a collaborator records it and runs the same add and Team offer as the join does. The join+paths record the Swarm too, so neither trigger runs it twice. The add's steps are unchanged.++**Tech stack:** Dart, Flutter, flutter_test.++**Spec:** task #3160.++## Global constraints++- The auto-add steps themselves (`SwarmJoinMachine.add`, `offerTeamAccount`) do not change.+- Viewers are never recorded and never added; an owner's Swarm is recorded and left alone.+- Tests use a memory store and a fake sign-in; nothing signs the real CLI in or out.+- Swarm code stays out of `cli/src/core` (nothing there changes).++## Design++- Growth: one Swarm id per Swarm the account belongs to, per account, on this computer. Each full discovery prunes the+ record to the Swarms still listed (plus any recorded in this session, which a list may not show yet).+- Concurrency: one app process owns the record; one pass at a time (a pass still running skips the next discovery),+ and the existing per-Swarm in-flight set keeps the join and discovery from adding at once.+- Read cost: nothing new is read for a Swarm already in the record. A new Swarm is opened once (its snapshot says the+ person's role and the machines in it).+- Scale: 10x Swarms per person is 10x ids in one small local value; the first warning is the pass's opens on a fresh+ install, one per collaborator Swarm, once.+- Compatibility: the first time this build keeps a record for an account, the Swarms already open or hidden on this+ computer are taken as seen, so updating never adds a long-time member's computer to Swarms they chose not to add it+ to. A fresh install has none, so a person who joined on the web first and then installs Desktop is added.+- Migration + rollback: a new local key (`swarm_join_seen.<account>`). An older build ignores it; rolling back leaves+ it unused.+- Audience: the server still decides who may add a machine (`machine.contribute`); the client only decides when to ask.+- Identity: the record and the add are per signed-in account; an account change mid-pass stops it.+- Failure: a step that fails after the person is known to be a collaborator shows the join note with what to do (add+ it from Machines, set up the Team account from Machines), not only a log line.+- Platforms: Desktop on macOS (the Team account is macOS only); on other systems the add stays as it is today.++## Review focus++- That it runs once per Swarm and person, never for a viewer, and never twice when the join dialog and discovery both+ see the same new Swarm.+- That an update does not add a long-time member's computer to Swarms it was never added to.+- That every failed step a collaborator meets ends in a note.++## Tasks++### Task 1: which Swarms are new on this computer++Files: `desktop/lib/super_tabs/join_seen.dart`, `desktop/test/swarm_join_seen_test.dart`.++- [ ] Failing test: the first pass takes the Swarms known here as seen and returns the rest; a recorded Swarm is never+ returned again, also after a restart (a new `SwarmJoinSeen` on the same store); records are per account; a Swarm no+ longer listed is pruned.+- [ ] Implement `SwarmJoinSeen`.++### Task 2: discovery runs the join's add once for a new collaborator Swarm++Files: `desktop/lib/state/app_state.dart`, `desktop/test/swarm_join_any_test.dart`.++- [ ] Failing test: a Swarm first seen through discovery (a domain auto-join) adds this Mac and offers the Team account+ once; a second discovery and a restart do nothing more; a viewer is neither added nor recorded; the join dialog's add+ then discovery adds once.+- [ ] Hook `SwarmJoinSeen` into `onTabs`; share one add path between the join and discovery.++### Task 3: a failed step shows the person a note++Files: `desktop/lib/super_tabs/join_machine.dart`, `desktop/lib/super_tabs/join_machine_note.dart`,+`desktop/lib/state/app_state.dart`, `desktop/test/swarm_join_any_test.dart`, `desktop/test/swarm_join_machine_test.dart`.++- [ ] Failing tests: reading the Swarm failing for a collaborator's join, and the Team offer not answering, each show a+ note saying what to do.+- [ ] Emit those notes; the note reads a Team offer that failed.diff --git a/docs/plans/2026-11-05-phone-push-backend-plan.md b/docs/plans/2026-11-05-phone-push-backend-plan.mdnew file mode 100644index 000000000..164efb49d--- /dev/null+++ b/docs/plans/2026-11-05-phone-push-backend-plan.md@@ -0,0 +1,468 @@+# Phone push notifications: backend plan (phase 1)++- **For:** the backend team (and whoever owns the CLI part in section 6.2).+- **Date:** 2026-11-05.+- **Phone side:** built in the same pull request as this plan (`feat/mobile-push-notifications`). The contract it was+ built to is `docs/design/2026-11-05-phone-push.md`. This plan is how to build the backend half of it in this repo.+- **Secrets:** the two APNs `.p8` files and the FCM credentials are **not** in this file. They are handed over+ separately, on a secure channel. Section 1 says where each one goes.++## Merged server, 11-05: what differs from this plan++The server part merged in #3071 (task #2905, backend v1.4.9) before this plan was read. The phone in this pull request+now follows what merged. One line per gap; **phone** ones are fixed here, **server** ones go to the PM as proposals.++| # | Gap | Plan | Merged | Where it goes |+| --- | --- | --- | --- | --- |+| 1 | Route | `PUT` / `DELETE /api/push-tokens` | `POST /api/push-devices`, `POST /api/push-devices/drop` | phone, fixed |+| 2 | Register body | `token`, `platform`, `environment`, `device` | strict `{platform, token}`: any other key answers 400 | phone, fixed |+| 3 | Payload field | `kind`, `swarm`, `conversation`, `message`, `thread`, `decision`, `key` | `key` and `link` (the app's `swarm:` payload) | phone, fixed |+| 4 | Platform: Android | data-only, drawn by `PushService` | a notification message Android draws (channel `swarm-needs-you`, tag = `key`) | phone, fixed: the tap is read from the launch intent |+| 5 | Platform: iOS gateway | the phone sends `environment`; one APNs key per gateway | one APNs key; a token production calls bad is retried on the sandbox and marked | phone, fixed (sends none). The owner's key must be valid for both hosts |+| 6 | Device key | rows carry `device`; removing a phone from the account deletes its rows | no `device`; a row goes at sign-out, when Apple or Google call it dead, or after 90 days | server, proposal |+| 7 | Triggers | decisions, tags and waiting work (`needs_human`, `blocked`); no thread replies | thread replies and tags only | server, proposal: decisions and waiting work |+| 8 | Held tags | pushed when a quiet chat's grace ends | a held tag is skipped and nothing pushes it later | server, proposal |+| 9 | Agent question / finished turn | CLI `push_request` frame (6.2) | not built | server and CLI, proposal (the phone reads none today) |+| 10 | Notice id | `apns-collapse-id` = the shared FNV id | none on iOS; Android tag is the `key` text | server, proposal: a push and the app's own notice can both show |+| 11 | Limits | 20 rows per account, 60 days | 10 rows per person, 90 days (TTL index) | none: the phone renews every 7 days |+| 12 | Sign-out on Android | `PushService` draws nothing once signed out | Android draws a notification message itself | none while the phone's drop or FCM token delete lands; both failing shows pushes until the server drops the row |++## 0. Scope++What the phone already does:++- Signed in, with notices allowed by the OS, it sends its push address to `PUT /api/push-tokens`. It sends it again+ when the token, its APNs gateway or the account changes, and otherwise once every 7 days. A failed call is retried+ after 1 hour or at the next launch, and is never shown to the person.+- On sign-out, or when notices are turned off, it calls `DELETE /api/push-tokens`. It also stops the OS delivering to+ that token.+- A push that lands while Harness is in front is not shown. A tapped push opens the Swarm conversation (at the message,+ thread or decision) or the agent it names.++What the backend builds:++| # | Part | Section |+| --- | --- | --- |+| 1 | Secrets and config | 1 |+| 2 | `PushToken` collection | 2 |+| 3 | `PUT` / `DELETE /api/push-tokens` | 3 |+| 4 | APNs and FCM senders | 4 |+| 5 | Payload and copy per kind | 5 |+| 6 | Triggers: Swarm needs, agent question / finished turn | 6 |+| 7 | Cleanup of dead tokens | 7 |+| 8 | Logs and metrics | 8 |+| 9 | Tests | 9 |++Not in phase 1: payload encrypted to the device key (phase 2, needs a Notification Service Extension), badge counts+sent by the server (the app sets its own), clearing a notice from the server once the need is resolved.++## 1. Secrets and config++Proposed names, read in `backend/src/config/env.ts` like the other optional keys. Rename freely, but keep them all+optional, so that an unset value turns the sender off (fail closed) without breaking boot.++| Env | Value | Secret? |+| --- | --- | --- |+| `APNS_TEAM_ID` | `54DJVWMJCC` | no |+| `APNS_TOPIC` | `ai.autonomous.harness.ios` (the iOS bundle id) | no |+| `APNS_SANDBOX_KEY_ID` | the sandbox key's id, handed over with its `.p8` | no |+| `APNS_SANDBOX_KEY` | base64 of the sandbox key's `.p8` | **yes** |+| `APNS_PRODUCTION_KEY_ID` | the production key's id, handed over with its `.p8` | no |+| `APNS_PRODUCTION_KEY` | base64 of the production key's `.p8` | **yes** |+| `FCM_PROJECT_ID` | `autonomous-harness` | no |+| `FCM_CREDENTIALS` | base64 of a service account JSON key. Empty: application default credentials (Workload Identity), the same rule as `SUPER_TAB_ATTACHMENTS_CREDENTIALS` | **yes** |++- Each APNs key is limited to **one** gateway: the sandbox key works only on `api.sandbox.push.apple.com`, the+ production key only on `api.push.apple.com`. Pick the key from the token's `environment`.+- The FCM identity (service account or Workload Identity) needs the role `roles/firebasecloudmessaging.admin` on the+ Firebase project `autonomous-harness`.+- Apple lets a `.p8` be downloaded only once. Keep the originals in the team's secret manager, not only in the cluster.+- Never write a key, a token or a push body to logs, errors, metrics, Sentry or a PR.+- Kill switch: with a gateway's key unset, nothing is sent to that gateway, and the routes keep storing tokens (so+ phones do not fall into retries).++## 2. Data: `PushToken`++One row per token. In `backend/prisma/schema.prisma`, in the style of the other models:++```prisma+/// Where to push to one phone (docs/design/2026-11-05-phone-push.md). One row per token; the last+/// account that registered a token owns it.+model PushToken {+ id String @id @default(auto()) @map("_id") @db.ObjectId+ token String @unique+ userId String // req.user.sub+ platform String // "ios" | "android"+ gateway String? // iOS only: "sandbox" | "production" (the request's `environment`)+ device String? // the phone's device key, base64, as sent to GET /api/device-keys `self`+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([userId])+ @@index([device])+ @@index([updatedAt])+ @@map("push_tokens")+}+```++- The column is called `gateway` rather than `environment` so it is never confused with the backend's own+ staging/production environment. The API field stays `environment`.+- New collection: no migration. Rollback drops the routes and the collection.++## 3. Routes: `backend/src/routes/pushTokens.ts`++Follow `routes/deviceKeys.ts`: zod body with `validateBody`, `sendSuccess` / `sendError`, a `createRateLimiter`, and an+export in `routes/index.ts`. Both routes use the caller's own sign-in (`Authorization: Bearer`). The account is always+`req.user.sub`, never a body field.++### `PUT /api/push-tokens`++```json+{ "token": "…", "platform": "ios", "environment": "production", "device": "…" }+```++Validation (strict object):++| Field | Rule |+| --- | --- |+| `token` | string, 1 to 4096 chars |+| `platform` | `"ios"` or `"android"` |+| `environment` | required when `platform` is `ios`: `"sandbox"` or `"production"`. Absent on Android; ignore it if sent |+| `device` | optional string, at most 512 chars |++Behaviour:++1. Upsert by `token`: set `userId` to the caller, `platform`, `gateway`, `device`, and refresh `updatedAt`. A token+ stored for another account **moves** to the caller: the last sign-in on a phone owns it.+2. Keep at most 20 rows per account: after the upsert, delete that account's oldest rows beyond 20.+3. Answer `{ "success": true, "data": {} }`. The phone treats any other answer as "not stored" and retries later.++### `DELETE /api/push-tokens`++```json+{ "token": "…" }+```++- `deleteMany({ token, userId: caller })`. Idempotent: an unknown token, or one owned by someone else, also answers+ success, and deletes nothing of another account's.+- The token is in the body, not in the path, so it never reaches access logs.++### Both++- Rate limit: about 20 calls per account per minute (`createRateLimiter('push-tokens', 60_000, 20)`). A phone sends+ about one call a week.+- Team sessions: do **not** add these routes to `TEAM_ROUTES` (`lib/teamSession.ts`). A team sign-in is a daemon, not a+ phone, and is refused by default.+- Never log the token. If a log needs to tell tokens apart, log the first 8 hex characters of its SHA-256.++## 4. Senders: `backend/src/lib/push/`++Proposed files: `apns.ts`, `fcm.ts`, and `send.ts`. `send.ts` reads the recipient's rows, picks the sender per row,+handles the answer and deletes dead tokens.++- The senders are a library, run in whichever process the trigger fires in (section 6): the API processes (PM2+ cluster, through `afterCommit`) or the worker. Each process keeps its own HTTP/2 session per APNs gateway, which+ Apple allows.+- Fire and forget after the commit: a send never blocks or fails the Swarm write. It has one retry inside the sender+ and no queue. A push lost to a crash is acceptable in phase 1: the app shows every need when it opens.+- Dedupe Swarm needs across processes with a Redis key per recipient and need:+ `SET push:sent:<userId>:<need key> 1 NX EX 86400`. Send only if the `SET` succeeded. Do not dedupe agent pushes this+ way: their notice id is per agent, so a second question from the same agent must still go. The rate limit in 6.2+ bounds them, and the shared notice id makes the newer one replace the older on the phone.++### 4.1 APNs (iOS)++- HTTP/2 with `node:http2`, no new dependency. One session per host, kept open and reused. Reconnect on `GOAWAY` or+ on error.+ - `sandbox` goes to `https://api.sandbox.push.apple.com`.+ - `production` goes to `https://api.push.apple.com`.+- Provider token (JWT, ES256), signed with `node:crypto` (`sign` with `dsaEncoding: 'ieee-p1363'`):+ - header `{ "alg": "ES256", "kid": <key id of that gateway> }`;+ - claims `{ "iss": APNS_TEAM_ID, "iat": <now, seconds> }`;+ - make a new one about every 40 minutes. Apple refuses one older than 60 minutes, and returns+ `TooManyProviderTokenUpdates` if it changes more often than every 20.+- Request `POST /3/device/<token>` with headers:+ - `authorization: bearer <jwt>`+ - `apns-topic: ai.autonomous.harness.ios`+ - `apns-push-type: alert`+ - `apns-priority: 10`+ - `apns-expiration: <now + 86400>`+ - `apns-collapse-id: <notice id, decimal>` (section 5.3)+- Body: section 5. At most 4 KB.+- Answers:++| Status / reason | Do |+| --- | --- |+| 200 | sent |+| 410 `Unregistered` | delete the row |+| 400 `BadDeviceToken` | delete the row; log the row's `gateway` (usually a sandbox token sent to production, or the reverse) |+| 400 `DeviceTokenNotForTopic` | delete the row |+| 403 `ExpiredProviderToken` | make a new JWT and retry once |+| 403 `InvalidProviderToken` | config error: log it loudly, stop sending to that gateway until the config changes |+| 429, 500, 503 | retry once with backoff, then drop and log |++### 4.2 FCM (Android)++- `POST https://fcm.googleapis.com/v1/projects/autonomous-harness/messages:send`.+- OAuth2 access token with scope `https://www.googleapis.com/auth/firebase.messaging`, from `google-auth-library`.+ It is already in `package-lock.json` (9.15.1, through `@google-cloud/storage`); declare it in `package.json` as a+ direct dependency. Cache the access token until shortly before it expires.+- **Data-only** message: no `notification` block. The phone draws the notice itself, on the channel for that kind+ (`PushService.kt`), so one switch in Android Settings silences both the push and the app's own notice.+- `android.priority: "HIGH"` and `android.ttl: "86400s"`. Every high-priority message must end in a notice, or Android+ lowers the app's priority. The phone drops one only when it is signed out or in front.+- Every value in `data` is a string. Do not use reserved keys (`from`, `notification`, `message_type`, anything+ starting with `google.` or `gcm.`).+- Answers:++| Status / error | Do |+| --- | --- |+| 200 | sent |+| 404 `UNREGISTERED` | delete the row |+| 400 `INVALID_ARGUMENT` about the token | delete the row |+| 403 `SENDER_ID_MISMATCH` | delete the row |+| 401 | refresh the access token and retry once; if it fails again, a config error, log it loudly |+| 429 `QUOTA_EXCEEDED`, 500, 503 `UNAVAILABLE` | retry once with backoff (honour `Retry-After`), then drop and log |++## 5. What a push carries++### 5.1 Keys, by kind++Every value is a string.++| `kind` | Keys | Opens |+| --- | --- | --- |+| `swarm` | `swarm`, `conversation`, then either `message` (plus `thread` when the message is only in a thread) or `decision`; `key` | the conversation, at the message or the decision |+| `agent_question`, `agent_done` | `machine`, `agent` | that agent |++- `key` is the need's key, the same as the phone's `SwarmNeed.key` (`mobile/lib/swarm/swarm_inbox.dart`):+ `decision:<id>`, `mention:<id>`, or `work:<swarm>:<conversation>:<assignment>:<status>`.+- Ids are the ones the phone already reads from the backend (section 6 says which row each comes from).+- Any key the phone does not know is ignored. A push with missing ids still shows; tapping it just opens the app.++### 5.2 Copy++Phase 1 says who and where, never what was asked or said: a notice can be read on a locked phone. Use exactly the+app's own copy (`swarmNotice` in `mobile/lib/swarm/swarm_notices.dart`), so a push and the app's notice read the same.+The subtitle is the project's name.++| Need | Title | Body |+| --- | --- | --- |+| Decision asked of the person | `<asker name> asks you` | `Open Harness to answer.` |+| Mention of the person | `<lead name> tagged you` | `Open Harness to read it.` |+| Work waiting on the person, status `blocked` | `<agent name> is stuck` | `Open Harness to see why.` |+| Work waiting on the person, other status | `<agent name> needs you` | `Open Harness to answer.` |+| Agent asks a question (`agent_question`) | `<agent name>`; subtitle: machine name | `Needs you. Open Harness to answer.` (**proposal, PM to confirm**) |+| Agent finished a turn (`agent_done`) | `<agent name>`; subtitle: machine name | `Finished. Open Harness to read it.` (**proposal, PM to confirm**) |++Send no `badge`.++### 5.3 Notice id (shared with the app's own notices)++A push and the local notice the running app posts for the same news carry the same id, so one replaces the other+instead of two stacking. FNV-1a over the text's UTF-16 code units, kept to 31 bits:++```ts+export function noticeId(text: string): number {+ let hash = 0x811c9dc5+ for (let i = 0; i < text.length; i++) {+ hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193) & 0x7fffffff+ }+ return hash+}+```++- Text: `swarm\n` + `key` for a Swarm need; `<machine id>\n<agent id>` for an agent.+- iOS: send it as `apns-collapse-id`, in decimal. Android: the phone computes it from the data, so send nothing.+- Pin these vectors in a unit test (the phone pins the same ones):++| Text | Id |+| --- | --- |+| `swarm\nmention:m1` | 1161357565 |+| `swarm\ndecision:d1` | 15921470 |+| `swarm\nwork:s1:c1:a1:needs_human` | 701122187 |+| `machine-1\nagent-7` | 1081005959 |++### 5.4 Examples++iOS (APNs body):++```json+{+ "aps": {+ "alert": { "title": "Ann asks you", "subtitle": "Website", "body": "Open Harness to answer." },+ "sound": "default",+ "thread-id": "swarm-needs-you"+ },+ "kind": "swarm", "swarm": "…", "conversation": "…", "decision": "…", "key": "decision:…"+}+```++`thread-id` is `swarm-needs-you`, `agent-question` or `agent-done`: the app's own threads.++Android (FCM HTTP v1 body):++```json+{ "message": {+ "token": "…",+ "data": { "kind": "swarm", "title": "Ann asks you", "subtitle": "Website",+ "body": "Open Harness to answer.", "swarm": "…", "conversation": "…",+ "decision": "…", "key": "decision:…" },+ "android": { "priority": "HIGH", "ttl": "86400s" } } }+```++On Android `title` must not be empty, or the phone drops the push.++## 6. Triggers++Paths are relative to `backend/` unless they start with `cli/` or `mobile/`. Line numbers are from+`feat/mobile-ios-android` @ `1da94962a` and will drift.++### 6.1 Swarm needs++In the backend, a Swarm is a `SuperTab`.++| Push key | Phone (`system_notices.dart` `openPushed`) | Backend |+| --- | --- | --- |+| `swarm` | Swarm id | `SuperTab.id` (`tabId`); **not** `workspaceId` |+| `conversation` | conversation id | `conversationId`: a `Conversation` inside the SuperTab state (`superTabs/model.ts`), with no collection of its own |+| `message` | message id | `SuperTabMessage.id` |+| `thread` | thread root, when the message is only in a thread | `SuperTabMessage.thread` (= `SuperTabThread.id`) |+| `decision` | decision id | `SuperTabDecision.id` |+| assignment in a `work:` key | | `conversation.assignment.id` |++**The hook.** Add one hook to `SuperTabStoreHooks` (`superTabs/store.ts:338`), for example+`needsRaised?: (tabId: string, needs: PushNeed[]) => void`. Call it through `afterCommit(tx, …)` (`store.ts:271`),+the way `swarmChanged` is. Like the other hooks, it runs after the commit and must not throw. Wire it where the store+is built in both processes: `routes/superTabs.ts:251-271` and `worker.ts:134`.++**Where each need is written:**++| Need | Written by | Called from | Recipient |+| --- | --- | --- | --- |+| Mention | `writeMentions()`, `superTabs/mentions.ts:161` (`createMany` at :167) | `store.ts:1983` (`executeOnce`); `store.ts:4397` (`archiveFinished`, worker) | the row's `personId` |+| Decision | `writeDecisions()`, `superTabs/decisions.ts:224` (`createMany` at :236). Push only for `fresh` drafts (:230): an exact repeat returns the existing id | `store.ts:2014` (`executeOnce`: `decision.ask`, and a `work.status` that asks, `commands.ts:3545-3556`); `store.ts:4251` (`postReflection`, worker) | the row's `personId` (`project.ownerId` for `postReflection`) |+| Work waiting on a person (`needs_human`, `blocked`) | the `work.status` command, `superTabs/commands.ts:3536-3599` (status at :3563, `askedOf` at :3567). A change of Swarm state, not a row: compare `original` with `effects.state`, as `workEnded` does (`store.ts:2020`) | `executeOnce` | the same person the phone uses (`mobile/lib/swarm/waiting_work.dart:45-63`): the conversation's partner, else `project.ownerId`. The backend never sets a partner, so today it is the project owner |++**Copy names** (asker, lead, agent, project) come from Swarm state, the same way the list views build them+(`decisions.ts:393-398`, `mentions.ts:350-352`). Reuse those helpers rather than a second copy.++**Rules:**++- A mention row with `holdUntil` (`mentions.ts:165`) is not listed until then (`listed()`, `mentions.ts:256`). Do not+ push it at write time. Push it when it becomes listed: a worker sweep every minute, in the `startX` pattern of+ `superTabs/deliveryRepush.ts`, over mentions whose `holdUntil` passed and that have no `push:sent` key.+- A `work.status` that asks a person writes a decision **and** puts the work in `needs_human`. Send only the decision+ push to that person.+- Never push a need to the person who caused it.+- The per-chat setting `SuperTabChatSetting.notify` (`all` / `mentions` / `muted`) does **not** apply. The app's own+ need notices ignore it too: it only decides the "New messages" notices (`mobile/lib/swarm/swarm_notices.dart:371`).+- No push for new chat messages or thread replies in phase 1.++### 6.2 Agent asks a question / finishes a turn (needs a CLI change)++The backend has no signal for these today:++- The CLI sends `commander_question` (`cli/src/core/questions.ts:98-121`), `turn_ended` and `turn_summary` over the+ relay. Their payloads are sealed end to end (`cli/src/lib/e2ee/core.ts:339-343`).+- `lib/adapterWs.ts:554-585` reads only the plain `type`, the top-level `agentId` and `replay`.+- Whether a finished turn is worth telling (alert, list or silent, `cli/src/lib/notifyTier.ts`) is inside the sealed+ payload.++So the daemon must ask the backend for the push. Proposal:++- **CLI:** when an agent asks a question, or finishes a turn whose tier is `alert`, and no Harness app is connected+ (`hasRemoteApp()`, `cli/src/backendSocket.ts:391`), send one plain frame on the machine socket:+ `{ "type": "push_request", "kind": "agent_question" | "agent_done", "agentId": "…" }`. It carries no content: what+ was asked stays sealed.+- **Backend** (`lib/adapterWs.ts`):+ - The machine id and account come from the socket, never from the frame.+ - The agent's name comes from `MachineAgent` (`schema.prisma:442`); the machine's name from `Machine`.+ - Send to that account's tokens with the copy in section 5.2. The notice id is `<machine id>\n<agent id>`.+ - Refuse the frame from a team session (`lib/teamSession.ts`).+ - Rate limit: about 30 frames per machine per minute.+- If this part is late, ship 6.1 first. The phone needs nothing more for 6.2.++## 7. Cleanup (what deletes a row)++- `DELETE /api/push-tokens` on sign-out, or when notices are turned off on the phone.+- A register of the same token by another account (the row moves).+- The provider says the token is dead (section 4).+- The device whose key the row carries is removed from the account. Hook where a removal entry is appended to the+ device key log (`lib/deviceKeyLog.ts`): delete `PushToken` rows with that `device`.+- No renewal for 60 days: a daily sweep in the worker, beside the other sweeps. The phone renews every 7 days.+- More than 20 rows for one account: the oldest go first (section 3).++## 8. Logs and metrics++- Each failed send: provider, status, reason, kind, `userId`, the row's `gateway`. Never the token or the body.+- `prom-client` counters: `push_sent_total{provider,kind}` and `push_failed_total{provider,reason}`. The first warning+ at 10x phones is the failure rate per provider.+- Product-usage measures, optional in phase 1. Counts the backend writes itself go through `RelayUsageMetric`+ (`lib/productUsage.ts:185-189`) and `recordRelayUsage(userId, now, metric)` (:254), as `relay_mobile_opens` does+ (`dailyTracking.ts:123`). For example, add `push_sent_ios` and `push_sent_android` there, in snake_case. A count the+ phone reports (a push opened) would be a new name in `PRODUCT_USAGE_METRICS` (`types/productUsage.ts:218-259`) and its+ CLI copy (`cli/src/lib/productUsageContract.ts`); a test keeps the two equal. That is a later change on both sides.++## 9. Tests++Unit tests (vitest, with the in-memory Mongo the other route tests use):++- Routes:+ - `PUT` stores the row with `userId` from the sign-in; the same token from another account moves.+ - 21st token drops the oldest.+ - Validation: bad `platform`, iOS without `environment`, token too long.+ - `DELETE` removes only the caller's row and answers success for an unknown token.+ - A team session is refused.+ - Rate limit.+- `noticeId` vectors (section 5.3).+- APNs: the JWT verifies with the key's public half; headers and body; each answer row in 4.1 (mock the HTTP/2+ session).+- FCM: body is data-only with string values; each answer row in 4.2 (mock `fetch` and the auth client).+- Triggers:+ - A need for person B sends to B's tokens only, never to the person who caused it.+ - The same need `key` twice sends once; two questions from one agent send twice.+ - A repeated decision draft (not `fresh`) sends nothing.+ - A `work.status` that asks a person sends one push (the decision), not two.+ - A held mention sends nothing at write time and one push once its `holdUntil` passes.+ - A muted chat still sends its needs.+ - `push_request` from a team session is refused.++End to end (by hand, once BE is on staging):++1. iOS sandbox: install the phone branch with `flutter run --profile` on an iPhone, sign in, allow notices. Check a row+ with `gateway: "sandbox"`. Trigger a need for that account; the push arrives; tap opens the right screen.+2. Android: same on a real phone, any build.+3. iOS production: a TestFlight build of the phone branch; check `gateway: "production"`.+4. Sign out: the row is gone and no push arrives.+5. App in front: no system notice from the push (the app shows its own).++Before triggers exist, a token can be tested with Apple's Push Notifications Console+(https://icloud.developer.apple.com/dashboard/notifications, environment *Development* for sandbox), using the token+read from the `push_tokens` row.++## 10. Rollout++1. Ship the model and routes first. Phones that are already out call nothing; the phone branch tolerates a 404.+2. Set the secrets; senders stay off for a gateway whose key is unset.+3. Turn on triggers on staging and run section 9 end to end.+4. Mobile merges and releases (TestFlight, Play internal), then production.++## 11. Done when++- [ ] `PUT` / `DELETE /api/push-tokens` live, with the tests in section 9.+- [ ] A sandbox iPhone build, a TestFlight build and an Android phone each receive a push for a real Swarm need, and+ tapping it opens the right conversation.+- [ ] An agent question and a finished turn reach the phone while no Harness app is open (section 6.2).+- [ ] Dead tokens are deleted on 410 / `UNREGISTERED`; the 60-day sweep runs.+- [ ] No key, token or push body in any log.++## 12. Open questions++1. Agent copy for `agent_question` / `agent_done` (section 5.2): PM to confirm.+2. Should a Swarm push be skipped while the person has Desktop open? Phase 1 proposal: send anyway; the phone hides+ it only if Harness is in front on the phone. (The backend has no live "phone connected" check: `?client=mobile` in+ `lib/webWs.ts` only writes daily presence rows.)+3. Clearing a delivered push once the need is resolved elsewhere: later phase.+4. Whether `hasRemoteApp()` is the right "nobody is looking" test for 6.2 (it is true while Desktop is connected, so+ the phone would stay silent then).diff --git a/docs/plans/2026-11-05-phone-push-server-contract-plan.md b/docs/plans/2026-11-05-phone-push-server-contract-plan.mdnew file mode 100644index 000000000..968913293--- /dev/null+++ b/docs/plans/2026-11-05-phone-push-server-contract-plan.md@@ -0,0 +1,127 @@+# Phone push on the merged server contract Implementation Plan++> Written by the writing-plans skill, implemented in this session test first (the project's Engineer workflow): each+> task's failing test is committed and watched failing before the code that passes it. Steps use checkbox (`- [ ]`)+> syntax.++**Goal:** The phone side of push (PR #3103) talks to the server part that merged in #3071 (backend v1.4.9): its routes,+its request bodies and the pushes it sends, so a signed-in phone is registered and a tapped push opens the chat it names.++**Architecture:** Only the phone changes. `ApiClient` calls `POST /api/push-devices` and `POST /api/push-devices/drop`+with `{platform, token}`; `PushTokens` keeps the platform it registered so it can drop that row; a tapped push is read by+its `link`, the app's own `swarm:` payload, through `decodeSwarmPayload`. Android stops drawing data-only pushes the+server never sends and takes the tap of the notification FCM draws itself; iOS stops working out an APNs gateway the+server never reads.++**Tech Stack:** Flutter 3.47.2 (Dart), Kotlin (firebase-messaging 26.0.1), Swift.++**Spec:** the merged server: `backend/src/routes/pushDevices.ts`, `backend/src/push/notices.ts`, `push/apns.ts`,+`push/fcm.ts`. Tony's `docs/design/2026-11-05-phone-push.md` and `docs/plans/2026-11-05-phone-push-backend-plan.md`+describe the contract as first proposed; where they differ, the merged server wins (gaps listed in the backend plan).++## Global Constraints++- Register body is exactly `{ "platform": "ios" | "android", "token": "<1..4096 of [A-Za-z0-9:_-]>" }`: the server's zod+ object is `.strict()`, so any other key (`environment`, `device`) answers 400.+- Drop body is the same object, sent to `POST /api/push-devices/drop`; the token never goes in a path or a log.+- A push carries two strings beside the platform's own fields: `key` and `link`. `link` is+ `swarm:<tab>/<conversation>/message/<message>[/thread/<root>]`, each part URI-encoded.+- The server forgets a phone not seen for 90 days; the phone renews every 7.+- Device tokens are credentials: never logged, never in chat; tests use fakes only.+- Format only changed files.++## Review Focus++1. A record on disk from before this change (no `platform`) — expected: read as never told, registered again.+2. A tapped push whose `link` is an agent or device payload, or not a `swarm:` link — expected: opens nothing.+3. A push with the old keys (`kind`, `swarm`, `conversation`) and no `link` — expected: opens nothing.+4. An Android tap on a notification another app forged into the launcher intent — expected: at most opens a chat, as a+ message link already can; never anything else.+5. A sign-out while a register is in flight — expected: nothing registered after it (Tony's epoch test stays).++---++### Task 1: The API calls the merged routes++**Files:**+- Modify: `mobile/lib/notify/push_tokens.dart` (`PushTokenApi`), `mobile/lib/notify/push_channel.dart` (`PushAddress`),+ `mobile/lib/api/api_client.dart`+- Test: `mobile/test/api/api_client_test.dart`, `mobile/test/viewer_app_fixture.dart`++**Interfaces:**+- Produces: `typedef PushAddress = ({String token, String platform})`;+ `PushTokenApi.registerPushToken(PushAddress address)`; `PushTokenApi.forgetPushToken(PushAddress address)`.++- [ ] **Step 1: Write the failing tests** — `registers on the merged route with exactly platform and token`: one request,+ `POST /api/push-devices`, bearer of the sign-in, body `{'platform': 'ios', 'token': 'apns-1'}`. `drops with the same+ body, never the token in the path`: `POST /api/push-devices/drop`, body `{'platform': 'android', 'token': 'fcm-1'}`.+ The 404 test keeps its status assertion.+- [ ] **Step 2: Run** `flutter test test/api/api_client_test.dart` — expected FAIL (PUT to `/api/push-tokens`).+- [ ] **Step 3: Commit the red test.**+- [ ] **Step 4: Implement** the two calls with `_dio.post`; drop `environment` from `PushAddress` and `device`.+- [ ] **Step 5: Run** the same file — PASS. Commit.++### Task 2: Token registration follows the address and drops what it registered++**Files:**+- Modify: `mobile/lib/notify/push_tokens.dart`, `mobile/lib/notify/push_channel.dart` (`pushAddressFrom`),+ `mobile/lib/state/app_state.dart` (`_initPush`)+- Test: `mobile/test/notify/push_tokens_test.dart`, `mobile/test/notify/push_channel_test.dart`,+ `mobile/test/app_state_push_test.dart`++**Interfaces:**+- Consumes: Task 1's `PushAddress` and `PushTokenApi`.+- Produces: `PushTokens({channel, storage, allowed, now})` (no `device`).++- [ ] **Step 1: Write the failing tests** — `push_tokens_test`: `registers the address, and again when the token or the+ account changes` (registered `[(ios, apns-1), (ios, apns-2), (ios, apns-2)]`); `notices off drops the row it+ registered` (`forgotten == [(token: 'apns-1', platform: 'ios')]`); `a record from before the platform was kept counts+ as never told` (record `{account, token, at}` → registered once, record now holds `platform`). `app_state_push_test`:+ `the token reaches the merged route after sign-in and again on change; logout drops it` asserting+ `FakeApi.pushRegistered`/`pushForgotten` as `PushAddress` lists.+- [ ] **Step 2: Run** the three files — expected FAIL (compile: `device`, `environment`).+- [ ] **Step 3: Commit the red tests.**+- [ ] **Step 4: Implement**: record `{account, platform, token, at}`; `_read` returns null without `platform`; `_take`+ sends the record's address; renew comment says 90 days; `pushAddressFrom` takes token and platform only.+- [ ] **Step 5: Run** — PASS. Commit.++### Task 3: A tapped push opens the chat its link names, and nothing else++**Files:**+- Modify: `mobile/lib/notify/system_notices.dart` (`openPushed`; remove `pushSwarmTarget`, `_pushId`)+- Test: `mobile/test/notify/local_system_notices_test.dart` (group `pushes`), `mobile/test/app_state_push_test.dart`++**Interfaces:**+- Produces: `void openPushed(Map<String, String> data, SystemNotices notices)`, reading only `data['link']`.++- [ ] **Step 1: Write the failing tests** — `a reply push opens the thread at the reply`:+ `{'key': 'reply:s1:r1', 'link': 'swarm:s1/c1/message/m1/thread/t1'}` → `openedSwarm` `(s1, c1, m1, null, t1)`;+ `a tag push opens the chat at the message`: link `swarm:s%2F1/c1/message/m1` → swarmId `s/1`;+ `a push opens nothing else`: links `machine-1\nagent-7`, `device:k`, `swarm:s1`, `https://x`, missing link, and the+ old `{'kind': 'agent_question', 'machine', 'agent'}` and `{'kind': 'swarm', 'swarm', 'conversation'}` leave both+ `openedSwarm` and `opened` null. `app_state_push_test`: `a tapped push opens the chat its link names`.+- [ ] **Step 2: Run** — expected FAIL (no `link` read).+- [ ] **Step 3: Commit the red tests.**+- [ ] **Step 4: Implement** `openPushed` via `decodeSwarmPayload(data['link'])`.+- [ ] **Step 5: Run** — PASS. Commit.++### Task 4: Native sides match what the server sends++**Files:**+- Modify: `mobile/android/.../MainActivity.kt`, `mobile/android/.../PushService.kt`,+ `mobile/android/app/src/main/AndroidManifest.xml`, `mobile/ios/Runner/AppDelegate.swift`++- [ ] **Step 1:** Android: FCM draws the server's notification message itself while the app is away; its tap starts the+ launcher activity with the data (`key`, `link`) and FCM's `google.message_id` as extras. `receivePush` takes such an+ intent's `key` and `link` once. `PushService` keeps `onNewToken` only (in front, the app's own notices decide).+- [ ] **Step 2:** iOS: `address` answers `{token, platform}`; the provisioning-profile gateway goes.+- [ ] **Step 3:** Type-check where the toolchain exists (`swiftc -typecheck`, `kotlinc`); no device or simulator install.+ Commit.++### Task 5: Gaps between the backend plan and the merged server++**Files:** Modify: `docs/plans/2026-11-05-phone-push-backend-plan.md` (a "Merged server, 11-05" section at the top),+`docs/design/2026-11-05-phone-push.md` (a pointer to it).++- [ ] **Step 1:** One line per gap: route, payload field, platform, trigger. Small phone-side ones are fixed in Tasks 1-4;+ server ones go to the PM as proposals. Commit.diff --git a/docs/plans/2026-11-05-task-priority-plan.md b/docs/plans/2026-11-05-task-priority-plan.mdnew file mode 100644index 000000000..f6cceaad4--- /dev/null+++ b/docs/plans/2026-11-05-task-priority-plan.md@@ -0,0 +1,90 @@+# Task Priority (P0–P3) Implementation Plan++> Implement task by task, test first, following the project's Engineer workflow (project instructions, Engineer).++**Goal:** Every task carries a priority P0–P3. People and agents can see it on the Tasks board, in the Backlog, in the task header, and in the CLI's `status` and `mine`. P0 goes first everywhere work is ordered.++**Architecture:** One optional `priority` field on the backend `Conversation`. `conversation.create` sets it, with P2 as the default and a warning in the reply. A proposal's low/normal/high maps onto it. A new `work.priority` command changes it and writes one plain-words system line into the task. Clients read an *effective* priority: the field, else the legacy title marker ("URGENT …", "(urgent)" → P0, "(high)" → P1), else P2. Clients sort by it inside each column or group.++**Tech Stack:** Backend TypeScript (zod commands, Vitest), CLI TypeScript (Vitest specs), Desktop Flutter/Dart (widget tests with a memory store and fake sign-in).++**Spec:** Swarm task #3117 brief; River's addition (one scale: proposal high→P1, normal→P2, low→P3; only the PM or a person sets P0); the ASCII mockup posted in the task's chat for Ken on 2026-11-05.++## Global Constraints++- Priorities are exactly `P0`, `P1`, `P2`, `P3`. Meanings (visible copy): P0 "Hotfix: something shipped is broken", P1 "Needed by users soon", P2 "Planned goal", P3 "Tools, docs or process".+- A task created without a priority gets P2, and the reply says so (`warnings` entry: `No priority given: this task is P2. Set P0–P3 with work.priority.`).+- Only the project's PM (coordinator) or a person sets P0 or changes a priority. A Buddy proposal maps high→P1, normal→P2, low→P3. A priority the PM writes on `conversation.create` wins over the proposal's.+- The change line, posted as a system row in the task: `{actor} changed the priority to {P}, {meaning lower-cased first letter} (was {old}).` For example: `Ken changed the priority to P0, hotfix: something shipped is broken (was P2).` Setting the same priority again changes nothing and posts nothing.+- Steps (`step` + `reviewOf`) and private chats (`audience`) carry no priority.+- Badge tokens: P0 `AppPalette.usageCritical`, P1 `AppPalette.warn`, P2/P3 `DesktopChrome.muted`. No new colors.+- Desktop tests use a memory store and a fake sign-in. Swarm code stays out of cli/src/core.++## Design++- growth: one short enum string per task, deleted with the task's conversation document. One system line per real change; same-value sets post nothing.+- concurrency: `work.priority` runs inside the existing per-Swarm command transaction like `work.queue`. Last write wins, and each write records its line.+- read cost: the field rides in the existing group part. No new read, query or index. The light loader lists it under `unread` (`parts/light.ts`).+- scale: 10x tasks is 10x four-byte fields, so it is not a factor. The metric that warns first stays the group-part size that is already tracked.+- compatibility: the field is additive. Old Desktop and CLI ignore it and keep reading the title marker. New clients treat a missing field as the title marker, else P2. Old backends never send it, and an old backend refuses `work.priority` as an unknown command, which Desktop shows as the menu's error.+- migration + rollback: no migration. Rolling back the backend leaves `priority` stored, and the old code ignores it.+- audience: the server enforces it. `coordinatorOrPerson` gates `work.priority`. `conversation.create` refuses P0 from an agent that is not the project's coordinator.+- identity: the change line names the actor (person's shown name or agent name). It never uses the machine owner's login.+- failure: a refused change returns a named error (`COORDINATOR_REQUIRED`, `PRIORITY_TASK_ONLY`). Desktop's header menu shows it inline.+- platforms: backend; CLI on macOS/Linux/Windows; Desktop on macOS, Linux, Windows and the web (shared Flutter).++## Review Focus++- Next up drag on Desktop after the priority sort: a card dropped between cards of another priority must still land in the shared queue at a sensible place. It stays inside its own priority band, so dropping it above a higher priority puts it first in its own band.+- A legacy task with no field but a "(urgent)" title shows P0 on the board, in the header and in `mine`, and the title shows without the marker.+- An Engineer opening a linked task with `priority: "P0"` is refused, but opening it with P1–P3 or none works.+- `work.priority` on a step, on the project chat or on a Buddy chat is refused (`PRIORITY_TASK_ONLY`), and the answer gives nothing away about other projects.+- A proposal with no or an unknown priority string maps to P2, without the "no priority given" warning.++---++### Task 1: Backend field, create default, proposal mapping, work.priority++**Files:**+- Create: `backend/src/superTabs/taskPriority.ts`, `backend/src/superTabs/taskPriority.test.ts`+- Modify: `backend/src/superTabs/model.ts` (Conversation), `backend/src/superTabs/commands.ts` (schema, `conversation.create`, new `work.priority` case), `backend/src/superTabs/parts/light.ts` (`GROUP_FIELDS.unread`), `backend/src/superTabs/proposals.ts` (`OpenProposal.priority`)++**Interfaces:**+- Produces: `type TaskPriority = 'P0' | 'P1' | 'P2' | 'P3'`; `TASK_PRIORITIES`; `PRIORITY_MEANING: Record<TaskPriority, string>`; `proposalPriority(value: unknown): TaskPriority` (high→P1, low→P3, else P2); `priorityLine(actorName: string, next: TaskPriority, previous: TaskPriority): string`.+- Wire: `Conversation.priority?: TaskPriority`. `conversation.create` takes an optional `priority`, and its result carries `priority`. Command `{ type: 'work.priority', conversationId, priority }`. `OpenProposal.priority: 'P1'|'P2'|'P3'`.++- [ ] Write failing tests in `taskPriority.test.ts`. A create with `priority: 'P0'` by the coordinator stores P0. A create without one stores P2 and the result has `priority: 'P2'` plus the warning. A create from a proposal whose source says `high` stores P1 with no warning. An Engineer's create with P0 is refused `PRIORITY_P0`. `work.priority` by a person stores the new value and posts the change line. A same-value set posts nothing. `work.priority` by a non-coordinator agent is refused `COORDINATOR_REQUIRED`. On a step it is refused `PRIORITY_TASK_ONLY`. The open proposals read carries the mapped priority.+- [ ] Run `cd backend && npx vitest run src/superTabs/taskPriority.test.ts`. Expected: FAIL.+- [ ] Implement it. Add `priority` to `GROUP_FIELDS.unread` so `light.test.ts` stays green.+- [ ] Run `npx vitest run src/superTabs/taskPriority.test.ts src/superTabs/parts/light.test.ts src/superTabs/proposals.test.ts src/superTabs/commands.test.ts`. Expected: PASS.+- [ ] Commit the test first, then the code.++### Task 2: CLI shows and asks for it++**Files:**+- Modify: `cli/src/superTabs/agentContext.ts` (label, `mine` order), `cli/src/superTabs/service.ts` (help text: `conversation.create` example gets `"priority":"P0|P1|P2|P3"` with the meanings, plus a `work.priority` example)+- Create: `cli/src/superTabs/taskPriority.ts`, `cli/src/superTabs/taskPriority.spec.ts`++**Interfaces:**+- Consumes: the `priority` field from Task 1.+- Produces: `effectivePriority(group: { priority?: unknown; title?: unknown }): 'P0'|'P1'|'P2'|'P3'`, which uses the field, else the title marker (leading `URGENT` → P0; trailing `(urgent)`/`(… , urgent)` → P0; `(high)`/`(… , high priority)` → P1), else P2.++- [ ] Write failing specs. `mineText` for the coordinator lists a P0 task before an older P2 task, and each line reads `#N P0 Title (conversation …)`. A legacy "(urgent)" title reads P0. An own-task line shows its priority. The help for `command` names `work.priority` and P0–P3.+- [ ] Run `cd cli && npx vitest run src/superTabs/taskPriority.spec.ts src/superTabs/agentContext.spec.ts`. Expected: FAIL.+- [ ] Implement it. Sort with a stable sort by priority rank and keep the existing order within a rank. `status` already prints the conversation JSON, so check in the spec that `priority` survives in the status payload.+- [ ] Run the same specs. Expected: PASS. Commit the test, then the code.++### Task 3: Desktop model, badge, sort, header menu++**Files:**+- Modify: `desktop/lib/super_tabs/model.dart` (`SuperTabConversation.priority`), `desktop/lib/super_tabs/backlog.dart` (`SuperTabTaskPriority` p0–p3 with `badge`/`meaning`; `superTabTaskPriority(task)` effective value; the title marker stays for stripping), `desktop/lib/super_tabs/task_groups.dart` (sort by priority first in every column; Next up then by queue order), `desktop/lib/super_tabs/task_card.dart` (badge leading the caption), `desktop/lib/super_tabs/tasks_view.dart` (pass priority; Next up moves stay inside their band), `desktop/lib/super_tabs/backlog_view.dart` (Px badge replaces URGENT/HIGH; sort within group), `desktop/lib/super_tabs/view.dart` (header badge button with a P0–P3 menu for tasks only), `desktop/lib/super_tabs/controller.dart` (`Future<String?> setTaskPriority(String taskId, SuperTabTaskPriority p)` sending `work.priority`, returning the refusal text or null), proposals (`SuperTabProposal.priority`)+- Test: `desktop/test/super_tab_task_priority_test.dart`++**Interfaces:**+- Consumes: `priority` on conversations and proposals; command `work.priority`.+- Produces: `enum SuperTabTaskPriority { p0, p1, p2, p3 }` with `badge` ('P0'…) and `meaning`; `SuperTabTaskPriority superTabTaskPriority(SuperTabConversation task)`.++- [ ] Write failing widget tests. A P0 task created after a P2 task shows the "P0" badge on its board card and sorts first in Next up and in Working. A legacy "(urgent)" title shows P0 and loses its marker. The header shows the badge and its menu lists the four meanings. Choosing P0 sends `work.priority` with P0. A refusal shows inline. The Backlog shows the Px badge and sorts P0 first. Dragging a P2 card above a P0 card in Next up places it first among P2s.+- [ ] Run `cd desktop && flutter test test/super_tab_task_priority_test.dart`. Expected: FAIL.+- [ ] Implement it, then run that file plus the affected existing tests (`super_tab_tasks_view_test.dart`, `super_tab_backlog_*`, `super_tab_task_groups_test.dart`). Expected: PASS. Run `flutter analyze` on the changed files.+- [ ] Commit the test first, then the code. Take light and dark screenshots of the board and the header for the PR.diff --git a/docs/plans/2026-11-05-team-setup-background-plan.md b/docs/plans/2026-11-05-team-setup-background-plan.mdnew file mode 100644index 000000000..f04dbfb7e--- /dev/null+++ b/docs/plans/2026-11-05-team-setup-background-plan.md@@ -0,0 +1,86 @@+# Team account setup runs in the background, shows progress, and takes less time — Plan++**Goal:** After the password, Harness Team setup no longer holds the app: the Mac's row in Machines shows the step and+the time left, a notice says when it is ready or failed (failure with a plain reason and Retry), and the setup itself+takes seconds instead of minutes on a Mac that already has Claude Code and Codex.+**Architecture:** The CLI's Mac setup script copies the owner's own installed Claude Code and Codex into the team+account (the owner's `tar` piped into the team account's `tar`, root reading and writing nothing of either), and runs+npm only for an engine it could not copy. Desktop gets one watcher per app (`TeamSetupWatch`, in+`super_tabs/team_account_setup.dart`) that follows the daemon's `teamSetupStatus` while setup runs; the lock steps+aside once the password is accepted, the machine row draws the watcher's line, and the watcher's end raises the notice.+**Tech Stack:** TypeScript CLI (vitest specs on the generated shell), Flutter Desktop (widget tests with a memory store+and fake daemon answers).+**Spec:** Task #3169 (Scholes, 2026-11-05; mockup posted to him at 16:00).++## Measured before (this Mac, real setup of 2026-11-04, from file birth times and the team daemon's log)++| Step (daemon step names) | Time |+|---|---|+| account, home, privacy | ≈ 8 s |+| runtime (copy Node, CLI, tmux) | 3 s |+| engines (`npm install` Claude Code + Codex, ≈ 650 MB) | 4 min 18 s |+| sign-in, daemon, report (privacy check) | ≈ 5 s |++The engine download is ≈ 94 % of the wait. Copying the two installed packages on the same Mac took 2.3 s (tar pipe).++## Global Constraints+- The team account's isolation rules in `cli/src/team/script.ts` stand: root never writes inside the team home and+ never reads the owner's files on their behalf; every value is checked and single-quoted.+- npm stays the fallback for an engine the Mac does not have (or whose copy does not check out); nothing new fails setup.+- Desktop tests use a memory store and fake daemon answers; no real CLI sign-in, no real macOS account.+- Follow the Harness design language; words follow docs/naming-system.md ("Harness Team", "this Mac").+- Linux and Windows scripts keep npm (out of this task's measurement); their behaviour is unchanged.+- Swarm code stays out of `cli/src/core`.++## Design+- growth: nothing new is stored; the watcher holds one status in memory while setup runs.+- concurrency: one setup at a time, as today (`TeamAutoSetup.running`); one watcher per app.+- read cost: one `teamSetupStatus` read every 2 s, only while setup runs, local daemon only.+- scale: N/A because it is one Mac's own setup.+- compatibility: an older daemon says `engines` for its npm step, which the estimate times as a download; a new daemon+ says `copy-engines` for the copy. An older Desktop shows the new step as an unknown one (its waiting words).+- migration + rollback: N/A because nothing is stored; rolling back restores the npm-only step.+- audience: only this Mac's own Desktop asks its own daemon (`teamSetupStatus` is local-owner only, unchanged).+- identity: the copy runs as the owner (read) and as the team account (write), never as root, never the owner's login.+- failure: a failed copy is said in the script's output and falls back to npm; a failed setup ends in a notice with its+ reason and Retry, and the lock returns where it holds.+- platforms: macOS for the copy; the Desktop watcher, row line and notice on every platform that offers Team setup.++## Review Focus+- The copy's shell: values checked and quoted, the two-phase unpack/commit, a failed owner `tar` detected, links+ inside the package that point into the owner's home (discarded, npm instead).+- The lock stepping aside only after the password, and coming back on failure.+- The estimate never says "0 min left"; it rises once when an npm download starts (a Mac without the engines).++## Tasks++### 1. CLI: copy the owner's installed engines (cli/src/team/script.ts, deps.ts, command.ts)+**Files:** `cli/src/team/script.ts`, `cli/src/team/script.spec.ts`, `cli/src/team/deps.ts`, `cli/src/team/command.ts`+**Interfaces:** `SetupScriptInput.engineSources?: { packageName, dir, binName, binPath }[]`;+`TEAM_ENGINE_COPY` (team-side unpack/commit/discard script); `ownerEngineSources(home, nodeRuntimeDir)` in deps.+- [ ] Failing spec: the Mac setup script says `step copy-engines`, pipes `as_owner tar` into `as_team` for each source,+ and passes npm only the packages not copied; with no sources it installs both from npm as before.+- [ ] Failing spec: `TEAM_ENGINE_COPY` run against a temp home unpacks into `.next`, refuses a copy whose bin is+ missing or a package.json of another name, commits by rename and links `~/.local/bin/<bin>` as npm does.+- [ ] Failing spec: `ownerEngineSources` takes `~/.local/lib/node_modules/<pkg>` first, then the Harness Node's, then+ Homebrew's; skips a folder whose package.json names another package or whose bin path is not a plain relative path.+- [ ] Code until green; time the new step on this Mac (after number).++### 2. Desktop: the watcher (super_tabs/team_account_setup.dart)+**Files:** `desktop/lib/super_tabs/team_account_setup.dart`, `desktop/test/team_setup_watch_test.dart`+**Interfaces:** `TeamSetupWatch.of(AppNotifier)`, `follow()`, `running`, `line` ("Harness Team: setting up · step 2 of 4 ·+about 4 min left"), `ended` stream of `TeamSetupEnd(ready | failed(reason))`.+- [ ] Failing tests: four steps from the daemon's eight; time left from the measured step times, at least "less than a+ minute" while running; `exists` ends ready, `failed`/`declined`/`incomplete`/`none` end failed+ with a plain reason; polling stops at the end.++### 3. Desktop: the lock steps aside, the row shows progress, the notice (team_account_setup.dart, machines.dart)+**Files:** `desktop/lib/super_tabs/team_account_setup.dart`, `desktop/lib/super_tabs/machines.dart`,+`desktop/test/team_account_lock_test.dart`, `desktop/test/team_setup_background_test.dart`+- [ ] Failing test: once setup reports a step after the password, the lock's barrier is gone and a button under it+ takes a tap (app usable), while `teamSetupLocked` still holds.+- [ ] Failing test: the Mac's row shows "Harness Team: setting up · step N of 4 · about M min left" and "Keep working.+ We'll tell you when it's ready."+- [ ] Failing test: setup ending ready shows a notice and the lock ends; ending failed shows a notice with the reason+ and Retry (Retry starts setup again), and where the lock holds it comes back with the reason and Try again.+- [ ] Code until green.diff --git a/mobile/RELEASE.md b/mobile/RELEASE.mdindex 6c0a11944..7788c9f82 100644--- a/mobile/RELEASE.md+++ b/mobile/RELEASE.md@@ -235,14 +235,18 @@ terminal,tmux,ssh,claude,codex,cursor,coding,agent,developer,remote,shell,devops## App Privacy-Answer these from what the code actually does, not from habit. The app has **no third-party SDK**:-analytics go to Autonomous's own `event_tracking` endpoint (`lib/analytics/`), and crash records are-written to a local `errors.log` and never leave the device (`lib/core/crash_log.dart`).+Answer these from what the code actually does, not from habit. The app has **one third-party SDK,+on Android only**: Firebase Cloud Messaging (`firebase-messaging`, no Analytics), which is how a push+reaches an Android app that is not running (`android/app/src/main/kotlin/ai/autonomous/harness/android/PushService.kt`).+iOS pushes go through Apple's own APNs, with no SDK. Analytics go to Autonomous's own+`event_tracking` endpoint (`lib/analytics/`), and crash records are written to a local `errors.log`+and never leave the device (`lib/core/crash_log.dart`).| Data type | Collected | Linked to the user | Purpose || --- | --- | --- | --- || Contact Info ▸ Email Address | Yes | Yes | App Functionality, Analytics || Identifiers ▸ User ID | Yes | Yes | App Functionality, Analytics |+| Identifiers ▸ Device ID | Yes | Yes | App Functionality: the push token, so the backend can notify this phone (`docs/design/2026-11-05-phone-push.md`) || Usage Data ▸ Product Interaction | Yes | Yes | Analytics || Diagnostics | No | — | crash log stays on device |@@ -344,8 +348,9 @@ team's password manager.**- *Ads*: no. *Content rating*: fill the questionnaire (a utility, no user-generated content shownto others). *Target audience*: 18+.- *Data safety*: the [App Privacy](#app-privacy) table above, restated — email address and user ID- (app functionality, analytics), app interactions (analytics); all encrypted in transit; no data- shared with third parties; crash logs stay on the device.+ (app functionality, analytics), app interactions (analytics), device or other IDs (the push+ token: app functionality); all encrypted in transit; no data shared with third parties (FCM+ carries the push as a service provider); crash logs stay on the device.⚠️ **Plus Audio ▸ Voice or sound recordings (app functionality)**, which that table leaves out:voice input uploads the recording to the backend's `/api/voice/stt` to be transcribed. Declare it*processed ephemerally* only if the backend keeps nothing — TODO(BE): confirm. The same gap is ondiff --git a/mobile/android/app/build.gradle.kts b/mobile/android/app/build.gradle.ktsindex be611dcfd..4bdac946d 100644--- a/mobile/android/app/build.gradle.kts+++ b/mobile/android/app/build.gradle.kts@@ -80,4 +80,7 @@ flutter {dependencies {coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")+ // Pushes (PushService.kt). FCM is the only way to wake an Android app that is not running; only+ // its messaging module, with no Analytics. Its project values are in res/values/firebase.xml.+ implementation("com.google.firebase:firebase-messaging:26.0.1")}diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xmlindex aa0759d0b..03b48ef14 100644--- a/mobile/android/app/src/main/AndroidManifest.xml+++ b/mobile/android/app/src/main/AndroidManifest.xml@@ -88,6 +88,19 @@<data android:scheme="ai.autonomous.harness.signin" /></intent-filter></activity>+ <!-- Pushes from FCM (PushService.kt): Android draws them; the service hears new tokens. -->+ <service+ android:name=".PushService"+ android:exported="false">+ <intent-filter>+ <action android:name="com.google.firebase.MESSAGING_EVENT" />+ </intent-filter>+ </service>+ <!-- No FCM token until someone signed in here has allowed notices (`harness/push` `address`+ in MainActivity.kt). -->+ <meta-data+ android:name="firebase_messaging_auto_init_enabled"+ android:value="false" /><!-- Don't delete the meta-data below.This is used by the Flutter tool to generate GeneratedPluginRegistrant.java --><meta-datadiff --git a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.ktindex 61ac4b95c..c5c59282b 100644--- a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt+++ b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt@@ -24,6 +24,8 @@ import android.os.Looperimport android.provider.Settingsimport java.io.ByteArrayOutputStreamimport java.net.Inet4Address+import com.google.firebase.FirebaseApp+import com.google.firebase.messaging.FirebaseMessagingimport io.flutter.FlutterInjectorimport io.flutter.embedding.android.FlutterActivityimport io.flutter.embedding.engine.FlutterEngine@@ -153,15 +155,103 @@ class MainActivity : FlutterActivity() {}}receiveLink(intent)++ // `harness/push` — this phone's push address, and the pushes tapped (Dart:+ // `lib/notify/push_channel.dart`; drawn by Android itself). `address` turns pushes on and answers+ // the FCM token; `forget` turns them off and deletes the token, so a phone signed out is reached+ // by nothing. A tapped push's data waits here until `take`, as a link does; `arrived` says more+ // wait, `changed` that FCM handed over a new token.+ push = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "harness/push").also {+ it.setMethodCallHandler { call, result ->+ when (call.method) {+ "address" -> pushAddress(result)+ "forget" -> forgetPush(result)+ "take" -> {+ result.success(ArrayList(waitingPushes))+ waitingPushes.clear()+ }+ else -> result.notImplemented()+ }+ }+ }+ PushService.tokenChanged = { push?.invokeMethod("changed", null) }+ receivePush(intent)+ }++ override fun cleanUpFlutterEngine(flutterEngine: FlutterEngine) {+ PushService.tokenChanged = null+ super.cleanUpFlutterEngine(flutterEngine)}private var links: MethodChannel? = nullprivate val waitingLinks = mutableListOf<String>()+ private var push: MethodChannel? = null+ private val waitingPushes = mutableListOf<Map<String, String>>()- // singleTop: a link opened while the app runs comes here, not to a new activity.+ // singleTop: a link opened while the app runs comes here, not to a new activity. So does a tapped+ // push.override fun onNewIntent(intent: Intent) {super.onNewIntent(intent)receiveLink(intent)+ receivePush(intent)+ }++ // The registration token, deprecated since firebase-messaging 25.1.0 for an Installation ID+ // (`register()`): FCM's HTTP v1 send, which the backend uses, documents tokens only so far.+ @Suppress("DEPRECATION")+ private fun pushAddress(result: MethodChannel.Result) {+ // No Firebase values in this build: no push to give.+ if (FirebaseApp.getApps(this).isEmpty()) {+ result.success(null)+ return+ }+ val messaging = FirebaseMessaging.getInstance()+ messaging.isAutoInitEnabled = true+ messaging.token.addOnCompleteListener { task ->+ val token = if (task.isSuccessful) task.result else null+ if (token.isNullOrEmpty()) {+ result.error("unregistered", task.exception?.message, null)+ } else {+ result.success(mapOf("token" to token, "platform" to "android"))+ }+ }+ }++ @Suppress("DEPRECATION")+ private fun forgetPush(result: MethodChannel.Result) {+ if (FirebaseApp.getApps(this).isEmpty()) {+ result.success(null)+ return+ }+ val messaging = FirebaseMessaging.getInstance()+ messaging.isAutoInitEnabled = false+ messaging.deleteToken().addOnCompleteListener { result.success(null) }+ }++ // The server's push is a notification Android draws itself while the app is away+ // (backend/src/push/fcm.ts). Its tap starts the app with the push's data as extras, beside FCM's+ // own `google.message_id`. Only `key` and `link` go on to Dart, which opens nothing but the chat a+ // `swarm:` link names, as a message link (`receiveLink`) already can.+ private fun receivePush(intent: Intent?) {+ if (intent == null) return+ // Reopened from Recents, Android hands back the intent that first started the app: that push+ // was opened then.+ if ((intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) return+ // Another app may start the launcher with extras of its own making: ones that cannot be read+ // are no push, not a crash.+ val data = HashMap<String, String>()+ try {+ val extras = intent.extras ?: return+ if (extras.getString(PushService.MESSAGE_ID).isNullOrEmpty()) return+ for (key in PushService.KEYS) extras.getString(key)?.let { data[key] = it }+ // Taken: the same intent handed back to a recreated activity is not tapped again.+ intent.removeExtra(PushService.MESSAGE_ID)+ } catch (error: RuntimeException) {+ return+ }+ waitingPushes.add(data)+ while (waitingPushes.size > 20) waitingPushes.removeAt(0)+ push?.invokeMethod("arrived", null)}private fun receiveLink(intent: Intent?) {diff --git a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/PushService.kt b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/PushService.ktnew file mode 100644index 000000000..2e9c17086--- /dev/null+++ b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/PushService.kt@@ -0,0 +1,30 @@+package ai.autonomous.harness.android++import android.os.Handler+import android.os.Looper+import com.google.firebase.messaging.FirebaseMessagingService++/**+ * FCM's side of push (Dart: `lib/notify/push_channel.dart`). The server sends a notification+ * message (backend/src/push/fcm.ts): while the app is away Android draws it on the app's Swarm+ * channel, and its tap reaches MainActivity's `receivePush`; while the app is in front it comes to+ * `onMessageReceived`, which draws nothing, as the app tells it with its own notices.+ */+class PushService : FirebaseMessagingService() {+ // Tokens, not Installation IDs (`onRegistered`): see `pushAddress` in MainActivity.kt.+ @Suppress("OVERRIDE_DEPRECATION")+ override fun onNewToken(token: String) {+ Handler(Looper.getMainLooper()).post { tokenChanged?.invoke() }+ }++ companion object {+ /** The extra FCM sets on the tap of a notification it drew. */+ const val MESSAGE_ID = "google.message_id"++ /** The push's own data the server sends, and all Dart is given of a tapped push. */+ val KEYS = listOf("key", "link")++ /** Tells Dart, on the main thread, that FCM handed the app a new token. */+ @Volatile var tokenChanged: (() -> Unit)? = null+ }+}diff --git a/mobile/android/app/src/main/res/values/firebase.xml b/mobile/android/app/src/main/res/values/firebase.xmlnew file mode 100644index 000000000..fd6abb823--- /dev/null+++ b/mobile/android/app/src/main/res/values/firebase.xml@@ -0,0 +1,13 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Firebase project `autonomous-harness`, app ai.autonomous.harness.android: only what FCM needs,+ from the console's google-services.json (Project settings ▸ General ▸ Your apps). Read by+ Firebase at start-up (FirebaseOptions.fromResource), in place of the google-services Gradle+ plugin, so the `.bench` copy (harnessIdSuffix) still builds. Not secrets: every APK carries+ them. -->+<resources>+ <string name="google_app_id" translatable="false">1:833365259120:android:ba216b0b3278c0a6d455b5</string>+ <string name="gcm_defaultSenderId" translatable="false">833365259120</string>+ <string name="google_api_key" translatable="false">AIzaSyCv-lM0AryK9lnW1PWlq71zLyESSw2rVDw</string>+ <string name="project_id" translatable="false">autonomous-harness</string>+ <string name="google_storage_bucket" translatable="false">autonomous-harness.firebasestorage.app</string>+</resources>diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swiftindex 698f39d23..52f307a3f 100644--- a/mobile/ios/Runner/AppDelegate.swift+++ b/mobile/ios/Runner/AppDelegate.swift@@ -19,6 +19,57 @@ import UserNotificationsreturn super.application(application, didFinishLaunchingWithOptions: launchOptions)}+ // The push address comes back here, not to whoever asked for it (`PushChannel` below). Flutter's+ // own delegate still passes it on to plugins.+ override func application(+ _ application: UIApplication,+ didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data+ ) {+ PushChannel.shared.registered(deviceToken)+ super.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)+ }++ override func application(+ _ application: UIApplication,+ didFailToRegisterForRemoteNotificationsWithError error: Error+ ) {+ PushChannel.shared.failed(error)+ super.application(application, didFailToRegisterForRemoteNotificationsWithError: error)+ }++ // A push that lands while Harness is in front is not drawn: the app is up, and says what it has to+ // with its own notices, which know what the person is looking at.+ override func userNotificationCenter(+ _ center: UNUserNotificationCenter,+ willPresent notification: UNNotification,+ withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void+ ) {+ if notification.request.trigger is UNPushNotificationTrigger {+ completionHandler([])+ return+ }+ super.userNotificationCenter(+ center, willPresent: notification, withCompletionHandler: completionHandler)+ }++ // A tapped push goes to Dart over `harness/push`; a tapped local notice stays with+ // flutter_local_notifications, as before.+ override func userNotificationCenter(+ _ center: UNUserNotificationCenter,+ didReceive response: UNNotificationResponse,+ withCompletionHandler completionHandler: @escaping () -> Void+ ) {+ if response.notification.request.trigger is UNPushNotificationTrigger {+ if response.actionIdentifier == UNNotificationDefaultActionIdentifier {+ PushChannel.shared.opened(response.notification.request.content.userInfo)+ }+ completionHandler()+ return+ }+ super.userNotificationCenter(+ center, didReceive: response, withCompletionHandler: completionHandler)+ }+func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)DeviceNameChannel.register(with: engineBridge.pluginRegistry)@@ -30,6 +81,81 @@ import UserNotificationsAppBadgeChannel.register(with: engineBridge.pluginRegistry)LinkChannel.register(with: engineBridge.pluginRegistry)SetupWifiChannel.register(with: engineBridge.pluginRegistry)+ PushChannel.shared.attach(to: engineBridge.pluginRegistry)+ }+}++/// `harness/push` — this phone's push address, and the pushes the person tapped (Dart:+/// `lib/notify/push_channel.dart`).+///+/// `address` asks iOS for the APNs device token, which comes back to the app delegate; every call+/// waiting then hears it. `forget` stops iOS delivering to it: the phone signed out. `changed` tells+/// Dart that iOS handed over another token while the app ran.+///+/// A tapped push's data waits here until Dart's `take` answers it, as `LinkChannel`'s links do: the+/// push that launched the app is tapped before the engine is up. At most 20 wait, the newest kept;+/// `arrived` tells a listening Dart that more wait. Everything here runs on the main thread.+final class PushChannel {+ static let shared = PushChannel()++ private var channel: FlutterMethodChannel?+ private var asking: [FlutterResult] = []+ private var waiting: [[String: String]] = []+ private var token: String?++ func attach(to registry: FlutterPluginRegistry) {+ guard let messenger = registry.registrar(forPlugin: "HarnessPush")?.messenger() else { return }+ let channel = FlutterMethodChannel(name: "harness/push", binaryMessenger: messenger)+ channel.setMethodCallHandler { [weak self] call, result in+ guard let self else {+ result(FlutterMethodNotImplemented)+ return+ }+ switch call.method {+ case "address":+ self.asking.append(result)+ UIApplication.shared.registerForRemoteNotifications()+ case "forget":+ UIApplication.shared.unregisterForRemoteNotifications()+ self.token = nil+ result(nil)+ case "take":+ result(self.waiting)+ self.waiting.removeAll()+ default:+ result(FlutterMethodNotImplemented)+ }+ }+ self.channel = channel+ }++ func registered(_ deviceToken: Data) {+ let hex = deviceToken.map { String(format: "%02x", $0) }.joined()+ let moved = token != nil && token != hex+ token = hex+ let answer: [String: Any] = ["token": hex, "platform": "ios"]+ let answering = asking+ asking.removeAll()+ answering.forEach { $0(answer) }+ if moved && answering.isEmpty { channel?.invokeMethod("changed", arguments: nil) }+ }++ func failed(_ error: Error) {+ let answering = asking+ asking.removeAll()+ answering.forEach {+ $0(FlutterError(code: "unregistered", message: error.localizedDescription, details: nil))+ }+ }++ /// Keeps the string keys only: `aps` is iOS's, and Dart reads what Harness put beside it.+ func opened(_ userInfo: [AnyHashable: Any]) {+ var data: [String: String] = [:]+ for (key, value) in userInfo {+ if let key = key as? String, let value = value as? String { data[key] = value }+ }+ waiting = Array((waiting + [data]).suffix(20))+ channel?.invokeMethod("arrived", arguments: nil)}}diff --git a/mobile/ios/Runner/Runner.entitlements b/mobile/ios/Runner/Runner.entitlementsindex a87a77e53..f76e63493 100644--- a/mobile/ios/Runner/Runner.entitlements+++ b/mobile/ios/Runner/Runner.entitlements@@ -5,5 +5,9 @@<!-- Joining a new device's open setup hotspot, Harness-XXXX (SetupWifiChannel in AppDelegate.swift). --><key>com.apple.developer.networking.HotspotConfiguration</key><true/>+ <!-- Pushes (PushChannel in AppDelegate.swift). An App Store export signs it as `production`, from+ the distribution profile; Xcode's own builds stay on the sandbox gateway. -->+ <key>aps-environment</key>+ <string>development</string></dict></plist>diff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dartindex 617ae5075..fcaefe948 100644--- a/mobile/lib/api/api_client.dart+++ b/mobile/lib/api/api_client.dart@@ -9,6 +9,8 @@ import '../core/config.dart';import '../core/models.dart';import '../logging/app_log.dart';import '../logging/http_log.dart';+import '../notify/push_channel.dart' show PushAddress;+import '../notify/push_tokens.dart' show PushTokenApi;import '../swarm/swarm_outgoing_files.dart';import '../swarm/swarm_request.dart' show SuperTabFailure;import '../viewer/device_ack.dart';@@ -20,7 +22,7 @@ import 'bearer_auth_interceptor.dart';import 'multipart_body.dart';/// Authenticated control-plane REST client for the phone.-class ApiClient {+class ApiClient implements PushTokenApi {Future<Map<String, dynamic>> productUsageReport(Map<String, dynamic> report,) async {@@ -144,6 +146,30 @@ class ApiClient {unwrapApiResponse(res);}+ // -- where to push to this phone (notify/push_tokens.dart) --++ @override+ Future<void> registerPushToken(PushAddress address) async {+ final res = await _dio.post('/api/push-devices', data: _pushBody(address));+ unwrapApiResponse(res);+ }++ @override+ Future<void> forgetPushToken(PushAddress address) async {+ // In the body, not the path: a path lands in access logs.+ final res = await _dio.post(+ '/api/push-devices/drop',+ data: _pushBody(address),+ );+ unwrapApiResponse(res);+ }++ /// The server's body is strict (`routes/pushDevices.ts`): these two keys, nothing else.+ static Map<String, String> _pushBody(PushAddress address) => {+ 'platform': address.platform,+ 'token': address.token,+ };+// -- the account's device key log (viewer/device_log_sync.dart) --/// `GET /api/device-keys?since=` — the log from [since]; null when there is none to read (an olderdiff --git a/mobile/lib/notify/agent_announcer.dart b/mobile/lib/notify/agent_announcer.dartindex 732efe67b..9789cf21b 100644--- a/mobile/lib/notify/agent_announcer.dart+++ b/mobile/lib/notify/agent_announcer.dart@@ -23,6 +23,23 @@ typedef _AwaitingTier = ({Timer timer,});+/// A question heard while the app is in front, waiting out+/// [AgentAnnouncer.questionGrace] before it buzzes.+typedef _PendingQuestion = ({+ NoticeAgent agent,+ String requestId,+ String prompt,+ bool Function() watching,+ Timer timer,+});++/// One request of one agent: what a question that comes back is known by.+typedef _QuestionKey = ({AgentRef ref, String requestId});++/// What the phone did with one question lately: when it was first heard, when+/// it was last heard or closed, and whether the person was told of it.+typedef _HeardQuestion = ({DateTime first, DateTime touched, bool told});+/// Carries out the dial's two rules — [decideDoneNotice] and/// [decideQuestionNotice]: the chime, the unread mark, the system notice. The/// notifier says what happened; this decides what it is worth and does it, so@@ -33,13 +50,52 @@ class AgentAnnouncer {Future<void> Function()? chime,bool Function()? inFront,this.tierWait = const Duration(seconds: 4),+ this.questionGrace = const Duration(seconds: 15),+ this.alertCooldown = const Duration(minutes: 5),+ this.reopenWindow = const Duration(minutes: 10),+ DateTime Function()? now,}) : _chime = chime ?? _haptic,- _inFront = inFront ?? _appInFront;+ _inFront = inFront ?? _appInFront,+ _now = now ?? DateTime.now {+ _away.attach();+ }final SystemNotices system;final unread = AgentUnread();final _asked = AskedQuestions();+ /// How long a question waits, while the app is in front, before it buzzes.+ /// One answered within it — at the computer, by an auto mode, on another+ /// client — was never the person's to hear (2026-11-05: a Team machine's+ /// approvals, each answered at its desk in seconds, buzzed a phone over and+ /// over). Its mark shows at once. Away it goes at once, and so does one+ /// still waiting when the app goes away ([wentAway]): iOS suspends a+ /// backgrounded app within seconds, and a timer then fires only when it is+ /// opened again.+ final Duration questionGrace;++ /// After an agent buzzes for a question, its next ones within this long are+ /// posted quietly ([AgentNotice.quiet]): a run of approvals is one+ /// interruption, then quiet updates of the same notice.+ final Duration alertCooldown;++ /// How long a question is remembered after it was last heard or closed. One+ /// back within it — its dialog flickered off the pane and on, and the daemon+ /// closed and announced it again with the same id — never buzzes twice.+ final Duration reopenWindow;++ final DateTime Function() _now;+ late final _away = _AwayWatch(wentAway);++ /// Questions waiting out [questionGrace]: the newest per agent.+ final _pendingQuestions = <AgentRef, _PendingQuestion>{};++ /// Questions heard within [reopenWindow], and those still open.+ final _heard = <_QuestionKey, _HeardQuestion>{};++ /// When each agent last buzzed for a question ([alertCooldown]).+ final _lastBuzz = <AgentRef, DateTime>{};+/// How long a turn's end waits for the daemon's tier. It follows/// `turn_ended` by the daemon's decision — at most a second of Jev — and the/// relay; an older daemon's `turn_summary`, with none, comes at once. A@@ -158,30 +214,132 @@ class AgentAnnouncer {static String _short(AgentRef ref) => ref.agentId.length > 8 ? ref.agentId.substring(0, 8) : ref.agentId;/// The agent stopped to ask the person [prompt]. [requestId] is the- /// daemon's id for it, which a re-announce repeats.+ /// daemon's id for it, which a re-announce repeats. What was done now: a+ /// new question in front is only marked until its [questionGrace] runs out.AgentNotice questionAsked(NoticeAgent agent, {required String requestId,required String prompt,required bool Function() watching,}) {+ final ref = agent.ref;+ final now = _now();+ // Before hearing it: heard first, this very request would read as open,+ // and be kept however long ago it was last told.+ _forgetOldQuestions(now);+ if (!_asked.hear(ref, requestId)) {+ appLog.debug('notify', 'question · ${_short(ref)} · open already · none');+ return AgentNotice.none;+ }+ // Only the newest question is asked: one still waiting is dropped.+ _pendingQuestions.remove(ref)?.timer.cancel();+ final key = (ref: ref, requestId: requestId);+ final before = _heard[key];+ final heard = (+ first: before?.first ?? now,+ touched: now,+ told: before?.told ?? false,+ );+ _heard[key] = heard;+ final front = inFront;+ final wait = heard.first.add(questionGrace).difference(now);+ // Away there is no time to wait; on the agent its pane shows the dialog;+ // one told of already never buzzes; one back after its grace ran out,+ // while its dialog was off the pane, has waited long enough.+ if (!front || watching() || heard.told || wait <= Duration.zero) {+ return _askNow(agent, requestId: requestId, prompt: prompt, watching: watching);+ }+ unread.mark(ref, NoticeKind.question);+ _pendingQuestions[ref] = (+ agent: agent,+ requestId: requestId,+ prompt: prompt,+ watching: watching,+ timer: Timer(wait, () => _questionDue(ref)),+ );+ appLog.debug('notify', 'question · ${_short(ref)} · front · waits ${wait.inSeconds}s · filed');+ return AgentNotice.filed;+ }++ /// Tells of question [requestId] now, by where the person is ([decideQuestionNotice]).+ AgentNotice _askNow(+ NoticeAgent agent, {+ required String requestId,+ required String prompt,+ required bool Function() watching,+ }) {+ final ref = agent.ref;+ final now = _now();+ final key = (ref: ref, requestId: requestId);+ final heard = _heard[key];+ final told = heard?.told ?? false;final front = inFront;final seen = front && watching();+ final last = _lastBuzz[ref];+ final cooling = last != null && now.difference(last) < alertCooldown;final notice = decideQuestionNotice(- isNew: _asked.hear(agent.ref, requestId),+ isNew: true,inFront: front,watching: seen,+ told: told,+ cooling: cooling,);- appLog.debug('notify', 'question · ${_short(agent.ref)} · ${front ? 'front' : 'away'}${seen ? ' · watching' : ''} · ${notice.name}');+ if (notice == AgentNotice.alert) _lastBuzz[ref] = now;+ _heard[key] = (first: heard?.first ?? now, touched: now, told: true);+ appLog.debug('notify', 'question · ${_short(ref)} · ${front ? 'front' : 'away'}${seen ? ' · watching' : ''}${told ? ' · told' : ''}${cooling ? ' · cooling' : ''} · ${notice.name}');_deliver(agent, notice, NoticeKind.question, () => noticeBody(prompt));return notice;}+ /// [ref]'s question waited out its grace, or the app is going away while it+ /// waits: told now.+ void _questionDue(AgentRef ref) {+ final waiting = _pendingQuestions.remove(ref);+ if (waiting == null) return;+ waiting.timer.cancel();+ _askNow(+ waiting.agent,+ requestId: waiting.requestId,+ prompt: waiting.prompt,+ watching: waiting.watching,+ );+ }++ /// The app left the screen: every question still waiting out its grace is+ /// told now, while there is time to post it — iOS suspends a backgrounded+ /// app within seconds, and its timers with it.+ void wentAway() {+ for (final ref in _pendingQuestions.keys.toList()) {+ _questionDue(ref);+ }+ }++ /// Forgets the questions last heard or closed more than [reopenWindow] ago,+ /// keeping those still open: one asked for an hour is still the same+ /// question when its dialog flickers.+ void _forgetOldQuestions(DateTime now) {+ _heard.removeWhere(+ (key, heard) =>+ now.difference(heard.touched) > reopenWindow &&+ _asked.openOn(key.ref) != key.requestId,+ );+ }+/// The question is off the pane — answered here, by hand, on another client/// or on the dial. Its mark and its notice go with it: news nobody can act- /// on any more is not news. A finished turn's mark is left alone.+ /// on any more is not news. A finished turn's mark is left alone. What was+ /// told of it is kept ([reopenWindow]), and a grace it was waiting out+ /// resumes if it comes back.void questionClosed(AgentRef ref, {String? requestId}) {+ final open = _asked.openOn(ref);if (!_asked.forget(ref, requestId: requestId)) return;+ _pendingQuestions.remove(ref)?.timer.cancel();+ if (open != null) {+ final key = (ref: ref, requestId: open);+ if (_heard[key] case final heard?) {+ _heard[key] = (first: heard.first, touched: _now(), told: heard.told);+ }+ }if (unread.kindFor(ref) != NoticeKind.question) return;unread.clear(ref, kind: NoticeKind.question);_withdraw(ref);@@ -203,9 +361,20 @@ class AgentAnnouncer {/// The person went to the agent — tapped its row, its notice, or came back/// to the app on it. Whatever it was carrying has been read: the mark AND/// the notice still sitting in the OS centre come down together, and a- /// finished turn still waiting for its tier is not announced after.+ /// finished turn still waiting for its tier is not announced after. A+ /// question still waiting out its grace is not either: the person has seen+ /// its dialog, and it counts as told. Its [alertCooldown] ends: the run of+ /// questions it grouped has been dealt with, and the next one is news.void seen(AgentRef ref) {_awaitingTier.remove(ref)?.timer.cancel();+ _pendingQuestions.remove(ref)?.timer.cancel();+ _lastBuzz.remove(ref);+ if (_asked.openOn(ref) case final open?) {+ final key = (ref: ref, requestId: open);+ final heard = _heard[key];+ final now = _now();+ _heard[key] = (first: heard?.first ?? now, touched: now, told: true);+ }unread.clear(ref);_withdraw(ref);}@@ -215,6 +384,8 @@ class AgentAnnouncer {void forgetAgent(AgentRef ref) {_asked.forget(ref);seen(ref);+ _heard.removeWhere((key, _) => key.ref == ref);+ _lastBuzz.remove(ref);}/// Signed out: nothing any of it was about is this person's any more.@@ -222,6 +393,8 @@ class AgentAnnouncer {_cancelAwaiting();unread.clearAll();_asked.clear();+ _heard.clear();+ _lastBuzz.clear();_posted.toList().forEach(_withdraw);}@@ -230,6 +403,10 @@ class AgentAnnouncer {waiting.timer.cancel();}_awaitingTier.clear();+ for (final waiting in _pendingQuestions.values) {+ waiting.timer.cancel();+ }+ _pendingQuestions.clear();}void _withdraw(AgentRef ref) {@@ -252,6 +429,7 @@ class AgentAnnouncer {title: agent.name,machine: agent.machine,body: body(),+ quiet: notice == AgentNotice.quiet,));}@@ -259,10 +437,47 @@ class AgentAnnouncer {/// [SystemNotices.opened] after the notifier has gone.void dispose() {_cancelAwaiting();+ _away.detach();unread.dispose();}}+/// Calls [onAway] when the app leaves the screen: hidden or paused. A plain+/// observer rather than an `AppLifecycleListener`, which asserts on the jumps+/// between states that widget tests make.+class _AwayWatch extends WidgetsBindingObserver {+ _AwayWatch(this.onAway);++ final VoidCallback onAway;+ bool _attached = false;++ /// Tolerant of there being NO binding, as [AgentAnnouncer._appInFront] is:+ /// plain `test()`s build the announcer without one.+ void attach() {+ try {+ WidgetsBinding.instance.addObserver(this);+ _attached = true;+ } catch (_) {}+ }++ void detach() {+ if (!_attached) return;+ _attached = false;+ try {+ WidgetsBinding.instance.removeObserver(this);+ } catch (_) {}+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ if (state == AppLifecycleState.hidden ||+ state == AppLifecycleState.paused ||+ state == AppLifecycleState.detached) {+ onAway();+ }+ }+}+/// The text, cut to what a lock screen shows: its last paragraph — where an/// agent says what it did — on one line, at most [limit] characters.String noticeBody(String text, {int limit = 180}) {diff --git a/mobile/lib/notify/agent_notice.dart b/mobile/lib/notify/agent_notice.dartindex 59552efec..33b048ce9 100644--- a/mobile/lib/notify/agent_notice.dart+++ b/mobile/lib/notify/agent_notice.dart@@ -19,6 +19,13 @@ enum AgentNotice {/// without a beep or a wake.filed,+ /// Still news, but the person was told already: the same question back after+ /// its dialog flickered off the pane, or another one from an agent that+ /// buzzed moments ago (2026-11-05: a Team machine's approvals buzzed a phone+ /// over and over). Marked and posted to the OS centre with no sound, no+ /// vibration and no banner — there to find, not a second interruption.+ quiet,+/// The person is looking straight at this agent. The tap still comes — the/// dial's beep ALWAYS sounded before the daemon sent a tier — but nothing is/// filed for later: they are already where the news is.@@ -33,8 +40,11 @@ enum AgentNotice {alert;bool get chimes => this == chime || this == alert;- bool get marks => this == filed || this == alert;- bool get alerts => this == alert;+ bool get marks => this == filed || this == quiet || this == alert;++ /// Whether a system notice is posted: loudly for [alert], silently for+ /// [quiet].+ bool get alerts => this == quiet || this == alert;}/// How far news that IS news goes, by where the person is. [watching] — thediff --git a/mobile/lib/notify/push_channel.dart b/mobile/lib/notify/push_channel.dartnew file mode 100644index 000000000..adba2fb9e--- /dev/null+++ b/mobile/lib/notify/push_channel.dart@@ -0,0 +1,111 @@+import 'dart:async';++import 'package:flutter/services.dart';++import '../logging/app_log.dart';++/// Where the OS delivers this phone's pushes: the APNs device token on iOS, the FCM registration+/// token on Android. The server finds an Xcode build's sandbox token by itself (`push/apns.ts`).+typedef PushAddress = ({String token, String platform});++/// `harness/push` (iOS: `PushChannel` in `ios/Runner/AppDelegate.swift`; Android: `MainActivity.kt`+/// and `PushService.kt`): this phone's push address, and the pushes the person tapped.+///+/// The native side holds each tapped push's data until `take` answers it, so the push that launched+/// the app waits for Dart to ask; `arrived` says more wait. `changed` says the OS handed the app a+/// new address.+class PushChannel {+ PushChannel([MethodChannel? channel])+ : _channel = channel ?? const MethodChannel('harness/push');++ final MethodChannel _channel;++ /// iOS answers through `didRegisterForRemoteNotifications`, which never comes with no network.+ static const addressTimeout = Duration(seconds: 20);++ bool _closed = false;++ /// Asks the OS for this phone's push address. Null where there is none: no push in this build (the+ /// web, a test), or the OS could not give one, which is logged.+ Future<PushAddress?> address() async {+ try {+ final answer = await _channel+ .invokeMapMethod<String, Object?>('address')+ .timeout(addressTimeout);+ return pushAddressFrom(answer);+ } on MissingPluginException {+ return null;+ } on PlatformException catch (error) {+ appLog.warn('push', 'no push address: ${error.code}');+ return null;+ } on TimeoutException {+ appLog.warn('push', 'no push address: the OS did not answer');+ return null;+ }+ }++ /// Stops the OS delivering to the address it gave, so a phone that signed out is not reached.+ Future<void> forget() async {+ try {+ await _channel.invokeMethod<void>('forget');+ } on MissingPluginException {+ return;+ } on PlatformException catch (error) {+ appLog.warn('push', 'push address not forgotten: ${error.code}');+ }+ }++ /// Hears the pushes tapped ([onOpened], each with its data) and new addresses ([onChanged]) until+ /// [close]. Takes what already waits, such as the push that launched the app.+ void listen({+ required void Function(Map<String, String> data) onOpened,+ required void Function() onChanged,+ }) {+ _channel.setMethodCallHandler((call) async {+ switch (call.method) {+ case 'arrived':+ await _take(onOpened);+ case 'changed':+ onChanged();+ }+ return null;+ });+ unawaited(_take(onOpened));+ }++ Future<void> _take(void Function(Map<String, String> data) onOpened) async {+ List<Object?>? taken;+ try {+ taken = await _channel.invokeListMethod<Object?>('take');+ } on MissingPluginException {+ return;+ } on PlatformException catch (error) {+ appLog.warn('push', 'tapped pushes not read: ${error.code}');+ return;+ }+ if (_closed) return;+ for (final data in taken ?? const <Object?>[]) {+ if (data is Map) onOpened(_strings(data));+ }+ }++ /// Leaves tapped pushes waiting for the next listener.+ void close() {+ _closed = true;+ _channel.setMethodCallHandler(null);+ }+}++/// The address in [answer]; null when it does not name one.+PushAddress? pushAddressFrom(Map<String, Object?>? answer) {+ final token = answer?['token'], platform = answer?['platform'];+ if (token is! String || token.isEmpty) return null;+ if (platform != 'ios' && platform != 'android') return null;+ return (token: token, platform: platform as String);+}++/// A push's data as strings: APNs may nest values the app does not read; those are dropped.+Map<String, String> _strings(Map<Object?, Object?> data) => {+ for (final MapEntry(:key, :value) in data.entries)+ if (key is String && value is String) key: value,+};diff --git a/mobile/lib/notify/push_tokens.dart b/mobile/lib/notify/push_tokens.dartnew file mode 100644index 000000000..63b68ceff--- /dev/null+++ b/mobile/lib/notify/push_tokens.dart@@ -0,0 +1,191 @@+import 'dart:async';+import 'dart:convert';++import '../core/local_key_value_store.dart';+import '../logging/app_log.dart';+import 'push_channel.dart';++/// What the backend keeps of a phone's push address (`backend/src/routes/pushDevices.ts`).+abstract interface class PushTokenApi {+ /// `POST /api/push-devices`: [address] reaches the signed-in account from now on. Throws when+ /// the backend did not take it.+ Future<void> registerPushToken(PushAddress address);++ /// `POST /api/push-devices/drop`: [address] no longer reaches the account. Throws when the+ /// backend did not let it go.+ Future<void> forgetPushToken(PushAddress address);+}++/// Tells the backend where to push to this phone while someone is signed in, and takes it back when+/// they sign out or turn notifications off.+///+/// The address sent last is kept on disk with the account and the time, so a launch tells the+/// backend only when something changed, or when [renewEvery] has passed: the backend lets go of a+/// phone not seen for 90 days (`push/devices.ts`). Calls run one at a time, in the order made.+class PushTokens {+ PushTokens({+ required this.channel,+ required this._storage,+ required this._allowed,+ DateTime Function()? now,+ }) : _now = now ?? DateTime.now;++ final PushChannel channel;+ final LocalKeyValueStore _storage;++ /// Whether the OS lets this app post notices: null when it cannot say.+ final Future<bool?> Function() _allowed;++ final DateTime Function() _now;++ static const _key = 'push_token_sent_v1';++ /// How often an unchanged address is told again, well inside the backend's 90 days.+ static const renewEvery = Duration(days: 7);++ /// After the backend did not take an address, how long this launch waits before asking again: a+ /// backend from before push answers 404 to every resume.+ static const retryAfter = Duration(hours: 1);++ /// Each backend call is bounded, as a sign-out waits on [forget].+ static const callTimeout = Duration(seconds: 10);++ Future<void> _tail = Future.value();++ /// Raised by each [forget]: a [sync] asked for before it registers nothing.+ int _epoch = 0;+ DateTime? _failedAt;++ /// Signed in as [account]. Sends this phone's address when notices are allowed and the backend+ /// has not been told lately; takes it back when the person turned notices off. Nothing when the OS+ /// cannot say. [current] is asked right before the backend is told, and false means this sign-in+ /// is over.+ Future<void> sync({+ required String account,+ required PushTokenApi api,+ required bool Function() current,+ }) {+ final epoch = _epoch;+ return _serial(() async {+ final allowed = await _allowed();+ if (allowed == null) return;+ final sent = await _read();+ if (!allowed) {+ if (sent != null && sent.account == account) await _take(api, sent);+ return;+ }+ final failed = _failedAt;+ if (failed != null && _now().difference(failed) < retryAfter) return;+ final address = await channel.address();+ if (address == null) return;+ if (sent != null &&+ sent.account == account &&+ sent.address == address &&+ _now().difference(sent.at) < renewEvery) {+ return;+ }+ if (epoch != _epoch || !current()) return;+ try {+ await api.registerPushToken(address).timeout(callTimeout);+ } catch (error) {+ _failedAt = _now();+ appLog.warn(+ 'push',+ 'push address not registered',+ error: _describe(error, address.token),+ );+ return;+ }+ _failedAt = null;+ await _write((account: account, address: address, at: _now()));+ appLog.info('push', 'push address registered (${address.platform})');+ });+ }++ /// Signing out: the backend lets go of the address, and the OS stops delivering to it, so a+ /// backend that missed the first still reaches nothing. Best effort: the phone is signed out+ /// whatever the answer.+ Future<void> forget(PushTokenApi api) => _forget(api, always: true);++ /// A launch that found the session gone: as [forget], but only when this phone had told the+ /// backend an address, so a phone never signed in leaves the OS alone.+ Future<void> forgetIfTold(PushTokenApi api) => _forget(api, always: false);++ Future<void> _forget(PushTokenApi api, {required bool always}) {+ _epoch++;+ return _serial(() async {+ final sent = await _read();+ if (sent == null && !always) return;+ if (sent != null) await _take(api, sent);+ await _storage.delete(_key);+ _failedAt = null;+ await channel.forget();+ });+ }++ Future<void> _take(PushTokenApi api, _Sent sent) async {+ try {+ await api.forgetPushToken(sent.address).timeout(callTimeout);+ await _storage.delete(_key);+ appLog.info('push', 'push address forgotten');+ } catch (error) {+ appLog.warn(+ 'push',+ 'push address not forgotten',+ error: _describe(error, sent.address.token),+ );+ }+ }++ Future<void> _serial(Future<void> Function() run) {+ final next = _tail.then((_) => run());+ // One that failed must not stop the ones after it.+ _tail = next.catchError((Object error) {+ appLog.warn('push', 'push address step failed', error: _describe(error));+ });+ return _tail;+ }++ Future<_Sent?> _read() async {+ try {+ final raw = await _storage.read(_key);+ if (raw == null) return null;+ final json = jsonDecode(raw);+ if (json is! Map) return null;+ final account = json['account'], at = json['at'];+ final address = pushAddressFrom({+ 'token': json['token'],+ 'platform': json['platform'],+ });+ if (account is! String || address == null || at is! int) return null;+ return (+ account: account,+ address: address,+ at: DateTime.fromMillisecondsSinceEpoch(at),+ );+ } on FormatException {+ return null;+ }+ }++ Future<void> _write(_Sent sent) => _storage.write(+ _key,+ jsonEncode({+ 'account': sent.account,+ 'platform': sent.address.platform,+ 'token': sent.address.token,+ 'at': sent.at.millisecondsSinceEpoch,+ }),+ );+}++typedef _Sent = ({String account, PushAddress address, DateTime at});++/// The failure, short, and never with [token] in it: neither an `ApiException` nor a `DioException`+/// says the request's body, but a server's message may echo it.+String _describe(Object error, [String? token]) {+ if (error is TimeoutException) return 'timed out';+ var text = '$error';+ if (token != null && token.isNotEmpty) text = text.replaceAll(token, '…');+ return text.length > 160 ? '${text.substring(0, 160)}…' : text;+}diff --git a/mobile/lib/notify/question_notice.dart b/mobile/lib/notify/question_notice.dartindex 37de72b54..0df1dff6f 100644--- a/mobile/lib/notify/question_notice.dart+++ b/mobile/lib/notify/question_notice.dart@@ -42,6 +42,9 @@ class AskedQuestions {/// Whether a question is open on [ref] right now.bool asking(AgentRef ref) => _asked.containsKey(_key(ref));+ /// The request open on [ref] right now, or null.+ String? openOn(AgentRef ref) => _asked[_key(ref)];+/// The question stopped being on screen — answered, or its turn ended. An/// empty or null [requestId] means whichever one was open; a different one/// is a stale close for a question already replaced, and is ignored.@@ -72,12 +75,30 @@ class AskedQuestions {}/// What a question is worth. Only a NEW one is news; after that it is the same-/// escalation a finished turn gets.+/// escalation a finished turn gets — but never a second buzz for what the+/// person was already told:+///+/// - [told]: this very request buzzed, chimed or was posted already, and is+/// back after its dialog left the pane — a capture mid-repaint reads as no+/// dialog, and the daemon closes it and opens it again with the same id+/// (cli `questionController.ts` `noteGone`). Marked and posted quietly.+/// - [cooling]: the agent buzzed for another question moments ago+/// (`AgentAnnouncer.alertCooldown`). A run of approvals is one interruption,+/// then quiet updates of the same notice.+///+/// Where the person is looking at the agent, its pane already shows the+/// dialog: a chime for a new question, nothing for one they were told of.AgentNotice decideQuestionNotice({required bool isNew,required bool inFront,required bool watching,+ bool told = false,+ bool cooling = false,}) {if (!isNew) return AgentNotice.none;- return escalate(inFront: inFront, watching: watching);+ final seen = inFront && watching;+ if (told) return seen ? AgentNotice.none : AgentNotice.quiet;+ final notice = escalate(inFront: inFront, watching: watching);+ if (notice == AgentNotice.alert && cooling) return AgentNotice.quiet;+ return notice;}diff --git a/mobile/lib/notify/system_notices.dart b/mobile/lib/notify/system_notices.dartindex 3035202cd..96329db61 100644--- a/mobile/lib/notify/system_notices.dart+++ b/mobile/lib/notify/system_notices.dart@@ -9,13 +9,15 @@ import 'agent_notice.dart';/// One notice about one agent, as the OS draws it: the agent's name, the/// machine it runs on, and the news — what the turn said, or what it is asking-/// — the three lines of the dial's drawer row.+/// — the three lines of the dial's drawer row. [quiet] posts it with no sound,+/// no vibration and no banner ([AgentNotice.quiet]).typedef AgentNoticeMessage = ({AgentRef agent,NoticeKind kind,String title,String machine,String body,+ bool quiet,});/// Where a Swarm notice leads: the Swarm, and the conversation it is about;@@ -174,6 +176,10 @@ class LocalSystemNotices implements SystemNotices, SwarmNotices {@overridefinal openedSwarm = ValueNotifier<SwarmNoticeTarget?>(null);+ /// Told when the person has just allowed notices ([requestPermission]): the moment pushes can+ /// start reaching them (`notify/push_tokens.dart`).+ void Function()? onAllowed;+/// One Android channel per kind, so a person can silence finished turns and/// still hear questions — the two are not equally urgent. Also the iOS/// thread each kind is grouped under.@@ -260,7 +266,9 @@ class LocalSystemNotices implements SystemNotices, SwarmNotices {AndroidFlutterLocalNotificationsPlugin>()?.requestNotificationsPermission();- return ios ?? android;+ final allowed = ios ?? android;+ if (allowed == true) onAllowed?.call();+ return allowed;} catch (error) {appLog.warn('notify', 'permission request failed', error: error);return null;@@ -309,10 +317,19 @@ class LocalSystemNotices implements SystemNotices, SwarmNotices {importance: Importance.high,priority: Priority.high,subText: message.machine,+ // A quiet notice replaces or joins the list without a sound, a+ // vibration or a heads-up, whatever its channel says.+ silent: message.quiet,),iOS: DarwinNotificationDetails(subtitle: message.machine,threadIdentifier: channel.id,+ // Unset is the plugin's default, sound and banner. Without a sound+ // here iOS plays none in the background either; passive neither+ // lights the screen nor shows a banner, only the list.+ presentSound: message.quiet ? false : null,+ presentBanner: message.quiet ? false : null,+ interruptionLevel: message.quiet ? InterruptionLevel.passive : null,),),);@@ -500,3 +517,14 @@ AgentRef? decodeAgentPayload(String? payload) {if (parts[0].isEmpty || parts[1].isEmpty) return null;return (machineId: parts[0], agentId: parts[1]);}++/// A tapped push (`notify/push_channel.dart`) opens the chat its `link` names: the app's own+/// `swarm:` payload, which the server puts beside the notice's `key` (`backend/src/push/notices.ts`).+/// Anything else (no link, an agent's or a device's payload) only opened the app.+void openPushed(Map<String, String> data, SystemNotices notices) {+ if (notices case final SwarmNotices swarm) {+ if (decodeSwarmPayload(data['link']) case final target?) {+ swarm.openedSwarm.value = target;+ }+ }+}diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dartindex f26cc49a0..999910611 100644--- a/mobile/lib/phone/phone_shell.dart+++ b/mobile/lib/phone/phone_shell.dart@@ -607,6 +607,7 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {onMachineLinked: _followLinkedMachine,onOpenAgent: _openAgentAtHome,onShowSwarm: _showSwarm,+ home: _home,canOpenMachine: (machineId) =>phoneMachineOpensTerminals(widget.notifier.machineStates[machineId]),agentStopped: (machineId, agentId) =>diff --git a/mobile/lib/phone/phone_shell_scope.dart b/mobile/lib/phone/phone_shell_scope.dartindex 26960b657..25cdae111 100644--- a/mobile/lib/phone/phone_shell_scope.dart+++ b/mobile/lib/phone/phone_shell_scope.dart@@ -1,5 +1,7 @@import 'package:flutter/widgets.dart';+import '../swarm/swarm_home_root.dart';+/// What a page deep inside one tab can ask of the shell around all three.////// The pages live in per-tab navigators, so none of them can switch tabs or push onto another tab's@@ -11,6 +13,7 @@ class PhoneShellScope extends InheritedWidget {required this.onMachineLinked,required this.onOpenAgent,this.onShowSwarm,+ this.home,this.canOpenMachine,this.agentStopped,this.onResumeAgent,@@ -46,6 +49,11 @@ class PhoneShellScope extends InheritedWidget {/// go back to, and a Swarm page is pushed instead (`openSwarmHome`).final VoidCallback? onShowSwarm;+ /// What the root shows, Swarm Home or the terminal ([SwarmHomeChoice]): a terminal over Swarm+ /// Home asks it whether there is a Swarm to go back to ([SwarmHomeChoice.harnessOverSwarm]).+ /// Null outside the shell.+ final SwarmHomeChoice? home;+/// Null outside the shell — a page pumped on its own in a test simply has nowhere to go.static PhoneShellScope? maybeOf(BuildContext context) =>context.getInheritedWidgetOfExactType<PhoneShellScope>();diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dartindex ccd4c41c0..f09793c3a 100644--- a/mobile/lib/phone/terminal_page.dart+++ b/mobile/lib/phone/terminal_page.dart@@ -1,5 +1,6 @@import '../measurement/product_measurement.dart';import '../measurement/task_feedback.dart';+import 'dart:async';import 'dart:ui' as ui;@@ -83,6 +84,7 @@ import 'welcome/focus_hints.dart';import 'package:harness_mobile/demo/sample_mode.dart';import 'package:harness_mobile/notify/notifications_ask.dart';+import 'package:harness_mobile/swarm/swarm_home_root.dart';import 'package:harness_mobile/swarm/swarm_mark.dart';import 'voice_input_controller.dart';@@ -822,11 +824,29 @@ class _TerminalPageState extends State<TerminalPage>setState(() => _facts = facts);}+ SwarmHomeChoice? _swarmHome;++ void _swarmHomeChanged() {+ if (mounted) setState(() {});+ }++ /// Back to Swarm Home, while this terminal is what Swarm Home's agent opened: the terminal is the+ /// root page then, so no pop can leave it. Null with Swarm off, with Swarm Home showing, and+ /// outside the shell.+ VoidCallback? get _backToSwarm {+ final home = _swarmHome;+ if (home == null || !home.harnessOverSwarm) return null;+ return PhoneShellScope.maybeOf(context)?.onShowSwarm;+ }+@overridevoid initState() {super.initState();if (kTypingTrace) typingEvent('switch: terminal page mounted');WidgetsBinding.instance.addObserver(this);+ // Not a dependency (the scope never notifies): the shell's own choice of root is what changes.+ _swarmHome = PhoneShellScope.maybeOf(context)?.home+ ?..addListener(_swarmHomeChanged);_lifecycle =WidgetsBinding.instance.lifecycleState ?? AppLifecycleState.resumed;// A session already taking input when the page comes ticks nothing to raise from.@@ -902,6 +922,7 @@ class _TerminalPageState extends State<TerminalPage>@overridevoid dispose() {+ _swarmHome?.removeListener(_swarmHomeChanged);_endCardTimer?.cancel();// A take started here must not come back to a page that is gone.final session = widget.notifier@@ -2847,8 +2868,11 @@ class _TerminalPageState extends State<TerminalPage>// terminal drew** — see `reconnecting` above. Then the// screen stays and only [_Reconnecting] lies over it.if (reconnecting)- const Positioned.fill(child: _Reconnecting())- else if (session != null && !session.hasScreen)+ const Positioned.fill(+ child: _Reconnecting(),+ )+ else if (session != null &&+ !session.hasScreen)Positioned.fill(child: placeholder),// The mic and Search, floating in the// terminal's bottom-right corner — see@@ -2946,6 +2970,9 @@ class _TerminalPageState extends State<TerminalPage>mainAxisSize: MainAxisSize.min,children: [TerminalTitle(+ backInset: _backToSwarm == null+ ? 0+ : _BackToSwarm.inset,sample: SampleMode.maybeOf(context) != null,name:agent?.displayName ?? _cachedAgentName ?? '',@@ -3001,6 +3028,25 @@ class _TerminalPageState extends State<TerminalPage>),),),+ // The way back to Swarm, for a terminal opened from it. ⚠️ The terminal is+ // then the ROOT page, so there is nothing under it to pop and iOS has no+ // system back: the only way out was the dim Swarm mark in the title, which+ // folds away with it while the history is read. This stays, outside the slide.+ if (_backToSwarm case final toSwarm?) ...[+ Positioned(+ top: 0,+ left: 0,+ child: _BackToSwarm(onBack: toSwarm),+ ),+ if (defaultTargetPlatform == TargetPlatform.iOS)+ Positioned(+ top: 0,+ bottom: 0,+ left: 0,+ width: _BackToSwarm.edge,+ child: _EdgeBack(onBack: toSwarm),+ ),+ ],// ⚠️ No `[42/1380]` at the top right while reading back, by the owner's// call (2026-09-27): "we don't need the scrolling indicator". The history// scrolls like any list; scrolling down is the way back to the stream.@@ -3242,9 +3288,11 @@ class _TerminalPageState extends State<TerminalPage>PhoneSheetAction(icon: LucideIcons.messageSquareText300,label: 'Rate task outcome',- onTap: () => showTaskFeedback(context,+ onTap: () => showTaskFeedback(+ context,choice: () => widget.notifier.api.productUsageSettings(),- send: widget.notifier.api.productUsageFeedback),+ send: widget.notifier.api.productUsageFeedback,+ ),),PhoneSheetAction(icon: LucideIcons.settings300,@@ -3999,7 +4047,8 @@ class _ReconnectingState extends State<_Reconnecting> {child: TweenAnimationBuilder<double>(tween: Tween(begin: 0, end: 1),duration: still ? Duration.zero : const Duration(milliseconds: 180),- builder: (context, fade, child) => Opacity(opacity: fade, child: child),+ builder: (context, fade, child) =>+ Opacity(opacity: fade, child: child),child: Stack(fit: StackFit.expand,children: [@@ -5042,6 +5091,64 @@ class _SampleEndCard extends StatelessWidget {}}+/// The way back to Swarm Home over the terminal's top left corner: a chevron, as iOS draws back on+/// a pushed page, on the terminal's own ground so the output never reads through it. It sits+/// outside the header's slide, so it is there while the history is read back too.+class _BackToSwarm extends StatelessWidget {+ const _BackToSwarm({required this.onBack});++ final VoidCallback onBack;++ /// Room the title leaves for it: what its box takes, less the gutter the title keeps anyway,+ /// so the name starts where the box ends and no letter is under it.+ static const inset = TtyBackButton.width - Tty.origin;++ /// The width of the iOS edge swipe's strip ([_EdgeBack]).+ static const edge = 20.0;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return DecoratedBox(+ decoration: BoxDecoration(+ color: tty.ground,+ borderRadius: const BorderRadius.only(bottomRight: Radius.circular(14)),+ ),+ child: TtyBackButton(onPressed: onBack),+ );+ }+}++/// iOS's edge swipe back: a drag from the left edge that goes far enough, or is flung. A strip+/// only [_BackToSwarm.edge] wide, so the terminal keeps every other touch. Android has no such+/// swipe and is not given one: its system back is the shell's.+class _EdgeBack extends StatefulWidget {+ const _EdgeBack({required this.onBack});++ final VoidCallback onBack;++ @override+ State<_EdgeBack> createState() => _EdgeBackState();+}++class _EdgeBackState extends State<_EdgeBack> {+ double _dragged = 0;++ @override+ Widget build(BuildContext context) => GestureDetector(+ key: const ValueKey('terminal-edge-back'),+ behavior: HitTestBehavior.translucent,+ onHorizontalDragStart: (_) => _dragged = 0,+ onHorizontalDragUpdate: (details) => _dragged += details.delta.dx,+ onHorizontalDragEnd: (details) {+ if (_dragged > 80 || (details.primaryVelocity ?? 0) > 700) {+ HapticFeedback.selectionClick();+ widget.onBack();+ }+ },+ );+}+/// Find's hold on the back gesture — see `_TerminalPageState._findBack`.class _FindBack extends PopEntry<Object?> {_FindBack(this.onBack);diff --git a/mobile/lib/phone/terminal_title.dart b/mobile/lib/phone/terminal_title.dartindex b7a5e672f..5fb4b1c10 100644--- a/mobile/lib/phone/terminal_title.dart+++ b/mobile/lib/phone/terminal_title.dart@@ -42,11 +42,17 @@ class TerminalTitle extends StatelessWidget {this.daemon,this.away = false,this.sample = false,+ this.backInset = 0,});final String name;final bool sample;+ /// Room kept at the left for the back chevron the page draws over the title's corner+ /// (`terminal_page.dart`, only while Swarm Home is behind the terminal), so the name does not+ /// run under it. Zero otherwise: the title is as it was.+ final double backInset;+/// `machine:folder` — where the harness works.final String? place;@@ -193,7 +199,10 @@ class TerminalTitle extends StatelessWidget {child: ConstrainedBox(constraints: BoxConstraints(minHeight: height),child: Padding(- padding: const EdgeInsets.symmetric(horizontal: Tty.origin),+ padding: EdgeInsets.only(+ left: Tty.origin + backInset,+ right: Tty.origin,+ ),child: Row(children: [Expanded(diff --git a/mobile/lib/phone/tty_controls.dart b/mobile/lib/phone/tty_controls.dartindex f33db6886..1e6cbb9a5 100644--- a/mobile/lib/phone/tty_controls.dart+++ b/mobile/lib/phone/tty_controls.dart@@ -220,6 +220,9 @@ WidgetSpan ttyBranchMark(class TtyBackButton extends StatelessWidget {const TtyBackButton({super.key, required this.onPressed});+ /// The target's width.+ static const width = 52.0;+final VoidCallback? onPressed;@override@@ -239,7 +242,7 @@ class TtyBackButton extends StatelessWidget {onPressed!();},child: SizedBox(- width: 52,+ width: width,height: 44,child: Padding(padding: const EdgeInsets.only(left: Tty.origin - 5),diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 08e6682be..c7de1f888 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -17,7 +17,8 @@ import 'package:dio/dio.dart';import 'package:xterm/xterm.dart' show RemoteScrollMemory, Terminal;import 'package:flutter/foundation.dart';// The 80-character limit on a fork's name counts what a person sees, as the desktop's does.-import 'package:flutter/widgets.dart' show StringCharacters;+import 'package:flutter/widgets.dart'+ show AppLifecycleListener, StringCharacters;import 'package:flutter_riverpod/flutter_riverpod.dart';import '../api/api_client.dart';@@ -52,6 +53,8 @@ import '../logging/startup_trace.dart';import '../logging/typing_trace.dart';import '../notify/agent_announcer.dart';import '../notify/done_notice.dart';+import '../notify/push_channel.dart';+import '../notify/push_tokens.dart';import '../notify/system_notices.dart';import '../settings/config_store.dart';import '../stats/harness_stats.dart';@@ -1307,6 +1310,7 @@ class AppNotifier extends ChangeNotifier {ViewerServices? viewer,PaneLayoutStore? paneLayoutStore,SystemNotices? systemNotices,+ PushTokens? pushTokens,MachineCache? machineCache,KeptScreenStore? keptScreenStore,GroupSync? groupSync,@@ -1376,6 +1380,7 @@ class AppNotifier extends ChangeNotifier {addListener(_syncProductMeasurement);unawaited(_measurementContext());_initDeviceLog();+ _initPush(pushTokens, paneLayoutStore);}/// Which build this phone's reports come from ([ProductMeasurement.context]): the public release@@ -1810,6 +1815,9 @@ class AppNotifier extends ChangeNotifier {);if (!_authWorkCurrent(revision)) return;if (!authStatus.loggedIn) {+ // The session ended while the app was closed (revoked from another device): the OS stops+ // delivering this account's pushes to the phone. The backend drop fails without a session.+ if (_push case final push?) unawaited(push.forgetIfTold(api));currentUser = null;status = AppStatus.unauthenticated;notifyListeners();@@ -2035,6 +2043,7 @@ class AppNotifier extends ChangeNotifier {unawaited(_deviceLog?.signedInAs(id));_keepAccount(id);}+ _syncPush();notifyListeners();}} catch (error) {@@ -2082,6 +2091,9 @@ class AppNotifier extends ChangeNotifier {// who had just pressed Sign out. The sign-out finishes the job itself.if (_leftByHand) return;_invalidateAuthWork();+ // As on a sign-out here ([_endSession]): no lock-screen notice of this account after it. The+ // backend drop fails without a session; the OS one still stops delivery.+ if (_push case final push?) unawaited(push.forget(api));currentUser = null;signingIn = false;signInProvider = null;@@ -2396,6 +2408,12 @@ class AppNotifier extends ChangeNotifier {await log.leave().timeout(const Duration(seconds: 5));} catch (_) {}}+ // So does where to push to it: no notice of this account reaches a phone signed out of it.+ if (_push case final push?) {+ try {+ await push.forget(api).timeout(const Duration(seconds: 5));+ } catch (_) {}+ }final revision = _invalidateAuthWork();signingIn = false;signInProvider = null;@@ -3583,6 +3601,57 @@ class AppNotifier extends ChangeNotifier {}}+ // -- where to push to this phone (notify/push_tokens.dart) ---------------------------------------++ /// Null in a test and in the sample, which never reach the OS, and on the web, which has no push.+ PushTokens? _push;+ AppLifecycleListener? _pushLifecycle;++ void _initPush(PushTokens? given, PaneLayoutStore? paneLayoutStore) {+ final push = _push =+ given ??+ (kIsWeb || kUnderTest || paneLayoutStore == null+ ? null+ : PushTokens(+ channel: PushChannel(),+ storage: paneLayoutStore.storage,+ allowed: () => noticesEnabled(agentNotices.system),+ ));+ if (push == null) return;+ // Before the shell is up, so the push that launched the app is waiting for it as a tapped+ // notice is.+ push.channel.listen(+ onOpened: (data) => openPushed(data, agentNotices.system),+ onChanged: _syncPush,+ );+ if (agentNotices.system case final LocalSystemNotices notices) {+ notices.onAllowed = _syncPush;+ }+ // Back from the phone's Settings, where notices may have been turned on or off.+ _pushLifecycle = AppLifecycleListener(onResume: _syncPush);+ }++ /// Tells the backend where to push to this phone while signed in: once the account is known, when+ /// notices are allowed, when the OS hands over a new address, and back in the app.+ void _syncPush() {+ final push = _push;+ final account = swarmAccountId;+ if (push == null || _disposed || _signingOut != null || account == null) {+ return;+ }+ final revision = _authRevision;+ unawaited(+ push.sync(+ account: account,+ api: api,+ current: () =>+ _authWorkCurrent(revision) &&+ _signingOut == null &&+ status == AppStatus.authenticated,+ ),+ );+ }+void _initDeviceLog() {final log = _deviceLog = ViewerDeviceLog(keys: viewer.keys,@@ -11759,6 +11828,8 @@ class AppNotifier extends ChangeNotifier {swarm.panes.clear();}sessionPreviews.dispose();+ _pushLifecycle?.dispose();+ _push?.channel.close();agentNotices.dispose();_desk.dispose();daemonHabits.dispose();diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dartindex d592dabc1..4e1cbb22f 100644--- a/mobile/lib/swarm/model.dart+++ b/mobile/lib/swarm/model.dart@@ -395,6 +395,7 @@ class SuperTabConversation {): null,queueRank = (row['queueRank'] as num?)?.toDouble(),+ priority = row['priority'] as String?,notBefore = DateTime.tryParse(row['notBefore'] as String? ?? ''),lastMainSequence = (row['lastMainSequence'] as num?)?.toInt(),lastPersonSequence = (row['lastPersonSequence'] as num?)?.toInt() ?? 0,@@ -455,6 +456,11 @@ class SuperTabConversation {/// for the phone's Tasks view to come.final double? queueRank;final DateTime? notBefore;++ /// A task's priority, `P0` to `P3`, as the server keeps it (backend+ /// taskPriority.ts, task #3117); null on a step, a chat and a task from+ /// before it. Read here for the phone's Tasks view to come.+ final String? priority;String get label => number == null ? title : '#$number $title';final String? leadId;final List<String> agentIds;diff --git a/mobile/test/api/api_client_test.dart b/mobile/test/api/api_client_test.dartindex 16dfa40c3..94dd65940 100644--- a/mobile/test/api/api_client_test.dart+++ b/mobile/test/api/api_client_test.dart@@ -177,6 +177,34 @@ void main() {});});+ group('where to push to this phone (backend routes/pushDevices.ts)', () {+ test('registers on the merged route with exactly platform and token, signed as the phone', () async {+ await client(_Tokens(['phone-token'])).registerPushToken((token: 'apns-1', platform: 'ios'));+ final request = backend.requests.single;+ expect(request.method, 'POST');+ expect(request.path, '/api/push-devices');+ expect(request.headers.value('authorization'), 'Bearer phone-token');+ // The server's body is strict: any other key answers 400.+ expect(jsonDecode(utf8.decode(request.body)), {'platform': 'ios', 'token': 'apns-1'});+ });++ test('drops with the same body, never the token in the path', () async {+ await client(_Tokens(['t'])).forgetPushToken((token: 'fcm-1', platform: 'android'));+ final request = backend.requests.single;+ expect(request.method, 'POST');+ expect(request.path, '/api/push-devices/drop');+ expect(jsonDecode(utf8.decode(request.body)), {'platform': 'android', 'token': 'fcm-1'});+ });++ test('a backend that refuses throws with its status', () async {+ backend.answer = (_, _) => (status: 404, body: {'success': false, 'error': {'code': 'NOT_FOUND', 'message': 'Not found'}});+ await expectLater(+ client(_Tokens(['t'])).registerPushToken((token: 'a', platform: 'android')),+ throwsA(isA<ApiException>().having((e) => e.status, 'status', 404)),+ );+ });+ });+group('a Swarm read', () {test('answers the value, signed with this sign-in, its query kept', () async {backend.answer = (_, _) => (status: 200, body: ok({'tabs': <Object>[]}));diff --git a/mobile/test/app_state_push_test.dart b/mobile/test/app_state_push_test.dartnew file mode 100644index 000000000..ca838ed2e--- /dev/null+++ b/mobile/test/app_state_push_test.dart@@ -0,0 +1,145 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/push_channel.dart';+import 'package:harness_mobile/notify/push_tokens.dart';+import 'package:harness_mobile/notify/system_notices.dart' show SwarmNotices;++import 'viewer_app_fixture.dart';+import 'voice_fakes.dart' show MemoryKeyValueStore;++/// The phone's push address follows the sign-in: told to the backend once the account is known,+/// told again when the OS hands over a new one, taken back — and the OS stopped delivering — when+/// the person signs out. A tapped push opens what the same local notice would.+void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ const apns1 = (token: 'apns-1', platform: 'ios');+ late _Channel channel;+ late MemoryKeyValueStore storage;+ late PushTokens push;++ setUp(() {+ channel = _Channel()..next = apns1;+ storage = MemoryKeyValueStore();+ push = PushTokens(+ channel: channel,+ storage: storage,+ allowed: () async => true,+ );+ });++ test(+ 'signed in, the address reaches the backend; signed out, it is taken back',+ () async {+ final rig = viewerApp(pushTokens: push);+ await rig.app.bootstrap();+ await settle();+ expect(rig.api.pushRegistered, [apns1]);++ await rig.app.logout();+ await settle();+ expect(rig.api.pushForgotten, [apns1]);+ expect(channel.forgot, 1);+ rig.app.dispose();+ },+ );++ // A lost phone cut off from another device: no lock-screen notice of the account after it.+ test(+ 'a session ended elsewhere stops the OS delivering and forgets the record',+ () async {+ final rig = viewerApp(pushTokens: push);+ await rig.app.bootstrap();+ await settle();+ expect(rig.api.pushRegistered, [apns1]);++ rig.app.authFailureForTest('Your sign-in expired. Sign in again.');+ await settle();+ expect(channel.forgot, 1);+ expect(storage.values, isEmpty);+ rig.app.dispose();+ },+ );++ test(+ 'a launch that finds the session gone forgets a token it had told',+ () async {+ await storage.write(+ 'push_token_sent_v1',+ '{"account":"acct-1","platform":"ios","token":"apns-1","at":0}',+ );+ final rig = viewerApp(signedIn: false, pushTokens: push);+ await rig.app.bootstrap();+ await settle();+ expect(channel.forgot, 1);+ expect(storage.values, isEmpty);+ rig.app.dispose();+ },+ );++ test('a launch signed out with nothing told leaves the OS alone', () async {+ final rig = viewerApp(signedIn: false, pushTokens: push);+ await rig.app.bootstrap();+ await settle();+ expect(channel.forgot, 0);+ rig.app.dispose();+ });++ test('signed out, nothing reaches the backend', () async {+ final rig = viewerApp(signedIn: false, pushTokens: push);+ await rig.app.bootstrap();+ await settle();+ channel.onChanged!();+ await settle();+ expect(rig.api.pushRegistered, isEmpty);+ rig.app.dispose();+ });++ test('a new address from the OS is told again', () async {+ final rig = viewerApp(pushTokens: push);+ await rig.app.bootstrap();+ await settle();+ channel.next = (token: 'apns-2', platform: 'ios');+ channel.onChanged!();+ await settle();+ expect(rig.api.pushRegistered, [apns1, (token: 'apns-2', platform: 'ios')]);+ rig.app.dispose();+ });++ test('a tapped push opens the chat its link names', () async {+ final rig = viewerApp(pushTokens: push);+ await rig.app.bootstrap();+ await settle();+ channel.onOpened!({'key': 'mention:x1', 'link': 'swarm:s1/c1/message/m1'});+ final notices = rig.app.agentNotices.system as SwarmNotices;+ expect(notices.openedSwarm.value?.conversationId, 'c1');+ expect(notices.openedSwarm.value?.messageId, 'm1');+ rig.app.dispose();+ expect(channel.closed, isTrue);+ });+}++class _Channel extends PushChannel {+ PushAddress? next;+ int forgot = 0;+ bool closed = false;+ void Function(Map<String, String>)? onOpened;+ void Function()? onChanged;++ @override+ Future<PushAddress?> address() async => next;++ @override+ Future<void> forget() async => forgot++;++ @override+ void listen({+ required void Function(Map<String, String> data) onOpened,+ required void Function() onChanged,+ }) {+ this.onOpened = onOpened;+ this.onChanged = onChanged;+ }++ @override+ void close() => closed = true;+}diff --git a/mobile/test/notify/agent_announcer_test.dart b/mobile/test/notify/agent_announcer_test.dartindex 879180dc7..b51cdbbc0 100644--- a/mobile/test/notify/agent_announcer_test.dart+++ b/mobile/test/notify/agent_announcer_test.dart@@ -55,6 +55,9 @@ void main() {system: system,chime: () async => chimes++,inFront: () => front,+ // Told at once, so each rule here is read on its own; the wait is+ // pinned under fake time below ('a question in front').+ questionGrace: Duration.zero,);addTearDown(announcer.dispose);});@@ -416,8 +419,11 @@ void main() {expect(system.cancelled, [ref]);expect(announcer.unread.kindFor(other), NoticeKind.question);expect(announcer.unread.kindFor(elsewhere), NoticeKind.question, reason: 'another machine said nothing of it');- // Heard again later, it is news again: it is a question asked anew.- expect(ask(), AgentNotice.alert);+ // Heard again later it is open again, and posted again — but the person+ // was told of this very request already: no second buzz.+ expect(ask(), AgentNotice.quiet);+ expect(announcer.unread.kindFor(ref), NoticeKind.question);+ expect(system.shown.last.quiet, isTrue);});test('an open list leaves a finished turn\'s mark alone', () {@@ -440,9 +446,12 @@ void main() {expect(chimes, 1);});- test('the dialog moving to its next page is a new question', () {+ test('the dialog moving to its next page is a new question, posted without a second buzz', () {ask();- expect(ask(id: 'q2'), AgentNotice.alert);+ expect(ask(id: 'q2'), AgentNotice.quiet, reason: 'the agent buzzed a moment ago');+ expect(chimes, 1);+ expect(announcer.unread.kindFor(ref), NoticeKind.question);+ expect(system.shown.map((m) => m.quiet), [false, true]);});test('away: one notice, of the question kind, saying the question', () {@@ -491,7 +500,12 @@ void main() {tier: null,), watching: () => false);expect(announcer.unread.contains(ref), isFalse);- expect(ask(), AgentNotice.alert, reason: 'a new turn may ask it again');+ expect(+ ask(),+ AgentNotice.quiet,+ reason: 'a new turn may ask it again: marked and posted, but this very dialog buzzed moments ago',+ );+ expect(announcer.unread.kindFor(ref), NoticeKind.question);});test('a deleted agent takes its mark and its notice with it', () {@@ -503,6 +517,327 @@ void main() {});});+ // 2026-11-05: a Team machine's approvals ("Approve Bash command: …"), each+ // answered at its desk in seconds, and dialogs flickering off the pane and+ // on, buzzed a phone over and over. Three rules keep the first question that+ // really waits on the person, and drop the rest.+ group('a question in front: waits out its grace, buzzes once', () {+ const grace = Duration(seconds: 15);+ const cooldown = Duration(minutes: 5);+ const reopen = Duration(minutes: 10);+ final start = DateTime(2026, 11, 5, 12);+ const other = (machineId: 'm', agentId: 'b');+ const otherAgent = (ref: other, name: 'Other', machine: 'MacBook');++ /// The announcer under fake time and a clock that follows it, built+ /// inside [body]'s zone as its timers must be.+ void inFakeTime(void Function(FakeAsync time, AgentAnnouncer a) body) {+ fakeAsync((time) {+ final a = AgentAnnouncer(+ system: system,+ chime: () async => chimes++,+ inFront: () => front,+ questionGrace: grace,+ alertCooldown: cooldown,+ reopenWindow: reopen,+ now: () => start.add(time.elapsed),+ );+ body(time, a);+ a.dispose();+ });+ }++ AgentNotice ask(+ AgentAnnouncer a, {+ String id = 'q1',+ NoticeAgent who = agent,+ bool watching = false,+ }) => a.questionAsked(+ who,+ requestId: id,+ prompt: 'Approve Bash command: npm test',+ watching: () => watching,+ );++ List<bool> quietness() => [for (final m in system.shown) m.quiet];++ test('marked at once; it buzzes only once its grace runs out, still open', () {+ inFakeTime((time, a) {+ expect(ask(a), AgentNotice.filed);+ expect(a.unread.kindFor(ref), NoticeKind.question);+ expect(system.shown, isEmpty);+ expect(chimes, 0);+ time.elapse(grace - const Duration(milliseconds: 1));+ expect(system.shown, isEmpty);+ time.elapse(const Duration(milliseconds: 1));+ expect(quietness(), [false]);+ expect(system.shown.single.body, 'Approve Bash command: npm test');+ expect(chimes, 1);+ });+ });++ test('answered within its grace — at the desk, by an auto mode — it never buzzes', () {+ inFakeTime((time, a) {+ ask(a);+ time.elapse(const Duration(seconds: 3));+ a.questionClosed(ref, requestId: 'q1');+ time.elapse(grace * 2);+ expect(system.shown, isEmpty);+ expect(chimes, 0);+ expect(a.unread.contains(ref), isFalse);+ });+ });++ test('a run of approvals answered at the desk in seconds: nothing at all', () {+ inFakeTime((time, a) {+ for (var i = 0; i < 10; i++) {+ ask(a, id: 'q$i');+ time.elapse(const Duration(seconds: 2));+ a.questionClosed(ref, requestId: 'q$i');+ }+ time.elapse(grace * 2);+ expect(system.shown, isEmpty);+ expect(chimes, 0);+ });+ });++ test('a newer question replaces the one waiting, and is the one told, once', () {+ inFakeTime((time, a) {+ ask(a);+ time.elapse(const Duration(seconds: 5));+ expect(ask(a, id: 'q2'), AgentNotice.filed);+ time.elapse(const Duration(seconds: 10));+ expect(system.shown, isEmpty, reason: 'the first one\'s wait was dropped');+ time.elapse(const Duration(seconds: 5));+ expect(quietness(), [false]);+ time.elapse(grace * 2);+ expect(system.shown, hasLength(1));+ });+ });++ test('a dialog flickering off the pane buzzes once, then is only posted again quietly', () {+ inFakeTime((time, a) {+ ask(a);+ time.elapse(grace);+ expect(quietness(), [false]);+ for (var i = 0; i < 5; i++) {+ a.questionClosed(ref, requestId: 'q1');+ expect(a.unread.contains(ref), isFalse);+ time.elapse(const Duration(milliseconds: 1500));+ expect(ask(a), AgentNotice.quiet);+ expect(a.unread.kindFor(ref), NoticeKind.question, reason: 'it is open again');+ time.elapse(const Duration(seconds: 5));+ }+ expect(chimes, 1);+ expect(quietness(), [false, true, true, true, true, true]);+ });+ });++ test('a dialog flickering through its grace still buzzes, once, when the grace runs out', () {+ inFakeTime((time, a) {+ // Off the pane for 1.5 s every 4.5 s: each close drops the wait, and+ // each return resumes it rather than starting it over.+ ask(a);+ for (var i = 0; i < 3; i++) {+ time.elapse(const Duration(seconds: 3));+ a.questionClosed(ref, requestId: 'q1');+ time.elapse(const Duration(milliseconds: 1500));+ expect(ask(a), AgentNotice.filed);+ }+ expect(system.shown, isEmpty);+ time.elapse(const Duration(milliseconds: 1500));+ expect(quietness(), [false]);+ a.questionClosed(ref, requestId: 'q1');+ expect(ask(a), AgentNotice.quiet);+ expect(chimes, 1);+ });+ });++ test('one back after its grace ran out while off the pane is told at once', () {+ inFakeTime((time, a) {+ ask(a);+ time.elapse(const Duration(seconds: 3));+ a.questionClosed(ref, requestId: 'q1');+ time.elapse(grace);+ expect(ask(a), AgentNotice.alert);+ expect(quietness(), [false]);+ });+ });++ test('another question of the agent within the cooldown is posted quietly; after it, it buzzes again', () {+ inFakeTime((time, a) {+ ask(a);+ time.elapse(grace);+ a.questionClosed(ref, requestId: 'q1');+ ask(a, id: 'q2');+ time.elapse(grace);+ expect(quietness(), [false, true]);+ expect(chimes, 1);+ expect(a.unread.kindFor(ref), NoticeKind.question);+ time.elapse(cooldown);+ a.questionClosed(ref, requestId: 'q2');+ ask(a, id: 'q3');+ time.elapse(grace);+ expect(quietness(), [false, true, false]);+ expect(chimes, 2);+ });+ });++ test('going to the agent ends its cooldown: its next question buzzes', () {+ inFakeTime((time, a) {+ ask(a);+ time.elapse(grace);+ // The person opens the agent and answers there, then leaves its pane.+ a.seen(ref);+ a.questionClosed(ref, requestId: 'q1');+ ask(a, id: 'q2');+ time.elapse(grace);+ expect(quietness(), [false, false]);+ expect(chimes, 2);+ });+ });++ test('the cooldown is the agent\'s own: another agent still buzzes', () {+ inFakeTime((time, a) {+ ask(a);+ ask(a, who: otherAgent);+ time.elapse(grace);+ expect(quietness(), [false, false]);+ expect(system.shown.map((m) => m.agent), [ref, other]);+ expect(chimes, 2);+ });+ });++ test('the same dialog asked again after the reopen window is news again', () {+ inFakeTime((time, a) {+ ask(a);+ time.elapse(grace);+ a.questionClosed(ref, requestId: 'q1');+ time.elapse(reopen + const Duration(seconds: 1));+ expect(ask(a), AgentNotice.filed);+ time.elapse(grace);+ expect(quietness(), [false, false]);+ expect(chimes, 2);+ });+ });++ test('a question open longer than the window is still the same one when it flickers', () {+ inFakeTime((time, a) {+ ask(a);+ time.elapse(grace);+ time.elapse(reopen * 2);+ // Another agent's question is what forgets old ones.+ ask(a, who: otherAgent);+ a.questionClosed(ref, requestId: 'q1');+ expect(ask(a), AgentNotice.quiet);+ });+ });++ test('going to the agent within its grace: no buzz after, and it counts as told', () {+ inFakeTime((time, a) {+ ask(a);+ time.elapse(const Duration(seconds: 5));+ a.seen(ref);+ time.elapse(grace * 2);+ expect(system.shown, isEmpty);+ expect(chimes, 0);+ expect(a.unread.contains(ref), isFalse);+ // Its dialog flickers afterwards: never a buzz for what was seen.+ a.questionClosed(ref, requestId: 'q1');+ expect(ask(a), AgentNotice.quiet);+ expect(chimes, 0);+ });+ });++ test('going away within its grace: told at once, while there is time to post it', () {+ inFakeTime((time, a) {+ ask(a);+ time.elapse(const Duration(seconds: 2));+ front = false;+ a.wentAway();+ expect(quietness(), [false]);+ expect(system.shown.single.kind, NoticeKind.question);+ time.elapse(grace * 2);+ expect(system.shown, hasLength(1), reason: 'told once');+ });+ });++ test('going away with nothing waiting does nothing', () {+ inFakeTime((time, a) {+ front = false;+ a.wentAway();+ expect(system.shown, isEmpty);+ });+ });++ test('away: no wait at all', () {+ inFakeTime((time, a) {+ front = false;+ expect(ask(a), AgentNotice.alert);+ expect(quietness(), [false]);+ time.elapse(grace * 2);+ expect(system.shown, hasLength(1));+ });+ });++ test('away, a run of approvals: one buzz, then quiet updates of the same notice', () {+ inFakeTime((time, a) {+ front = false;+ for (var i = 0; i < 4; i++) {+ ask(a, id: 'q$i');+ a.questionClosed(ref, requestId: 'q$i');+ time.elapse(const Duration(seconds: 20));+ }+ expect(quietness(), [false, true, true, true]);+ });+ });++ test('on the agent: a chime at once, with no wait and no notice', () {+ inFakeTime((time, a) {+ expect(ask(a, watching: true), AgentNotice.chime);+ expect(chimes, 1);+ time.elapse(grace * 2);+ expect(system.shown, isEmpty);+ expect(a.unread.count, 0);+ });+ });++ test('a deleted agent forgets what it was told: its next question buzzes', () {+ inFakeTime((time, a) {+ ask(a);+ time.elapse(grace);+ a.forgetAgent(ref);+ expect(ask(a), AgentNotice.filed);+ time.elapse(grace);+ expect(quietness(), [false, false]);+ });+ });++ test('signing out drops a question still waiting, and what was told', () {+ inFakeTime((time, a) {+ ask(a);+ a.reset();+ time.elapse(grace * 2);+ expect(system.shown, isEmpty);+ expect(a.unread.count, 0);+ });+ });++ test('disposing leaves no timer behind', () {+ fakeAsync((time) {+ final a = AgentAnnouncer(+ system: system,+ inFront: () => true,+ now: () => start.add(time.elapsed),+ );+ a.questionAsked(agent, requestId: 'q1', prompt: 'x', watching: () => false);+ expect(time.pendingTimers, hasLength(1));+ a.dispose();+ expect(time.pendingTimers, isEmpty);+ });+ });+ });+group('noticeBody', () {test('keeps the last paragraph, on one line', () {expect(noticeBody('a\n\nb c\nd'), 'b c d');diff --git a/mobile/test/notify/announcer_lifecycle_test.dart b/mobile/test/notify/announcer_lifecycle_test.dartindex 90a255111..495af56ac 100644--- a/mobile/test/notify/announcer_lifecycle_test.dart+++ b/mobile/test/notify/announcer_lifecycle_test.dart@@ -65,6 +65,64 @@ void main() {tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);});++ testWidgets('a question waiting out its grace is told the moment the app is hidden', (+ tester,+ ) async {+ final system = _Recording();+ final announcer = AgentAnnouncer(system: system);+ addTearDown(announcer.dispose);++ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ expect(+ announcer.questionAsked(+ agent,+ requestId: 'q1',+ prompt: 'Approve Bash command: npm test',+ watching: () => false,+ ),+ AgentNotice.filed,+ );+ expect(system.shown, isEmpty, reason: 'in front, it waits out its grace');++ // Locking the phone: iOS suspends the app within seconds, and the wait's+ // timer with it — so it goes now, and loud.+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ expect(system.shown, isEmpty, reason: 'inactive is not away');+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);+ expect(system.shown, hasLength(1));+ expect(system.shown.single.quiet, isFalse);+ expect(system.shown.single.body, 'Approve Bash command: npm test');++ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);+ expect(system.shown, hasLength(1), reason: 'told once');+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ });++ testWidgets('going away after the announcer is disposed tells nothing, and throws nothing', (+ tester,+ ) async {+ final system = _Recording();+ final announcer = AgentAnnouncer(system: system);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ announcer.questionAsked(+ agent,+ requestId: 'q1',+ prompt: 'Approve Bash command: npm test',+ watching: () => false,+ );+ announcer.dispose();+ // Its wait went with it, and so did its ear: going away tells of nothing.+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);+ expect(system.shown, isEmpty);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ });}class _Recording extends SilentSystemNotices {diff --git a/mobile/test/notify/local_system_notices_test.dart b/mobile/test/notify/local_system_notices_test.dartindex 01867bcfa..1886baec8 100644--- a/mobile/test/notify/local_system_notices_test.dart+++ b/mobile/test/notify/local_system_notices_test.dart@@ -2,6 +2,7 @@ import 'package:flutter/foundation.dart';import 'package:flutter/services.dart';import 'package:flutter_local_notifications/flutter_local_notifications.dart';import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/last_opened_agent.dart' show AgentRef;import 'package:harness_mobile/notify/agent_notice.dart';import 'package:harness_mobile/notify/system_notices.dart';@@ -16,12 +17,17 @@ import 'package:harness_mobile/notify/system_notices.dart';void main() {const ref = (machineId: 'machine-1', agentId: 'agent-7');- AgentNoticeMessage message(NoticeKind kind, {String body = 'Fixed it.'}) => (+ AgentNoticeMessage message(+ NoticeKind kind, {+ String body = 'Fixed it.',+ bool quiet = false,+ }) => (agent: ref,kind: kind,title: 'Fix login',machine: 'MacBook',body: body,+ quiet: quiet,);late _FakePlugin plugin;@@ -200,6 +206,32 @@ void main() {},);+ test('a loud notice keeps the channel\'s sound, vibration and banner', () async {+ await notices.show(message(NoticeKind.question));+ final shown = plugin.shown.single;+ expect(shown.details!.android!.silent, isFalse);+ final ios = shown.details!.iOS!;+ expect(ios.presentSound, isNull, reason: 'the plugin default: sound');+ expect(ios.presentBanner, isNull, reason: 'the plugin default: a banner');+ expect(ios.interruptionLevel, isNull);+ });++ test('a quiet notice: no sound, no vibration, no banner — only the list', () async {+ await notices.show(+ message(NoticeKind.question, body: 'Approve Bash command: npm test', quiet: true),+ );+ final shown = plugin.shown.single;+ expect(shown.id, noticeIdFor(ref), reason: 'it replaces the agent\'s notice');+ expect(shown.body, 'Approve Bash command: npm test');+ expect(shown.details!.android!.channelId, 'agent-question');+ expect(shown.details!.android!.silent, isTrue);+ final ios = shown.details!.iOS!;+ expect(ios.presentSound, isFalse);+ expect(ios.presentBanner, isFalse);+ expect(ios.interruptionLevel, InterruptionLevel.passive);+ expect(ios.threadIdentifier, 'agent-question');+ });+test('newer news about the same agent replaces its notice', () async {await notices.show(message(NoticeKind.done));await notices.show(message(NoticeKind.question));@@ -335,6 +367,97 @@ void main() {expect(silent.opened.value, isNull);});});++ group('pushes', () {+ test('allowing notices is told, so pushes can start reaching the person', () async {+ var told = 0;+ notices.onAllowed = () => told++;+ await notices.requestPermission();+ expect(told, 1);+ });++ test('refusing them is not', () async {+ var told = 0;+ notices.onAllowed = () => told++;+ plugin.ios.allow = false;+ await notices.requestPermission();+ plugin.ios.fail = true;+ await notices.requestPermission();+ expect(told, 0);+ });++ // What the server sends (backend push/notices.ts): `key`, and `link`, the app's own `swarm:`+ // payload.+ test('a tapped reply push opens the thread at the reply', () {+ openPushed({'key': 'reply:s1:r1', 'link': 'swarm:s1/c1/message/m1/thread/t1'}, notices);+ expect(notices.openedSwarm.value, (+ swarmId: 's1',+ conversationId: 'c1',+ messageId: 'm1',+ decisionId: null,+ threadId: 't1',+ ));+ expect(notices.opened.value, isNull);+ });++ test('a tapped tag push opens the chat at the message, its ids decoded', () {+ openPushed({'key': 'mention:x1', 'link': 'swarm:s%2F1/c1/message/m1'}, notices);+ expect(notices.openedSwarm.value, (+ swarmId: 's/1',+ conversationId: 'c1',+ messageId: 'm1',+ decisionId: null,+ threadId: null,+ ));+ });++ test('a push opens the chat its link names and nothing else', () {+ for (final data in <Map<String, String>>[+ {},+ {'key': 'mention:x1'},+ {'link': 'machine-1\nagent-7'},+ {'link': 'device:key-1'},+ {'link': 'swarm:s1'},+ {'link': 'swarm:s1/c1/agent/a1'},+ {'link': 'https://example.com/swarm:s1/c1'},+ // The first contract's keys: the server never sends them, and they open nothing.+ {'kind': 'agent_question', 'machine': 'machine-1', 'agent': 'agent-7'},+ {'kind': 'swarm', 'swarm': 's1', 'conversation': 'c1', 'message': 'm1'},+ ]) {+ openPushed(data, notices);+ }+ expect(notices.openedSwarm.value, isNull);+ expect(notices.opened.value, isNull);+ expect(notices.openedDevice.value, isNull);+ });++ test('a centre without Swarm notices opens nothing', () {+ final silent = _AgentsOnly();+ openPushed({'link': 'swarm:s1/c1/message/m1'}, silent);+ openPushed({'link': 'machine-1\nagent-7'}, silent);+ expect(silent.opened.value, isNull);+ });++ // A push and the notice the running app posts for the same news share an id, so one replaces+ // the other: Android's PushService.noticeId computes these too, and the backend sets the same as+ // `apns-collapse-id` (docs/design/2026-11-05-phone-push.md lists them).+ test('the ids a push shares with the app’s own notices', () {+ expect(swarmNoticeIdFor('mention:m1'), 1161357565);+ expect(swarmNoticeIdFor('decision:d1'), 15921470);+ expect(swarmNoticeIdFor('work:s1:c1:a1:needs_human'), 701122187);+ expect(swarmNoticeIdFor('mention:é✓'), 1555091707);+ expect(noticeIdFor(ref), 1081005959);+ });+ });+}++/// A centre with no Swarm side: what [openPushed] must not assume.+class _AgentsOnly implements SystemNotices {+ @override+ final opened = ValueNotifier<AgentRef?>(null);++ @override+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);}typedef _Shown = ({@@ -421,6 +544,7 @@ class _FakePlugin implements FlutterLocalNotificationsPlugin {class _FakeIos implements IOSFlutterLocalNotificationsPlugin {final asked = <({bool alert, bool sound, bool badge})>[];bool fail = false;+ bool? allow = true;@overrideFuture<bool?> requestPermissions({@@ -434,7 +558,7 @@ class _FakeIos implements IOSFlutterLocalNotificationsPlugin {}) async {if (fail) throw PlatformException(code: 'permission');asked.add((alert: alert, sound: sound, badge: badge));- return true;+ return allow;}@overridediff --git a/mobile/test/notify/push_channel_test.dart b/mobile/test/notify/push_channel_test.dartnew file mode 100644index 000000000..0aea64a3f--- /dev/null+++ b/mobile/test/notify/push_channel_test.dart@@ -0,0 +1,154 @@+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/push_channel.dart';++/// `harness/push` as Dart sees it: the address the OS gave, read strictly, and the pushes the person+/// tapped, each handed over once — the one that launched the app included.+void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ const name = 'harness/push';+ const method = MethodChannel(name);+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;++ late List<MethodCall> calls;+ late List<Object?> waiting;+ late Object? Function(MethodCall call) answer;++ setUp(() {+ calls = [];+ waiting = [];+ answer = (_) => null;+ messenger.setMockMethodCallHandler(method, (call) async {+ calls.add(call);+ if (call.method == 'take') {+ final taken = [...waiting];+ waiting.clear();+ return taken;+ }+ return answer(call);+ });+ });++ tearDown(() => messenger.setMockMethodCallHandler(method, null));++ /// The native side calling Dart, as iOS or Android does.+ Future<void> fromNative(String call) async {+ await messenger.handlePlatformMessage(+ name,+ const StandardMethodCodec().encodeMethodCall(MethodCall(call)),+ (_) {},+ );+ }++ group('address', () {+ test(+ 'an iOS or Android token is its platform and token, nothing else',+ () async {+ answer = (_) => {+ 'token': 'abc',+ 'platform': 'ios',+ 'environment': 'sandbox',+ };+ expect(await PushChannel().address(), (token: 'abc', platform: 'ios'));+ answer = (_) => {'token': 'fcm:1', 'platform': 'android'};+ expect(await PushChannel().address(), (+ token: 'fcm:1',+ platform: 'android',+ ));+ },+ );++ test('anything else names no address', () async {+ for (final bad in <Object?>[+ null,+ {'platform': 'ios'},+ {'token': '', 'platform': 'ios'},+ {'token': 'abc', 'platform': 'web'},+ {'token': 'abc'},+ ]) {+ answer = (_) => bad;+ expect(await PushChannel().address(), isNull, reason: '$bad');+ }+ });++ test(+ 'the OS refusing (no network, no entitlement) is no address, not a crash',+ () async {+ answer = (_) => throw PlatformException(+ code: 'unregistered',+ message: 'no aps-environment',+ );+ expect(await PushChannel().address(), isNull);+ },+ );++ test('a build with no push side at all is no address', () async {+ messenger.setMockMethodCallHandler(method, null);+ expect(await PushChannel().address(), isNull);+ await PushChannel().forget();+ });+ });++ test('forget asks the OS to stop delivering', () async {+ await PushChannel().forget();+ expect(calls.map((c) => c.method), ['forget']);+ });++ group('tapped pushes', () {+ test(+ 'the one that launched the app is taken when Dart starts listening',+ () async {+ waiting.add({'kind': 'swarm', 'swarm': 's1', 'conversation': 'c1'});+ final opened = <Map<String, String>>[];+ PushChannel().listen(onOpened: opened.add, onChanged: () {});+ await pumpEventQueue();+ expect(opened, [+ {'kind': 'swarm', 'swarm': 's1', 'conversation': 'c1'},+ ]);+ },+ );++ test(+ 'one tapped while running is taken when the native side says it arrived',+ () async {+ final opened = <Map<String, String>>[];+ PushChannel().listen(onOpened: opened.add, onChanged: () {});+ await pumpEventQueue();+ expect(opened, isEmpty);++ waiting.add({+ 'kind': 'agent_done',+ 'machine': 'm1',+ 'agent': 'a1',+ 'aps': {'alert': 'x'},+ });+ await fromNative('arrived');+ await pumpEventQueue();+ expect(opened, [+ {'kind': 'agent_done', 'machine': 'm1', 'agent': 'a1'},+ ], reason: 'values that are not strings are dropped');+ },+ );++ test('a new address from the OS is told', () async {+ var changed = 0;+ PushChannel().listen(onOpened: (_) {}, onChanged: () => changed++);+ await fromNative('changed');+ expect(changed, 1);+ });++ test('after close, what is tapped waits for the next listener', () async {+ final opened = <Map<String, String>>[];+ final channel = PushChannel()+ ..listen(onOpened: opened.add, onChanged: () {});+ await pumpEventQueue();+ channel.close();+ waiting.add({'kind': 'swarm'});+ await fromNative('arrived');+ await pumpEventQueue();+ expect(opened, isEmpty);+ expect(waiting, isNotEmpty);+ });+ });+}diff --git a/mobile/test/notify/push_tokens_test.dart b/mobile/test/notify/push_tokens_test.dartnew file mode 100644index 000000000..e88ce2b31--- /dev/null+++ b/mobile/test/notify/push_tokens_test.dart@@ -0,0 +1,291 @@+import 'dart:async';+import 'dart:convert';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/api/api_client.dart' show ApiException;+import 'package:harness_mobile/logging/app_log.dart';+import 'package:harness_mobile/notify/push_channel.dart';+import 'package:harness_mobile/notify/push_tokens.dart';++import '../voice_fakes.dart' show MemoryKeyValueStore;++/// What the backend is told of this phone's push address, and when: once per address and account,+/// again each week, never for a phone whose person refused notices or signed out — and a phone that+/// signed out is reached by nothing, even when the backend could not be told.+void main() {+ const ios = (token: 'apns-1', platform: 'ios');++ late _Channel channel;+ late _Api api;+ late MemoryKeyValueStore storage;+ late DateTime now;+ bool? allowed;+ late PushTokens push;++ setUp(() {+ channel = _Channel()..next = ios;+ api = _Api();+ storage = MemoryKeyValueStore();+ now = DateTime(2026, 11, 5, 9);+ allowed = true;+ push = PushTokens(+ channel: channel,+ storage: storage,+ allowed: () async => allowed,+ now: () => now,+ );+ });++ Future<void> sync({String account = 'acct-1', bool current = true}) =>+ push.sync(account: account, api: api, current: () => current);++ test('tells the backend once, and not again within the week', () async {+ await sync();+ expect(api.registered, [ios]);++ now = now.add(const Duration(days: 6));+ await sync();+ expect(api.registered, hasLength(1));++ now = now.add(const Duration(days: 2));+ await sync();+ expect(+ api.registered,+ hasLength(2),+ reason: 'renewed, so the backend keeps it',+ );+ });++ test('tells again when the token or the account changes', () async {+ await sync();+ channel.next = (token: 'apns-2', platform: 'ios');+ await sync();+ await sync(account: 'acct-2');+ expect(api.registered, [+ ios,+ (token: 'apns-2', platform: 'ios'),+ (token: 'apns-2', platform: 'ios'),+ ]);+ });++ test(+ 'an Android token is registered and dropped with its platform',+ () async {+ channel.next = (token: 'fcm:1', platform: 'android');+ await sync();+ await sync();+ expect(api.registered, [(token: 'fcm:1', platform: 'android')]);+ await push.forget(api);+ expect(api.forgotten, [(token: 'fcm:1', platform: 'android')]);+ },+ );++ test('nothing while the OS cannot say whether notices are allowed', () async {+ allowed = null;+ await sync();+ expect(channel.asked, 0);+ expect(api.registered, isEmpty);+ expect(api.forgotten, isEmpty);+ });++ test('notices turned off: the backend lets go of the address it had for this account', () async {+ await sync();+ allowed = false;+ await sync();+ expect(api.forgotten, [ios]);+ expect(+ channel.asked,+ 1,+ reason: 'no address is asked for while notices are off',+ );++ // Back on: told again at once, not a week later.+ allowed = true;+ await sync();+ expect(api.registered, hasLength(2));+ });++ test('notices off on a phone never told: nothing to take back', () async {+ allowed = false;+ await sync();+ expect(api.forgotten, isEmpty);+ });++ test(+ 'no address (no push in this build, or the OS gave none): nothing is sent',+ () async {+ channel.next = null;+ await sync();+ expect(api.registered, isEmpty);+ expect(storage.values, isEmpty);+ },+ );++ test('a backend that did not take it is asked again after an hour, not at every resume', () async {+ api.refuseRegister = ApiException('Request failed (404)', status: 404);+ await sync();+ await sync();+ expect(api.attempts, 1);+ expect(storage.values, isEmpty, reason: 'not kept as told');++ api.refuseRegister = null;+ now = now.add(const Duration(minutes: 61));+ await sync();+ expect(api.registered, hasLength(1));+ });++ test('a failure that echoes the token logs no token', () async {+ final log = _Log();+ final before = appLog;+ appLog = log;+ addTearDown(() => appLog = before);++ api.refuseRegister = ApiException(+ 'Request failed (400): token apns-1 is not valid',+ status: 400,+ );+ await sync();+ api.refuseRegister = null;+ now = now.add(const Duration(hours: 2));+ await sync();+ api.refuseForget = ApiException(+ 'Request failed (503) for apns-1',+ status: 503,+ );+ await push.forget(api);++ expect(log.lines, isNotEmpty);+ expect(log.lines.where((line) => line.contains('apns-1')), isEmpty);+ });++ test('a sign-in that ended meanwhile registers nothing', () async {+ await sync(current: false);+ expect(api.registered, isEmpty);+ expect(storage.values, isEmpty);+ });++ test(+ 'a sign-out takes the address back and stops the OS delivering to it',+ () async {+ await sync();+ await push.forget(api);+ expect(api.forgotten, [ios]);+ expect(channel.forgot, 1);+ expect(storage.values, isEmpty);++ // The next sign-in tells the backend again, whatever the week said.+ await sync();+ expect(api.registered, hasLength(2));+ },+ );++ test(+ 'a sign-out the backend did not hear still stops the OS delivering',+ () async {+ await sync();+ api.refuseForget = ApiException('Request failed (503)', status: 503);+ await push.forget(api);+ expect(api.forgotten, isEmpty);+ expect(channel.forgot, 1);+ expect(+ storage.values,+ isEmpty,+ reason: 'the next account starts from nothing',+ );+ },+ );++ test(+ 'a sync asked for before a sign-out registers nothing after it',+ () async {+ final answer = Completer<bool?>();+ push = PushTokens(+ channel: channel,+ storage: storage,+ allowed: () => answer.future,+ now: () => now,+ );+ final syncing = sync();+ final forgetting = push.forget(api);+ answer.complete(true);+ await Future.wait([syncing, forgetting]);+ expect(api.registered, isEmpty);+ expect(channel.forgot, 1);+ },+ );++ test('a record on disk it cannot read counts as never told', () async {+ await storage.write('push_token_sent_v1', '{not json');+ await sync();+ expect(api.registered, hasLength(1));+ final kept = jsonDecode(storage.values['push_token_sent_v1']!) as Map;+ expect(kept['account'], 'acct-1');+ expect(kept['token'], 'apns-1');+ expect(kept['platform'], 'ios');+ });++ test(+ 'a record from before the platform was kept counts as never told',+ () async {+ await storage.write(+ 'push_token_sent_v1',+ jsonEncode({+ 'account': 'acct-1',+ 'token': 'apns-1',+ 'at': now.millisecondsSinceEpoch,+ }),+ );+ await sync();+ expect(api.registered, [ios]);+ },+ );+}++class _Channel extends PushChannel {+ PushAddress? next;+ int asked = 0;+ int forgot = 0;++ @override+ Future<PushAddress?> address() async {+ asked++;+ return next;+ }++ @override+ Future<void> forget() async => forgot++;+}++class _Api implements PushTokenApi {+ final registered = <PushAddress>[];+ final forgotten = <PushAddress>[];+ int attempts = 0;+ Object? refuseRegister;+ Object? refuseForget;++ @override+ Future<void> registerPushToken(PushAddress address) async {+ attempts++;+ if (refuseRegister case final error?) throw error;+ registered.add(address);+ }++ @override+ Future<void> forgetPushToken(PushAddress address) async {+ if (refuseForget case final error?) throw error;+ forgotten.add(address);+ }+}++class _Log implements AppLog {+ final lines = <String>[];++ @override+ void record(+ AppLogLevel level,+ String category,+ String message, {+ Object? error,+ StackTrace? stackTrace,+ }) => lines.add('$category $message ${error ?? ''}');+}diff --git a/mobile/test/notify/question_notice_test.dart b/mobile/test/notify/question_notice_test.dartindex 20782f101..9c3f307c4 100644--- a/mobile/test/notify/question_notice_test.dart+++ b/mobile/test/notify/question_notice_test.dart@@ -59,4 +59,60 @@ void main() {AgentNotice.alert,);});++ test('the request open on an agent, or none', () {+ final asked = AskedQuestions()..hear(a, 'q1');+ expect(asked.openOn(a), 'q1');+ expect(asked.openOn(b), isNull);+ asked.hear(a, 'q2');+ expect(asked.openOn(a), 'q2', reason: 'the next page is the one open');+ asked.forget(a);+ expect(asked.openOn(a), isNull);+ });++ group('never a second buzz for what the person was told', () {+ test('told already: posted quietly, or nothing on the agent being watched', () {+ expect(+ decideQuestionNotice(isNew: true, inFront: true, watching: false, told: true),+ AgentNotice.quiet,+ );+ expect(+ decideQuestionNotice(isNew: true, inFront: false, watching: true, told: true),+ AgentNotice.quiet,+ reason: 'watching only counts in front',+ );+ expect(+ decideQuestionNotice(isNew: true, inFront: true, watching: true, told: true),+ AgentNotice.none,+ );+ });++ test('cooling: what would buzz is posted quietly; a chime on the agent watched stays', () {+ expect(+ decideQuestionNotice(isNew: true, inFront: true, watching: false, cooling: true),+ AgentNotice.quiet,+ );+ expect(+ decideQuestionNotice(isNew: true, inFront: false, watching: false, cooling: true),+ AgentNotice.quiet,+ );+ expect(+ decideQuestionNotice(isNew: true, inFront: true, watching: true, cooling: true),+ AgentNotice.chime,+ );+ });++ test('a repeat is nothing, whatever was told', () {+ expect(+ decideQuestionNotice(isNew: false, inFront: false, watching: false, told: true, cooling: true),+ AgentNotice.none,+ );+ });++ test('quiet marks and posts, and never taps', () {+ expect(AgentNotice.quiet.marks, isTrue);+ expect(AgentNotice.quiet.alerts, isTrue);+ expect(AgentNotice.quiet.chimes, isFalse);+ });+ });}diff --git a/mobile/test/notify/question_spam_incident_test.dart b/mobile/test/notify/question_spam_incident_test.dartnew file mode 100644index 000000000..cf3dbfa35--- /dev/null+++ b/mobile/test/notify/question_spam_incident_test.dart@@ -0,0 +1,112 @@+import 'package:fake_async/fake_async.dart';+import 'package:flutter/foundation.dart';+import 'package:flutter_test/flutter_test.dart';++import 'package:harness_mobile/core/last_opened_agent.dart';+import 'package:harness_mobile/notify/agent_announcer.dart';+import 'package:harness_mobile/notify/system_notices.dart';++class _RecordingNotices implements SystemNotices {+ final shown = <AgentNoticeMessage>[];++ @override+ final opened = ValueNotifier<AgentRef?>(null);++ @override+ final openedDevice = ValueNotifier<String?>(null);++ @override+ Future<bool?> requestPermission() async => null;++ @override+ Future<void> show(AgentNoticeMessage message) async => shown.add(message);++ @override+ Future<void> cancel(AgentRef agent) async {}++ @override+ Future<void> showAccountNotice({+ required String key,+ required String title,+ required String body,+ }) async {}+}++/// The 11-05 incident (Tony, task #3198), through the announcer's calls only:+/// a phone in front buzzed "Agent needs you" over and over for a Team machine's+/// agent, whose approvals were each answered at its desk within seconds, and+/// whose dialog flickered off its pane and back with the same id.+void main() {+ const ref = (machineId: 'm', agentId: 'a');+ const agent = (+ ref: ref,+ name: 'TestPine',+ machine: 'Elvis-MacBook-Pro.local',+ );++ test('approvals answered at the desk within seconds never buzz a phone in front', () {+ fakeAsync((async) {+ final system = _RecordingNotices();+ var buzzes = 0;+ final announcer = AgentAnnouncer(+ system: system,+ chime: () async => buzzes++,+ inFront: () => true,+ );+ for (var i = 0; i < 10; i++) {+ announcer.questionAsked(+ agent,+ requestId: 'approval-$i',+ prompt:+ 'Approve Bash command: Rerun Desktop scenario and related tests',+ watching: () => false,+ );+ async.elapse(const Duration(seconds: 2));+ announcer.questionClosed(ref, requestId: 'approval-$i');+ async.elapse(const Duration(seconds: 1));+ }+ async.elapse(const Duration(minutes: 1));++ expect(buzzes, 0);+ announcer.dispose();+ });+ });++ test('one dialog flickering off the pane and back buzzes a phone in front once', () {+ fakeAsync((async) {+ final system = _RecordingNotices();+ var buzzes = 0;+ final announcer = AgentAnnouncer(+ system: system,+ chime: () async => buzzes++,+ inFront: () => true,+ );+ for (var flicker = 0; flicker < 6; flicker++) {+ announcer.questionAsked(+ agent,+ requestId: 'approval-1',+ prompt:+ 'Approve Bash command: Rerun Desktop scenario and related tests',+ watching: () => false,+ );+ async.elapse(const Duration(seconds: 3));+ // The daemon misses the dialog twice and closes it, then reads it+ // again and announces it with the same id.+ announcer.questionClosed(ref, requestId: 'approval-1');+ async.elapse(const Duration(seconds: 1));+ }+ announcer.questionAsked(+ agent,+ requestId: 'approval-1',+ prompt:+ 'Approve Bash command: Rerun Desktop scenario and related tests',+ watching: () => false,+ );+ async.elapse(const Duration(minutes: 1));++ // Still open: the person is told, once.+ expect(buzzes, 1);+ announcer.dispose();+ });+ });+}diff --git a/mobile/test/phone/phone_shell_agent_notice_chat_test.dart b/mobile/test/phone/phone_shell_agent_notice_chat_test.dartindex 998594b4c..46ecab0d0 100644--- a/mobile/test/phone/phone_shell_agent_notice_chat_test.dart+++ b/mobile/test/phone/phone_shell_agent_notice_chat_test.dart@@ -180,6 +180,7 @@ void main() {title: 'Nova',machine: 'Mac',body: 'News',+ quiet: false,));plugin.onResponse!(NotificationResponse(diff --git a/mobile/test/phone/phone_shell_swarm_home_test.dart b/mobile/test/phone/phone_shell_swarm_home_test.dartindex 2082a9b7a..3dfa13de1 100644--- a/mobile/test/phone/phone_shell_swarm_home_test.dart+++ b/mobile/test/phone/phone_shell_swarm_home_test.dart@@ -16,8 +16,10 @@ import 'package:harness_mobile/swarm/swarm_you_page.dart';import 'devices_fixture.dart';/// With Swarm on, the app opens on Swarm Home, full screen, with Settings in-/// You — opened from the avatar on Home since 2026-11-03, no longer a tab —-/// and no way to Harness there: Settings ▸ Swarm off is the way back to it. With it off, the app opens on the terminal, as it always has.+/// You — opened from the avatar on Home since 2026-11-03, no longer a tab. Harness is the root+/// while an agent is open, with a back chevron in its header to Swarm Home (and, on iOS, an edge+/// swipe), as Android's system back always went; Settings ▸ Swarm off turns Swarm Home off. With+/// Swarm off, the app opens on the terminal, as it always has.void main() {late DevicesApp app;diff --git a/mobile/test/phone/phone_shell_terminal_back_test.dart b/mobile/test/phone/phone_shell_terminal_back_test.dartnew file mode 100644index 000000000..504c9fa5f--- /dev/null+++ b/mobile/test/phone/phone_shell_terminal_back_test.dart@@ -0,0 +1,109 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/phone/phone_shell.dart';+import 'package:harness_mobile/phone/phone_shell_scope.dart';+import 'package:harness_mobile/phone/terminal_page.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/terminal/terminal_session.dart';++import 'devices_fixture.dart';++/// From Swarm to an agent's terminal and back, the way an iPhone does it: no system back event.+///+/// Opening an agent makes its terminal the root page, so there is no page under it and iOS has no+/// back button of its own. The header's chevron is the way back.+void main() {+ late DevicesApp app;++ setUp(() {+ app = DevicesApp()+ ..currentUser = const CurrentUserProfile(+ id: 'person-me',+ email: '[email protected]',+ );+ const machine = Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: 'Test host',+ );+ app.machines = [machine];+ app.machineStates['m'] = MachineState(machine)+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..agents = [+ const Agent(+ id: 'a',+ name: 'builder',+ engine: 'claude',+ project: AgentProject(name: 'grid', cwd: '/src/grid'),+ terminalAvailable: true,+ ),+ ];+ final session = TerminalSession(+ machineId: 'm',+ agentId: 'a',+ agentName: 'builder',+ engineId: 'claude',+ send: (type, payload) async => true,+ sendBinary: (_) async => true,+ )..status = TerminalSessionStatus.controlling;+ session.streamId = 's';+ app.adoptSessionForTest(session);+ experimentalFeaturesStore.value = {PhoneExperiment.swarm};+ });+ tearDown(() {+ experimentalFeaturesStore.value = const {};+ app.dispose();+ });++ Future<void> frames(WidgetTester tester) async {+ for (var i = 0; i < 8; i++) {+ await tester.pump(const Duration(milliseconds: 150));+ }+ }++ testWidgets('an agent opened from Swarm, then the header chevron: Swarm '+ 'Home again, with no system back', (tester) async {+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ await frames(tester);+ expect(find.byType(SwarmPage), findsOneWidget);++ PhoneShellScope.maybeOf(tester.element(find.byType(SwarmPage)))!+ .onOpenAgent('m', 'a');+ await frames(tester);+ expect(find.byType(TerminalPage), findsOneWidget);+ expect(find.byType(SwarmPage), findsNothing);++ await tester.tap(find.byKey(const ValueKey('tty-back')));+ await frames(tester);++ expect(find.byType(SwarmPage), findsOneWidget);+ expect(find.byType(TerminalPage), findsNothing);++ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 1));+ });++ testWidgets(+ 'with Swarm off, the terminal has no chevron: nothing is behind it',+ (tester) async {+ experimentalFeaturesStore.value = const {};+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ await frames(tester);+ tester+ .widget<PhoneShellScope>(find.byType(PhoneShellScope))+ .onOpenAgent('m', 'a');+ await frames(tester);++ expect(find.byType(TerminalPage), findsOneWidget);+ expect(find.byKey(const ValueKey('tty-back')), findsNothing);++ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 1));+ },+ );+}diff --git a/mobile/test/phone/terminal_swarm_back_test.dart b/mobile/test/phone/terminal_swarm_back_test.dartnew file mode 100644index 000000000..e20440b0f--- /dev/null+++ b/mobile/test/phone/terminal_swarm_back_test.dart@@ -0,0 +1,209 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/phone/phone_shell_scope.dart';+import 'package:harness_mobile/phone/terminal_page.dart';+import 'package:harness_mobile/phone/terminal_title.dart';+import 'package:harness_mobile/phone/voice_input_controller.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/swarm/swarm_home_root.dart';+import 'package:harness_mobile/terminal/terminal_session.dart';++import '../voice_fakes.dart';++/// A terminal opened from Swarm has a way back to Swarm on screen.+///+/// Opening an agent makes its terminal the ROOT page, so it has no page under it to pop to and+/// iOS has no system back: the only way out was a small dim mark in the title, which folds away+/// while the history is read. The header now carries a back chevron to Swarm, always drawn, and on+/// iOS the left edge goes back too. Android's system back is the shell's, as before.+void main() {+ late AppNotifier notifier;+ late TerminalSession session;+ late VoiceInputController voice;+ late ValueNotifier<String> language;+ late ExperimentalFeaturesStore features;+ late SwarmHomeChoice home;+ late int toSwarm;++ setUp(() {+ notifier = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ );+ session = TerminalSession(+ machineId: 'm',+ agentId: 'a',+ agentName: 'Agent',+ engineId: 'claude',+ send: (type, payload) async => true,+ sendBinary: (_) async => true,+ );+ session.status = TerminalSessionStatus.controlling;+ session.streamId = 's';+ for (var line = 0; line < 400; line++) {+ session.terminal.write('output line $line\r\n');+ }+ notifier.adoptSessionForTest(session);+ language = ValueNotifier('en');+ voice = VoiceInputController(+ transcriber: FakeTranscriber().call,+ recorder: FakeVoiceRecorder(),+ language: language,+ );+ features = ExperimentalFeaturesStore(storage: null)+ ..value = {PhoneExperiment.swarm};+ home = SwarmHomeChoice(features);+ toSwarm = 0;+ });++ tearDown(() {+ voice.dispose();+ language.dispose();+ home.dispose();+ features.dispose();+ notifier.dispose();+ });++ Widget terminal({bool inShell = true}) {+ final page = TerminalPage(+ notifier: notifier,+ machineId: 'm',+ agentId: 'a',+ voice: voice,+ );+ return MaterialApp(+ home: inShell+ ? PhoneShellScope(+ onMachineLinked: (_) {},+ onOpenAgent: (_, _) {},+ onShowSwarm: () => toSwarm++,+ home: home,+ child: page,+ )+ : page,+ );+ }++ Finder back() => find.byKey(const ValueKey('tty-back'));++ testWidgets('a terminal opened from Swarm has a back chevron, and tapping it '+ 'goes to Swarm with no system back event', (tester) async {+ home.showHarness();+ await tester.pumpWidget(terminal());+ await tester.pump(const Duration(milliseconds: 100));++ expect(back().hitTestable(), findsOneWidget);+ await tester.tap(back());+ await tester.pump();+ expect(toSwarm, 1);+ });++ testWidgets('the chevron stays on screen while the history is read back and '+ 'the title has folded away', (tester) async {+ home.showHarness();+ await tester.pumpWidget(terminal());+ await tester.pump(const Duration(milliseconds: 100));++ await tester.drag(find.byType(TerminalPage), const Offset(0, 160));+ await tester.pump(const Duration(milliseconds: 50));+ await tester.drag(find.byType(TerminalPage), const Offset(0, -80));+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 500));++ expect(find.byType(TerminalTitle).hitTestable(), findsNothing);+ expect(back().hitTestable(), findsOneWidget);+ });++ testWidgets('no chevron without Swarm behind the terminal: Swarm off, or '+ 'Swarm Home is what shows', (tester) async {+ await tester.pumpWidget(terminal());+ await tester.pump(const Duration(milliseconds: 100));+ expect(back(), findsNothing, reason: 'Swarm Home is the root');++ features.value = const {};+ home.showHarness();+ await tester.pump();+ expect(+ back(),+ findsNothing,+ reason: 'Swarm off: the terminal is all there is',+ );++ await tester.pumpWidget(terminal(inShell: false));+ await tester.pump(const Duration(milliseconds: 100));+ expect(back(), findsNothing, reason: 'outside the shell, nowhere to go');+ });++ testWidgets('the chevron follows Swarm Home coming and going behind the '+ 'terminal', (tester) async {+ await tester.pumpWidget(terminal());+ await tester.pump(const Duration(milliseconds: 100));+ expect(back(), findsNothing);++ home.showHarness();+ await tester.pump();+ expect(back(), findsOneWidget);++ home.showSwarm();+ await tester.pump();+ expect(back(), findsNothing);+ });++ testWidgets("the agent's name starts to the right of the chevron's box, so "+ 'its first letter is not under it', (tester) async {+ home.showHarness();+ await tester.pumpWidget(terminal());+ await tester.pump(const Duration(milliseconds: 100));++ final chevron = tester.getRect(back());+ final name = tester.getRect(+ find+ .descendant(+ of: find.byType(TerminalTitle),+ matching: find.byType(Text),+ )+ .first,+ );+ expect(name.left, greaterThanOrEqualTo(chevron.right));+ });++ testWidgets('on iOS, a swipe from the left edge goes back to Swarm', (+ tester,+ ) async {+ home.showHarness();+ await tester.pumpWidget(terminal());+ await tester.pump(const Duration(milliseconds: 100));++ await tester.dragFrom(const Offset(2, 300), const Offset(220, 0));+ await tester.pump();+ expect(toSwarm, 1);+ }, variant: TargetPlatformVariant.only(TargetPlatform.iOS));++ testWidgets('on iOS, a swipe that does not start at the edge is not back', (+ tester,+ ) async {+ home.showHarness();+ await tester.pumpWidget(terminal());+ await tester.pump(const Duration(milliseconds: 100));++ await tester.dragFrom(const Offset(120, 300), const Offset(220, 0));+ await tester.pump(const Duration(milliseconds: 300));+ expect(toSwarm, 0);+ }, variant: TargetPlatformVariant.only(TargetPlatform.iOS));++ testWidgets("Android has no edge swipe: its system back is the shell's", (+ tester,+ ) async {+ home.showHarness();+ await tester.pumpWidget(terminal());+ await tester.pump(const Duration(milliseconds: 100));++ await tester.dragFrom(const Offset(2, 300), const Offset(220, 0));+ await tester.pump(const Duration(milliseconds: 300));+ expect(toSwarm, 0);+ }, variant: TargetPlatformVariant.only(TargetPlatform.android));+}diff --git a/mobile/test/viewer_app_fixture.dart b/mobile/test/viewer_app_fixture.dartindex 251b70dfe..41453e251 100644--- a/mobile/test/viewer_app_fixture.dart+++ b/mobile/test/viewer_app_fixture.dart@@ -15,6 +15,8 @@ import 'package:harness_mobile/core/machine_cache.dart';import 'package:harness_mobile/core/models.dart';import 'package:harness_mobile/core/snapshot_store.dart';import 'package:harness_mobile/measurement/product_measurement.dart';+import 'package:harness_mobile/notify/push_channel.dart';+import 'package:harness_mobile/notify/push_tokens.dart';import 'package:harness_mobile/notify/system_notices.dart';import 'package:harness_mobile/state/app_state.dart';import 'package:harness_mobile/state/desk_sync.dart';@@ -151,6 +153,18 @@ class FakeApi extends ApiClient {return onMachines();}+ /// The push addresses told to the backend, and those taken back. Never the network.+ final List<PushAddress> pushRegistered = [];+ final List<PushAddress> pushForgotten = [];++ @override+ Future<void> registerPushToken(PushAddress address) async =>+ pushRegistered.add(address);++ @override+ Future<void> forgetPushToken(PushAddress address) async =>+ pushForgotten.add(address);+// No acknowledgements ("It's mine" said on another device) unless a test serves some: never the network.@overrideFuture<List<Object?>?> deviceAcks(int since) async => null;@@ -516,6 +530,7 @@ ViewerRig viewerApp({LocalKeyValueStore? storage,Duration turnActivityTimeout = const Duration(seconds: 12),ProductMeasurement? productMeasurement,+ PushTokens? pushTokens,}) {final session = AuthSession(storage: MemoryKeyValueStore());final viewer = FakeViewer(session);@@ -531,6 +546,7 @@ ViewerRig viewerApp({viewer: viewer,paneLayoutStore: storage == null ? null : PaneLayoutStore(storage: storage),systemNotices: SilentSystemNotices(),+ pushTokens: pushTokens,machineCache:machineCache ??(storage == null ? null : MachineCache(store: MemorySnapshotStore())),