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 i1915: #3090 #3166 #3154 (#3177)
0xken1532563e5e9d7f
diff --git a/backend/integration/superTabActivity.test.ts b/backend/integration/superTabActivity.test.tsindex 88a423ec1..72e682d44 100644--- a/backend/integration/superTabActivity.test.ts+++ b/backend/integration/superTabActivity.test.ts@@ -17,13 +17,19 @@ import { HostReads } from '../src/superTabs/read/host.js'import { buddyChatId, openSwarmBuddyChat } from '../src/superTabs/buddies.js'import { ACTIVITY_EXPIRY_MS, ACTIVITY_READS, activityDigest, resetActivityReads, sweepActivity, writeReplyActivity } from '../src/superTabs/activity.js'import { listNamedIndexes } from '../src/superTabs/parts/indexed.js'-import { profiled } from './plans.test-support.js'+import { plan, profiled, reads } from './plans.test-support.js'import { SESSION_ENDED_KIND } from '../src/superTabs/buddySessions.js'import { threadFacet } from '../src/superTabs/pageReads.js'import { CHAT_SETTING_DEFAULT_KEEP_MS, sweepChatSettings } from '../src/superTabs/chatSettings.js'import type { Command, SuperTabState } from '../src/superTabs/model.js'import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'-import type { PhoneNotice } from '../src/push/sender.js'+import { swarmNoticeId, type PhoneNotice } from '../src/push/sender.js'+import { generateKeyPairSync } from 'node:crypto'+import { sendPhoneNotices } from '../src/push/send.js'+import { apnsSender, type ApnsRequest } from '../src/push/apns.js'+import { fcmSender } from '../src/push/fcm.js'+import { registerPushDevice } from '../src/push/devices.js'+import { quietRepeats } from '../src/push/repeats.js'import { NOW, outsider as outsiderActor, owner as ownerActor, peer as peerActor, swarm } from '../src/superTabs/read/fixture.test-support.js'// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.@@ -217,6 +223,259 @@ describe('Phone push: a write tells the phones of whoever its rows tell (task #2})})+describe('Phone push end to end on the server: a write, its phones, and what Apple and Google are sent (task #3248)', () => {+ const apnsKeys = { teamId: 'TEAM123456', topic: 'ai.autonomous.harness.ios', sandbox: null,+ production: { keyId: 'ABC123DEFG', privateKey: generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).privateKey } }+ const fcmAccount = { projectId: 'harness-push', clientEmail: '[email protected]', tokenUri: 'https://oauth2.googleapis.com/token',+ privateKey: generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey }++ it('a reply\'s write reaches each phone of the person it tells, in the request Apple and Google take, and never the author\'s phone', async () => {+ const apple: ApnsRequest[] = []+ const google: Array<{ url: string; body: string }> = []+ const fetcher = (async (url: string, init: RequestInit) => {+ google.push({ url, body: String(init.body) })+ return url === fcmAccount.tokenUri ? new Response(JSON.stringify({ access_token: 'access', expires_in: 3600 }), { status: 200 })+ : new Response(JSON.stringify({ name: 'projects/harness-push/messages/1' }), { status: 200 })+ }) as unknown as typeof fetch+ const senders = { ios: apnsSender(apnsKeys, { transport: async request => { apple.push(request); return { status: 200, reason: null } } }),+ android: fcmSender(fcmAccount, { fetcher }) }+ const sending: Array<Promise<void>> = []+ const pushing = new SuperTabStore(db, Date.now, null, { phoneNotices: notices => { sending.push(sendPhoneNotices(db, senders, notices)) } })+ const s = await scene()+ const iphone = `${'a1'.repeat(32)}`, android = 'fcm:owner-android', authors = `${'b2'.repeat(32)}`+ await registerPushDevice(db, owner.sub, { platform: 'ios', token: iphone }, Date.now())+ await registerPushDevice(db, owner.sub, { platform: 'android', token: android }, Date.now())+ await registerPushDevice(db, peer.sub, { platform: 'ios', token: authors }, Date.now())+ const root = await send(s.tabId, s.web, 'Owner root')+ const reply = (await pushing.execute(peer, s.tabId, { operationId: randomUUID(),+ command: { type: 'message.send', conversationId: s.web, text: 'Peer answers: the secret plan', replyTo: root, recipientIds: [] } }) as { result: Record<string, unknown> }).result.messageId as string+ await Promise.all(sending)+ const row = await db.superTabActivity.findFirstOrThrow({ where: { tabId: s.tabId, personId: owner.sub, messageId: reply } })+ const key = `reply:${s.tabId}:${row.id}`, link = `swarm:${s.tabId}/${s.web}/message/${reply}/thread/${root}`, slot = `thread:${s.tabId}:${s.web}:${root}`+ // Apple: one request, to the owner's iPhone alone.+ expect(apple.map(r => r.path)).toEqual([`/3/device/${iphone}`])+ expect(apple[0]!.headers).toMatchObject({ 'apns-topic': 'ai.autonomous.harness.ios', 'apns-push-type': 'alert', 'apns-priority': '10',+ 'apns-collapse-id': String(swarmNoticeId(slot)) })+ const body = JSON.parse(apple[0]!.body)+ expect(body).toEqual({ aps: { alert: { title: expect.stringMatching(/ replied in a thread$/), subtitle: expect.any(String), body: 'Open Harness to read it.' },+ sound: 'default', 'thread-id': 'swarm-needs-you', category: 'swarm-needs-you' }, key, link, slot })+ // Google: one message, to the owner's Android phone, tagged with the thread's slot, its key in its data so the app knows it.+ const messages = google.filter(c => c.url !== fcmAccount.tokenUri).map(c => JSON.parse(c.body).message)+ expect(messages).toEqual([{ token: android, notification: { title: body.aps.alert.title, body: `${body.aps.alert.subtitle} · Open Harness to read it.` },+ android: { priority: 'high', notification: { channel_id: 'swarm-needs-you', tag: slot, visibility: 'PRIVATE' } }, data: { key, link, slot } }])+ // Nothing written in the chat leaves the server.+ expect(JSON.stringify([apple, google])).not.toContain('secret plan')+ expect(JSON.stringify(apple)).not.toContain(authors)+ })+})++describe('Phone push: a thread sounds once until it is read (task #3248)', () => {+ const readThrough = async (tabId: string, conversationId: string, root: string, messageId: string, as: AuthUser) => {+ const { sequence } = await db.superTabMessage.findUniqueOrThrow({ where: { id: messageId } })+ expect((await call('POST', `/api/super-tabs/${tabId}/conversations/${conversationId}/threads/${root}/read`, as, { sequence })).status).toBe(200)+ }+ /** The notices a write made, as they go out: each person's, and whether it is quiet. */+ const sent = async (write: () => Promise<unknown>) => {+ phones.length = 0+ await write()+ return (await quietRepeats(db, [...phones])).map(n => ({ to: n.personId, kind: n.key.split(':')[0], quiet: n.quiet === true }))+ }++ it('sends a thread\'s next reply quietly while one before it is unread, and with sound again once the thread is read', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Owner root')+ let second = ''+ expect(await sent(() => send(s.tabId, s.web, 'Peer answers', peer, root))).toEqual([{ to: owner.sub, kind: 'reply', quiet: false }])+ expect(await sent(async () => { second = await send(s.tabId, s.web, 'Peer again', peer, root) })).toEqual([{ to: owner.sub, kind: 'reply', quiet: true }])+ await readThrough(s.tabId, s.web, root, second, owner)+ expect(await sent(() => send(s.tabId, s.web, 'Peer a third time', peer, root))).toEqual([{ to: owner.sub, kind: 'reply', quiet: false }])+ })++ it('keeps each person and each thread apart, and never quiets a tag', async () => {+ const s = await scene()+ const first = await send(s.tabId, s.web, 'Owner root')+ const other = await send(s.tabId, s.web, 'Owner second root')+ await send(s.tabId, s.web, 'Peer answers', peer, first)+ // Another thread of the owner's has no unread reply yet: it sounds.+ expect(await sent(() => send(s.tabId, s.web, 'Peer answers there', peer, other))).toEqual([{ to: owner.sub, kind: 'reply', quiet: false }])+ // Outsider is tagged in the first thread (peer, who only replied there, hears nothing); outsider then hears of its next+ // reply with sound: the unread replies are the owner's.+ expect(await sent(() => run(s.tabId, { type: 'message.send', conversationId: s.web, text: 'Outsider, look', replyTo: first, recipientIds: [], mentions: [outsider.sub] })))+ .toEqual([{ to: outsider.sub, kind: 'mention', quiet: false }])+ expect((await sent(() => send(s.tabId, s.web, 'Peer once more', peer, first))).sort((a, b) => a.to.localeCompare(b.to)))+ .toEqual([{ to: owner.sub, kind: 'reply', quiet: true }, { to: outsider.sub, kind: 'reply', quiet: false }].sort((a, b) => a.to.localeCompare(b.to)))+ })++ it('reads a thread\'s unread replies once, through the Activity thread index', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Owner root')+ for (let i = 0; i < 3; i++) await send(s.tabId, s.web, `Peer answers ${i}`, peer, root)+ // Another thread's rows, which the read must not examine.+ const other = await send(s.tabId, s.web, 'Owner other root')+ for (let i = 0; i < 3; i++) await send(s.tabId, s.web, `Peer elsewhere ${i}`, peer, other)+ phones.length = 0+ await send(s.tabId, s.web, 'Peer last', peer, root)+ const notices = [...phones]+ const rows = reads(await profiled(db, () => quietRepeats(db, notices)), 'SuperTabActivity', ['threadId'])+ expect(rows).toHaveLength(1)+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ tabId: 1, personId: 1, conversationId: 1, threadId: 1 \}/)+ expect(rows[0]!.docsExamined).toBeLessThanOrEqual(4)+ })++ it('reads nothing when no reply is pushed', async () => {+ const tag: PhoneNotice = { personId: owner.sub, key: 'mention:t', title: 't', subtitle: '', body: '', link: 'swarm:t/c/message/m', slot: 'mention:t' }+ const rows = await profiled(db, async () => { expect(await quietRepeats(db, [tag])).toEqual([tag]) })+ expect(rows.filter(e => e.ns.endsWith('.SuperTabActivity'))).toEqual([])+ })+})++describe('Phone push: who each push type reaches, and what it carries (task #3248)', () => {+ const tagging = async (tabId: string, conversationId: string, text: string, as: AuthUser, replyTo: string | null, mentions: string[],+ extra: Record<string, unknown> = {}, asAgentId?: string) =>+ (await run(tabId, { type: 'message.send', conversationId, text, replyTo, recipientIds: [], mentions, ...extra } as Command, as, asAgentId)).result.messageId as string+ /** Every notice the write made, whole. */+ const pushed = async (write: () => Promise<unknown>) => {+ phones.length = 0+ await write()+ return [...phones]+ }+ /** Whom the write told, by kind: `reply` or `mention`, per person. */+ const whom = async (write: () => Promise<unknown>) => (await pushed(write)).map(n => `${n.key.split(':')[0]}:${n.personId}`).sort()+ const swarmName = async (tabId: string) => ((await store.read(owner, tabId)).state as unknown as SuperTabState).name+ const tellsIn = (list: string[], kind: 'reply' | 'mention', as: AuthUser) => list.includes(`${kind}:${as.sub}`)++ it('a reply push carries its row\'s key, who replied, the project, no words of the reply, and the link to the reply in its thread', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Owner root')+ let reply = ''+ const [notice, ...more] = await pushed(async () => { reply = await send(s.tabId, s.web, 'Peer answers: the secret plan', peer, root) })+ expect(more).toEqual([])+ const row = await db.superTabActivity.findFirstOrThrow({ where: { tabId: s.tabId, personId: owner.sub, messageId: reply } })+ expect(notice).toEqual({ personId: owner.sub, key: `reply:${s.tabId}:${row.id}`, title: expect.stringMatching(/^.+ replied in a thread$/),+ subtitle: await swarmName(s.tabId), body: 'Open Harness to read it.', link: `swarm:${s.tabId}/${s.web}/message/${reply}/thread/${root}`,+ slot: `thread:${s.tabId}:${s.web}:${root}`, thread: { tabId: s.tabId, conversationId: s.web, threadId: root, rowId: row.id, at: row.createdAt.getTime() } })+ expect(notice!.title).not.toMatch(/^Someone /)+ expect(JSON.stringify(notice)).not.toContain('secret plan')+ // A project's own chat names that project.+ const openRoot = await send(s.tabId, s.openChat, 'Owner root in Open')+ const [inOpen] = await pushed(() => send(s.tabId, s.openChat, 'Peer answers', peer, openRoot))+ expect(inOpen!.subtitle).toBe('Open')+ })++ it('a reply reaches the thread\'s starter, the quoted message\'s author and people tagged earlier in it, never its author nor one who only replied (Tony\'s rule)', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Owner root')+ // The starter alone hears of the first reply; its author never.+ const peerReply = await send(s.tabId, s.web, 'Peer answers', peer, root)+ // The owner tags outsider in the thread: outsider hears of that by the tag alone; peer, who only replied, hears nothing.+ expect(await whom(() => tagging(s.tabId, s.web, 'Outsider, look', owner, root, [outsider.sub]))).toEqual([`mention:${outsider.sub}`])+ // Outsider answers peer's reply: the starter, and peer as the quoted author, hear of it; outsider never.+ expect(await whom(() => send(s.tabId, s.web, 'Outsider answers peer', outsider, peerReply))).toEqual([`reply:${owner.sub}`, `reply:${peer.sub}`].sort())+ // The owner answers in their own thread: outsider, tagged in it, hears; peer, who only replied there, reads it in Activity.+ const ownAnswer = await whom(() => send(s.tabId, s.web, 'Owner again', owner, root))+ expect(ownAnswer).toEqual([`reply:${outsider.sub}`])+ expect((await items(s.tabId, peer)).some(i => i.text === 'Owner again')).toBe(true)+ })++ it('an agent\'s reply in a person\'s thread is worded with the agent\'s name', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Owner root')+ const [notice, ...more] = await pushed(() => send(s.tabId, s.web, 'Worker answers', owner, root, s.worker))+ expect(more).toEqual([])+ expect(notice).toMatchObject({ personId: owner.sub, title: 'worker-harness replied in a thread' })+ })++ it('a reply that tags a person tells them by the tag alone, once', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Owner root')+ await send(s.tabId, s.web, 'Peer answers', peer, root)+ expect(await whom(() => tagging(s.tabId, s.web, 'Owner, here', peer, root, [owner.sub]))).toEqual([`mention:${owner.sub}`])+ })++ it('a reply never reaches a person who muted the chat, unfollowed the thread, or can no longer read the chat', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.openChat, 'Owner root')+ // Both are tagged in the thread, so each would hear of its replies.+ await tagging(s.tabId, s.openChat, 'Peer and outsider, look', owner, root, [peer.sub, outsider.sub])+ expect(await whom(() => send(s.tabId, s.openChat, 'Owner adds', owner, root))).toEqual([`reply:${outsider.sub}`, `reply:${peer.sub}`].sort())+ expect((await notify(s.tabId, s.openChat, 'muted', peer)).status).toBe(200)+ expect((await call('POST', `/api/super-tabs/${s.tabId}/conversations/${s.openChat}/threads/${root}/follow`, outsider, { follow: false })).status).toBe(200)+ expect(await whom(() => send(s.tabId, s.openChat, 'Owner again', owner, root))).toEqual([])+ // Outsider follows again; then the owner makes the project private to themselves, and outsider can no longer read it.+ expect((await call('POST', `/api/super-tabs/${s.tabId}/conversations/${s.openChat}/threads/${root}/follow`, outsider, { follow: true })).status).toBe(200)+ expect(await whom(() => send(s.tabId, s.openChat, 'Owner once more', owner, root))).toEqual([`reply:${outsider.sub}`])+ await run(s.tabId, { type: 'project.sharing', projectId: s.open, visibility: 'private', memberIds: [] })+ expect(await whom(() => send(s.tabId, s.openChat, 'Owner after closing', owner, root))).toEqual([])+ })++ it('pushes nothing for a message outside threads that tags nobody, or for a reaction', async () => {+ const s = await scene()+ let top = ''+ expect(await whom(async () => { top = await send(s.tabId, s.web, 'Top level by peer', peer) })).toEqual([])+ expect(await whom(() => react(s.tabId, s.web, top, true, owner))).toEqual([])+ })++ it('a tag links the message in the chat, in its thread only when it is only there', async () => {+ const s = await scene()+ let top = ''+ const [inChat] = await pushed(async () => { top = await tagging(s.tabId, s.web, 'Peer, look', owner, null, [peer.sub]) })+ const row = await db.superTabMention.findFirstOrThrow({ where: { tabId: s.tabId, personId: peer.sub, messageId: top } })+ expect(inChat).toEqual({ personId: peer.sub, key: `mention:${row.id}`, title: expect.stringMatching(/^.+ tagged you$/), subtitle: await swarmName(s.tabId),+ body: 'Open Harness to read it.', link: `swarm:${s.tabId}/${s.web}/message/${top}`, slot: `mention:${row.id}` })+ let threadOnly = ''+ const [inThread] = await pushed(async () => { threadOnly = await tagging(s.tabId, s.web, 'Peer, in here', owner, top, [peer.sub]) })+ expect(inThread!.link).toBe(`swarm:${s.tabId}/${s.web}/message/${threadOnly}/thread/${top}`)+ let alsoInChat = ''+ const [both] = await pushed(async () => { alsoInChat = await tagging(s.tabId, s.web, 'Peer, everyone sees this', owner, top, [peer.sub], { alsoSend: true }) })+ expect(both!.link).toBe(`swarm:${s.tabId}/${s.web}/message/${alsoInChat}`)+ })++ it('an agent\'s tag is worded with the agent\'s name; one\'s own tag tells nobody; a tag held for a quiet chat is not pushed', async () => {+ const s = await scene()+ expect(await pushed(() => tagging(s.tabId, s.web, 'Peer, the build is red', owner, null, [peer.sub], {}, s.worker)))+ .toEqual([expect.objectContaining({ personId: peer.sub, title: 'worker-harness tagged you' })])+ expect(await whom(() => tagging(s.tabId, s.web, 'Note to self', owner, null, [owner.sub]))).toEqual([])+ expect(await whom(() => tagging(s.tabId, s.web, 'Peer, if nobody takes this', owner, null, [peer.sub], { mentionsIfNoWorker: true }))).toEqual([])+ })++ it('a decision asked of a person reaches their phone once, worded as the app does, linking its card; asking it again does not', async () => {+ const s = await scene()+ const ask = (question: string) => run(s.tabId, { type: 'decision.ask', conversationId: s.web, personId: peer.sub,+ questions: [{ question, options: ['Yes', 'No'], recommended: 0, unblocks: 'The release' }] } as Command, owner, s.worker)+ let ids: string[] = []+ const notices = await pushed(async () => { ids = (await ask('Ship it today?')).result.decisionIds as string[] })+ expect(notices).toEqual([{ personId: peer.sub, key: `decision:${ids[0]}`, slot: `decision:${ids[0]}`, title: 'worker-harness asks you',+ subtitle: await swarmName(s.tabId), body: 'Open Harness to answer.', link: `swarm:${s.tabId}/${s.web}/decision/${ids[0]}` }])+ // The same open question asked again is the same decision: no second push.+ expect(await pushed(() => ask('Ship it today?'))).toEqual([])+ })++ it('a decision a task\'s needs_human asks of a person reaches their phone too', async () => {+ const s = await scene()+ const state = (await store.read(owner, s.tabId)).state as unknown as SuperTabState+ const assignmentId = state.conversations.find(c => c.id === s.web)!.assignment!.id+ const notices = await pushed(() => run(s.tabId, { type: 'work.status', conversationId: s.web, assignmentId, status: 'needs_human',+ result: 'Ship it behind a flag?', ask: { personId: peer.sub, options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'The release' } } as Command,+ owner, s.worker))+ expect(notices.map(n => [n.personId, n.key.split(':')[0], n.title, n.link.includes('/decision/'), n.quiet === true]))+ .toEqual([[peer.sub, 'decision', 'worker-harness asks you', true, false]])+ })++ it('one ask of several questions sounds once', async () => {+ const s = await scene()+ const notices = await pushed(() => run(s.tabId, { type: 'decision.ask', conversationId: s.web, personId: peer.sub, questions: [+ { question: 'Which day?', options: ['Mon', 'Tue'], recommended: 0, unblocks: 'The plan' },+ { question: 'Which machine?', options: ['Mac', 'Linux'], recommended: 0, unblocks: 'The plan' }] } as Command, owner, s.worker))+ expect(notices.map(n => [n.personId, n.title, n.quiet === true])).toEqual([[peer.sub, 'worker-harness asks you', false], [peer.sub, 'worker-harness asks you', true]])+ })++ it('tags nobody who cannot read the chat, so no push reaches them', async () => {+ const s = await scene()+ await expect(tagging(s.tabId, s.secretGroup, 'Peer, see this', owner, null, [peer.sub])).rejects.toMatchObject({ code: 'INVALID_MENTION' })+ expect(phones.filter(n => n.personId === peer.sub && n.link.includes(s.secretGroup))).toEqual([])+ })+})+describe('Activity: a reply tells everyone in its thread (task #2745)', () => {const tagging = async (tabId: string, conversationId: string, text: string, as: AuthUser, replyTo: string | null, mentions: string[]) =>(await run(tabId, { type: 'message.send', conversationId, text, replyTo, recipientIds: [], mentions }, as)).result.messageId as stringdiff --git a/backend/integration/superTabCache.test.ts b/backend/integration/superTabCache.test.tsindex 9caac1214..9deff8f42 100644--- a/backend/integration/superTabCache.test.ts+++ b/backend/integration/superTabCache.test.ts@@ -150,6 +150,39 @@ const groupKeys = (read: { groups: Array<{ key: string }> }) => read.groups.map(const partReads = <T>(run: () => Promise<T>) => profiledReads(db, /\.Swarm(Head|Member|Agent|Group|Machine|Start|Progress)$/, run)describe('reads through the cache', () => {+ it('reuses row metadata per pod and observes deletion when the short hold expires', async () => {+ const { tabId } = await privateScene()+ let now = Date.now()+ const { store } = pod()+ const reads = new SwarmReads(store, { now: () => now })+ await expect(reads.firstLoad({ ...people.owner, autonomousEnv: 'other' }, tabId)).rejects.toMatchObject({ code: 'NOT_FOUND' })+ const first = await profiledReads(db, /\.SuperTab$/, () => reads.firstLoad(people.owner, tabId))+ const second = await profiledReads(db, /\.SuperTab$/, () => reads.firstLoad(people.owner, tabId))+ expect(first.reads).toBe(1)+ expect(second.reads).toBe(0)++ await db.superTab.update({ where: { id: tabId }, data: { deletedAt: new Date(now) } })+ now += 2_999+ await expect(reads.firstLoad(people.owner, tabId)).resolves.toBeDefined()+ now += 1+ await expect(reads.firstLoad(people.owner, tabId)).rejects.toMatchObject({ code: 'NOT_FOUND' })+ })++ it('checks a changed format at hold expiry and refuses an invalid legacy row', async () => {+ const { tabId } = await privateScene()+ let now = Date.now()+ const { store } = pod()+ const reads = new SwarmReads(store, { now: () => now })+ await reads.firstLoad(people.owner, tabId)++ // Simulate an incompatible format transition: the fenced v2 state cannot be migrated as a legacy v1 state.+ await db.superTab.update({ where: { id: tabId }, data: { format: 1 } })+ now += 2_999+ await expect(reads.firstLoad(people.owner, tabId)).resolves.toBeDefined()+ now += 1+ await expect(reads.firstLoad(people.owner, tabId)).rejects.toMatchObject({ code: 'SWARM_MIGRATING' })+ })+it('reads a Swarm whose stamp did not move without asking Mongo for its parts', async () => {const { tabId } = await privateScene()const { reads } = pod()diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.tsindex 665e6ab43..7d59ab8e8 100644--- a/backend/integration/superTabRead.test.ts+++ b/backend/integration/superTabRead.test.ts@@ -18,7 +18,7 @@ import { guardedWrite } from '../src/superTabs/parts/write.js'import { migrateSwarm } from '../src/superTabs/migration/migrate.js'import { SwarmReads } from '../src/superTabs/read/service.js'import { decisionsWaiting, MAX_OPEN_DECISIONS, REFLECTION_DECISION } from '../src/superTabs/decisions.js'-import { waitingTagConversations } from '../src/superTabs/mentions.js'+import { waitingMentions, waitingTagConversations } from '../src/superTabs/mentions.js'import { writeReadMark } from '../src/superTabs/readMarks.js'import { buddyChatId } from '../src/superTabs/buddies.js'import { HostReads } from '../src/superTabs/read/host.js'@@ -27,6 +27,7 @@ import { sendsEmptyIn, watched, type Query } from '../src/lib/queryRecorder.testimport { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'import { NOW, outsider as outsiderActor, owner as ownerActor, peer as peerActor, swarm } from '../src/superTabs/read/fixture.test-support.js'import { PROFILE_STAGES, profileEntry, type ProfileEntry } from './bench/profile.js'+import { profiledReads } from './profiledReads.test-support.js'// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.let replica: MongoMemoryReplSet@@ -122,6 +123,61 @@ async function writeGroup(tabId: string, key: string, at: number, change: (group}describe('first load (design 4.3)', () => {+ it('counts waiting tags from quiet groups without fetching unrelated group payloads', async () => {+ const quiet: string[] = []+ const s = await scene(state => {+ for (let i = 0; i < 21; i++) {+ const id = state.group(`Quiet ${i}`)+ state.edit(current => {+ const group = current.conversations.find(each => each.id === id)!+ group.dormant = true+ group.brief = 'unused task detail '.repeat(220)+ })+ quiet.push(id)+ }+ return quiet+ })+ await db.superTabMention.createMany({ data: quiet.map((conversationId, i) => ({+ id: `${s.tabId}-quiet-tag-${i}`, tabId: s.tabId, personId: peer.sub, projectId: 'lead', conversationId,+ messageId: `${s.tabId}-quiet-message-${i}`, authorAgentId: s.lead, createdAt: new Date(NOW - 1_000), resolvedAt: null, resolvedBy: null,+ })) })++ const { state } = await new SuperTabStore(db, () => NOW).read(peer, s.tabId)+ const stateWithoutQuietGroups = { ...state, conversations: state.conversations.filter(group => !quiet.includes(group.id)) }+ const match = { tabId: s.tabId, deleted: false, key: { $in: quiet } }+ const fullPipeline = [{ $match: match }, { $project: { _id: 0, key: 1, data: 1 } }]+ await db.$runCommandRaw({ profile: 2 })+ try {+ await db.swarmGroup.aggregateRaw({ pipeline: fullPipeline, options: { batchSize: 200, hint: { tabId: 1, key: 1 } } })+ const count = await waitingMentions(db as never, s.tabId, stateWithoutQuietGroups, { kind: 'person', userId: peer.sub, email: peer.email }, NOW)+ expect(count.count).toBe(quiet.length)+ } finally { await db.$runCommandRaw({ profile: 0 }) }++ const profile = await db.$runCommandRaw({ find: 'system.profile', filter: { ns: { $regex: '\\.SwarmGroup$' } },+ projection: { _id: 0, command: 1, responseLength: 1, nreturned: 1, docsExamined: 1, planSummary: 1 }, batchSize: 10_000 }) as unknown as+ { cursor: { firstBatch: Array<{ command?: { pipeline?: Array<Record<string, any>>; hint?: Record<string, number> }; responseLength?: number;+ nreturned?: number; docsExamined?: number; planSummary?: string }> } }+ const rows = profile.cursor.firstBatch.filter(row => row.command?.pipeline?.some(stage =>+ (stage.$match as { key?: { $in?: string[] } } | undefined)?.key?.$in?.includes(quiet[0]!)))+ expect(rows).toHaveLength(2)+ const baseline = rows.find(row => row.command!.pipeline!.some(stage => (stage.$project as { data?: unknown } | undefined)?.data === 1))!+ const projected = rows.find(row => row.command!.pipeline!.some(stage => (stage.$project as { data?: { kind?: number } } | undefined)?.data?.kind === 1))!+ expect(baseline.nreturned).toBe(quiet.length)+ expect(projected.nreturned).toBe(quiet.length)+ expect(baseline.planSummary).toMatch(/IXSCAN/)+ expect(projected.planSummary).toMatch(/IXSCAN/)+ expect(baseline.docsExamined).toBeLessThanOrEqual(baseline.nreturned!)+ expect(projected.docsExamined).toBeLessThanOrEqual(projected.nreturned!)+ expect(projected.responseLength, `full=${baseline.responseLength} bytes; projected=${projected.responseLength} bytes for ${projected.nreturned} groups`)+ .toBeLessThan(baseline.responseLength! / 10)+ for (const pipeline of [fullPipeline, projected.command!.pipeline!]) {+ const explain = await db.$runCommandRaw({ explain: { aggregate: 'SwarmGroup', pipeline, cursor: {}, hint: { tabId: 1, key: 1 } },+ verbosity: 'executionStats' }) as unknown as { executionStats: { totalDocsExamined: number; nReturned: number; executionStages: unknown } }+ expect(JSON.stringify(explain.executionStats.executionStages)).toContain('IXSCAN')+ expect(explain.executionStats.totalDocsExamined).toBeLessThanOrEqual(explain.executionStats.nReturned)+ }+ })+it('answers the design\'s shape: cursor 30 s before the read, epoch, newest change, the reader\'s parts and derived values', async () => {const s = await scene()clock = NOW@@ -1072,6 +1128,35 @@ describe('decisions asked of one person (v2)', () => {expect((await derived(owner)).derived.mentionsDigest).toBe(expired.mentionsDigest)})+ it('keeps quiet conversation titles in waiting and earlier tag lists', async () => {+ const s = await scene()+ const tag = await post(s.tabId, { type: 'message.send', conversationId: s.web, text: 'Please look.', replyTo: null,+ recipientIds: [], mentions: [peer.sub] }, owner, s.lead)+ expect(tag.status).toBe(200)+ await writeGroup(s.tabId, s.web, Date.now(), group => { group.dormant = true })++ const waiting = (await get(`/api/super-tabs/${s.tabId}/mentions?state=waiting`, peer)).body.data.mentions as Array<{ conversationTitle: string }>+ expect(waiting.map(row => row.conversationTitle)).toContain('Web')++ expect((await post(s.tabId, { type: 'message.send', conversationId: s.web, text: 'Looked.', replyTo: null, recipientIds: [] }, peer)).status).toBe(200)+ const earlier = (await get(`/api/super-tabs/${s.tabId}/mentions?state=earlier`, peer)).body.data.mentions as Array<{ conversationTitle: string }>+ expect(earlier.map(row => row.conversationTitle)).toContain('Web')+ })++ it('reads waiting tags once in a changes poll while keeping its count and digest', async () => {+ const s = await scene()+ clock = NOW+ await db.superTabMention.create({ data: { id: `${s.tabId}-quiet-tag`, tabId: s.tabId, personId: peer.sub, projectId: 'lead',+ conversationId: s.done, messageId: `${s.tabId}-quiet-message`, authorAgentId: s.lead, createdAt: new Date(NOW - 1_000), resolvedAt: null, resolvedBy: null } })+ const before = await get(`/api/super-tabs/${s.tabId}/parts`, peer)+ expect(before.body.data.derived).toMatchObject({ mentionsWaiting: 1 })++ const measured = await profiledReads(db, /\.SuperTabMention$/, () => get(`/api/super-tabs/${s.tabId}/changes?cursor=${before.body.data.cursor}`, peer))+ expect(measured.value.status).toBe(200)+ expect(measured.value.body.data.derived).toMatchObject({ mentionsWaiting: 1, mentionsDigest: before.body.data.derived.mentionsDigest })+ expect(measured.reads).toBe(1)+ })+it('counts every open decision the reader can open, past 200, reading only which ones and where', async () => {const s = await scene()clock = Date.now()diff --git a/backend/src/push/apns.test.ts b/backend/src/push/apns.test.tsindex 3c7b55c14..e2b408060 100644--- a/backend/src/push/apns.test.ts+++ b/backend/src/push/apns.test.ts@@ -1,10 +1,11 @@import { createPublicKey, generateKeyPairSync, verify } from 'node:crypto'+import { readFileSync } from 'node:fs'import http2 from 'node:http2'import type { AddressInfo } from 'node:net'import { afterAll, describe, expect, it } from 'vitest'import { apnsSender, http2Transport, type ApnsAnswer, type ApnsRequest } from './apns.js'import type { PushDevice } from './devices.js'-import type { PhoneNotice } from './sender.js'+import { swarmNoticeId, type PhoneNotice } from './sender.js'const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' })const sandboxKey = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).privateKey@@ -14,7 +15,7 @@ const keys = { teamId: 'TEAM123456', topic: 'ai.autonomous.harness.ios', productconst productionOnly = { ...keys, sandbox: null }const device: PushDevice = { id: 'd1', userId: 'u1', platform: 'ios', token: 'ab'.repeat(32), sandbox: false }const notice: PhoneNotice = { personId: 'u1', key: 'reply:tab:row', title: 'Mia replied in a thread', subtitle: 'openharness',- body: 'Open Harness to read it.', link: 'swarm:tab/conv/message/m/thread/root' }+ body: 'Open Harness to read it.', link: 'swarm:tab/conv/message/m/thread/root', slot: 'thread:tab:conv:root' }const NOW = Date.UTC(2026, 10, 5, 9)/** A transport that answers each request in turn and remembers what it was asked. */@@ -36,10 +37,11 @@ describe('APNs sender (task #2905)', () => {expect(await apnsSender(keys, { transport, now: () => NOW }).send(device, notice)).toEqual({ outcome: 'sent' })const [request] = askedexpect(request).toMatchObject({ sandbox: false, path: `/3/device/${device.token}` })- expect(request!.headers).toMatchObject({ 'apns-topic': 'ai.autonomous.harness.ios', 'apns-push-type': 'alert', 'apns-priority': '10' })+ expect(request!.headers).toMatchObject({ 'apns-topic': 'ai.autonomous.harness.ios', 'apns-push-type': 'alert', 'apns-priority': '10',+ 'apns-collapse-id': String(swarmNoticeId('thread:tab:conv:root')) })expect(JSON.parse(request!.body)).toEqual({aps: { alert: { title: notice.title, subtitle: notice.subtitle, body: notice.body }, sound: 'default', 'thread-id': 'swarm-needs-you', category: 'swarm-needs-you' },- key: notice.key, link: notice.link,+ key: notice.key, link: notice.link, slot: notice.slot,})const jwt = jwtOf(request!)expect(part(jwt, 0)).toEqual({ alg: 'ES256', kid: 'ABC123DEFG' })@@ -112,6 +114,33 @@ describe('APNs sender (task #2905)', () => {})})+describe('APNs: one notification per slot, and quiet repeats (task #3248)', () => {+ it('collapses on the app\'s own id for the slot, so the app\'s notice and the push are one notification', () => {+ // mobile/test/notify/local_system_notices_test.dart pins the same ids.+ expect(swarmNoticeId('mention:m1')).toBe(1161357565)+ expect(swarmNoticeId('decision:d1')).toBe(15921470)+ expect(swarmNoticeId('work:s1:c1:a1:needs_human')).toBe(701122187)+ expect(swarmNoticeId('mention:é✓')).toBe(1555091707)+ })++ it('sends the body the phone end to end replays on a simulator (mobile/integration_test/push_e2e)', async () => {+ const replay = JSON.parse(readFileSync(new URL('../../../mobile/integration_test/push_e2e/reply_push.apns', import.meta.url), 'utf8'))+ const { asked, transport } = scripted({ status: 200, reason: null })+ await apnsSender(keys, { transport, now: () => NOW }).send(device, { personId: 'u1', ...replay.aps.alert, key: replay.key,+ link: replay.link, slot: replay.slot })+ expect(JSON.parse(asked[0]!.body)).toEqual(replay)+ })++ it('sends a quiet push with no sound and passive, so it only replaces what its slot showed', async () => {+ const { asked, transport } = scripted({ status: 200, reason: null })+ await apnsSender(keys, { transport, now: () => NOW }).send(device, { ...notice, quiet: true })+ const body = JSON.parse(asked[0]!.body)+ expect(body.aps).toEqual({ alert: { title: notice.title, subtitle: notice.subtitle, body: notice.body }, 'interruption-level': 'passive',+ 'thread-id': 'swarm-needs-you', category: 'swarm-needs-you' })+ expect(asked[0]!.headers['apns-collapse-id']).toBe(String(swarmNoticeId(notice.slot)))+ })+})+describe('APNs over HTTP/2', () => {const seen: Array<{ headers: http2.IncomingHttpHeaders; body: string }> = []const server = http2.createServer((request, response) => {diff --git a/backend/src/push/apns.ts b/backend/src/push/apns.tsindex 6ada2cecf..2360be3ae 100644--- a/backend/src/push/apns.ts+++ b/backend/src/push/apns.ts@@ -2,7 +2,7 @@ import { sign } from 'node:crypto'import http2 from 'node:http2'import type { ApnsKey, ApnsKeys } from './keys.js'import type { PushDevice } from './devices.js'-import { SEND_TIMEOUT_MS, SWARM_CHANNEL, withTimeout, type PhoneNotice, type Sender, type SendResult } from './sender.js'+import { SEND_TIMEOUT_MS, SWARM_CHANNEL, swarmNoticeId, withTimeout, type PhoneNotice, type Sender, type SendResult } from './sender.js'/** One request to Apple: to its production host, or to the sandbox host a development build's token needs. */export interface ApnsRequest { sandbox: boolean; path: string; headers: Record<string, string>; body: string }@@ -36,10 +36,14 @@ export function apnsSender(keys: ApnsKeys, options: { transport?: ApnsTransport;const noSandboxKey: SendResult = { outcome: 'unconfigured', reason: 'no APNs sandbox key' }const ask = async (device: PushDevice, notice: PhoneNotice, sandbox: boolean): Promise<ApnsAnswer> => withTimeout(transport({sandbox, path: `/3/device/${device.token}`,+ // The collapse id is the app's own notice id for the slot (task #3248): a newer push for it, or the app's notice, replaces+ // the one shown instead of adding a second.headers: { authorization: `bearer ${bearer(sandbox ? keys.sandbox! : keys.production)}`, 'apns-topic': keys.topic, 'apns-push-type': 'alert', 'apns-priority': '10',- 'apns-expiration': String(Math.floor(now() / 1000) + 24 * 60 * 60) },- body: JSON.stringify({ aps: { alert: { title: notice.title, subtitle: notice.subtitle, body: notice.body }, sound: 'default',- 'thread-id': SWARM_CHANNEL, category: SWARM_CHANNEL }, key: notice.key, link: notice.link }),+ 'apns-expiration': String(Math.floor(now() / 1000) + 24 * 60 * 60), 'apns-collapse-id': String(swarmNoticeId(notice.slot)) },+ // A quiet push has no sound and is passive: it replaces its slot's notification without lighting the screen or a banner.+ body: JSON.stringify({ aps: { alert: { title: notice.title, subtitle: notice.subtitle, body: notice.body },+ ...notice.quiet ? { 'interruption-level': 'passive' } : { sound: 'default' }, 'thread-id': SWARM_CHANNEL, category: SWARM_CHANNEL },+ key: notice.key, link: notice.link, slot: notice.slot }),}, timeoutMs), timeoutMs)const judged = (answer: ApnsAnswer, sandboxNow: boolean): SendResult => {if (answer.status === 200) return { outcome: sandboxNow ? 'sandbox' : 'sent' }diff --git a/backend/src/push/fcm.test.ts b/backend/src/push/fcm.test.tsindex 3e5fb7729..0d51618f8 100644--- a/backend/src/push/fcm.test.ts+++ b/backend/src/push/fcm.test.ts@@ -8,7 +8,7 @@ const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 })const account = { projectId: 'harness-push', clientEmail: '[email protected]', privateKey, tokenUri: 'https://oauth2.googleapis.com/token' }const device: PushDevice = { id: 'd1', userId: 'u1', platform: 'android', token: 'fcm:token_1', sandbox: false }const notice: PhoneNotice = { personId: 'u1', key: 'mention:m1', title: 'Mia tagged you', subtitle: 'openharness',- body: 'Open Harness to read it.', link: 'swarm:tab/conv/message/m' }+ body: 'Open Harness to read it.', link: 'swarm:tab/conv/message/m', slot: 'mention:m1' }const NOW = Date.UTC(2026, 10, 5, 9)type Call = { url: string; init: RequestInit }@@ -45,10 +45,22 @@ describe('FCM sender (task #2905)', () => {token: device.token,notification: { title: 'Mia tagged you', body: 'openharness · Open Harness to read it.' },android: { priority: 'high', notification: { channel_id: 'swarm-needs-you', tag: 'mention:m1', visibility: 'PRIVATE' } },- data: { key: 'mention:m1', link: notice.link },+ data: { key: 'mention:m1', link: notice.link, slot: 'mention:m1' },} })})+ it('tags the notification with its slot, so a thread\'s replies share one, and sends a quiet one on the app\'s silent channel (task #3248)', async () => {+ const { fetcher, sends } = google()+ const reply = { ...notice, key: 'reply:tab:row2', slot: 'thread:tab:conv:root' }+ const sender = fcmSender(account, { fetcher, now: () => NOW })+ await sender.send(device, reply)+ await sender.send(device, { ...reply, quiet: true })+ const [loud, quiet] = sends().map(c => JSON.parse(String(c.init.body)).message)+ expect(loud.android.notification).toEqual({ channel_id: 'swarm-needs-you', tag: 'thread:tab:conv:root', visibility: 'PRIVATE' })+ expect(quiet.android.notification).toEqual({ channel_id: 'swarm-quiet', tag: 'thread:tab:conv:root', visibility: 'PRIVATE' })+ expect(quiet.data).toEqual({ key: 'reply:tab:row2', link: notice.link, slot: 'thread:tab:conv:root' })+ })+it('keeps its access token until five minutes before it runs out', async () => {let now = NOWconst { calls, fetcher } = google()diff --git a/backend/src/push/fcm.ts b/backend/src/push/fcm.tsindex 0ba01e435..d0cb3a966 100644--- a/backend/src/push/fcm.ts+++ b/backend/src/push/fcm.ts@@ -1,6 +1,6 @@import { sign } from 'node:crypto'import type { FcmAccount } from './keys.js'-import { SEND_TIMEOUT_MS, SWARM_CHANNEL, withTimeout, type Sender } from './sender.js'+import { SEND_TIMEOUT_MS, SWARM_CHANNEL, SWARM_QUIET_CHANNEL, withTimeout, type Sender } from './sender.js'const SCOPE = 'https://www.googleapis.com/auth/firebase.messaging'/** An access token is used until this long before Google says it runs out. */@@ -43,8 +43,10 @@ export function fcmSender(account: FcmAccount, options: { fetcher?: typeof fetchtoken: device.token,// Android's notification has no subtitle: the project leads the body, as the local notice's subtext shows it.notification: { title: notice.title, body: notice.subtitle ? `${notice.subtitle} · ${notice.body}` : notice.body },- android: { priority: 'high', notification: { channel_id: SWARM_CHANNEL, tag: notice.key, visibility: 'PRIVATE' } },- data: { key: notice.key, link: notice.link },+ // Tagged with its slot (task #3248): Android replaces a notification of the same tag, so a thread's replies share+ // one, and the app posts its own notice for it under the same tag. A quiet one goes on the app's silent channel.+ android: { priority: 'high', notification: { channel_id: notice.quiet ? SWARM_QUIET_CHANNEL : SWARM_CHANNEL, tag: notice.slot, visibility: 'PRIVATE' } },+ data: { key: notice.key, link: notice.link, slot: notice.slot },} }),})if (answer.ok) return { outcome: 'sent' }diff --git a/backend/src/push/notices.test.ts b/backend/src/push/notices.test.tsindex dc7662da4..df4d1925b 100644--- a/backend/src/push/notices.test.ts+++ b/backend/src/push/notices.test.ts@@ -16,15 +16,17 @@ function scene() {const draft = (over: Partial<MessageDraft> & Pick<MessageDraft, 'id' | 'conversationId' | 'author'>): MessageDraft =>({ text: 'never in a notice', replyTo: null, recipients: [], ...over })const person = (p: typeof peer) => ({ kind: 'person' as const, id: p.userId, name: p.email, membershipGeneration: 'g' })+const AT = new Date(Date.UTC(2026, 10, 5, 10))describe('phoneNotices: what a write tells phones (task #2905)', () => {it('words a reply as the phone does, and links the thread at the reply', () => {const { state, web } = scene()const reply = draft({ id: 'r1', conversationId: web, author: person(peer), thread: 'root1' })const notices = phoneNotices('tab', state, { replies: [{ id: 'row1', personId: owner.userId, conversationId: web, messageId: 'r1', threadId: 'root1',- actorKind: 'person', actorId: peer.userId }], tags: [] }, [reply])+ actorKind: 'person', actorId: peer.userId, why: 'starter', createdAt: AT }], tags: [] }, [reply])expect(notices).toEqual([{ personId: owner.userId, key: 'reply:tab:row1', title: `${shownNameOf(state, peer.userId)} replied in a thread`,- subtitle: 'Web launch', body: 'Open Harness to read it.', link: `swarm:tab/${web}/message/r1/thread/root1` }])+ subtitle: 'Web launch', body: 'Open Harness to read it.', link: `swarm:tab/${web}/message/r1/thread/root1`,+ slot: `thread:tab:${web}:root1`, thread: { tabId: 'tab', conversationId: web, threadId: 'root1', rowId: 'row1', at: AT.getTime() } }])})it('words a tag as the phone does, and links the message, in its thread only when it is only there', () => {@@ -35,6 +37,8 @@ describe('phoneNotices: what a write tells phones (task #2905)', () => {const alsoInChat = draft({ id: 'm3', conversationId: web, author: person(peer), mentions: [owner.userId], thread: 'root2', alsoInChat: true })const tag = (id: string, messageId: string) => ({ id, personId: owner.userId, conversationId: web, messageId })const notices = phoneNotices('tab', state, { replies: [], tags: [tag('t1', 'm1'), tag('t2', 'm2'), tag('t3', 'm3')] }, [inChat, inThread, alsoInChat])+ // A tag is a notice of its own: it shows in the slot of its key, as the app's notice for it does.+ expect(notices.every(n => n.slot === n.key && !n.thread && !n.quiet)).toBe(true)expect(notices.map(n => [n.key, n.title, n.subtitle, n.link])).toEqual([['mention:t1', 'worker-harness tagged you', 'Web launch', `swarm:tab/${web}/message/m1`],['mention:t2', `${shownNameOf(state, peer.userId)} tagged you`, 'Web launch', `swarm:tab/${web}/message/m2/thread/root2`],@@ -49,7 +53,7 @@ describe('phoneNotices: what a write tells phones (task #2905)', () => {const agent = { kind: 'agent' as const, id: 'buddy-session', name: 'Buddy', membershipGeneration: 'g' }const reply = draft({ id: 'r1', conversationId: buddy, author: agent, thread: 'root1' })const notices = phoneNotices('tab', state, { replies: [{ id: 'row1', personId: peer.userId, conversationId: buddy, messageId: 'r1', threadId: 'root1',- actorKind: 'agent', actorId: 'buddy-session' }], tags: [] }, [reply])+ actorKind: 'agent', actorId: 'buddy-session', why: 'starter', createdAt: AT }], tags: [] }, [reply])expect(notices).toEqual([expect.objectContaining({ personId: peer.userId, subtitle: '', link: `swarm:tab/${buddy}/message/r1/thread/root1` })])})@@ -63,7 +67,7 @@ describe('phoneNotices: what a write tells phones (task #2905)', () => {const { state, web } = scene()const reply = draft({ id: 'r/1', conversationId: web, author: person(peer), thread: 'root 1' })const [notice] = phoneNotices('tab:x', state, { replies: [{ id: 'row1', personId: owner.userId, conversationId: web, messageId: 'r/1', threadId: 'root 1',- actorKind: 'person', actorId: peer.userId }], tags: [] }, [reply])+ actorKind: 'person', actorId: peer.userId, why: 'starter', createdAt: AT }], tags: [] }, [reply])expect(notice!.link).toBe(`swarm:tab%3Ax/${web}/message/r%2F1/thread/root%201`)})@@ -71,7 +75,54 @@ describe('phoneNotices: what a write tells phones (task #2905)', () => {const { state, web } = scene()const reply = draft({ id: 'r1', conversationId: web, author: person(peer), thread: 'root1', mentions: [owner.userId] })const notices = phoneNotices('tab', state, { replies: [{ id: 'row1', personId: owner.userId, conversationId: web, messageId: 'r1', threadId: 'root1',- actorKind: 'person', actorId: peer.userId }], tags: [{ id: 't1', personId: owner.userId, conversationId: web, messageId: 'r1' }] }, [reply])+ actorKind: 'person', actorId: peer.userId, why: 'starter', createdAt: AT }], tags: [{ id: 't1', personId: owner.userId, conversationId: web, messageId: 'r1' }] }, [reply])expect(JSON.stringify(notices)).not.toContain('never in a notice')})})++describe('phoneNotices: the push rule Tony approved (task #3248)', () => {+ const row = (id: string, personId: string, why: 'starter' | 'quoted' | 'tagged' | 'replier', messageId = 'r1') =>+ ({ id, personId, conversationId: '', messageId, threadId: 'root1', actorKind: 'person', actorId: peer.userId, why, createdAt: AT })++ it('pushes a reply to the thread\'s starter, the quoted message\'s author and people tagged in the thread, never to one who only replied there', () => {+ const { state, web } = scene()+ const reply = draft({ id: 'r1', conversationId: web, author: person(peer), thread: 'root1' })+ const at = (r: ReturnType<typeof row>) => ({ ...r, conversationId: web })+ const notices = phoneNotices('tab', state, { replies: [at(row('a', 'starter-id', 'starter')), at(row('b', 'quoted-id', 'quoted')), at(row('c', 'tagged-id', 'tagged')),+ at(row('d', 'replier-id', 'replier'))], tags: [] }, [reply])+ expect(notices.map(n => n.personId)).toEqual(['starter-id', 'quoted-id', 'tagged-id'])+ // One slot per thread: a newer reply there replaces the notice of the one before.+ expect(new Set(notices.map(n => n.slot))).toEqual(new Set([`thread:tab:${web}:root1`]))+ })++ it('pushes no Swarm line in a thread (a status, a ship or review notice): it stays in Activity', () => {+ const { state, web, worker } = scene()+ const agent = { kind: 'agent' as const, id: worker, name: 'worker-harness', membershipGeneration: 'g' }+ const line = draft({ id: 'r1', conversationId: web, author: agent, thread: 'root1', source: { kind: 'system' } })+ expect(phoneNotices('tab', state, { replies: [{ ...row('a', owner.userId, 'starter'), conversationId: web }], tags: [] }, [line])).toEqual([])+ // The same row for an agent's own words is pushed.+ const words = draft({ id: 'r1', conversationId: web, author: agent, thread: 'root1' })+ expect(phoneNotices('tab', state, { replies: [{ ...row('a', owner.userId, 'starter'), conversationId: web, actorKind: 'agent', actorId: worker }], tags: [] }, [words]))+ .toEqual([expect.objectContaining({ personId: owner.userId, title: 'worker-harness replied in a thread' })])+ })++ it('pushes a decision asked of a person as the app words it, linking its card, and only the first of one ask\'s questions sounds', () => {+ const { state, web, worker } = scene()+ const decision = (id: string, personId: string) => ({ id, personId, conversationId: web, askerAgentId: worker })+ const notices = phoneNotices('tab', state, { replies: [], tags: [], decisions: [decision('d1', owner.userId), decision('d2', owner.userId), decision('d3', peer.userId)] }, [])+ expect(notices).toEqual([+ { personId: owner.userId, key: 'decision:d1', slot: 'decision:d1', title: 'worker-harness asks you', subtitle: 'Web launch', body: 'Open Harness to answer.',+ link: `swarm:tab/${web}/decision/d1` },+ { personId: owner.userId, key: 'decision:d2', slot: 'decision:d2', title: 'worker-harness asks you', subtitle: 'Web launch', body: 'Open Harness to answer.',+ link: `swarm:tab/${web}/decision/d2`, quiet: true },+ { personId: peer.userId, key: 'decision:d3', slot: 'decision:d3', title: 'worker-harness asks you', subtitle: 'Web launch', body: 'Open Harness to answer.',+ link: `swarm:tab/${web}/decision/d3` },+ ])+ })++ it('names an asker that is gone as the app does', () => {+ const { state, web } = scene()+ expect(phoneNotices('tab', state, { replies: [], tags: [], decisions: [{ id: 'd1', personId: owner.userId, conversationId: web, askerAgentId: 'gone' }] }, [])[0]!.title)+ .toBe('Agent asks you')+ })+})diff --git a/backend/src/push/notices.ts b/backend/src/push/notices.tsindex a30b461b5..b1c077c43 100644--- a/backend/src/push/notices.ts+++ b/backend/src/push/notices.ts@@ -5,27 +5,49 @@ import { projectsOf } from '../superTabs/projects.js'import { isSwarmBuddyChat } from '../superTabs/buddies.js'import type { PhoneNotice } from './sender.js'-/** A reply's Activity row as writeReplyActivity wrote it: who it tells, and whose reply. */-export interface ReplyRow { id: string; personId: string; conversationId: string; messageId: string; threadId: string; actorKind: string; actorId: string }+/** Why a reply's row tells its person (activity.ts writeReplyActivity): they started the thread, wrote the message it+ * quotes, were tagged in the thread, or only replied in it. */+export type ReplyReason = 'starter' | 'quoted' | 'tagged' | 'replier'+/** A reply's Activity row as writeReplyActivity wrote it: who it tells, whose reply, why, and when. */+export interface ReplyRow {+ id: string; personId: string; conversationId: string; messageId: string; threadId: string; actorKind: string; actorId: string+ why: ReplyReason; createdAt: Date+}/** A tag's row as writeMentions wrote it; `holdUntil` while it waits for a quiet chat's grace. */export interface TagRow { id: string; personId: string; conversationId: string; messageId: string; holdUntil?: Date }+/** A decision a write asked of a person, new in that write (decisions.ts writeDecisions). */+export interface DecisionRow { id: string; personId: string; conversationId: string; askerAgentId: string }/** The phone's notice body (mobile lib/swarm/swarm_notices.dart): a notice can be read on a locked phone, so it never says* what was written. */const BODY = 'Open Harness to read it.'+/** A decision's, as the app's own (swarm_notices.dart swarmNotice). */+const ANSWER = 'Open Harness to answer.'++/** Whom a reply's push tells, of those its Activity row tells (task #3248, Tony's rule): a reply in a thread they started,+ * a reply to their own message, or one in a thread they were tagged in. A person who only replied in the thread reads it in+ * Activity, with no push. */+const PUSHED: ReadonlySet<ReplyReason> = new Set(['starter', 'quoted', 'tagged'])+const e = encodeURIComponent/** The phone's `swarm:` payload (mobile lib/notify/system_notices.dart encodeSwarmPayload), each part URI-encoded. */function linkOf(tabId: string, conversationId: string, messageId: string, threadId: string | null): string {- const e = encodeURIComponentreturn `swarm:${e(tabId)}/${e(conversationId)}/message/${e(messageId)}${threadId ? `/thread/${e(threadId)}` : ''}`}+/** The one notification a thread's replies share on a phone (task #3248): the app's own reply notices use it too+ * (mobile lib/swarm/swarm_notices.dart threadSlot). */+export const threadSlot = (tabId: string, conversationId: string, threadId: string) => `thread:${tabId}:${conversationId}:${threadId}`+/**- * What one write tells phones (task #2905): a notice for each reply row and each tag row it wrote, worded and keyed as the- * phone's own notices are, so the phone shows one or the other, never both. Who is told was decided with the rows (#2954:- * muted chats and Unfollow write no reply row; a tag always tells). A tag held for a quiet chat is not news yet.+ * What one write tells phones (tasks #2905, #3248): a notice for each reply row and tag row it wrote, and each decision it+ * asked, worded and keyed as the phone's own notices are, so the phone shows one or the other, never both. Who is told was+ * decided with the rows (#2954: muted chats and Unfollow write no reply row; a tag always tells); of a reply's rows, only+ * those Tony's rule pushes (PUSHED), and never for a Swarm line in a thread (a row with a source), which stays in Activity.+ * A tag held for a quiet chat is not news yet. Of one ask's decisions to a person, only the first sounds.*/-export function phoneNotices(tabId: string, state: SuperTabState, written: { replies: ReplyRow[]; tags: TagRow[] }, messages: MessageDraft[]): PhoneNotice[] {+export function phoneNotices(tabId: string, state: SuperTabState, written: { replies: ReplyRow[]; tags: TagRow[]; decisions?: DecisionRow[] },+ messages: MessageDraft[]): PhoneNotice[] {const byId = new Map(messages.map(m => [m.id, m]))// Where it is, as the phone names it; none for a person's Swarm Buddy chat, which belongs to no project. Never throws: this// runs inside the write (projects.ts groupProject refuses a Buddy chat, security review 2).@@ -34,18 +56,31 @@ export function phoneNotices(tabId: string, state: SuperTabState, written: { repif (!group || isSwarmBuddyChat(group)) return ''return projectsOf(state).find(p => p.id === (group.projectId ?? 'lead'))?.name ?? ''}- const replies = written.replies.map(row => ({+ const replies = written.replies.filter(row => PUSHED.has(row.why) && !byId.get(row.messageId)?.source).map((row): PhoneNotice => ({personId: row.personId, key: `reply:${tabId}:${row.id}`,title: `${actorName(state, row.actorKind, row.actorId, byId.get(row.messageId)?.author)} replied in a thread`,subtitle: project(row.conversationId), body: BODY, link: linkOf(tabId, row.conversationId, row.messageId, row.threadId),+ slot: threadSlot(tabId, row.conversationId, row.threadId),+ thread: { tabId, conversationId: row.conversationId, threadId: row.threadId, rowId: row.id, at: row.createdAt.getTime() },}))- const tags = written.tags.filter(row => !row.holdUntil).flatMap(row => {+ const tags = written.tags.filter(row => !row.holdUntil).flatMap((row): PhoneNotice[] => {const message = byId.get(row.messageId)if (!message) return []// A tag in a reply only in its thread opens that thread (swarm_notices.dart).const thread = message.thread && message.thread !== message.id && !message.alsoInChat ? message.thread : null- return [{ personId: row.personId, key: `mention:${row.id}`, title: `${taggerName(state, message.author)} tagged you`,- subtitle: project(row.conversationId), body: BODY, link: linkOf(tabId, row.conversationId, row.messageId, thread) }]+ const key = `mention:${row.id}`+ return [{ personId: row.personId, key, title: `${taggerName(state, message.author)} tagged you`,+ subtitle: project(row.conversationId), body: BODY, link: linkOf(tabId, row.conversationId, row.messageId, thread), slot: key }]+ })+ const asked = new Set<string>()+ const decisions = (written.decisions ?? []).map((row): PhoneNotice => {+ // As the app names the asker (decisions.ts listDecisions askerName).+ const asker = state.agents.find(a => a.id === row.askerAgentId)+ const key = `decision:${row.id}`+ const first = !asked.has(row.personId)+ asked.add(row.personId)+ return { personId: row.personId, key, title: `${asker?.displayName ?? asker?.name ?? 'Agent'} asks you`, subtitle: project(row.conversationId),+ body: ANSWER, link: `swarm:${e(tabId)}/${e(row.conversationId)}/decision/${e(row.id)}`, slot: key, ...first ? {} : { quiet: true as const } }})- return [...replies, ...tags]+ return [...replies, ...tags, ...decisions]}diff --git a/backend/src/push/repeats.ts b/backend/src/push/repeats.tsnew file mode 100644index 000000000..b79910919--- /dev/null+++ b/backend/src/push/repeats.ts@@ -0,0 +1,44 @@+import type { PrismaClient } from '@prisma/client'+import type { PhoneNotice } from './sender.js'++type Unread = { _id: string; personId: string; createdAt?: { $date: string } }+/** SuperTabActivity's `@@index([tabId, personId, conversationId, threadId])` (prisma/schema.prisma). */+const THREAD_INDEX = { tabId: 1, personId: 1, conversationId: 1, threadId: 1 }++/**+ * Tony's rule for a thread's replies (task #3248): a reply's push sounds only when its person had no unread reply in that+ * thread before it. Otherwise it goes quietly, replacing the thread's one notification (its slot) without a sound or a+ * banner; once the person reads the thread, the next reply sounds again. Of one person's notices for one thread in `notices`,+ * only the earliest can sound.+ *+ * One read per thread the reply notices are in, by the Activity thread index (tabId, personId, conversationId, threadId),+ * as a plain $match: Prisma sends `in` as $expr, which no index bounds (backend/AGENTS.md rule 3). Tags and decisions are+ * never quieted here, and nothing is read when no reply is pushed.+ */+export async function quietRepeats(db: PrismaClient, notices: PhoneNotice[]): Promise<PhoneNotice[]> {+ const threads = new Map<string, PhoneNotice[]>()+ for (const notice of notices) {+ if (notice.thread && !notice.quiet) threads.set(notice.slot, [...threads.get(notice.slot) ?? [], notice])+ }+ if (!threads.size) return notices+ const quiet = new Set<PhoneNotice>()+ for (const group of threads.values()) {+ const { tabId, conversationId, threadId } = group[0]!.thread!+ const latest = Math.max(...group.map(n => n.thread!.at))+ const rows = await db.superTabActivity.aggregateRaw({ pipeline: [+ { $match: { tabId, personId: { $in: [...new Set(group.map(n => n.personId))] }, conversationId, threadId, kind: 'reply', readAt: null,+ createdAt: { $lt: { $date: new Date(latest).toISOString() } } } },+ { $project: { _id: 1, personId: 1, createdAt: 1 } },+ // The thread's rows, read or not, are a few; the person's unread rows (the digest's index, which the planner may race+ // it against) can be hundreds across the Swarm.+ ], options: { hint: THREAD_INDEX } }) as unknown as Unread[]+ const earlier = (n: PhoneNotice) => rows.some(row => row.personId === n.personId && row._id !== n.thread!.rowId+ && Date.parse(row.createdAt?.$date ?? '') < n.thread!.at)+ const first = new Map<string, PhoneNotice>()+ for (const notice of [...group].sort((a, b) => a.thread!.at - b.thread!.at)) {+ if (earlier(notice) || first.has(notice.personId)) quiet.add(notice)+ else first.set(notice.personId, notice)+ }+ }+ return notices.map(notice => quiet.has(notice) ? { ...notice, quiet: true as const } : notice)+}diff --git a/backend/src/push/send.test.ts b/backend/src/push/send.test.tsindex d9ed7b7d0..7d2efe254 100644--- a/backend/src/push/send.test.ts+++ b/backend/src/push/send.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-const m = vi.hoisted(() => ({ devicesOf: vi.fn(), forget: vi.fn(), sandbox: vi.fn(), count: vi.fn(), warn: vi.fn(), info: vi.fn() }))+const m = vi.hoisted(() => ({ devicesOf: vi.fn(), forget: vi.fn(), sandbox: vi.fn(), count: vi.fn(), warn: vi.fn(), info: vi.fn(), repeats: vi.fn() }))vi.mock('./devices.js', () => ({ devicesOf: m.devicesOf, forgetPushDevice: m.forget, markSandbox: m.sandbox }))+vi.mock('./repeats.js', () => ({ quietRepeats: m.repeats }))vi.mock('../lib/metrics.js', () => ({ metrics: { phonePush: m.count } }))vi.mock('../utils/logger.js', () => ({ logger: { warn: m.warn, info: m.info, error: m.warn } }))import { sendPhoneNotices } from './send.js'@@ -9,7 +10,7 @@ import type { PhoneNotice, Sender, SendResult } from './sender.js'const db = { fixture: 'db' } as neverconst notice = (personId: string, key = `reply:tab:${personId}`): PhoneNotice =>- ({ personId, key, title: 'Mia replied in a thread', subtitle: 'openharness', body: 'Open Harness to read it.', link: 'swarm:tab/c' })+ ({ personId, key, title: 'Mia replied in a thread', subtitle: 'openharness', body: 'Open Harness to read it.', link: 'swarm:tab/c', slot: key })const phone = (id: string, userId: string, platform: 'ios' | 'android' = 'ios'): PushDevice => ({ id, userId, platform, token: `secret-token-${id}`, sandbox: false })const answering = (results: Record<string, SendResult>) => {const sent: Array<[string, string]> = []@@ -18,7 +19,29 @@ const answering = (results: Record<string, SendResult>) => {}describe('sendPhoneNotices (task #2905)', () => {- beforeEach(() => vi.resetAllMocks())+ beforeEach(() => {+ vi.resetAllMocks()+ m.repeats.mockImplementation(async (_db: unknown, notices: PhoneNotice[]) => notices)+ })++ it('sends each notice as its thread\'s repeats make it: quiet where the person has an unread reply there (task #3248)', async () => {+ m.devicesOf.mockResolvedValue([phone('a1', 'a')])+ m.repeats.mockImplementation(async (_db: unknown, notices: PhoneNotice[]) => notices.map(n => ({ ...n, quiet: true })))+ const seen: PhoneNotice[] = []+ const sender: Sender = { send: async (_device, n) => { seen.push(n); return { outcome: 'sent' } } }+ await sendPhoneNotices(db, { ios: sender, android: null }, [notice('a')])+ expect(m.repeats).toHaveBeenCalledWith(db, [notice('a')])+ expect(seen).toEqual([{ ...notice('a'), quiet: true }])+ })++ it('still sends, with sound, when the repeats cannot be read, and says so (task #3248)', async () => {+ m.devicesOf.mockResolvedValue([phone('a1', 'a')])+ m.repeats.mockRejectedValue(new Error('primary stepped down'))+ const ios = answering({})+ await sendPhoneNotices(db, { ios: ios.sender, android: null }, [notice('a')])+ expect(ios.sent).toEqual([['a1', 'reply:tab:a']])+ expect(m.warn).toHaveBeenCalledWith('phone push repeats not read', expect.objectContaining({ error: 'primary stepped down' }))+ })it('reads the told people\'s phones once and sends each notice to each of its person\'s phones', async () => {m.devicesOf.mockResolvedValue([phone('a1', 'a'), phone('a2', 'a', 'android'), phone('b1', 'b')])diff --git a/backend/src/push/send.ts b/backend/src/push/send.tsindex db3c270b9..d64cf2bb8 100644--- a/backend/src/push/send.ts+++ b/backend/src/push/send.ts@@ -5,6 +5,7 @@ import { devicesOf, forgetPushDevice, markSandbox, type PushDevice, type PushPlaimport { apnsSender } from './apns.js'import { fcmSender } from './fcm.js'import { pushKeysFromEnv, type PushEnv } from './keys.js'+import { quietRepeats } from './repeats.js'import type { PhoneNotice, Sender } from './sender.js'/** A platform's sender, or null when the server has no keys for it. */@@ -27,10 +28,16 @@ export function phoneSendersFromEnv(env: PushEnv): PhoneSenders {* of those people's phones; each notice to each of its person's phones, AT_ONCE at a time. A dead token is forgotten, a* sandbox one remembered. It never throws: what failed is logged, by platform and Apple's or Google's reason, and counted.*/-export async function sendPhoneNotices(db: PrismaClient, senders: PhoneSenders, notices: PhoneNotice[]): Promise<void> {- if (!notices.length) return+export async function sendPhoneNotices(db: PrismaClient, senders: PhoneSenders, given: PhoneNotice[]): Promise<void> {+ if (!given.length) returnconst started = Date.now()+ let notices = giventry {+ // A thread's repeat goes quietly (task #3248). Not read, each goes with its sound: a notice is never lost to it.+ notices = await quietRepeats(db, given).catch((error: unknown) => {+ logger.warn('phone push repeats not read', { notices: given.length, error: error instanceof Error ? error.message : String(error) })+ return given+ })const phones = new Map<string, PushDevice[]>()for (const device of await devicesOf(db, [...new Set(notices.map(n => n.personId))])) phones.set(device.userId, [...phones.get(device.userId) ?? [], device])const sends = notices.flatMap(notice => (phones.get(notice.personId) ?? []).map(device => ({ notice, device })))diff --git a/backend/src/push/sender.ts b/backend/src/push/sender.tsindex 6a10b4b6c..c9c77db95 100644--- a/backend/src/push/sender.ts+++ b/backend/src/push/sender.ts@@ -4,8 +4,26 @@ import type { PushDevice } from './devices.js'* One notification for one person's phones (task #2905), as the phone's own notices word it (mobile* lib/swarm/swarm_notices.dart): who and where, never what was written. `key` is the phone's key for the same notice, so the* app never posts it a second time; `link` is the phone's `swarm:` payload, which opens the thread at the reply.+ *+ * `slot` is the notification it shows in, the one the app's own notice for the same thing uses (task #3248): a tag's or a+ * decision's own key, and one per thread for its replies, so a newer reply replaces the one before and the app's notice+ * replaces the push instead of showing beside it. `quiet` shows it with no sound and no banner: it only replaces what that+ * slot showed. `thread` is a reply's thread and Activity row, by which repeats are found (push/repeats.ts).*/-export interface PhoneNotice { personId: string; key: string; title: string; subtitle: string; body: string; link: string }+export interface PhoneNotice {+ personId: string; key: string; title: string; subtitle: string; body: string; link: string; slot: string; quiet?: true+ thread?: { tabId: string; conversationId: string; threadId: string; rowId: string; at: number }+}++/** The app's id for the notice in `slot` (mobile lib/notify/system_notices.dart swarmNoticeIdFor: FNV-1a over UTF-16 code+ * units, kept positive at each step): APNs's collapse id, so a push and the app's notice for it are one notification. */+export function swarmNoticeId(slot: string): number {+ const text = `swarm\n${slot}`+ let hash = 0x811c9dc5+ // Math.imul keeps the product's low 32 bits, all the mask reads: Dart multiplies in 64 bits, past a double's precision.+ for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193) & 0x7fffffff+ return hash+}/** sent; gone: the token is dead, forget it; sandbox: taken by Apple's sandbox host, send there from now on; failed;* unconfigured: the server has no key for where it would go (Apple's sandbox host), so nothing was sent and the token is kept. */@@ -20,6 +38,9 @@ export const SEND_TIMEOUT_MS = 10_000/** The iOS thread and category, and the Android channel, of Swarm notices: the ones the app's local notices use. */export const SWARM_CHANNEL = 'swarm-needs-you'+/** The Android channel of a quiet push (task #3248), which the app makes with no sound: Android's channel, not the message,+ * decides whether a notification sounds. */+export const SWARM_QUIET_CHANNEL = 'swarm-quiet'/** `promise`, or a rejection with `timeout` after `ms`. */export function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {diff --git a/backend/src/superTabs/activity.ts b/backend/src/superTabs/activity.tsindex e86eaaf4d..a6363d406 100644--- a/backend/src/superTabs/activity.ts+++ b/backend/src/superTabs/activity.ts@@ -22,7 +22,7 @@ import { SESSION_ENDED_KIND } from './buddySessions.js'import { canReadGroup, projectOf } from './projects.js'import { groupsBy, readBy } from './parts/indexed.js'import type { ThreadFacet } from './pageReads.js'-import type { ReplyRow } from '../push/notices.js'+import type { ReplyReason, ReplyRow } from '../push/notices.js'import { shownNameOf } from './personNames.js'import { FIELDS, readable, row as messageRow, type Row } from './read/inbox.js'@@ -104,6 +104,9 @@ export async function writeReplyActivity(tx: Tx, tabId: string, messages: Messagconst group = fanout?.state.conversations.find(c => c.id === m.conversationId)const spread = fanout && group && !m.source ? threadPeople(fanout.threads.get(m.thread!), m.thread!) : { tagged: [], repliers: [] }const tagsHere = new Set(m.mentions ?? [])+ // Why each person is told, for the phone's push (push/notices.ts): the first that holds, in replyAudience's order.+ const why = (personId: string): ReplyReason => personId === starter ? 'starter' : personId === quoted ? 'quoted'+ : spread.tagged.includes(personId) ? 'tagged' : 'replier'const told = replyAudience({ starter, quoted, ...spread }).filter(personId => {if (own(m.author, personId) || tagsHere.has(personId)) return false// A chat the command's state does not hold (a quiet one) tells the starter and the quoted author, as without `fanout`.@@ -111,7 +114,7 @@ export async function writeReplyActivity(tx: Tx, tabId: string, messages: Messagconst person = people.get(personId)return !!person && canReadGroup(fanout!.state, { kind: 'person', userId: person.id, email: person.email }, group)})- return { message: m, people: told }+ return { message: m, people: told, why }})const markIds = [...new Set(recipients.flatMap(({ message, people }) => people.map(personId =>stableId(tabId, message.conversationId, message.thread!, personId))))]@@ -126,14 +129,14 @@ export async function writeReplyActivity(tx: Tx, tabId: string, messages: Messag{ $match: { _id: { $in: settingIds } } }, { $project: { _id: 1, notify: 1 } },] }) as unknown as Array<{ _id: string; notify?: string }>const muted = new Set(settings.filter(row => row.notify === 'muted').map(row => row._id))- const data = recipients.flatMap(({ message: m, people }) => {+ const data = recipients.flatMap(({ message: m, people, why }) => {return people.filter(personId => !unfollowed.has(stableId(tabId, m.conversationId, m.thread!, personId))- && !muted.has(stableId(tabId, m.conversationId, personId, 'notify'))).map(personId => ({ id: stableId(tabId, 'reply', m.id, personId), tabId, personId, kind: 'reply', conversationId: m.conversationId,+ && !muted.has(stableId(tabId, m.conversationId, personId, 'notify'))).map(personId => ({ why: why(personId), row: { id: stableId(tabId, 'reply', m.id, personId), tabId, personId, kind: 'reply', conversationId: m.conversationId,messageId: m.id, threadId: m.thread!, actorKind: m.author.kind, actorId: m.author.id, emoji: null, createdAt: new Date(now), readAt: null,- ...sequences.has(m.id) ? { sequence: sequences.get(m.id)! } : {}, ...m.alsoInChat ? { alsoInChat: true } : {} }))+ ...sequences.has(m.id) ? { sequence: sequences.get(m.id)! } : {}, ...m.alsoInChat ? { alsoInChat: true } : {} } }))})- if (data.length) await tx.superTabActivity.createMany({ data })- return data+ if (data.length) await tx.superTabActivity.createMany({ data: data.map(({ row }) => row) })+ return data.map(({ row, why }) => ({ ...row, why }))}/** The row of the reaction `reactionId`, for the person who wrote the message, unless they reacted themselves: written when thediff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.tsindex 1d6c33b41..22f858774 100644--- a/backend/src/superTabs/mentions.ts+++ b/backend/src/superTabs/mentions.ts@@ -291,6 +291,15 @@ const tagRows = (tabId: string, personId: string, now: number, open: boolean | norderBy: { createdAt: 'desc' as const }, take: 500,})+/** The fields a changes poll needs both to hold tagged conversations and derive its mention badge from the same read. */+export type WaitingTagRow = { id: string; projectId: string; conversationId: string; messageId: string; authorAgentId: string; createdAt: Date;+ resolvedAt: Date | null; resolvedBy: string | null; holdUntil: Date | null }+export async function waitingTagRows(tx: Tx, tabId: string, personId: string, now: number): Promise<WaitingTagRow[]> {+ return await tx.superTabMention.findMany({ ...tagRows(tabId, personId, now, true),+ select: { id: true, projectId: true, conversationId: true, messageId: true, authorAgentId: true, createdAt: true, resolvedAt: true, resolvedBy: true,+ holdUntil: true } })+}+/** The conversations of a person's waiting tags, newest tag first, once each: those [waitingMentions] may read beyond what a* read holds, so a change poll can hold them per conversation (read/service.ts). */export async function waitingTagConversations(tx: Tx, tabId: string, personId: string, now: number): Promise<string[]> {@@ -302,14 +311,16 @@ export async function waitingTagConversations(tx: Tx, tabId: string, personId: s* counts this same list. Ordinary loads leave quiet (dormant) conversations out of the state, so the ones a tag is in are* read here: the count and the list check the same conversations whichever state they get.* ponytail: capped at 500 per state; page it if a person ever gets more in 30 days. */-async function readable(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, now: number, open: boolean | null) {+async function readable(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, now: number, open: boolean | null,+ waitingRows?: WaitingTagRow[]) {person(state, actor.userId)- const rows = await tx.superTabMention.findMany(tagRows(tabId, actor.userId, now, open))+ const rows = open && waitingRows ? waitingRows : await tx.superTabMention.findMany(tagRows(tabId, actor.userId, now, open))const groups = new Map(state.conversations.map(c => [c.id, c]))const missing = [...new Set(rows.map(r => r.conversationId))].filter(id => !groups.has(id))if (missing.length) {// By id through its index (parts/indexed.ts): every person's read counts these on each poll.- for (const row of await groupsBy(tx, 'key', [{ $match: { tabId, deleted: false, key: { $in: missing } } }, { $project: { _id: 0, key: 1, data: 1 } }])) {+ for (const row of await groupsBy(tx, 'key', [{ $match: { tabId, deleted: false, key: { $in: missing } } }, { $project: { _id: 0, key: 1,+ data: { title: 1, kind: 1, projectId: 1, audience: 1, archived: 1, assignment: { status: 1 } } } }])) {groups.set(row.key as string, row.data as unknown as Conversation)}}@@ -327,8 +338,8 @@ export async function mentionsWaiting(tx: Tx, tabId: string, state: SuperTabStat* when either moves (a tag made, answered or expired, though the count may stay), not on every change of the Swarm. Only* the person's own tags they can still read go into it, and only their ids. */export async function waitingMentions(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>,- now: number): Promise<{ count: number; digest: string }> {- const ids = (await readable(tx, tabId, state, actor, now, true)).map(({ row }) => row.id).sort()+ now: number, waitingRows?: WaitingTagRow[]): Promise<{ count: number; digest: string }> {+ const ids = (await readable(tx, tabId, state, actor, now, true, waitingRows)).map(({ row }) => row.id).sort()return { count: ids.length, digest: mentionsDigest(ids) }}diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex 4759d5003..be4935f8d 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -8,7 +8,7 @@ import type { AuthUser } from '../../lib/ssoAuth.js'import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../../lib/teamSession.js'import { agentOnly, author, fail, groupForBuddy, isLeads, seenMachineIds, stableId, SuperTabError, visibleState, type Actor, type AgentStart, type Conversation, type SuperTabState } from '../model.js'import { logger } from '../../utils/logger.js'-import { mentionsDigest, resolveRead, swarmsWithTags, waitingMentions, waitingTagConversations } from '../mentions.js'+import { mentionsDigest, resolveRead, swarmsWithTags, waitingMentions, waitingTagRows, type WaitingTagRow } from '../mentions.js'import { decisionsWaiting } from '../decisions.js'import { lowerReadMark, readMarkRows, readThreadMarks, writeThreadFollow, writeThreadMark, type ReadMarkRow } from '../readMarks.js'import { activityDigest, listActivity, markActivityRead, markActivityThreadRead, type ActivityItem } from '../activity.js'@@ -51,6 +51,11 @@ interface Read { parts: SwarmParts; actor: Actor; view: ReaderView; lastChangedAexport const GROUP_ROWS_BYTES = 8 * 1024 * 1024/** How long one Swarm's machine lookups below are reused: machines report every 15 s anyway (Diego's review, item 5, 2026-10-28). */const MACHINE_READS_MS = 15_000+/** The format and deletion metadata can be reused briefly: deletion and migration take effect on each pod within this window. */+export const SWARM_ROW_READS_MS = 3_000+const MAX_SWARM_ROW_READS = 2_000+type SwarmRow = { format: number | null; deletedAt: Date | null }+type SwarmRowRead = { at: number; read: Promise<SwarmRow | null> }type MachineReads = [teamMachines: string[], otherWorkspaceMachines: string[], machineVersions: Record<string, string>, joiningTeams: string[]]/** The conversations the reader can read now, a dormant one read by id included. */@@ -114,6 +119,8 @@ export class SwarmReads {private readonly servedTops: ServedTops/** The machine lookups of each Swarm read in the last MACHINE_READS_MS, oldest first, keyed by what they depend on. */private readonly machineReads = new Map<string, { at: number; read: Promise<MachineReads> }>()+ /** The small format/deletion row for each Swarm, held briefly per process. */+ private readonly swarmRows = new Map<string, SwarmRowRead>()async firstLoad(user: AuthUser, tabId: string, asAgentId?: string): Promise<FirstLoad> {const t0 = this.now()@@ -188,8 +195,8 @@ export class SwarmReads {if ('reload' in from) { await this.load(tx, cached, user, tabId, asAgentId, t0, {}, async () => base); return from }// Without asAgentId the reader is a person (store.ts actor), whose marks moved since the cursor go out with this reply.const person = asAgentId ? null : user.sub- const [changed, tagged, marks, threadMarks, settings] = await Promise.all([readChanged(tx, cached, tabId, from.since),- person ? waitingTagConversations(tx, tabId, person, t0) : [],+ const [changed, taggedRows, marks, threadMarks, settings] = await Promise.all([readChanged(tx, cached, tabId, from.since),+ person ? waitingTagRows(tx, tabId, person, t0) : [],person ? readMarkRows(tx, tabId, person, from.since) : [],person ? readThreadMarks(tx, tabId, person, from.since) : new Map<string, Map<string, number>>(),person ? readChatSettings(tx, tabId, person, from.since) : new Map<string, NotifyLevel>()])@@ -200,10 +207,10 @@ export class SwarmReads {// read against its conversation, quiet or not, and its readers alone learn of it. So is a conversation whose read mark// moved, so the mark goes only to a reader who can still read it.const held = new Set(base.groups.map(g => g.key))- const named = [...new Set([...tagged, ...[...changed.filter(p => p.kind === 'start'), ...extra].map(p => (p.data as AgentStart).request.conversationId),+ const named = [...new Set([...taggedRows.map(row => row.conversationId), ...[...changed.filter(p => p.kind === 'start'), ...extra].map(p => (p.data as AgentStart).request.conversationId),...marks.map(mark => mark.conversationId), ...threadMarks.keys(), ...settings.keys()])].filter(id => !held.has(id))const read = await this.load(tx, cached, user, tabId, asAgentId, t0, {},- async () => withStarts(withGroups(base, await readLightGroups(tx, cached, tabId, named)), extra))+ async () => withStarts(withGroups(base, await readLightGroups(tx, cached, tabId, named)), extra), taggedRows)const sent = changesFor(read.view, changed, read.actor, options.lightMachines ? { since: from.since } : undefined)// A changed project chat comes whole from the change feed, with its stored newest main row (servedTops.ts).if (!asAgentId) sent.groups = await this.servedTops.served(tabId, read.view.state, sent.groups)@@ -565,22 +572,43 @@ export class SwarmReads {* and only the read of the base parts on a miss is a transaction (cachedReads.ts). A Swarm still in one row is migrated* first, as a safety net for one the job did not see (design 6.1), and answers 503 while that cannot be done. */private async read<T>(user: AuthUser, tabId: string, body: (tx: PrismaClient, view: CacheView) => Promise<T>): Promise<T> {- // The row's format only: a migrated row still holds its old state, as large as the Swarm, until the owner drops it.- const row = await this.db.superTab.findFirst({ where: { id: tabId, autonomousEnv: user.autonomousEnv }, select: { format: true, deletedAt: true } })+ const row = await this.swarmRow(user, tabId)// A deleted Swarm reads as one that does not exist (deletion.ts).if (!row || row.deletedAt) fail('NOT_FOUND', 'This Super Tab is unavailable.', 404)if (row.format !== 2 && !(await migrateSwarm(this.db, tabId)).ok) fail(SWARM_MIGRATING.code, SWARM_MIGRATING.message, SWARM_MIGRATING.status)return body(this.db, await this.store.view([tabId]))}+ /** The row's format only: a migrated row still holds its old state, as large as the Swarm, until the owner drops it. */+ private swarmRow(user: AuthUser, tabId: string): Promise<SwarmRow | null> {+ const now = this.now(), key = JSON.stringify([user.autonomousEnv, tabId])+ const kept = this.swarmRows.get(key)+ if (kept && now >= kept.at && now - kept.at < SWARM_ROW_READS_MS) return kept.read+ if (kept) this.swarmRows.delete(key)+ // Entries are inserted in time order, so an expired prefix is enough to clear old Swarms on each request.+ for (const [old, entry] of this.swarmRows) {+ if (now >= entry.at && now - entry.at < SWARM_ROW_READS_MS) break+ this.swarmRows.delete(old)+ }+ const entry: SwarmRowRead = { at: now, read: this.db.superTab.findFirst({ where: { id: tabId, autonomousEnv: user.autonomousEnv },+ select: { format: true, deletedAt: true } }) }+ this.swarmRows.set(key, entry)+ while (this.swarmRows.size > MAX_SWARM_ROW_READS) this.swarmRows.delete(this.swarmRows.keys().next().value!)+ // A missing row or a failed read is not held: a newly created Swarm and a recovered database answer on the next request.+ entry.read.then(row => { if (!row && this.swarmRows.get(key) === entry) this.swarmRows.delete(key) }, () => {+ if (this.swarmRows.get(key) === entry) this.swarmRows.delete(key)+ })+ return entry.read+ }+private async load(tx: PrismaClient, cached: CacheView, user: AuthUser, tabId: string, asAgentId: string | undefined, t0: number, opts: LoadOptions,- loader: Loader = (view, id, named) => readParts(tx, view, id, named)): Promise<Read> {+ loader: Loader = (view, id, named) => readParts(tx, view, id, named), waitingRows?: WaitingTagRow[]): Promise<Read> {const loaded = await loader(cached, tabId, opts)const state = parts.reassemble(loaded, { share: true })const actor = await this.store.actor(tx, user, state, asAgentId)const [[teamMachines, otherWorkspaceMachines, machineVersions, joiningTeams], counts, newest] = await Promise.all([this.machineLookups(state),- actor.kind === 'person' ? Promise.all([waitingMentions(tx, tabId, state, actor, t0), decisionsWaiting(tx, tabId, state, actor),+ actor.kind === 'person' ? Promise.all([waitingMentions(tx, tabId, state, actor, t0, waitingRows), decisionsWaiting(tx, tabId, state, actor),activityDigest(tx, tabId, actor.userId, t0), remindersDigest(tx, tabId, actor.userId)]) : undefined,readLastChangedAt(tx, cached, tabId),])diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex e71b15045..6b05433ac 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1,6 +1,6 @@import { refusalLogFields, type DeclaredClient } from './refusalLog.js'import { writeReactionActivity, writeReplyActivity } from './activity.js'-import { phoneNotices, type ReplyRow, type TagRow } from '../push/notices.js'+import { phoneNotices, type DecisionRow, type ReplyRow, type TagRow } from '../push/notices.js'import type { PhoneNotice } from '../push/sender.js'import { joiningTeamMacs, type TeamMachineRow, accountMachineName, availableSlots, expireRemovals, followAccountName, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, slotCounter, machineTeamWork, preparableStart, readingOnly, refusableStart, recordAgentPresence, renamedBy, removalPreview, startPreparing, storedObservation, swarmGridRow, teamAccountRequired, teamWorkRefusal, ownAccountWork, ownAccountNote, type MachineObservation } from './machines.js'import { expireAccess } from './machineAccess.js'@@ -2074,6 +2074,9 @@ export class SuperTabStore {if (effects.decisions) {const ids = await writeDecisions(tx, tabId, effects.decisions, context.now)if (command.type === 'decision.ask') effects.result.decisionIds = ids+ // A decision new in this write reaches its person's phones (task #3248); one asked again is the open one, told already.+ const asked = effects.decisions.filter((draft, i) => ids[i] === draft.id)+ this.tellPhones(tx, tabId, effects.state, { replies: [], tags: [], decisions: asked }, [])}if (effects.decisionAnswer) await recordAnswer(tx, tabId, effects.decisionAnswer, context.now)// Work this command ended (done, cancelled, archived) closes the decisions still waiting there (Dee, 10-31). After this@@ -4608,9 +4611,10 @@ export class SuperTabStore {}/** The phones of whoever `written` tells hear of it once the write commits (push/send.ts). */- private tellPhones(tx: Transaction, tabId: string, state: SuperTabState, written: { replies: ReplyRow[]; tags: TagRow[] }, messages: MessageDraft[]): void {+ private tellPhones(tx: Transaction, tabId: string, state: SuperTabState, written: { replies: ReplyRow[]; tags: TagRow[]; decisions?: DecisionRow[] },+ messages: MessageDraft[]): void {const tell = this.hooks.phoneNotices- if (!tell || (!written.replies.length && !written.tags.length)) return+ if (!tell || (!written.replies.length && !written.tags.length && !written.decisions?.length)) return// A notice is never worth a write: one that cannot be made is logged and the write goes on (security review 2).let notices: PhoneNotice[]try {diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex b155f840e..337e69e35 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -5314,6 +5314,7 @@ class AppNotifier extends ChangeNotifier {activeSwarm.arrangedKey = null;notifyListeners();_persistLayout();+ _personArranged(activeSwarm);}int _paneResizeRequest = 0;@@ -5381,17 +5382,37 @@ class AppNotifier extends ChangeNotifier {return false;}if (identical(activeSwarm.paneSizes[layoutKey], arrangement)) {- if (persist) _persistLayout();+ if (persist) {+ _persistLayout();+ _personArranged(activeSwarm);+ }return true;}activeSwarm.savePaneSizes(layoutKey, arrangement);activeSwarm.arranged = arrangement;_paneLayoutRequest++;notifyListeners();- if (persist) _persistLayout();+ if (persist) {+ _persistLayout();+ _personArranged(activeSwarm);+ }return true;}+ final _arrangedListeners = <void Function(Swarm)>[];++ /// [listener] hears each time the person arranged a tab's panes: a+ /// finished divider drag or a preset chosen (a Personal project keeps its+ /// own sizes, task #3099).+ void addArrangedListener(void Function(Swarm) listener) =>+ _arrangedListeners.add(listener);++ void _personArranged(Swarm swarm) {+ for (final listener in _arrangedListeners.toList()) {+ listener(swarm);+ }+ }+void resetPaneSizes() {setPreset(panes.length, presetFor(panes.length) ?? PanePreset.auto);}@@ -14276,6 +14297,7 @@ class AppNotifier extends ChangeNotifier {// A Swarm's tab keeps the Swarm's name (task #2647).if (!tab.nameIsCustom &&!tab.isSuperTab &&+ !tab.isProjectTab &&tab.titleMachineId == machine.machine.machineId &&tab.titleAgentId == agent.id) {final title = Swarm.titleFor(agent);@@ -20209,6 +20231,41 @@ class AppNotifier extends ChangeNotifier {notifyListeners();}+ /// A saved arrangement for Swarm tab [swarmId]'s [count] panes (a Personal+ /// project's own, kept on this computer): what [copySuperTabLayout] takes+ /// from a tab, from a record instead.+ void applySuperTabLayout(+ String swarmId, {+ required int count,+ PanePreset? preset,+ Map<String, PaneArrangement> sizes = const {},+ String? arrangedKey,+ int? gridColumns,+ }) {+ final tab = swarms+ .where((s) => s.id == swarmId && s.isSuperTab)+ .firstOrNull;+ if (tab == null || _disposed || tab.panes.length != count) return;+ final prefix = '$count:';+ tab.presets.remove(count);+ if (preset != null && preset.supportsCount(count)) {+ tab.presets[count] = preset;+ }+ tab.paneSizes.removeWhere((key, _) => key.startsWith(prefix));+ for (final MapEntry(:key, :value) in sizes.entries) {+ if (key.startsWith(prefix) && value.tiles.length == count) {+ tab.paneSizes[key] = value;+ }+ }+ final arranged = arrangedKey == null ? null : tab.paneSizes[arrangedKey];+ tab.arranged = arranged;+ tab.arrangedKey = arranged == null ? null : arrangedKey;+ tab.gridColumns = gridColumns;+ _paneLayoutRequest++;+ _persistLayout();+ notifyListeners();+ }+void reserveSuperTabPane(String swarmId, String machineId, String harnessId) {final tab = swarms.where((s) => s.id == swarmId && s.superTabId != null)@@ -20518,6 +20575,7 @@ class AppNotifier extends ChangeNotifier {if (firstAgent &&!target.nameIsCustom &&!target.isSuperTab &&+ !target.isProjectTab &&!target.isCompanions &&!target.isDevices) {final agent = machine.agents@@ -21294,6 +21352,7 @@ class AppNotifier extends ChangeNotifier {if (firstAgent &&!target.nameIsCustom &&!target.isSuperTab &&+ !target.isProjectTab &&pane.agentId != null) {final agent = machineStates[pane.machineId]?.agents.where((agent) => agent.id == pane.agentId)@@ -21453,6 +21512,41 @@ class AppNotifier extends ChangeNotifier {bool _deskTracks(Swarm swarm) =>swarm.kind == 'harness' && !isDraftSwarm(swarm.id);+ /// The most tabs the desk keeps (backend `DESK_MAX_TABS`): it drops a 25th+ /// without an error, so a caller that adds one checks first.+ static const deskMaxTabs = 24;++ /// How many of this window's tabs the desk holds.+ int get deskTabCount => swarms.where(_deskTracks).length;++ /// Tab [id] takes [name] without it becoming the person's: a Personal+ /// project's tab following its project's rename. A name the person chose+ /// stays.+ void renameTabAutomatically(String id, String name) {+ final swarm = swarms.where((s) => s.id == id).firstOrNull;+ final clean = name.trim();+ if (swarm == null || swarm.nameIsCustom || clean.isEmpty) return;+ final next = clean.length > 80 ? clean.substring(0, 80) : clean;+ if (swarm.name == next) return;+ swarm.name = next;+ _persistLayout();+ notifyListeners();+ }++ /// Tab [id] named [name], made in the background when it is not here yet:+ /// the tab on screen stays, and the name is not the person's, so it may+ /// follow what it is named after (a Personal project's own tab, task+ /// #3099). It reaches the desk as any new tab does.+ Swarm ensureBackgroundTab(String id, String name) {+ final existing = swarms.where((s) => s.id == id).firstOrNull;+ if (existing != null) return existing;+ final swarm = Swarm(id: id, name: name, nameIsCustom: false);+ swarms.add(swarm);+ _persistLayout();+ notifyListeners();+ return swarm;+ }+/// `swarms` as the desk would hold them.List<DeskTab> _deskProjection() => [for (final swarm in swarms)diff --git a/desktop/lib/state/swarm.dart b/desktop/lib/state/swarm.dartindex 0ea9ce85b..b367eacff 100644--- a/desktop/lib/state/swarm.dart+++ b/desktop/lib/state/swarm.dart@@ -5,6 +5,12 @@ import 'pane_preset.dart';import 'pane_arrangement.dart';import 'terminal_pane.dart';+/// A Personal project's own desk tab id: `project-`, 24 hex characters of+/// the project id's hash, then `-2`, `-3` for its further tabs.+final kProjectTabId = RegExp(+ r'^(project-[0-9a-f]{24})(?:-([2-9]|[1-9][0-9]+))?$',+);+/// A named arrangement of agents. Membership never owns the agent process./// Shared agents reuse the same pane/session across swarms, so the daemon has/// exactly one controller and switching tabs cannot take over our own stream.@@ -43,6 +49,10 @@ class Swarm {bool get isCompanions => kind == 'companions';bool get isDevices => kind == 'devices';bool get isUtility => isStore || isCompanions || isDevices;++ /// A Personal project's own tab (super_tabs/personal_projects.dart, task+ /// #3099): it is named after its project, never after a harness in it.+ bool get isProjectTab => kProjectTabId.hasMatch(id);bool get isOrchestrator =>kind == 'orchestrator' &&orchestratorId != null &&diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dartindex f4829cec5..028d1b767 100644--- a/desktop/lib/super_tabs/launch.dart+++ b/desktop/lib/super_tabs/launch.dart@@ -6,6 +6,7 @@ import 'package:flutter/foundation.dart' show visibleForTesting;import 'package:path/path.dart' as p;import '../core/first_task.dart';+import '../logging/app_log.dart';import '../core/models.dart';import '../state/app_state.dart';import '../state/harness_attachments.dart';@@ -18,6 +19,7 @@ import 'controller.dart';import 'machine_icon.dart';import 'machine_status.dart';import 'model.dart';+import 'personal_projects.dart' show PersonalProjects;import 'launch_prompt.dart';import 'identity.dart' show superTabMachineName;import 'instructions_model.dart';@@ -817,8 +819,30 @@ class SuperTabLaunch {checkAccount();}+ /// A Personal start whose pane would need a tab the full desk cannot hold+ /// is refused here, before any agent runs (task #3099). A start already+ /// asked for is not: its agent may be running. A Product Manager started+ /// on a Swarm machine ([startInSwarm]) puts no pane on this desk, so it+ /// needs no tab.+ void refuseFullDesk() {+ if (started) return;+ final refusal = PersonalProjects.of(app).startRefusal(+ saved['tabId'] as String?,+ saved['conversationId'] as String?,+ newProject:+ saved['newProject'] == true && saved['projectPrepared'] != true,+ );+ if (refusal != null) {+ // Said in the log by its code alone: how often a full desk stops a+ // start is what warns that the desk's 24 tabs are near.+ appLog.warn('super-tabs', 'Personal start refused (TABS_FULL)');+ throw SuperTabFailure('TABS_FULL', refusal);+ }+ }+Future<String> prepare(String machine, String task) async {checkAccount();+ refuseFullDesk();if (app.stateOf(machine)?.belongsToOtherAccount == true) {throw const SuperTabFailure('CONTRIBUTION_REQUIRED',@@ -1099,6 +1123,20 @@ class SuperTabLaunch {saved['visibility'] == 'private' ? 'Swarm' : saved['title'] as String,);}+ // The pane goes to its project's own tab in Personal (task #3099). A+ // failure there never undoes the join: the agent is in its project.+ if (controller.snapshot?.projectFor(saved['conversationId'] as String)+ case final project?) {+ try {+ await PersonalProjects.of(app)+ .placeInProjectTab(controller, project.id, machine, harnessId);+ } catch (error) {+ appLog.warn(+ 'super-tabs',+ 'Personal project tab placement failed (${error.runtimeType})',+ );+ }+ }controller.select(saved['conversationId'] as String);await app.superTabs.storage.delete(key);}diff --git a/desktop/lib/super_tabs/personal_projects.dart b/desktop/lib/super_tabs/personal_projects.dartindex c97bb420c..c9d8edb96 100644--- a/desktop/lib/super_tabs/personal_projects.dart+++ b/desktop/lib/super_tabs/personal_projects.dart@@ -7,6 +7,9 @@ import 'package:flutter/foundation.dart';import '../logging/app_log.dart';import '../state/app_state.dart';+import '../state/pane_arrangement.dart';+import '../state/pane_layout_store.dart';+import '../state/pane_preset.dart';import '../state/swarm.dart';import '../state/terminal_pane.dart';import 'controller.dart';@@ -127,14 +130,69 @@ String personalProjectOperation(String key) => _isTab(key)bool _isTab(String key) => key.startsWith('tab:');+/// A Personal project's own desk tab (task #3099, migration plan Phase 1):+/// `project-` and a hash of the project's id, the same on every computer, so+/// each finds the project a tab belongs to by hashing the projects Personal+/// lists. A project with more than 9 panes gets a second tab, `-2`, then `-3`.+/// It fits the desk's id rule (backend `lib/desk.ts`).+String personalProjectTabId(String projectId, [int number = 1]) {+ // Views read it while they build: each project's hash is worked out once.+ if (_projectTabIds.length > 512) _projectTabIds.clear();+ final base = _projectTabIds[projectId] ??=+ 'project-${_hash('project:$projectId')}';+ return number <= 1 ? base : '$base-$number';+}++final _projectTabIds = <String, String>{};++/// [tabId] as a project tab: its first tab's id and its number (1 for the+/// first), or null for any other tab.+({String base, int number})? personalProjectTabParts(String tabId) {+ final match = kProjectTabId.firstMatch(tabId);+ if (match == null) return null;+ final number = match.group(2);+ return (+ base: match.group(1)!,+ number: number == null ? 1 : int.parse(number),+ );+}++/// What the person reads when a start needs a tab and the desk is full+/// (migration plan, Phase 1 item 2).+const kTabsFullMessage =+ 'Your tabs are full (24). Close a tab to start another agent.';++/// A project tab's name: the project's, then "api 2", "api 3", within the+/// desk's 80 characters.+String projectTabName(String projectName, int number) {+ final suffix = number <= 1 ? '' : ' $number';+ var name = projectName.trim();+ if (name.isEmpty) name = kTabProjectName;+ if (name.length + suffix.length > 80) {+ name = name.substring(0, 80 - suffix.length).trimRight();+ }+ return '$name$suffix';+}++/// Whether [key] is the project key of a project tab's no-repo panes: their+/// project is the tab's own, never one made for the tab.+bool _isProjectTab(String key) =>+ _isTab(key) && personalProjectTabParts(key.substring(4)) != null;+/// One of the person's panes, the tab it is first in, and its project's key:/// its repo, or [personalTabKey] of its tab for none.typedef PersonalPane = ({Swarm tab, TerminalPane pane, String repo});/// The person's own panes in their tabs, in tab order then each tab's reading/// order, each once. Swarm tabs, viewers and panes on another person's or a-/// shared machine, or on a Harness Team account, are left out.-List<PersonalPane> personalPanes(AppNotifier app) {+/// shared machine, or on a Harness Team account, are left out. A pane in the+/// own tab of a project Personal lists ([projectTabs], their first tabs' ids)+/// is that project's whatever its repo: it was started there (Reed's review+/// of #3090).+List<PersonalPane> personalPanes(+ AppNotifier app, {+ Set<String> projectTabs = const {},+}) {final seen = <(String, String)>{};final out = <PersonalPane>[];for (final tab in app.swarms) {@@ -158,10 +216,11 @@ List<PersonalPane> personalPanes(AppNotifier app) {pane: pane,// The repo an SSH alias stands for first, so a clone through// `Host gh-work` and one straight from GitHub are one (task #2476).- repo:- normalizedRemote(project?.repository) ??- normalizedRemote(project?.remote) ??- personalTabKey(tab.id),+ repo: projectTabs.contains(personalProjectTabParts(tab.id)?.base)+ ? personalTabKey(tab.id)+ : normalizedRemote(project?.repository) ??+ normalizedRemote(project?.remote) ??+ personalTabKey(tab.id),));}}@@ -172,7 +231,9 @@ List<PersonalPane> personalPanes(AppNotifier app) {/// made once, remembered on this computer, and found again by the same/// request on another.class PersonalProjects extends ChangeNotifier {- PersonalProjects._(this.app);+ PersonalProjects._(this.app) {+ app.addArrangedListener(_arranged);+ }static final _of = Expando<PersonalProjects>();static PersonalProjects of(AppNotifier app) =>_of[app] ??= PersonalProjects._(app);@@ -192,6 +253,15 @@ class PersonalProjects extends ChangeNotifier {/// Repos renamed to their long name, per account and Swarm.final _renamed = <String, Map<String, Set<String>>>{};++ /// Each project's own split sizes, per account and Swarm: project id to+ /// the arrangement the person gave its panes here. Kept on this computer+ /// only, beside the project map, and never sent (task #3099).+ final _layouts = <String, Map<String, Map<String, Map<String, dynamic>>>>{};++ /// The order Personal first saw its projects in the tabs, per account and+ /// Swarm (migration plan, Phase 1 item 5): its PROJECTS list can start so.+ final _order = <String, Map<String, List<String>>>{};final _loads = <String, Future<void>>{};final _syncing = <String>{};final _again = <String>{};@@ -236,13 +306,239 @@ class PersonalProjects extends ChangeNotifier {final project = snapshot.projectFor(conversationId);if (project == null) return const [];final repos = _reposOf(c.accountId, c.tabId, project.id);- if (repos.isEmpty) return const [];+ final ownTab = personalProjectTabId(project.id);return [- for (final entry in personalPanes(app))- if (repos.contains(entry.repo)) entry.pane,+ for (final entry in personalPanes(app, projectTabs: _projectTabs(c)))+ if (repos.contains(entry.repo) ||+ (_isProjectTab(entry.repo) &&+ personalProjectTabParts(entry.repo.substring(4))?.base ==+ ownTab))+ entry.pane,];}+ /// The first-tab ids of the projects [c] lists ([personalProjectTabId]).+ Set<String> _projectTabs(SuperTabController c) => {+ for (final p in c.snapshot?.projects ?? const <SuperTabProject>[])+ personalProjectTabId(p.id),+ };++ /// The project of Personal whose own tab [tabId] is ([personalProjectTabId]),+ /// or null: another kind of tab, or a project Personal does not list.+ SuperTabProject? projectOfTab(SuperTabController c, String tabId) {+ if (!eligible(c)) return null;+ final base = personalProjectTabParts(tabId)?.base;+ if (base == null) return null;+ return c.snapshot!.projects+ .where((p) => personalProjectTabId(p.id) == base)+ .firstOrNull;+ }++ /// Project [projectId]'s own tabs here, by number.+ List<(int, Swarm)> _tabsOf(String projectId) {+ final base = personalProjectTabId(projectId);+ return [+ for (final tab in app.swarms)+ if (!tab.isSuperTab && !tab.isUtility)+ if (personalProjectTabParts(tab.id)+ case (base: final b, :final number) when b == base)+ (number, tab),+ ]..sort((a, b) => a.$1.compareTo(b.$1));+ }++ /// Each project tab whose name the person did not choose takes its+ /// project's current name ("api 2" for the second).+ void _nameProjectTabs(SuperTabController c) {+ for (final tab in app.swarms.toList()) {+ if (tab.nameIsCustom || !tab.isProjectTab) continue;+ final project = projectOfTab(c, tab.id);+ final number = personalProjectTabParts(tab.id)?.number;+ if (project == null || number == null) continue;+ app.renameTabAutomatically(tab.id, projectTabName(project.name, number));+ }+ }++ /// The person arranged [view]'s panes: kept as the project's own when+ /// Personal shows one of its projects there ([rememberLayout]).+ void _arranged(Swarm view) {+ final id = view.superTabId;+ if (!view.isSuperTab || id == null || PersonalSwarm.of(app).id != id) {+ return;+ }+ final c = app.superTabs.peek(id);+ if (c == null) return;+ final chat = c.selectedId;+ if (!c.groupTerminalsOpen(chat) || c.terminalAgents(chat).isNotEmpty) {+ return;+ }+ rememberLayout(c, chat, view);+ }++ /// Keeps [view]'s arrangement as project [conversationId]'s own, on this+ /// computer only (migration plan, Phase 1 item 4): for a project whose+ /// panes are not exactly one tab's, which lends its sizes ([soleTab]).+ void rememberLayout(SuperTabController c, String conversationId, Swarm view) {+ if (!eligible(c) || !c.snapshot!.isProjectLead(conversationId)) return;+ final project = c.snapshot!.projectFor(conversationId);+ if (project == null) return;+ final panes = panesFor(c, conversationId);+ if (panes.isEmpty ||+ view.panes.length != panes.length ||+ soleTab(panes) != null) {+ return;+ }+ final count = panes.length, prefix = '$count:';+ ((_layouts[c.accountId] ??= {})[c.tabId] ??= {})[project.id] = {+ 'count': count,+ if (view.presets[count] case final preset?) 'preset': preset.id,+ 'sizes': {+ for (final MapEntry(:key, :value) in view.paneSizes.entries)+ if (key.startsWith(prefix)) key: value.toJson(),+ },+ if (view.arrangedKey case final key? when key.startsWith(prefix))+ 'arrangedKey': key,+ 'gridColumns': ?view.gridColumns,+ };+ // What this computer kept is read first, so the save keeps it.+ final account = c.accountId;+ unawaited(_load(account).then((_) => _save(account)));+ }++ /// Gives [view] project [conversationId]'s own arrangement, when the person+ /// made one here for this many panes; false otherwise (the view keeps its+ /// default).+ bool applyLayout(SuperTabController c, String conversationId, Swarm view) {+ if (!eligible(c)) return false;+ final project = c.snapshot!.projectFor(conversationId);+ if (project == null) return false;+ final saved = _layouts[c.accountId]?[c.tabId]?[project.id];+ final count = view.panes.length;+ if (saved == null || saved['count'] != count) return false;+ final sizes = <String, PaneArrangement>{};+ if (saved['sizes'] case final Map raw) {+ for (final MapEntry(:key, :value) in raw.entries) {+ final arrangement = PaneArrangement.fromJson(value);+ if (key is String && arrangement != null) sizes[key] = arrangement;+ }+ }+ app.applySuperTabLayout(+ view.id,+ count: count,+ preset: PanePreset.byId(saved['preset'] as String?),+ sizes: sizes,+ arrangedKey: saved['arrangedKey'] as String?,+ gridColumns: saved['gridColumns'] as int?,+ );+ return true;+ }++ /// The order Personal first saw its projects in the tabs: each project+ /// where its first pane was then, new ones after (migration plan, Phase 1+ /// item 5). Kept on this computer.+ List<String> projectOrder(SuperTabController c) =>+ List.unmodifiable(_order[c.accountId]?[c.tabId] ?? const <String>[]);++ /// Adds the projects of the panes now in the tabs that the order lacks, in+ /// tab order, and drops those gone from Personal; whether it changed.+ bool _noteOrder(SuperTabController c) {+ final order = (_order[c.accountId] ??= {})[c.tabId] ??= [];+ final projects = _projects(c.accountId, c.tabId);+ final listed = {for (final p in c.snapshot!.projects) p.id};+ final before = order.length;+ order.removeWhere((id) => !listed.contains(id));+ var changed = order.length != before;+ for (final entry in personalPanes(app, projectTabs: _projectTabs(c))) {+ final id = _isProjectTab(entry.repo)+ ? projectOfTab(c, entry.repo.substring(4))?.id+ : projects[entry.repo];+ if (id == null || !listed.contains(id) || order.contains(id)) continue;+ order.add(id);+ changed = true;+ }+ return changed;+ }++ /// A project gone from Personal takes its saved layout with it.+ void _dropGoneLayouts(SuperTabController c) {+ final saved = _layouts[c.accountId]?[c.tabId];+ if (saved == null || saved.isEmpty) return;+ final ids = {for (final p in c.snapshot!.projects) p.id};+ final before = saved.length;+ saved.removeWhere((id, _) => !ids.contains(id));+ if (saved.length != before) unawaited(_save(c.accountId));+ }++ /// A desk tab holds 9 harnesses (backend `DESK_MAX_PANES`); it drops a 10th+ /// without an error.+ static bool _hasRoom(Swarm tab) =>+ tab.panes.where((p) => p.agentId != null).length <+ PaneLayoutStore.maxPanes;++ /// Why a start in Personal's [conversationId] (a new project's when+ /// [newProject]) is refused before any agent runs, or null: its pane needs+ /// a tab, and the desk holds [AppNotifier.deskMaxTabs] already (migration+ /// plan, Phase 1 item 2). Never for another Swarm.+ String? startRefusal(+ String? tabId,+ String? conversationId, {+ bool newProject = false,+ }) {+ if (tabId == null || PersonalSwarm.of(app).id != tabId) return null;+ final c = app.superTabs.peek(tabId);+ if (c == null || !eligible(c)) return null;+ final projectId = newProject || conversationId == null+ ? null+ : c.snapshot!.projectFor(conversationId)?.id;+ if (projectId != null && _tabsOf(projectId).any((t) => _hasRoom(t.$2))) {+ return null;+ }+ return app.deskTabCount >= AppNotifier.deskMaxTabs+ ? kTabsFullMessage+ : null;+ }++ /// Puts the pane of the agent just started from Personal's project+ /// [projectId] in that project's own tab (migration plan, Phase 1 item 1),+ /// so the phone and older Desktops see it: the first with room, else the+ /// next, "api 2". The tab on screen stays. Nothing when the pane is in one+ /// already, or when the desk filled up since the start was checked (said+ /// in the log: the agent stays in its project).+ Future<void> placeInProjectTab(+ SuperTabController c,+ String projectId,+ String machineId,+ String agentId,+ ) async {+ if (!eligible(c)) return;+ final project = c.snapshot!.projectById(projectId);+ if (project == null) return;+ final tabs = _tabsOf(projectId);+ bool holds(Swarm tab) =>+ tab.panes.any((p) => p.machineId == machineId && p.agentId == agentId);+ if (tabs.any((t) => holds(t.$2))) return;+ var target = tabs.where((t) => _hasRoom(t.$2)).firstOrNull?.$2;+ if (target == null) {+ if (app.deskTabCount >= AppNotifier.deskMaxTabs) {+ appLog.warn('super-tabs', 'Personal project tab not made: desk full');+ return;+ }+ final number = tabs.isEmpty ? 1 : tabs.last.$1 + 1;+ target = app.ensureBackgroundTab(+ personalProjectTabId(projectId, number),+ projectTabName(project.name, number),+ );+ }+ await app.assignAgentToPane(+ null,+ machineId,+ agentId,+ swarmId: target.id,+ autoTile: true,+ focus: false,+ intent: AttachIntent.automatic,+ );+ }+/// Whether project [projectId] of [c] leaves the project list (Huy, 11-05,/// task #3042): one made for the person's panes, with none of them open/// now. Nothing about it changes on the server, so its chat is there when a@@ -262,7 +558,15 @@ class PersonalProjects extends ChangeNotifier {if (known == null || known.isEmpty || _unresolvedPanes(app)) {return const {};}- final shown = {for (final entry in personalPanes(app)) ?known[entry.repo]};+ // A pane in a listed project's own tab is that project's, as panesFor+ // reads it (#3090): counted for it, never for its repo.+ final shown = {+ for (final entry in personalPanes(app, projectTabs: _projectTabs(c)))+ if (_isProjectTab(entry.repo))+ ?projectOfTab(c, entry.repo.substring(4))?.id+ else+ ?known[entry.repo],+ };final snapshot = c.snapshot!;return {for (final id in known.values)@@ -315,7 +619,10 @@ class PersonalProjects extends ChangeNotifier {/// Personal lost: what this computer kept of its projects goes.void _forget(String account, String swarm) {- final had = _known[account]?.remove(swarm) != null;+ final had =+ (_known[account]?.remove(swarm) != null) |+ (_layouts[account]?.remove(swarm) != null) |+ (_order[account]?.remove(swarm) != null);_renamed[account]?.remove(swarm);// Called while a view builds: saved after, and no one is told now.if (had) unawaited(_save(account));@@ -344,6 +651,22 @@ class PersonalProjects extends ChangeNotifier {renamed.whereType<String>(),);}+ final order = entry['order'];+ if (order is List) {+ final kept = (_order[account] ??= {})[swarm] ??= [];+ for (final id in order.whereType<String>()) {+ if (!kept.contains(id)) kept.add(id);+ }+ }+ final layouts = entry['layouts'];+ if (layouts is Map) {+ final kept = (_layouts[account] ??= {})[swarm] ??= {};+ for (final MapEntry(:key, :value) in layouts.entries) {+ if (key is String && value is Map) {+ kept.putIfAbsent(key, () => Map<String, dynamic>.from(value));+ }+ }+ }}} catch (_) {// Nothing kept: each project is asked for again, and the server answers@@ -353,11 +676,20 @@ class PersonalProjects extends ChangeNotifier {Future<void> _save(String account) async {final known = _known[account] ?? const {};+ final layouts = _layouts[account] ?? const {};final value = jsonEncode({- for (final MapEntry(key: swarm, value: projects) in known.entries)+ for (final swarm in {+ ...known.keys,+ ...layouts.keys,+ ...?_order[account]?.keys,+ })swarm: {- 'projects': projects,+ 'projects': known[swarm] ?? const <String, String?>{},'renamed': [...?_renamed[account]?[swarm]],+ if (layouts[swarm] case final saved? when saved.isNotEmpty)+ 'layouts': saved,+ if (_order[account]?[swarm] case final order? when order.isNotEmpty)+ 'order': order,},});try {@@ -376,6 +708,7 @@ class PersonalProjects extends ChangeNotifier {if (c.accessRevoked) _forget(c.accountId, c.tabId);return;}+ _nameProjectTabs(c);final account = c.accountId, swarm = c.tabId;final scope = '$account/$swarm';if (!_syncing.add(scope)) {@@ -384,6 +717,7 @@ class PersonalProjects extends ChangeNotifier {}try {await _load(account);+ if (eligible(c)) _dropGoneLayouts(c);do {_again.remove(scope);if (!eligible(c)) return;@@ -391,11 +725,14 @@ class PersonalProjects extends ChangeNotifier {// Each project's name: the repo's own, or its tab's name, given once its// project is made (a later rename of the tab keeps the project, and its// name).+ // A project tab's no-repo panes are its project's (panesFor): no+ // project is made for that tab, on any computer.final wanted = <String, String>{- for (final p in personalPanes(app))- p.repo: _isTab(p.repo)- ? tabProjectName(p.tab.name)- : repoName(p.repo),+ for (final p in personalPanes(app, projectTabs: _projectTabs(c)))+ if (!_isProjectTab(p.repo))+ p.repo: _isTab(p.repo)+ ? tabProjectName(p.tab.name)+ : repoName(p.repo),};var made = false;for (final MapEntry(key: repo, value: name) in wanted.entries) {@@ -421,6 +758,7 @@ class PersonalProjects extends ChangeNotifier {if (await _nameTabs(c, wanted) && eligible(c)) await _reread(c);if (!eligible(c)) return;if (await _tellApart(c) && eligible(c)) await _reread(c);+ if (eligible(c) && _noteOrder(c)) await _save(account);} while (_again.contains(scope));} finally {_syncing.remove(scope);diff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dartindex 11c045b95..9526fcab8 100644--- a/desktop/lib/super_tabs/workspace.dart+++ b/desktop/lib/super_tabs/workspace.dart@@ -233,8 +233,13 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {);}if (current() && agents.isEmpty && tab != null) {- if (PersonalProjects.of(app).soleTab(local) case final source?) {+ final personal = PersonalProjects.of(app);+ if (personal.soleTab(local) case final source?) {app.copySuperTabLayout(swarmId, source);+ } else if (local.isNotEmpty) {+ // Panes from several tabs: the sizes the person gave this+ // project on this computer, if any (task #3099).+ personal.applyLayout(controller, request.$2, tab);}}if (current()) {diff --git a/desktop/test/personal_project_tabs_test.dart b/desktop/test/personal_project_tabs_test.dartnew file mode 100644index 000000000..8af9c0479--- /dev/null+++ b/desktop/test/personal_project_tabs_test.dart@@ -0,0 +1,722 @@+// Tabs to Personal Swarm, Phase 1 (task #3099; plan+// docs/plans/2026-11-04-tabs-to-personal-swarm-migration.md): a project that+// starts an agent gets its own desk tab, the one link from tab to project on+// every computer.+import 'dart:convert';+import 'dart:io' show Platform;++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/state/new_harness.dart';+import 'package:harness/state/pane_arrangement.dart';+import 'package:harness/state/swarm.dart';+import 'package:harness/state/terminal_pane.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/launch.dart';+import 'package:harness/super_tabs/personal_projects.dart';+import 'package:harness/super_tabs/swarm_switcher.dart';+import 'package:harness/widgets/desktop_workspace_tab.dart';+import 'package:harness/widgets/new_harness_form.dart';++import 'support/capture.dart';+import 'super_tab_launch_test.dart'+ show SuperTabLaunchFixture, tabId, withCoordinator;++/// Set to a folder to write the PR's pictures there.+final _shots = Platform.environment['PROJECT_TABS_SHOTS'];++/// The desk's id rule (backend `lib/desk.ts`).+final _deskId = RegExp(r'^[A-Za-z0-9_-]{1,64}$');++Agent _agent(String id, {String? remote, String cwd = '/work/x'}) => Agent(+ id: id,+ name: 'Agent $id',+ engine: 'codex',+ terminalAvailable: true,+ project: AgentProject(+ name: cwd.split('/').last,+ cwd: cwd,+ root: remote == null ? null : cwd,+ remote: remote,+ ),+);++var _paneIds = 7000;+TerminalPane _pane(String machineId, String agentId) =>+ TerminalPane(id: _paneIds++, machineId: machineId, agentId: agentId);++Swarm _tab(+ AppNotifier app,+ String id,+ List<TerminalPane> panes, {+ String? name,+ bool? nameIsCustom,+}) {+ // A name given here is automatic unless said otherwise.+ final tab = Swarm(+ id: id,+ name: name ?? id,+ nameIsCustom: nameIsCustom ?? false,+ )..panes.addAll(panes);+ app.swarms.add(tab);+ return tab;+}++List<Map<String, dynamic>> _commands(+ SuperTabLaunchFixture f, [+ String type = 'project.create',+]) => [+ for (final post in f.connection.server.posts)+ if ((post['command'] as Map?)?['type'] == type)+ Map<String, dynamic>.from(post),+];++/// The fixture's Swarm as the person's Personal one, theirs alone.+Future<SuperTabController> _personal(SuperTabLaunchFixture f) async {+ for (final state in f.app.machineStates.values) {+ state.localOnly = true;+ }+ f.connection.server.state+ ..['name'] = 'Personal'+ ..['ownerId'] = 'owner'+ ..['people'] = [+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},+ ];+ await f.app.superTabs.storage.write('super_tab.personal.owner', tabId);+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Personal');+ PersonalSwarm.of(f.app).id;+ for (var i = 0; i < 20; i++) {+ await Future<void>.microtask(() {});+ }+ expect(PersonalSwarm.of(f.app).id, tabId);+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ return c;+}++/// Personal with one project of the person's, `api`, made on the server+/// before (its id is the server's).+Future<({SuperTabController c, String project, String chat})> _withApi(+ SuperTabLaunchFixture f, {+ Map<String, dynamic>? copyOf,+}) async {+ if (copyOf != null) {+ f.connection.server.state+ ..['projects'] = jsonDecode(jsonEncode(copyOf['projects']))+ ..['conversations'] = jsonDecode(jsonEncode(copyOf['conversations']));+ }+ final c = await _personal(f);+ if (copyOf == null) {+ await c.request(+ 'POST',+ '/api/super-tabs/$tabId/commands',+ body: {+ 'operationId': 'make-api',+ 'command': {+ 'type': 'project.create',+ 'name': 'api',+ 'visibility': 'private',+ 'brief': '',+ },+ },+ );+ await c.refresh();+ }+ final api = c.snapshot!.projects.firstWhere((p) => p.name == 'api');+ return (c: c, project: api.id, chat: api.leadConversationId);+}++/// New Harness from the chat [chat] of the Swarm on screen, as its project's+/// "add agent" opens it.+Future<NewHarnessController> _boxIn(+ SuperTabLaunchFixture f,+ String chat,+) async {+ final integration = await SuperTabLaunch.open(f.app, f.app.activeSwarm, chat);+ final box = NewHarnessController(+ f.app,+ machineId: 'm',+ engine: 'codex',+ folder: '/work/project',+ task: 'Fix the login page.',+ integration: integration,+ );+ addTearDown(box.dispose);+ await Future<void>.delayed(Duration.zero);+ return box;+}++/// Ordinary tabs until the desk holds [count] (the desk's tabs: every+/// harness tab that is not a draft).+void _fillDesk(SuperTabLaunchFixture f, int count) {+ var i = 0;+ while (f.app.deskTabCount < count) {+ _tab(f.app, 'desk-fill-${i++}', []);+ }+}++bool _started(SuperTabLaunchFixture f) =>+ f.connection.calls.any((c) => c.$1 == 'agent_create');++void main() {+ setUpAll(() => loadCaptureFonts(_shots));++ for (final brightness in Brightness.values) {+ testWidgets('pictures: a project tab beside ordinary tabs, and a full '+ 'desk, in ${brightness.name}', (tester) async {+ if (_shots == null) return;+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ tester.view.devicePixelRatio = 2;+ // The tab strip first: a window as tall as the strip.+ tester.view.physicalSize = const Size(1440, 80);+ addTearDown(tester.view.reset);+ final f = SuperTabLaunchFixture();+ final api = await tester.runAsync(() async {+ f.app.machineStates['m']!.agents = [+ _agent('c1', remote: 'https://github.com/acme/web', cwd: '/w/web'),+ ];+ _tab(f.app, 'desk-code', [_pane('m', 'c1')], name: 'web');+ final api = await _withApi(f);+ final box = await _boxIn(f, api.chat);+ expect(await box.create(), NewHarnessOutcome.created);+ return api;+ });+ final tabs = [+ for (final s in f.app.swarms)+ if (!s.isSuperTab && s.kind == 'harness') s.name,+ ];+ expect(tabs, containsAll(['web', 'api']));+ final shortcuts = ValueNotifier(false);+ addTearDown(shortcuts.dispose);+ Widget strip(List<String> names, String selected) => Container(+ height: 40,+ color: grid.AppPalette.panelBg,+ child: Row(+ children: [+ for (final name in names)+ SizedBox(+ width: 180,+ child: DesktopWorkspaceTab(+ id: name,+ label: name,+ selected: name == selected,+ showShortcuts: shortcuts,+ onSelect: () {},+ onClose: () {},+ ),+ ),+ ],+ ),+ );+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ strip(['Personal', ...tabs], 'Personal'),+ ],+ ),+ ),+ ),+ );+ await tester.pump();+ await captureWindow(tester, _shots, 'project-tab-${brightness.name}');+ tester.view.physicalSize = const Size(1800, 1100);++ // The api tab holds 9, and the desk 24: the next start has nowhere.+ f.app.swarms+ .firstWhere((t) => t.id == personalProjectTabId(api!.project))+ .panes+ .addAll([for (var i = 0; i < 8; i++) _pane('m', 'more-$i')]);+ _fillDesk(f, 24);+ final full = await tester.runAsync(() async {+ final box = await _boxIn(f, api!.chat);+ expect(await box.create(), NewHarnessOutcome.failed);+ return box;+ });+ expect(full!.error, kTabsFullMessage);+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: SizedBox(+ width: 900,+ height: 550,+ child: NewHarnessForm(+ controller: full,+ onClose: () {},+ onCreated: () {},+ desktop: true,+ embedded: true,+ ),+ ),+ ),+ ),+ );+ for (var i = 0; i < 5; i++) {+ await tester.pump(const Duration(milliseconds: 20));+ }+ await captureWindow(tester, _shots, 'tabs-full-${brightness.name}');+ await tester.pumpWidget(const SizedBox());+ f.app.superTabs.dispose();+ await tester.pump();+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));+ }++ group('a project tab id', () {+ test('is made from the project id alone and fits the desk', () {+ final id = personalProjectTabId('project-7');+ expect(id, startsWith('project-'));+ expect(id, matches(_deskId));+ expect(personalProjectTabId('project-7'), id);+ expect(personalProjectTabId('project-8'), isNot(id));+ expect(personalProjectTabId('project-7', 2), '$id-2');+ expect(personalProjectTabId('project-7', 3), matches(_deskId));+ expect(personalProjectTabParts(id), (base: id, number: 1));+ expect(personalProjectTabParts('$id-3'), (base: id, number: 3));+ expect(personalProjectTabParts('desk-code'), isNull);+ expect(personalProjectTabParts('project-abc'), isNull);+ expect(personalProjectTabParts('$id-1'), isNull);+ });++ test('links a no-repo pane in it to its project on every computer, and no '+ 'computer makes a project for that tab', () async {+ final one = SuperTabLaunchFixture();+ final first = await _withApi(one);+ final two = SuperTabLaunchFixture();+ final second = await _withApi(two, copyOf: one.connection.server.state);+ expect(second.project, first.project);+ final tabOnBoth = personalProjectTabId(first.project);+ final made = <int>[];+ for (final (f, c, chat) in [+ (one, first.c, first.chat),+ (two, second.c, second.chat),+ ]) {+ f.app.machineStates['m']!.agents = [+ _agent('notes', cwd: '/Users/me/notes'),+ ];+ final pane = _pane('m', 'notes');+ _tab(f.app, tabOnBoth, [pane], name: 'api');+ final before = _commands(f).length;+ await PersonalProjects.of(f.app).sync(c);+ made.add(_commands(f).length - before);+ expect(+ PersonalProjects.of(f.app).projectOfTab(c, tabOnBoth)?.id,+ first.project,+ );+ expect(PersonalProjects.of(f.app).panesFor(c, chat), [pane]);+ expect(+ PersonalProjects.of(f.app).knownForTest('owner', tabId).keys,+ isNot(contains(personalTabKey(tabOnBoth))),+ );+ }+ expect(made, [0, 0]);+ });++ test('of a project Personal does not list makes no project, and an '+ 'ordinary tab keeps its own project', () async {+ final f = SuperTabLaunchFixture();+ final api = await _withApi(f);+ f.app.machineStates['m']!.agents = [+ _agent('a', cwd: '/Users/me/a'),+ _agent('b', cwd: '/Users/me/b'),+ ];+ final stray = personalProjectTabId('gone');+ _tab(f.app, stray, [_pane('m', 'a')], name: 'old');+ _tab(f.app, 'desk-code', [_pane('m', 'b')], name: 'code');+ final before = _commands(f).length;+ await PersonalProjects.of(f.app).sync(api.c);+ final created = _commands(f).skip(before).toList();+ expect(created, hasLength(1));+ expect(+ PersonalProjects.of(f.app).knownForTest('owner', tabId).keys,+ allOf(+ contains(personalTabKey('desk-code')),+ isNot(contains(personalTabKey(stray))),+ ),+ );+ expect(PersonalProjects.of(f.app).projectOfTab(api.c, stray), isNull);+ });+ });++ group('a full desk', () {+ test('refuses a start from a Personal project before any agent runs, '+ 'and lets it go once a tab is closed', () async {+ final f = SuperTabLaunchFixture();+ final api = await _withApi(f);+ _fillDesk(f, 24);+ final box = await _boxIn(f, api.chat);+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.error, kTabsFullMessage);+ expect(+ kTabsFullMessage,+ 'Your tabs are full (24). Close a tab to start another agent.',+ );+ expect(_started(f), isFalse);+ expect(f.connection.joins, isEmpty);+ f.app.swarms.removeWhere((s) => s.id == 'desk-fill-0');+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);+ expect(_started(f), isTrue);+ });++ test('takes the start when the project\'s tab still has room', () async {+ final f = SuperTabLaunchFixture();+ final api = await _withApi(f);+ _tab(f.app, personalProjectTabId(api.project), [+ for (var i = 0; i < 8; i++) _pane('m', 'old-$i'),+ ], name: 'api');+ _fillDesk(f, 24);+ final box = await _boxIn(f, api.chat);+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);+ });++ test('refuses a new Personal project at 24 tabs, and never refuses in '+ 'another Swarm', () async {+ final f = SuperTabLaunchFixture();+ await _withApi(f);+ _fillDesk(f, 24);+ final integration = await SuperTabLaunch.open(+ f.app,+ f.app.activeSwarm,+ 'new-project',+ newProject: true,+ );+ final box = NewHarnessController(+ f.app,+ machineId: 'm',+ engine: 'codex',+ folder: '/work/project',+ task: 'A new thing.',+ integration: integration,+ );+ addTearDown(box.dispose);+ await Future<void>.delayed(Duration.zero);+ if (integration.leadMachines?.any((m) => m.id == 'm' && m.startable) ??+ false) {+ box.chooseLeadMachine('m');+ }+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.error, kTabsFullMessage);+ expect(+ _commands(f).where((p) => p['operationId'] != 'make-api'),+ isEmpty,+ );++ final team = SuperTabLaunchFixture();+ withCoordinator(team);+ team.app.bindSuperTab(team.app.activeSwarmId, tabId, 'Company');+ _fillDesk(team, 24);+ final other = await team.box();+ expect(+ await other.create(),+ NewHarnessOutcome.created,+ reason: other.error,+ );+ });+ });++ group('a start from a Personal project', () {+ test('lands in the project\'s own tab, named after it, on the desk, '+ 'without leaving the tab on screen', () async {+ final f = SuperTabLaunchFixture();+ final api = await _withApi(f);+ final shown = f.app.activeSwarmId;+ final box = await _boxIn(f, api.chat);+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);+ await Future<void>.delayed(Duration.zero);+ final tab = f.app.swarms+ .where((s) => s.id == personalProjectTabId(api.project))+ .single;+ expect(tab.name, 'api');+ expect(tab.nameIsCustom, isFalse);+ expect(tab.kind, 'harness');+ expect(f.app.isDraftSwarm(tab.id), isFalse);+ expect(tab.panes.map((p) => (p.machineId, p.agentId)), [+ ('m', 'native-lead'),+ ]);+ expect(f.app.activeSwarmId, shown);+ });++ test('goes to a second tab, "api 2", once the first holds 9', () async {+ final f = SuperTabLaunchFixture();+ final api = await _withApi(f);+ final first = _tab(f.app, personalProjectTabId(api.project), [+ for (var i = 0; i < 9; i++) _pane('m', 'old-$i'),+ ], name: 'api');+ final box = await _boxIn(f, api.chat);+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);+ await Future<void>.delayed(Duration.zero);+ expect(first.panes, hasLength(9));+ final second = f.app.swarms+ .where((s) => s.id == personalProjectTabId(api.project, 2))+ .single;+ expect(second.name, 'api 2');+ expect(second.panes.map((p) => (p.machineId, p.agentId)), [+ ('m', 'native-lead'),+ ]);+ });++ // Reed's review of #3090: a pane with a repo started from a project is+ // that project's, not a new project for its repo.+ test('with a repo stays in that project: no project is made for its '+ 'repo, on this computer or another', () async {+ final f = SuperTabLaunchFixture()+ ..connection.nativeProject = {+ 'name': 'web',+ 'cwd': '/work/web',+ 'root': '/work/web',+ 'remote': 'github.com/acme/web',+ };+ final api = await _withApi(f);+ final box = await _boxIn(f, api.chat);+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);+ await Future<void>.delayed(Duration.zero);+ final tab = f.app.swarms+ .where((s) => s.id == personalProjectTabId(api.project))+ .single;+ final pane = tab.panes.single;+ final before = _commands(f).length;+ await PersonalProjects.of(f.app).sync(api.c);+ expect(_commands(f).skip(before), isEmpty);+ expect(+ PersonalProjects.of(f.app).knownForTest('owner', tabId).keys,+ isNot(contains('github.com/acme/web')),+ );+ expect(PersonalProjects.of(f.app).panesFor(api.c, api.chat), [pane]);+ });++ test('a repo pane in the tab of a project Personal does not list joins '+ 'its repo\'s project', () async {+ final f = SuperTabLaunchFixture();+ final api = await _withApi(f);+ f.app.machineStates['m']!.agents = [+ _agent('w', remote: 'https://github.com/acme/web', cwd: '/w/web'),+ ];+ _tab(f.app, personalProjectTabId('gone'), [_pane('m', 'w')], name: 'x');+ await PersonalProjects.of(f.app).sync(api.c);+ expect(+ PersonalProjects.of(f.app).knownForTest('owner', tabId).keys,+ contains('github.com/acme/web'),+ );+ });++ test('in another Swarm makes no project tab', () async {+ final f = SuperTabLaunchFixture();+ withCoordinator(f);+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');+ final tabs = f.app.swarms.length;+ final box = await f.box();+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);+ expect(+ f.app.swarms.where((s) => personalProjectTabParts(s.id) != null),+ isEmpty,+ );+ expect(f.app.swarms.length, tabs);+ });+ });++ test('a project tab follows its project\'s renames, unless the person '+ 'renamed it', () async {+ final f = SuperTabLaunchFixture();+ final api = await _withApi(f);+ final first = _tab(f.app, personalProjectTabId(api.project), [+ _pane('m', 'a'),+ ], name: 'api');+ final second = _tab(f.app, personalProjectTabId(api.project, 2), [+ _pane('m', 'b'),+ ], name: 'api 2');+ final mine = _tab(+ f.app,+ personalProjectTabId(api.project, 3),+ [_pane('m', 'c')],+ name: 'my work',+ nameIsCustom: true,+ );+ await api.c.request(+ 'POST',+ '/api/super-tabs/$tabId/commands',+ body: {+ 'operationId': 'rename-api',+ 'command': {+ 'type': 'project.rename',+ 'projectId': api.project,+ 'name': 'payments',+ },+ },+ );+ await api.c.refresh();+ await PersonalProjects.of(f.app).sync(api.c);+ expect(first.name, 'payments');+ expect(first.nameIsCustom, isFalse);+ expect(second.name, 'payments 2');+ expect(mine.name, 'my work');+ expect(mine.nameIsCustom, isTrue);+ });++ group('a project\'s own layout', () {+ /// Personal on screen showing the api project behind [term]: its two+ /// panes come from two tabs, so no tab's sizes are theirs.+ Future<({SuperTabController c, String chat, String project, Swarm view})>+ showApi(SuperTabLaunchFixture f) async {+ f.app.machineStates['m']!.agents = [+ _agent('a1', remote: '[email protected]:acme/api.git', cwd: '/w/api'),+ _agent('a2', remote: 'https://github.com/acme/api', cwd: '/w/api2'),+ ];+ final one = _pane('m', 'a1'), two = _pane('m', 'a2');+ _tab(f.app, 'desk-one', [one], name: 'one');+ _tab(f.app, 'desk-two', [two], name: 'two');+ final c = await _personal(f);+ await PersonalProjects.of(f.app).sync(c);+ final api = c.snapshot!.projects.firstWhere((p) => p.name == 'api');+ c.select(api.leadConversationId);+ c.selectGroupTerminals(api.leadConversationId);+ final view = f.app.activeSwarm;+ expect(view.superTabId, tabId);+ view.panes.addAll([one, two]);+ expect(PersonalProjects.of(f.app).panesFor(c, api.leadConversationId), [+ one,+ two,+ ]);+ expect(PersonalProjects.of(f.app).soleTab([one, two]), isNull);+ return (c: c, chat: api.leadConversationId, project: api.id, view: view);+ }++ test('is saved when the person arranges it, on this computer only, and '+ 'comes back when the project is shown again', () async {+ final f = SuperTabLaunchFixture();+ final api = await showApi(f);+ final arranged = PaneArrangement(const [+ Rect.fromLTRB(0, 0, 0.3125, 1),+ Rect.fromLTRB(0.3125, 0, 1, 1),+ ]);+ api.view.arrangedKey = '2:manual';+ final postsBefore = f.connection.server.posts.length;+ final callsBefore = f.connection.calls.length;+ expect(f.app.resizePanes(api.view.id, '2:manual', arranged), isTrue);+ await Future<void>.delayed(Duration.zero);+ final saved = jsonDecode(+ (await f.app.superTabs.storage.read(+ PersonalProjects.storageKey('owner'),+ ))!,+ ) as Map;+ final layout = (saved[tabId] as Map)['layouts'][api.project] as Map;+ expect(layout['count'], 2);+ expect((layout['sizes'] as Map)['2:manual'], arranged.toJson());+ // Never sent: nothing the server or a machine heard carries it.+ final heard = jsonEncode([+ ...f.connection.server.posts.skip(postsBefore),+ for (final call in f.connection.calls.skip(callsBefore)) call.$2,+ ]);+ expect(heard, isNot(contains('0.3125')));++ // Another project's sizes take the view; the api's come back.+ api.view.paneSizes.clear();+ api.view.arranged = null;+ api.view.arrangedKey = null;+ expect(+ PersonalProjects.of(f.app).applyLayout(api.c, api.chat, api.view),+ isTrue,+ );+ expect(api.view.paneSizes['2:manual']?.tiles, arranged.tiles);+ });++ test('is applied only to the number of panes it was saved for', () async {+ final f = SuperTabLaunchFixture();+ final api = await showApi(f);+ api.view.arrangedKey = '2:manual';+ f.app.resizePanes(+ api.view.id,+ '2:manual',+ PaneArrangement(const [+ Rect.fromLTRB(0, 0, 0.5, 1),+ Rect.fromLTRB(0.5, 0, 1, 1),+ ]),+ );+ await Future<void>.delayed(Duration.zero);+ api.view.panes.removeLast();+ expect(+ PersonalProjects.of(f.app).applyLayout(api.c, api.chat, api.view),+ isFalse,+ );+ });+ });++ test('Personal remembers the order its projects first appear in the tabs, '+ 'and keeps it when the tabs move', () async {+ final f = SuperTabLaunchFixture();+ f.app.machineStates['m']!.agents = [+ _agent('w', remote: 'https://github.com/acme/web', cwd: '/w/web'),+ _agent('a', remote: 'https://github.com/acme/api', cwd: '/w/api'),+ _agent('n', cwd: '/Users/me/notes'),+ _agent('d', remote: 'https://github.com/acme/docs', cwd: '/w/docs'),+ ];+ final web = _tab(f.app, 'desk-web', [_pane('m', 'w')], name: 'web');+ _tab(f.app, 'desk-api', [_pane('m', 'a')], name: 'api');+ _tab(f.app, 'desk-notes', [_pane('m', 'n')], name: 'notes');+ final c = await _personal(f);+ final personal = PersonalProjects.of(f.app);+ await personal.sync(c);+ String id(String name) =>+ c.snapshot!.projects.firstWhere((p) => p.name == name).id;+ expect(personal.projectOrder(c), [id('web'), id('api'), id('notes')]);++ // The person moves the web tab last and opens docs: the order seen+ // first stays, and docs comes after.+ f.app.swarms+ ..remove(web)+ ..add(web);+ _tab(f.app, 'desk-docs', [_pane('m', 'd')], name: 'docs');+ await personal.sync(c);+ final order = [id('web'), id('api'), id('notes'), id('docs')];+ expect(personal.projectOrder(c), order);+ final saved = jsonDecode(+ (await f.app.superTabs.storage.read(+ PersonalProjects.storageKey('owner'),+ ))!,+ ) as Map;+ expect((saved[tabId] as Map)['order'], order);+ });++ // Agreed with Lupine2 for the merge with #3073: the project list's one-pass+ // hide check reads a pane in a project's own tab as panesFor does.+ test('a project whose only open pane sits in its own tab is not hidden, '+ 'and the hide check agrees with panesFor', () async {+ final f = SuperTabLaunchFixture();+ f.app.machineStates['m']!+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..agents = [+ _agent('a1', remote: 'https://github.com/acme/api', cwd: '/w/api'),+ // Started from api's chat in a folder of another repo.+ _agent('a2', remote: 'https://github.com/acme/web', cwd: '/w/web'),+ ];+ final first = _tab(f.app, 'desk-api', [_pane('m', 'a1')], name: 'api');+ final c = await _personal(f);+ final projects = PersonalProjects.of(f.app);+ await projects.sync(c);+ final api = c.snapshot!.projects.firstWhere((p) => p.name == 'api');+ // The repo's own tab closes; an agent started from api's chat stays open+ // in api's own tab.+ f.app.swarms.remove(first);+ final started = _pane('m', 'a2');+ _tab(f.app, personalProjectTabId(api.id), [started], name: 'api');+ expect(projects.panesFor(c, api.leadConversationId), [started]);+ expect(projects.hiddenIn(c), isNot(contains(api.id)));+ for (final project in c.snapshot!.projects) {+ expect(+ projects.hiddenIn(c).contains(project.id),+ projects.knownForTest('owner', tabId).containsValue(project.id) &&+ projects.panesFor(c, project.leadConversationId).isEmpty,+ reason: project.name,+ );+ }+ });+}diff --git a/docs/phone-notifications.md b/docs/phone-notifications.mdnew file mode 100644index 000000000..c731448cd--- /dev/null+++ b/docs/phone-notifications.md@@ -0,0 +1,74 @@+# Phone notifications++Every notification the Harness phone app (iOS and Android) can show in the system's notification centre, as of+2026-11-05 (task #3248). **Push** comes from the server through Apple (APNs) or Google (FCM) and reaches a phone+whose app is closed or in the background. **Local** is posted by the app itself, from what it reads while it runs.++A notice never says what was written: it can be read on a locked phone. It says who, and in which project.++The rule below is the one Tony approved on 2026-11-05 ("Yes, as proposed"): only what needs you pushes, and repeats+collapse.++## The table++| Type | When it is received | Event | Title | Example | Test evidence |+|---|---|---|---|---|---|+| Push | App closed or in the background. With Harness in front the push is not drawn (iOS `willPresent`, Android FCM in front): the app's own Local notice decides. | A reply, by a person or an agent, in a thread you started or were tagged in, or to your own message (it quotes it). Never your own reply, a Swarm status line in a thread (Working, Ready for review, Done), a thread you only replied in, a muted chat, an unfollowed thread, or a reply that tags you (the tag push tells you instead). **One notification per thread:** a newer reply replaces it. It sounds only when nothing in that thread was unread for you; otherwise it replaces quietly (iOS `passive`, no sound; Android channel `swarm-quiet`). | `<name> replied in a thread`, subtitle the project, body `Open Harness to read it.` | **River replied in a thread** · openharness · Open Harness to read it. Tap: the thread, at the newest reply. | `backend/src/push/notices.test.ts` "phoneNotices: the push rule Tony approved"; `backend/integration/superTabActivity.test.ts` "Phone push: who each push type reaches, and what it carries", "Phone push: a thread sounds once until it is read", "Phone push end to end on the server…"; `apns.test.ts` "APNs: one notification per slot, and quiet repeats"; `fcm.test.ts` "tags the notification with its slot…"; `send.test.ts` "sends each notice as its thread's repeats make it…" |+| Push | As above. | You are tagged, by a person or by an agent of the project, in a chat you can read, including a muted one; also the server's "no reviewer can start" notice, which tags the people who can fix it when no coordinator is in that chat. Never your own tag. A tag held for a quiet chat (no agent working there yet) is not pushed, then or later. Always with sound. | `<name> tagged you`, subtitle the project, body `Open Harness to read it.` | **Tony tagged you** · openharness · Open Harness to read it. Tap: the message, in its thread when it is only there. | `notices.test.ts` "words a tag as the phone does…", "pushes no tag held back for a quiet chat"; `superTabActivity.test.ts` "a tag links the message in the chat…", "keeps each person and each thread apart, and never quiets a tag"; `mobile/test/app_state_push_test.dart` "a tapped push opens the chat its link names" |+| Push | As above. **New in #3248.** | A decision an agent asks of you (`decision.ask`, or `needs_human` with an ask), the first time it is asked. One ask of several questions sounds once; the rest are quiet. | `<asker> asks you`, subtitle the project, body `Open Harness to answer.` | **River asks you** · openharness · Open Harness to answer. Tap: Activity, at the card. | `notices.test.ts` "pushes a decision asked of a person as the app words it…"; `superTabActivity.test.ts` "a decision asked of a person reaches their phone once…", "one ask of several questions sounds once" |+| Local | Harness in front with no Swarm screen open: the Swarm read every 15 s. | A reply in a thread, from the same Activity rows the reply push uses. Shares the push's notification for that thread: it replaces the push rather than adding a second, and posts nothing while a push still shows that thread. Quiet while the thread has an unread reply; taken down, with the push in it, once the thread is read. | `<name> replied in a thread` (`Someone` with no name), project, `Open Harness to read it.` | **Oak replied in a thread** · openharness | `mobile/test/swarm/swarm_notices_test.dart` "shares one notification per thread, the push's too…", "is not posted for a thread a push shows…", "a thread whose push was swiped away unread only replaces quietly…"; `swarm_activity_feed_test.dart`; `test/phone/phone_shell_swarm_notice_test.dart` |+| Local | As above. | A tag waiting for you (the same tags as the tag push), in the push's notification. | `<name> tagged you`, project, `Open Harness to read it.` | **River tagged you** · openharness | `swarm_notices_test.dart` "a tag in a thread opens that thread at the tag"; `swarm_notice_repeat_test.dart` "read again and again, each ask is told once" |+| Local | As above. | A decision asked of you, in the push's notification. | `<asker> asks you`, project, `Open Harness to answer.` | **River asks you** · openharness · Open Harness to answer. Tap: Activity, at the card. | `swarm_notices_test.dart` "a decision says who asks…"; `phone_shell_swarm_notice_test.dart` |+| Local | As above. | A task waiting on you is `blocked`: you are its chat's partner, or else the project's owner. | `<agent> is stuck`, project, `Open Harness to see why.` | **Magnolia2 is stuck** · openharness | `swarm_notices_test.dart` |+| Local | As above. | A task waiting on you (as above) needs a person (`needs_human`). | `<agent> needs you`, project, `Open Harness to answer.` | **Oak needs you** · openharness | `swarm_notices_test.dart` |+| Local | As above. | A new message in a chat you set to **All new messages**. One notice per chat; it sounds once until you read the chat, and a newer message replaces it quietly. | `New messages`, project, `Open Harness to read them.` | **New messages** · openharness | `mobile/test/swarm/swarm_chat_notices_test.dart` "All new messages: each new message in the chat is told, one notice…", "read, the chat's next message sounds again" |+| Local | Harness in front, or seconds after it goes to the background (the machine's socket). Not while you look at that agent. | An agent on your machine finished a turn the daemon ranks worth telling (not `silent` or `list`). One notice per agent; it sounds once until you go to the agent, and a newer turn replaces it quietly. | The agent's name, subtitle the machine, body the reply's last paragraph (180 characters at most). | **Fix login** · MacBook · Fixed it. Tap: the agent's chat (or terminal with Swarm off). | `mobile/test/notify/agent_announcer_test.dart` "a finished turn sounds once until the person goes to the agent…"; `local_system_notices_test.dart` "a finished turn: the agent, its machine, its news, on the done channel"; `announcer_lifecycle_test.dart`; `done_notice_test.dart` |+| Local | As above; in front, only after 15 s still unanswered. | An agent on your machine asks a question (approval, choice). A repeat within 5 minutes is quiet: no sound, no banner. | The agent's name, the machine, the question. | **Fix login** · MacBook · Approve Bash command: rm -rf dist | `local_system_notices_test.dart` "a question rides a channel of its own…", "a quiet notice…"; `question_notice_test.dart`; `question_spam_incident_test.dart` |+| Local | When the phone next reads the account's devices (sign-in, or a device-keys change on a machine socket). | A new device joined or signed in to your account. Once per device. | `New device on your account` | **New device on your account** · Pixel 9 signed in to your account and can reach your machines. Not yours? Remove it in Settings ▸ Your devices. | `local_system_notices_test.dart` "a new device on the account…"; `test/phone/phone_shell_device_notice_test.dart` |+| Local | As above. | A device left your account: it signed out, another device removed it, or a new device you have not looked at removed it. | `Device signed out`, `Device removed` or `Removed by a new device` | **Device removed** · iPad was removed from your account by MacBook. | `test/state/device_removal_notice_test.dart`; `phone_shell_device_notice_test.dart` |++**Silent, never pushed** (in the app's Activity and badge only): a reply in a thread you only replied in, a Swarm status+line in a thread, reactions, and messages outside threads that tag nobody. Evidence: `superTabActivity.test.ts` "a reply+reaches the thread's starter, the quoted message's author and people tagged earlier in it, never its author nor one who+only replied", "tells the starter and every person who replied, but never the reply's author" (the Activity rows), "pushes+nothing for a message outside threads that tags nobody, or for a reaction"; `notices.test.ts` "pushes no Swarm line in a+thread…".++Not in the notification centre, so not in the table: the app icon's badge (the Swarm's waiting count, iOS), the unread dot+and buzz on an agent, the new-device and removed-device bands, and snackbars. The PM's routing proposals (the routine's+reflection decisions) are listed in Activity and are not pushed.++## Where each one comes from++- Push: `backend/src/push/notices.ts` words the three kinds from the rows a write made (`superTabs/activity.ts`+ `writeReplyActivity`, which says why each person is told; `superTabs/mentions.ts` `writeMentions`; the decisions+ `superTabs/store.ts` writes for `decision.ask` and `needs_human`). `push/repeats.ts` makes a thread's reply quiet when+ the person has an earlier unread reply there (one indexed read per thread, on the Activity thread index; if it cannot+ read, the push goes with sound and a warning is logged). `push/send.ts` sends them after the write commits, to every+ phone the person registered (`push/devices.ts`); `push/apns.ts` and `push/fcm.ts` talk to Apple and Google.+- Keys and slots. Each notice has a **key** (`reply:<swarm>:<row>`, `mention:<row>`, `decision:<id>`), the same as the+ app's Local notice for the same thing, and a **slot**, the notification it shows in: `thread:<swarm>:<chat>:<root>` for a+ reply, the key for a tag or a decision. APNs: `apns-collapse-id` is the slot's id (`swarmNoticeId`, FNV-1a, the same as+ the app's `swarmNoticeIdFor`), so the app's notice under that id replaces the push. FCM: the notification's tag is the+ slot, and the app posts under that tag with id 0, as FCM draws it. The payload's `link` is+ `swarm:<swarm>/<chat>/message/<message>[/thread/<root>]` or `swarm:<swarm>/<chat>/decision/<id>`.+- Local: `mobile/lib/notify/system_notices.dart` posts all of them. Swarm ones come from `lib/swarm/swarm_notices.dart`+ (Android channel and iOS thread `swarm-needs-you`), agent ones from `lib/notify/agent_announcer.dart` (`agent-done`,+ `agent-question`), device ones from `lib/state/app_state.dart` (`account-device`). On Android the app makes the+ `swarm-needs-you` and `swarm-quiet` channels when push starts, before any push can arrive.+- Back in front, the app asks which pushes are still shown (`PushChannel.shown`: iOS gives each push's key and slot,+ Android its tag, the slot) and posts none of them again (#3150), nor anything for a thread a push still shows.++## What the inventory found, and what was done++1. Opening the app after a push could show the same reply or tag a second time. Fixed by #3150 (Sequoia2), extended here+ to slots.+2. A push and the app's Local notice for the same thing were two entries in the notification centre. Fixed: they share+ one slot (`apns-collapse-id`, the FCM tag).+3. Every reply in a thread was its own push with sound. Fixed: one notification per thread, sounding once until read;+ repliers-only and Swarm status lines no longer push.+4. Android: the `swarm-needs-you` channel was made only with the app's first Swarm notice, so an earlier push landed on+ FCM's default channel. Fixed: both push channels are made when push starts.+5. A tag held for a quiet chat is never pushed, even once the hold ends. Unchanged (not part of the approved rule).+6. A decision asked of you was Local only. Fixed: it pushes.+7. A chat set to All new messages, and an agent's finished turns, buzzed every time. Fixed: they sound once until seen.diff --git a/docs/plans/2026-11-05-personal-project-tabs-plan.md b/docs/plans/2026-11-05-personal-project-tabs-plan.mdnew file mode 100644index 000000000..f5f9a8dba--- /dev/null+++ b/docs/plans/2026-11-05-personal-project-tabs-plan.md@@ -0,0 +1,160 @@+# Personal project tabs (tabs to Personal Swarm, Phase 1): plan++> Way of working: this project's Engineer workflow (test first, one commit for each failing test and one for its+> code, one independent review on the pull request). No subagent-driven development and no execution handoff.++**Goal:** Phase 1 of Huy's migration plan (`docs/plans/2026-11-04-tabs-to-personal-swarm-migration.md`, "fill the gaps,+existing tabs unchanged"), task #3099. A pane started from a Personal project lands in that project's own desk tab,+which every computer links to the same project; a full desk refuses the start before any agent runs; a no-repo pane+joins its project through that tab; a project of panes from several tabs keeps its own split sizes on this computer+only; Personal remembers the tab order it saw. Existing tabs stay exactly as they are.++**Architecture:** all of it is Desktop. `PersonalProjects` (`desktop/lib/super_tabs/personal_projects.dart`) owns the+rules: the project tab id, the link from a tab id back to a project, the room check, placing a pane, keeping the tab's+name, the saved layouts and the order. The Swarm launch (`desktop/lib/super_tabs/launch.dart`) asks it for room in+`prepare` (before the native start) and places the pane after the join in `complete`. `AppNotifier` gains three small+seams: make a desk tab in the background, rename a tab without marking the name the person's, and tell a listener when+the person arranged the panes of a Swarm tab. The desk and its server are unchanged: `project-` plus 24 hex characters+(and `-2`, `-3`) fits `backend/src/lib/desk.ts`'s id rule, so `desk.ts` is not touched.++**Tech Stack:** Flutter/Dart (Desktop), `flutter_test` with the existing `SuperTabLaunchFixture` (memory store, fake+sign-in, fake Swarm server).++**Spec:** the migration plan's Phase 1, items 1 to 5, and the task brief (#3099).++## Global Constraints++- No on/off switch. Rollback is a revert; project tabs already made stay as ordinary tabs.+- Existing tabs, their ids, their project keys (`tab:<id>`) and `super_tab.repos.<account>` entries stay as they are.+- A project's layout and the remembered order are kept in this computer's store only (`super_tab.repos.<account>`),+ never sent to the server or the desk.+- The refusal text is exactly: "Your tabs are full (24). Close a tab to start another agent."+- Tests use a memory store and a fake sign-in; nothing signs the real CLI out.+- Lupine2 changes `personal_projects.dart` in #3073 (task #3042, `hidden()` after `panesFor`): this work keeps its+ additions apart from those lines and rebases on whichever merges first. Project-tab links are read from the+ snapshot, never written into `_known`, so #3073's `hidden()` (which reads `_known`) never hides a project the+ person made.++## Decisions taken where the plan leaves a choice++- **Id:** `project-` + the first 24 hex characters of sha256(`project:<projectId>`); the second and third tabs add+ `-2`, `-3`. The same project id gives the same tab id on every computer.+- **Link:** a tab whose id has that shape belongs to the Personal project whose id hashes to it. Every pane in it joins+ that project, a pane with a repo too: it was started there, and its repo must not get a second project for it+ (Reed's review). If no project of Personal matches (deleted, or not read yet), no project is made for the tab: a+ no-repo pane stays in its tab only, and a repo pane joins its repo's project as in any ordinary tab.+- **Name:** the first tab takes the project's name, the next ones "api 2", "api 3". On each Personal sync a tab whose+ name the person did not choose follows the project's current name. A person's rename (`nameIsCustom`) stays.+- **Room:** a project tab is full at 9 harness panes (`PaneLayoutStore.maxPanes`, the desk's `DESK_MAX_PANES`). With+ no project tab of the project having room and 24 tabs on the desk, `prepare` throws `TABS_FULL` with the message.+ A new project needs a new tab, so it is refused at 24 tabs too. A start already asked for (a retried journal) is+ never refused, and a Product Manager started on a Swarm machine puts no pane here, so it is not checked.+- **Layout:** saved when the person drags the dividers or picks a preset in Personal while it shows a project whose+ panes are not exactly one tab's (where `soleTab` already gives the sizes). Applied when that project is shown again+ with the same number of panes. Removed when the project is gone from Personal.+- **Order:** the project ids in the order their panes first appear across the tabs, kept and extended on each sync+ (`projectOrder`). Phase 1 only remembers it: the PROJECTS list stays A to Z because the round dial swipes projects+ in that order (`superTabSidebarOrder`, cli `cards.ts`); Phase 2 starts the list from it.++## Review Focus++- The refusal happens before the native start: no `agents_create` (or equivalent) is sent when the desk is full.+- No project is ever created for a project tab, on any computer.+- The layout never leaves the computer: not in a server request, not in a desk op.+- Ordinary tabs and their projects are unchanged (existing tests stay green).++## Tasks++### Task 1: the project tab id and its link back to a project++**Files:** `desktop/lib/super_tabs/personal_projects.dart`, `desktop/test/personal_project_tabs_test.dart` (new).++**Interfaces:** `String personalProjectTabId(String projectId, [int number = 1])`;+`({String base, int number})? personalProjectTabParts(String tabId)`;+`SuperTabProject? PersonalProjects.projectOfTab(SuperTabController c, String tabId)`.++- [ ] Failing test: two computers (two fixtures) with the same project id compute the same id; it matches the desk+ id rule; `-2`/`-3` parse back; an ordinary tab id does not parse.+- [ ] Failing test: a no-repo pane in a project tab is shown by that project's `panesFor`, and `sync` creates no+ project for it; on a second computer the same.+- [ ] Code.++### Task 2: room on the desk, and the refusal before any agent runs++**Files:** `personal_projects.dart`, `desktop/lib/super_tabs/launch.dart`, `desktop/lib/state/app_state.dart`+(`deskTabCount`), the new test file.++**Interfaces:** `const kTabsFullMessage`; `String? PersonalProjects.projectTabRefusal(String? projectId)`.++- [ ] Failing test: with 24 desk tabs and no project tab with room, submitting New Harness from a Personal project+ fails with the message and no native start is asked for; with a project tab holding 8 panes it goes ahead; a+ Swarm that is not Personal is never refused.+- [ ] Code.++### Task 3: placing the started pane in the project's tab++**Files:** `personal_projects.dart`, `launch.dart`, `app_state.dart` (`ensureBackgroundTab`), the new test file.++**Interfaces:** `Future<void> PersonalProjects.placeInProjectTab(SuperTabController c, String projectId, String+machineId, String agentId)`.++- [ ] Failing test: after a start from a Personal project the pane is in tab `project-…` named after the project,+ which is on the desk projection; a 10th pane goes to "api 2" (`-2`); the active tab does not change.+- [ ] Code.++### Task 4: the tab follows the project's renames, unless the person renamed it++**Files:** `personal_projects.dart`, `app_state.dart` (`setTabNameAutomatic`), the new test file.++- [ ] Failing test: the project renamed on the server renames its tab (and "api 2") on the next sync; a tab the+ person renamed keeps its name.+- [ ] Code.++### Task 5: a project's own layout, on this computer only++**Files:** `personal_projects.dart`, `desktop/lib/super_tabs/workspace.dart`, `app_state.dart` (arranged listener),+the new test file.++**Interfaces:** `void PersonalProjects.rememberLayout(SuperTabController c, String conversationId, Swarm view)`;+`bool PersonalProjects.applyLayout(SuperTabController c, String conversationId, Swarm view)`.++- [ ] Failing test: arranging a project of panes from two tabs saves its sizes in `super_tab.repos.<account>`;+ showing another project and coming back restores them; no server post and no desk op carries them.+- [ ] Code.++### Task 6: Personal remembers the tab order it saw++**Files:** `personal_projects.dart`, the new test file.++**Interfaces:** `List<String> PersonalProjects.projectOrder(SuperTabController c)`.++- [ ] Failing test: projects come in the order their panes first appear in the tabs, survive a reload from the store,+ and a later reorder of tabs appends only new projects.+- [ ] Code.++### Task 7: evidence++- [ ] Run the new test file, `super_tab_personal_projects_test.dart`, `super_tab_launch_test.dart`, the desk tests+ (`desk_sync_test.dart`, `shared_tabs_desk_test.dart`) and the guard tests; `flutter analyze` on the changed files.+- [ ] Light and dark screenshots of a project tab beside an ordinary tab and of the refusal, sent to Huy.+- [ ] Red/green evidence in a pull request comment.++## Design++- Growth: one desk tab per Personal project that started a pane (two or three past 9 panes), closed by the person like+ any tab; one saved layout and one order entry per Personal project on each computer, deleted when the project is gone.+- Concurrency: desk changes go through the desk's existing idempotent ops (`tab.create` of an id already there changes+ nothing), so two computers placing at once make one tab. Local store writes are per account, as today.+- Read cost: nothing new is read; the link hashes the projects the Personal snapshot already holds.+- Scale: the desk's 24 tabs is reached first; the refusal names it and is logged by its code (`TABS_FULL`). A product+ measure of refusals needs a new flow in the shared measurement vocabulary (backend and phone), proposed separately+ rather than built here.+- Compatibility: older Desktops, the phone and the web read a project tab as an ordinary desk tab. An older Desktop+ maps its no-repo panes to a `tab:` project as today (one stray project there, until it updates).+- Migration and rollback: no data migrated; a revert leaves project tabs as ordinary tabs.+- Audience: the desk is the person's own document; the tab adds only a hashed project id. Layouts and order stay on+ the computer.+- Identity: Personal belongs to the signed-in account (`eligible`), never the machine owner's login.+- Failure: a full desk is refused with the message before the start; a failed tab placement leaves the agent in its+ project's Swarm view and is logged by its code.+- Platforms: Desktop on macOS, Windows and Linux; nothing platform-specific.diff --git a/docs/plans/2026-11-05-phone-notifications-plan.md b/docs/plans/2026-11-05-phone-notifications-plan.mdnew file mode 100644index 000000000..ff5f1dd4c--- /dev/null+++ b/docs/plans/2026-11-05-phone-notifications-plan.md@@ -0,0 +1,120 @@+# Phone notifications: tested end to end, listed in one table, no spam (task #3248) Plan++> Worked by the Engineer, test first (superpowers test-driven-development): each task's failing test is committed and+> seen red before the code that passes it. Characterization tests of what already ships are committed green, and a+> red one is a finding fixed in the task after it.++**Goal:** Every notification the phone can show is listed in `docs/phone-notifications.md`; each server push type has+integration tests (who gets it, its payload, the link it carries, never the author, never drawn while the app is in+front); a push reaches a closed app and its tap opens the right chat, shown end to end on a simulator and on Tony's+iPhone 14; and the push rule Tony approves is built with tests.++**Architecture:** Server: `superTabs/store.ts` writes reply rows (`activity.ts writeReplyActivity`) and tag rows+(`mentions.ts writeMentions`) in a command's transaction; `push/notices.ts` words a `PhoneNotice` for each;+`push/send.ts` sends them after commit to every registered phone (`push/devices.ts`) through `push/apns.ts` or+`push/fcm.ts`. Phone: `lib/notify/system_notices.dart` posts every Local notice and opens a tapped push's `link`+(`lib/notify/push_channel.dart`, native `AppDelegate.swift` / `MainActivity.kt`). #3150 (Sequoia2) adds the "a push+already shown is not posted again" half; this task builds on it.++**Tech Stack:** TypeScript, Fastify, Prisma on MongoDB, vitest with a loopback replica set (`npm run test:super-tabs`+in CI); Flutter 3.47, `flutter test`; an XCUITest runner for the springboard taps; `xcrun simctl push` for a+simulator push; the production backend's APNs sandbox key for the iPhone (a development build's token).++**Spec:** task #3248 brief; `docs/design/2026-11-05-phone-push.md`; `docs/phone-notifications.md`.++## Global Constraints++- Owned paths only: `docs/phone-notifications.md`, `mobile/`, `backend/src/push/`, `backend/integration/` (and this plan).+- Push keys and signing secrets never in chat, logs or the repository; the iPhone run uses the production backend's own+ keys, nothing local.+- One installer on Tony's iPhone at a time: say in the task when an install starts and ends; ask first that it is free.+ `flutter drive` always with `-d` and `--keep-app-running`; never a debug drive on the phone (it cannot attach from here).+- Nothing in this task changes which events push until Tony approves the rule (Task 5). Two security reviews if it does.+- Never a test that signs the Mac out of the real CLI. Stop only processes started here, by id. Temp files in `mktemp -d`.++## Design++- growth: no new collection in Tasks 1 to 4. Task 5 adds none either: the "sound once per unread thread" check reads the+ person's existing Activity rows (TTL `ACTIVITY_EXPIRY_MS`).+- concurrency: unchanged; notices are made inside the write's transaction and sent after it commits.+- read cost: Task 5 adds at most one indexed read of unread reply rows per reply write that tells someone.+- scale: a 100-person thread is 100 notices sent 8 at a time (`AT_ONCE`); collapsing per thread lowers what a phone shows,+ not what the server sends. The metric that warns first: `phone_push` counts by outcome.+- compatibility: an old app ignores fields it does not read (`apns-collapse-id` is a header; `key`/`link` unchanged).+- migration + rollback: none; reverting restores today's pushes.+- audience: the server decides who is told (rows written for people who can read the chat); the phone never widens it.+- identity: each phone token belongs to the person who registered it last; nothing uses the machine owner's login.+- failure: a push that cannot be made or sent is logged and counted, never the write's failure (as today).+- platforms: iOS and Android phone app, backend.++## Review Focus++- The integration tests assert the real audience (`writeReplyActivity`, `writeMentions`) and the real request body Apple+ receives, not a copy of the code under test.+- The e2e: the push reaches an app that is not running, and the tap opens the chat its `link` names.+- Task 5 (after Tony's yes): who stops being told, and that nobody new is told who could not read the chat.++## Task 1: Server integration tests for each push type++**Files:** `backend/integration/superTabActivity.test.ts`++**Interfaces:** none new.++- [x] Reply push: the thread's starter, the quoted message's author, a person tagged earlier in the thread and a person+ who replied are told; the author never; a muted chat, an unfollowed thread and a person who cannot read the chat+ never; a reply that tags someone tells them by the tag alone; an agent's reply is worded with the agent's name;+ a Swarm line in a thread tells only the starter and the quoted author; a top-level message and a reaction tell+ nobody. Each notice: key `reply:<swarm>:<row>`, title, the project as subtitle, `Open Harness to read it.`, and+ the link to the reply in its thread.+- [x] Tag push: a tag in the chat links the message; a tag in a reply only in its thread links that thread; a reply+ also sent to the chat links the message in the chat; one's own tag is dropped; an agent's tag is worded with its+ name; a tag held for a quiet chat is not pushed; key `mention:<row>`.+- [x] Run: `npx vitest run --config vitest.super-tabs.config.ts integration/superTabActivity.test.ts`.++## Task 2: The whole server path, write to Apple's request++**Files:** `backend/integration/superTabActivity.test.ts`++**Interfaces:** none new; `sendPhoneNotices` with `apnsSender` and `fcmSender` over a recording transport.++- [x] A registered iPhone and Android phone of the starter; a reply's write ends in one APNs request and one FCM+ message: the alert's title, subtitle and body, `thread-id` and `category` `swarm-needs-you`, `key` and `link`; the+ author's own phone gets nothing; nothing written in the chat is in either request.++## Task 3: Fixes the tests and the inventory found that change no rule++**Files:** `mobile/lib/notify/system_notices.dart` (and its test), `mobile/android/...` only if needed.++- [x] Android: the `swarm-needs-you` channel exists before a push can arrive (made when notices start), so a push is+ never drawn on FCM's default channel. Failing test first: the channel is created at start, before any Swarm notice.+- [x] Any red test of Tasks 1, 2 or 4: its failing test, then its fix.++## Task 4: Phone end to end: a push to a closed app, and its tap++**Files:** `mobile/integration_test/push_e2e_app.dart` (the real `PhoneShell` with a scripted Swarm, real+`LocalSystemNotices` and `PushChannel`), `mobile/integration_test/push_e2e/` (XCUITest runner, `simctl push` payload,+the script that runs it and keeps its screenshots).++- [x] Simulator: the app is not running; `xcrun simctl push` delivers a reply push whose `link` names a thread of the+ scripted Swarm; the runner taps the notification on the springboard; the app starts and shows that thread.+ Also: with the app in front, the same push is not drawn.+- [ ] Tony's iPhone 14 (after asking that it is free): a development build, signed in to Tony's account; the app closed;+ a real reply in a thread Tony started reaches the phone through the production backend's APNs sandbox key; the+ tap opens that thread. Evidence in the PR: the run's log and a description of the screenshots (they stay in the+ task chat: no photos of a real phone in this public repository).++## Task 5: The push rule Tony approves (only after his yes)++**Files:** `backend/src/push/notices.ts`, `backend/src/push/apns.ts`, `backend/src/push/fcm.ts`,+`backend/src/push/sender.ts`, their tests, `backend/integration/superTabActivity.test.ts`, `mobile/lib/notify/`,+`mobile/lib/swarm/swarm_notices.dart`, `docs/phone-notifications.md`.++- [x] Each change of who is told or how repeats collapse, as Tony approved it: a failing test first, then the code.+- [ ] The table updated to the new rule; two security reviews requested (it changes who receives a push).++## Status (2026-11-05 17:45)++Tasks 1 to 3 and 5 are built and green. Task 1's audience lines were rewritten to the rule Tony approved: a person who+only replied, and Swarm lines, are no longer pushed. Task 4's simulator run passes+(`mobile/integration_test/push_e2e/run.sh`). The iPhone run is next. Then Task 5's table update is done, and the two+security reviews are requested with the PR.diff --git a/docs/plans/2026-11-05-swarm-read-costs-plan.md b/docs/plans/2026-11-05-swarm-read-costs-plan.mdnew file mode 100644index 000000000..3dfdd53e4--- /dev/null+++ b/docs/plans/2026-11-05-swarm-read-costs-plan.md@@ -0,0 +1,81 @@+# Super Tab Read Costs Implementation Plan++> **For agentic workers:** Use the Harness Engineer workflow in project instructions: implement each plan task test first, commit the failing test, then commit the code that passes it.++**Goal:** Reduce Super Tab read traffic while preserving mention counts and promptly observing Swarm deletion.++**Architecture:** Project only conversation fields needed for person mention visibility, held-tag eligibility, and tag-list titles. A changes poll carries its already-read waiting tags into the derived mention count. Each `SwarmReads` instance caches only the Super Tab format and deletion fields for a short bounded window, with failures and expired entries refreshed from MongoDB.++**Tech Stack:** TypeScript, Prisma, MongoDB, Vitest, MongoDB Memory Replica Set.++**Spec:** Task #3261 in Harness Super Tab conversation `8901918033bb2fd0e85480b5`.++## Global Constraints++- Backend only; do not change `cli/src/core`.+- Changed backend reads use indexed MongoDB query shapes and are checked with `explain()` against a test database.+- Waiting-tag counts and digests remain unchanged; each changes poll reads `SuperTabMention` once.+- Waiting and earlier tag lists retain quiet conversation titles.+- A cached deleted Swarm becomes unavailable after at most the metadata hold window.+- A cached format transition is checked at expiry and retains migration/refusal behavior.+- Before Ready, run affected integration files and the backend unit suite (`npm test`); Super Tab integration coverage runs in PR CI.+- PR evidence includes before/after examined documents and returned bytes per request; start its body with `Requested by 0xKen15 through Harness.`++## Review Focus++- Quiet conversations may contain large task or status payloads; the projected row must retain only fields used by visibility, held-tag checks, and tag-list titles, tested against counts and list output.+- A tag or group update racing a changes poll must use one coherent tag query and still load each tagged conversation.+- Missing, deleted, and newly migrated Swarms must retain their existing refusal and migration behavior across cache expiration.+- Cache entries must be isolated by environment and tab, bounded, and refreshed after expiry or a failed read.+- The projection must preserve query index use; a test-database explain records the plan and examined-document count.++---++### Task 1: Project quiet conversations during mention checks++**Files:**+- Modify: `backend/src/superTabs/mentions.ts`+- Test: `backend/integration/superTabRead.test.ts`++**Interfaces:**+- Consume: `waitingMentions(tx, tabId, state, actor, now)` and existing group-by-key index helper.+- Produce: an aggregate projection containing the conversation `key` plus `data.title`, `data.kind`, `data.projectId`, `data.audience`, `data.archived`, and `data.assignment.status`, sufficient for `canReadGroup`, `isLeads`, held-tag listing, and mention titles.++- [ ] **Step 1: Write failing coverage** proving waiting-tag counts remain unchanged when 21 quiet groups contain large unrelated conversation fields, fetched BSON excludes those fields, and quiet titles remain in waiting and earlier tag lists.+- [ ] **Step 2: Run the targeted test** and record its expected failure against full conversation payloads.+- [ ] **Step 3: Project only the fields required by the mention check** in the missing-conversations aggregate.+- [ ] **Step 4: Run the targeted test** and capture before/after `explain("executionStats")`, examined documents, and returned BSON bytes on the same test fixture.+- [ ] **Step 5: Commit** the test and implementation separately, test first.++### Task 2: Reuse waiting tags within a changes poll++**Files:**+- Modify: `backend/src/superTabs/mentions.ts`+- Modify: `backend/src/superTabs/read/service.ts`+- Test: `backend/integration/superTabRead.test.ts`++**Interfaces:**+- Consume: `changes()`' waiting-tag lookup and `waitingMentions()`' count/digest calculation.+- Produce: projected waiting-tag rows (id, conversation id, creation time, resolution time, and hold time) reusable by `waitingMentions`; the existing `waitingTagConversations()` result remains a list of distinct conversation ids.++- [ ] **Step 1: Write failing coverage** profiling a changes poll with a waiting tag and asserting exactly one read of `SuperTabMention` with unchanged derived count and digest.+- [ ] **Step 2: Run the targeted test** and record its expected failure with two tag reads.+- [ ] **Step 3: Pass the one projected tag-row set from `changes()` into `load()` and `waitingMentions()`**, avoiding a second tag query while retaining the separate indexed conversation lookup.+- [ ] **Step 4: Run the targeted test** and report before/after `SuperTabMention` reads and request bytes.+- [ ] **Step 5: Commit** the test and implementation separately, test first.++### Task 3: Hold Swarm format and deletion metadata per pod++**Files:**+- Modify: `backend/src/superTabs/read/service.ts`+- Test: `backend/integration/superTabCache.test.ts`++**Interfaces:**+- Consume: the scoped `SuperTab.findFirst` selection of `format` and `deletedAt` in `SwarmReads.read()`.+- Produce: a per-instance cache keyed by environment and tab id, with a short exported/testable hold duration, bounded size, and cached metadata only.++- [ ] **Step 1: Write failing coverage** proving repeated reads share one metadata lookup, soft deletion and format transitions are observed at hold expiry with existing migration/refusal behavior, and another environment cannot reuse a cached row.+- [ ] **Step 2: Run the targeted test** and record its expected failure against one metadata lookup per request.+- [ ] **Step 3: Add the bounded per-instance metadata cache**, expiring entries by the injected clock and discarding failed lookups.+- [ ] **Step 4: Run the targeted test** and report before/after row reads and deletion visibility latency.+- [ ] **Step 5: Commit** the test and implementation separately, test first.diff --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 19f89a554..6a2761b82 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@@ -170,12 +170,13 @@ class MainActivity : FlutterActivity() {result.success(ArrayList(waitingPushes))waitingPushes.clear()}- // The keys of our pushes still shown: the app does not post them again. The server tags each- // push with the key the app gives its own notice for the same reply or tag.+ // The slots of our pushes still shown: the app does not post them again. The server tags each+ // push with the slot the app gives its own notice for the same thing: a thread's, a tag's, a+ // decision's (task #3248); an older server tagged a reply's push with its own key."shown" -> result.success(if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) emptyList()else getSystemService(android.app.NotificationManager::class.java).activeNotifications- .mapNotNull { shown -> shown.tag?.takeIf { it.startsWith("reply:") || it.startsWith("mention:") } }+ .mapNotNull { shown -> shown.tag?.takeIf { tag -> PUSH_SLOTS.any { tag.startsWith(it) } } })else -> result.notImplemented()}@@ -361,6 +362,9 @@ class MainActivity : FlutterActivity() {}private companion object {+ /** How the server tags a push's notification (backend `push/fcm.ts`, the notice's slot). */+ val PUSH_SLOTS = listOf("thread:", "mention:", "decision:", "reply:")+/** The long edge a clipboard image leaves here at, at most: `_preferredMaxEdge` in Dart's* `lib/terminal/image_transcode.dart`, which every picture is scaled to before it is sent. */const val MAX_EDGE = 1600diff --git a/mobile/integration_test/push_e2e/PushE2E.swift b/mobile/integration_test/push_e2e/PushE2E.swiftnew file mode 100644index 000000000..32c3a5cf9--- /dev/null+++ b/mobile/integration_test/push_e2e/PushE2E.swift@@ -0,0 +1,102 @@+import XCTest++/// The phone push end to end on an iOS simulator (task #3248), driven by `run.sh`, which installs+/// `integration_test/push_e2e_app.dart` and sends each push this runner asks for with+/// `xcrun simctl push`: the body the server sends (`reply_push.apns`, pinned by backend+/// `src/push/apns.test.ts`).+///+/// 1. The app's first launch: notices allowed, the app up on its Swarm, then closed.+/// 2. A reply push to the closed app: iOS draws it, and its tap starts the app on that thread.+/// 3. The same push with the app in front: not drawn (the app's own notices decide there).+///+/// The method is `testDrive`, never `testRun`, which is XCTest's own and would skip the body.+final class PushE2E: XCTestCase {+ let app = XCUIApplication(bundleIdentifier: "ai.autonomous.harness.ios")+ let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")+ let notice = "River replied in a thread"++ override func setUp() {+ continueAfterFailure = false+ }++ func testDrive() throws {+ // 1. First launch.+ app.launch()+ let allow = springboard.alerts.buttons["Allow"]+ if allow.waitForExistence(timeout: 25) { allow.tap() }+ XCTAssertTrue(element(app, containing: "Phone Swarm").waitForExistence(timeout: 40), "the app is up on its Swarm")+ shot("01-app-up")+ app.terminate()+ XCTAssertEqual(app.state, .notRunning)+ log("app closed")++ // 2. The push to the closed app, drawn by iOS; its tap.+ push("push-1")+ var drawn = element(springboard, containing: notice)+ if !drawn.waitForExistence(timeout: 8) {+ // The banner went before it was looked for: the push waits in Notification Centre.+ let top = springboard.coordinate(withNormalizedOffset: CGVector(dx: 0.3, dy: 0.002))+ top.press(forDuration: 0.1, thenDragTo: springboard.coordinate(withNormalizedOffset: CGVector(dx: 0.3, dy: 0.7)))+ drawn = element(springboard, containing: notice)+ XCTAssertTrue(drawn.waitForExistence(timeout: 10), "the push is drawn")+ }+ log("push drawn: \(drawn.label)")+ shot("02-push-drawn")+ // In Notification Centre a first tap may only open the stack the push sits in: tap it again.+ var started = false+ for attempt in 0..<3 where !started {+ log("tap \(attempt): \(drawn.elementType.rawValue) frame \(drawn.frame) hittable \(drawn.isHittable)")+ if attempt == 0 { drawn.tap() } else { drawn.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap() }+ started = app.wait(for: .runningForeground, timeout: 10)+ drawn = element(springboard, containing: notice)+ }+ XCTAssertTrue(started, "the tap starts the app")+ XCTAssertTrue(element(app, containing: "Drafted the first two screens").waitForExistence(timeout: 40), "the thread is open at River's reply")+ XCTAssertTrue(element(app, containing: "Onboarding copy").exists, "in the chat its link names")+ shot("03-thread-opened")+ log("thread opened")++ // 3. The same push with the app in front.+ push("push-2")+ XCTAssertFalse(element(springboard, containing: notice).waitForExistence(timeout: 8), "no push drawn over the app")+ shot("04-in-front-not-drawn")+ log("in front: not drawn")+ }++ /// What is on screen whose label holds [text]: Flutter's semantics, or the springboard's own.+ private func element(_ on: XCUIApplication, containing text: String) -> XCUIElement {+ on.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS %@", text)).firstMatch+ }++ private var out: URL {+ URL(fileURLWithPath: ProcessInfo.processInfo.environment["OUT"] ?? NSTemporaryDirectory())+ }++ /// Asks `run.sh` for push [name] and waits until it was sent.+ private func push(_ name: String) {+ FileManager.default.createFile(atPath: out.appendingPathComponent("want-\(name)").path, contents: nil)+ let sent = out.appendingPathComponent("sent-\(name)").path+ let until = Date().addingTimeInterval(60)+ while !FileManager.default.fileExists(atPath: sent) {+ XCTAssertLessThan(Date(), until, "\(name) was not sent")+ Thread.sleep(forTimeInterval: 0.2)+ }+ log("\(name) sent")+ }++ private func shot(_ name: String) {+ try? XCUIScreen.main.screenshot().pngRepresentation.write(to: out.appendingPathComponent("\(name).png"))+ }++ private func log(_ line: String) {+ let file = out.appendingPathComponent("runner.log")+ let text = "\(ISO8601DateFormatter().string(from: Date())) \(line)\n"+ if let handle = try? FileHandle(forWritingTo: file) {+ handle.seekToEndOfFile()+ handle.write(text.data(using: .utf8)!)+ try? handle.close()+ } else {+ try? text.write(to: file, atomically: true, encoding: .utf8)+ }+ }+}diff --git a/mobile/integration_test/push_e2e/gen.rb b/mobile/integration_test/push_e2e/gen.rbnew file mode 100644index 000000000..06b727032--- /dev/null+++ b/mobile/integration_test/push_e2e/gen.rb@@ -0,0 +1,19 @@+# Writes the runner's Xcode project: a UI test bundle with no host app, driving the installed app by+# its bundle id (PushE2E.swift). Usage: ruby gen.rb <dir> <PushE2E.swift>+require 'xcodeproj'++dir, source = ARGV+project = Xcodeproj::Project.new(File.join(dir, 'PushE2E.xcodeproj'))+target = project.new_target(:ui_test_bundle, 'PushE2E', :ios, '17.0')+target.add_file_references([project.main_group.new_file(File.expand_path(source))])+target.build_configurations.each do |config|+ config.build_settings['PRODUCT_BUNDLE_IDENTIFIER'] = 'ai.autonomous.harness.pushe2e'+ config.build_settings['GENERATE_INFOPLIST_FILE'] = 'YES'+ config.build_settings['SWIFT_VERSION'] = '5.0'+ config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO'+end+project.save+scheme = Xcodeproj::XCScheme.new+scheme.add_build_target(target)+scheme.add_test_target(target)+scheme.save_as(project.path, 'PushE2E', true)diff --git a/mobile/integration_test/push_e2e/reply_push.apns b/mobile/integration_test/push_e2e/reply_push.apnsnew file mode 100644index 000000000..d50dc9871--- /dev/null+++ b/mobile/integration_test/push_e2e/reply_push.apns@@ -0,0 +1,11 @@+{+ "aps": {+ "alert": { "title": "River replied in a thread", "subtitle": "Phone Swarm", "body": "Open Harness to read it." },+ "sound": "default",+ "thread-id": "swarm-needs-you",+ "category": "swarm-needs-you"+ },+ "key": "reply:tab-1:act-r2",+ "link": "swarm:tab-1/g1/message/r2/thread/m1",+ "slot": "thread:tab-1:g1:m1"+}diff --git a/mobile/integration_test/push_e2e/run.sh b/mobile/integration_test/push_e2e/run.shnew file mode 100755index 000000000..4be142b35--- /dev/null+++ b/mobile/integration_test/push_e2e/run.sh@@ -0,0 +1,78 @@+#!/usr/bin/env bash+# The phone push end to end on an iOS simulator (task #3248): a reply push reaches the app while it+# is closed, iOS draws it, its tap starts the app on the thread its link names, and the same push+# with the app in front is not drawn. Screenshots and logs land in OUT (default: a new mktemp -d).+#+# mobile/integration_test/push_e2e/run.sh <simulator udid> [out dir]+#+# Simulators only: the udid must be one `xcrun simctl` lists. The app is uninstalled first, so its+# first launch asks for notices again. Nothing reaches an account or the backend+# (`push_e2e_app.dart`). Needs Xcode and the xcodeproj gem (CocoaPods bundles it; set+# XCODEPROJ_RUBY to a ruby that can `require "xcodeproj"` when the default one cannot).+set -euo pipefail++udid=${1:?usage: run.sh <simulator udid> [out dir]}+here=$(cd "$(dirname "$0")" && pwd)+mobile=$(cd "$here/../.." && pwd)+work=$(mktemp -d)+out=${2:-$work/out}+mkdir -p "$out"+bundle=ai.autonomous.harness.ios++xcrun simctl list devices | grep -q "($udid)" || { echo "no simulator $udid" >&2; exit 2; }++ruby=${XCODEPROJ_RUBY:-}+if [[ -z $ruby ]]; then+ if ruby -e 'require "xcodeproj"' 2>/dev/null; then+ ruby=ruby+ else+ # CocoaPods' own gems, and the gems they need from Homebrew's ruby (rexml).+ pods=$(brew --prefix cocoapods 2>/dev/null)/libexec+ brewruby=$(brew --prefix ruby 2>/dev/null)/bin/ruby+ ruby="env GEM_HOME=$pods GEM_PATH=$pods:$($brewruby -e 'print Gem.default_dir') $brewruby"+ fi+fi++echo "build: the e2e app"+(cd "$mobile" && flutter build ios --simulator --debug --target=integration_test/push_e2e_app.dart)++echo "simulator: $udid"+xcrun simctl boot "$udid" 2>/dev/null || true+xcrun simctl bootstatus "$udid" -b >/dev/null+xcrun simctl uninstall "$udid" "$bundle" 2>/dev/null || true+xcrun simctl install "$udid" "$mobile/build/ios/iphonesimulator/Runner.app"++echo "build: the runner"+$ruby "$here/gen.rb" "$work/runner" "$here/PushE2E.swift"+xcodebuild build-for-testing -project "$work/runner/PushE2E.xcodeproj" -scheme PushE2E \+ -destination "id=$udid" -derivedDataPath "$work/derived" CODE_SIGNING_ALLOWED=NO -quiet++# What the tapped push opened, as the app says it (`push-e2e:` lines).+xcrun simctl spawn "$udid" log stream --style compact --predicate 'eventMessage CONTAINS "push-e2e"' \+ > "$out/app.log" 2>&1 &+logger=$!+trap 'kill $logger 2>/dev/null || true' EXIT++echo "run: logs and screenshots in $out"+TEST_RUNNER_OUT="$out" xcodebuild test-without-building -project "$work/runner/PushE2E.xcodeproj" \+ -scheme PushE2E -destination "id=$udid" -derivedDataPath "$work/derived" \+ -only-testing:PushE2E/PushE2E/testDrive > "$out/xcodebuild.log" 2>&1 &+runner=$!++# Each push the runner asks for: the server's body for River's reply.+for push in push-1 push-2; do+ until [[ -e "$out/want-$push" ]]; do+ kill -0 $runner 2>/dev/null || break 2+ sleep 0.2+ done+ xcrun simctl push "$udid" "$bundle" "$here/reply_push.apns"+ touch "$out/sent-$push"+done++status=0+wait $runner || status=$?+sleep 1+grep -E "Test (Case|Suite).*(passed|failed)|error:" "$out/xcodebuild.log" | tail -5 || true+echo "runner:"; cat "$out/runner.log" 2>/dev/null || true+echo "app:"; grep "push-e2e:" "$out/app.log" || true+exit $statusdiff --git a/mobile/integration_test/push_e2e_app.dart b/mobile/integration_test/push_e2e_app.dartnew file mode 100644index 000000000..ea7afcbde--- /dev/null+++ b/mobile/integration_test/push_e2e_app.dart@@ -0,0 +1,197 @@+import 'dart:async';++import 'package:flutter/material.dart';++import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/core/local_key_value_store.dart';+import 'package:harness_mobile/core/models.dart' show CurrentUserProfile;+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/phone/phone_shell.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/state/app_state.dart';++import '../test/swarm/swarm_fixture.dart';++/// The phone app for the push end to end (task #3248, `push_e2e/run.sh`): the real [PhoneShell] with the+/// real notices ([LocalSystemNotices]) and the real push channel ([PushChannel]: `AppDelegate.swift`,+/// `MainActivity.kt`), signed in to a Swarm scripted in memory. A push the simulator is sent with the+/// app closed is drawn by iOS; its tap starts the app, which opens the thread its `link` names.+///+/// Nothing reaches an account, a machine or the backend: the Swarm is [FakeSwarm], the backend address+/// is a closed local port, and this phone's push address is never registered ([_NeverRegistered]).+///+/// flutter build ios --simulator --debug --target=integration_test/push_e2e_app.dart+Future<void> main() async {+ WidgetsFlutterBinding.ensureInitialized();+ // XCUITest finds what is on screen by its semantics.+ WidgetsBinding.instance.ensureSemantics();+ // In memory only: the value, not the store's write.+ experimentalFeaturesStore.value = {PhoneExperiment.swarm};++ final notices = LocalSystemNotices();+ final app = _PushE2eApp(+ _swarm(),+ systemNotices: notices,+ pushTokens: _NeverRegistered(+ channel: PushChannel(),+ storage: _Memory(),+ allowed: () async => true,+ ),+ )..currentUser = const CurrentUserProfile(id: me, email: '[email protected]');+ // What the runner reads in the simulator's log: the push the tap opened.+ notices.openedSwarm.addListener(() {+ final target = notices.openedSwarm.value;+ if (target == null) return;+ debugPrint(+ 'push-e2e: opened ${target.swarmId}/${target.conversationId} '+ 'message ${target.messageId} thread ${target.threadId}',+ );+ });+ runApp(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ home: PhoneShell(notifier: app),+ ),+ );+ // As Settings asks: the first launch's prompt, which the runner allows.+ unawaited(notices.requestPermission());+}++/// The Swarm the phone reads: chat "Onboarding copy" in project Mobile, where Sam asked something in+/// a thread (`m1`) and River and Nova replied in it. The push the runner sends is River's reply's.+FakeSwarm _swarm() {+ const chat = 'g1';+ Map<String, dynamic> message(+ String id,+ int sequence,+ String text, {+ required Map<String, dynamic> author,+ String? thread,+ int replies = 0,+ }) => {+ 'id': id,+ 'conversationId': chat,+ 'text': text,+ 'sequence': sequence,+ 'replyTo': ?thread,+ 'thread': ?thread,+ if (replies > 0) 'replyCount': replies,+ 'author': author,+ 'attachments': <Object>[],+ 'reactions': <Object>[],+ 'createdAt': DateTime.utc(2026, 11, 5, 9, sequence).toIso8601String(),+ };+ const sam = {'kind': 'person', 'id': me, 'name': 'Sam'};+ const river = {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'};+ const nova = {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'};+ final root = message(+ 'm1',+ 1,+ 'Who can draft the onboarding copy for the three welcome screens?',+ author: sam,+ replies: 2,+ );++ const path = '/api/super-tabs/$tab';+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['$path/parts'] = (_) => firstLoad(+ groups: [+ groupData(+ chat,+ title: 'Onboarding copy',+ agentIds: ['agent-lead', 'agent-builder'],+ lastMessageSequence: 3,+ ),+ ],+ );+ fake.routes['$path/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['$path/decisions'] = (_) => {'decisions': <Object>[]};+ fake.routes['$path/mentions'] = (_) => {'mentions': <Object>[]};+ fake.routes['$path/activity'] = (_) => {'items': <Object>[]};+ fake.routes['$path/commands'] = (_) => <String, dynamic>{'result': {}};+ // Whatever else a screen reads: nothing there.+ fake.routes['$path/'] = (_) => <String, dynamic>{+ 'messages': <Object>[],+ 'next': null,+ };+ fake.routes['$path/conversations/$chat/messages'] = (_) => {+ 'messages': [root],+ 'next': null,+ };+ fake.routes['$path/conversations/$chat/messages?thread=m1'] = (_) => {+ 'messages': [+ message(+ 'r3',+ 3,+ 'I can take the third screen once the first two land.',+ author: nova,+ thread: 'm1',+ ),+ message(+ 'r2',+ 2,+ 'Drafted the first two screens: short, one idea each.',+ author: river,+ thread: 'm1',+ ),+ ],+ };+ return fake;+}++class _PushE2eApp extends AppNotifier {+ _PushE2eApp(this._fake, {super.systemNotices, super.pushTokens})+ : super(+ // A closed local port: anything that is not the scripted Swarm fails here, at once.+ config: const AppConfig(apiBaseUrl: 'http://127.0.0.1:9'),+ authSession: AuthSession(storage: _Memory()),+ configStore: null,+ );++ final FakeSwarm _fake;++ @override+ Future<Object?> swarmRequest(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) => _fake.request(method, path, body: body);+}++/// The real push channel, whose address is never sent anywhere.+class _NeverRegistered extends PushTokens {+ _NeverRegistered({+ required super.channel,+ required super.storage,+ required super.allowed,+ });++ @override+ Future<void> sync({+ required String account,+ required PushTokenApi api,+ required bool Function() current,+ }) async {}+}++class _Memory implements LocalKeyValueStore {+ final values = <String, String>{};++ @override+ Future<String?> read(String key) async => values[key];++ @override+ Future<void> write(String key, String value) async => values[key] = value;++ @override+ Future<void> delete(String key) async => values.remove(key);+}diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swiftindex c019ecee1..85ca986fd 100644--- a/mobile/ios/Runner/AppDelegate.swift+++ b/mobile/ios/Runner/AppDelegate.swift@@ -123,12 +123,16 @@ final class PushChannel {result(self.waiting)self.waiting.removeAll()case "shown":- // The keys of our pushes still in the notification centre: the app does not post them again- // (Dart: `PushChannel.shown`). The server keys a push as the app keys its own notice.+ // The keys of our pushes still in the notification centre, and the slots they show in: the+ // app does not post them again (Dart: `PushChannel.shown`). The server keys a push as the app+ // keys its own notice, and a thread's replies share one slot (task #3248).UNUserNotificationCenter.current().getDeliveredNotifications { delivered inlet keys = delivered.filter { $0.request.trigger is UNPushNotificationTrigger }- .compactMap { $0.request.content.userInfo["key"] as? String }+ .flatMap { shown -> [String] in+ let info = shown.request.content.userInfo+ return [info["key"], info["slot"]].compactMap { $0 as? String }+ }DispatchQueue.main.async { result(keys) }}default:diff --git a/mobile/lib/notify/agent_announcer.dart b/mobile/lib/notify/agent_announcer.dartindex 9789cf21b..7ab8c2b02 100644--- a/mobile/lib/notify/agent_announcer.dart+++ b/mobile/lib/notify/agent_announcer.dart@@ -111,6 +111,10 @@ class AgentAnnouncer {/// second thing to dismiss by hand — without asking the OS for one that was/// never posted.final _posted = <AgentRef>{};++ /// Of [_posted], the agents whose notice up tells of a finished turn: the+ /// next turn's end replaces it quietly (task #3248).+ final _doneUp = <AgentRef>{};final Future<void> Function() _chime;final bool Function() _inFront;@@ -204,7 +208,13 @@ class AgentAnnouncer {}) {final front = inFront;final seen = front && watching();- final notice = decideDoneNotice(end, inFront: front, watching: seen);+ var notice = decideDoneNotice(end, inFront: front, watching: seen);+ // Sounds once until the person goes to the agent (task #3248, the rule+ // Tony approved): a turn that ends while the last one's notice is still up+ // replaces it quietly.+ if (notice == AgentNotice.alert && _doneUp.contains(agent.ref)) {+ notice = AgentNotice.quiet;+ }// Ids and decisions only: what the turn said stays out of the log.appLog.debug('notify', 'done · ${_short(agent.ref)} · ${front ? 'front' : 'away'}${seen ? ' · watching' : ''} · ${notice.name}');_deliver(agent, notice, NoticeKind.done, () => noticeBody(end.reply!));@@ -410,6 +420,7 @@ class AgentAnnouncer {}void _withdraw(AgentRef ref) {+ _doneUp.remove(ref);if (_posted.remove(ref)) system.cancel(ref);}@@ -423,6 +434,13 @@ class AgentAnnouncer {if (notice.marks) unread.mark(agent.ref, kind);if (!notice.alerts) return;_posted.add(agent.ref);+ // The agent's one notice now tells of this kind: a question over a+ // finished turn leaves the next turn's end free to sound.+ if (kind == NoticeKind.done) {+ _doneUp.add(agent.ref);+ } else {+ _doneUp.remove(agent.ref);+ }system.show((agent: agent.ref,kind: kind,diff --git a/mobile/lib/notify/system_notices.dart b/mobile/lib/notify/system_notices.dartindex 96329db61..9d5130c15 100644--- a/mobile/lib/notify/system_notices.dart+++ b/mobile/lib/notify/system_notices.dart@@ -31,14 +31,18 @@ typedef SwarmNoticeTarget = ({String? threadId,});-/// One notice about what a Swarm asks of the person. [key] names it, so the-/// same need posted twice replaces itself; [subtitle] says where it is.+/// One notice about what a Swarm asks of the person. [key] names the+/// notification it shows in, so the same need posted twice replaces itself,+/// and so does the server's push for it (task #3248: a thread's replies share+/// one); [subtitle] says where it is. [quiet] replaces what that notification+/// showed with no sound, no vibration and no banner.typedef SwarmNoticeMessage = ({String key,String title,String subtitle,String body,SwarmNoticeTarget target,+ bool quiet,});/// The notification centre's Swarm notices: decisions asked of the person,@@ -153,6 +157,21 @@ const _swarmPayload = 'swarm:';/// The Android channel, iOS thread and iOS category of Swarm notices.const _swarmChannel = 'swarm-needs-you';+/// The Android channel of a quiet push (task #3248; backend `push/sender.ts` SWARM_QUIET_CHANNEL): on+/// Android the channel, not the push, decides whether it sounds, so this one never does.+const _swarmQuietChannel = 'swarm-quiet';++/// How Android names the Swarm channel, here and when a notice makes it.+const _swarmChannelName = 'Swarm needs you';+const _swarmChannelDescription =+ 'A Swarm asks you to decide, tags you, or has work waiting on you.';++/// Android draws an FCM push under its tag with this id (the server tags it with the notice's key), so a+/// Swarm notice posted under the same tag and id replaces the push, and the other way round.+const _androidPushId = 0;++bool get _android => defaultTargetPlatform == TargetPlatform.android;+/// `harness/app_badge` — the app icon's count (Swift: `AppBadgeChannel` in `ios/Runner/AppDelegate.swift`).const _appBadge = MethodChannel('harness/app_badge');@@ -180,6 +199,41 @@ class LocalSystemNotices implements SystemNotices, SwarmNotices {/// start reaching them (`notify/push_tokens.dart`).void Function()? onAllowed;+ /// Android: makes the channels pushes are drawn on, before one can arrive (task #3248). Without+ /// them a push that came before the app's first Swarm notice landed on FCM's default channel, and+ /// a quiet one would sound. Needs no start of the centre; nothing on iOS, whose pushes have no+ /// channel.+ Future<void> preparePush() async {+ if (!_android) return;+ try {+ final android = _plugin+ .resolvePlatformSpecificImplementation<+ AndroidFlutterLocalNotificationsPlugin+ >();+ await android?.createNotificationChannel(+ const AndroidNotificationChannel(+ _swarmChannel,+ _swarmChannelName,+ description: _swarmChannelDescription,+ importance: Importance.high,+ ),+ );+ await android?.createNotificationChannel(+ const AndroidNotificationChannel(+ _swarmQuietChannel,+ 'Swarm, quiet updates',+ description:+ 'A newer reply in a thread you have not read yet: it replaces the notice already there.',+ importance: Importance.low,+ playSound: false,+ enableVibration: false,+ ),+ );+ } catch (error) {+ appLog.warn('notify', 'push channels not made', error: error);+ }+ }+/// 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.@@ -363,31 +417,46 @@ class LocalSystemNotices implements SystemNotices, SwarmNotices {}}+ /// Where a Swarm notice is in the notification centre: the notification the server's push for the+ /// same thing uses (task #3248). Android: its key as the tag, with FCM's id. iOS: [swarmNoticeIdFor],+ /// which the push carries in decimal as its `apns-collapse-id`.+ ({int id, String? tag}) _swarmPlace(String key) => _android+ ? (id: _androidPushId, tag: key)+ : (id: swarmNoticeIdFor(key), tag: null);+@overrideFuture<void> showSwarm(SwarmNoticeMessage message) async {+ final place = _swarmPlace(message.key);+ final quiet = message.quiet;try {await _init();await _plugin.show(- id: swarmNoticeIdFor(message.key),+ id: place.id,title: message.title,body: message.body,payload: encodeSwarmPayload(message.target),notificationDetails: NotificationDetails(android: AndroidNotificationDetails(_swarmChannel,- 'Swarm needs you',- channelDescription:- 'A Swarm asks you to decide, tags you, or has work waiting on you.',+ _swarmChannelName,+ channelDescription: _swarmChannelDescription,importance: Importance.high,priority: Priority.high,subText: message.subtitle,// Hidden on a secure lock screen set to hide private content.visibility: NotificationVisibility.private,+ tag: place.tag,+ // A quiet one replaces what its notification showed, without a sound, a vibration or a+ // heads-up, as a quiet agent notice does.+ silent: quiet,),iOS: DarwinNotificationDetails(subtitle: message.subtitle,threadIdentifier: _swarmChannel,categoryIdentifier: _swarmChannel,+ presentSound: quiet ? false : null,+ presentBanner: quiet ? false : null,+ interruptionLevel: quiet ? InterruptionLevel.passive : null,),),);@@ -396,11 +465,13 @@ class LocalSystemNotices implements SystemNotices, SwarmNotices {}}+ /// Also takes down the push shown in the same notification.@overrideFuture<void> cancelSwarm(String key) async {+ final place = _swarmPlace(key);try {await _init();- await _plugin.cancel(id: swarmNoticeIdFor(key));+ await _plugin.cancel(id: place.id, tag: place.tag);} catch (error) {appLog.warn('notify', 'swarm cancel failed', error: error);}diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 914e1e08c..5730d26dc 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -3635,6 +3635,8 @@ class AppNotifier extends ChangeNotifier {);if (agentNotices.system case final LocalSystemNotices notices) {notices.onAllowed = _syncPush;+ // Android: the channels a push is drawn on, before the first can arrive (task #3248).+ unawaited(notices.preparePush());}// Back from the phone's Settings, where notices may have been turned on or off._pushLifecycle = AppLifecycleListener(onResume: _syncPush);diff --git a/mobile/lib/swarm/swarm_notices.dart b/mobile/lib/swarm/swarm_notices.dartindex 479daa526..a23911a07 100644--- a/mobile/lib/swarm/swarm_notices.dart+++ b/mobile/lib/swarm/swarm_notices.dart@@ -51,9 +51,16 @@ SwarmNoticeMessage swarmNotice(SwarmNeed need) {// A tag in a reply only in its thread opens that thread.threadId: need is SwarmMentionNeed ? need.mention.threadId : null,),+ quiet: false,);}+/// The notification a thread's replies share, the server's push for them too+/// (task #3248; backend `push/notices.ts` threadSlot): a newer reply replaces+/// the one shown.+String threadSlot(String swarmId, String conversationId, String threadId) =>+ 'thread:$swarmId:$conversationId:$threadId';+/// Posts a notice for each need that arrives ([SwarmInbox.onArrived]) unless/// the person is already looking at it ([quiet]), and takes it down once the/// need is gone: answered on the desktop, done, or no longer waiting — missing@@ -163,6 +170,9 @@ class SwarmAnnouncer {}) {if (quiet(null)) return;final key = 'chat:$swarmId:$chatId';+ // Sounds once until the person reads the chat; a newer message only+ // replaces it (task #3248).+ final up = _chats.containsKey(key);_chats[key] = (swarmId: swarmId, chatId: chatId, sequence: sequence);unawaited(notices.showSwarm((@@ -177,6 +187,7 @@ class SwarmAnnouncer {decisionId: null,threadId: null,),+ quiet: up,)),);}@@ -196,13 +207,18 @@ class SwarmAnnouncer {}}- /// The notices of replies in threads the person is in: each key's Swarm- /// and Activity row.- final _replies = <String, ({String swarmId, String rowId})>{};+ /// The notifications of threads the person is in, by [threadSlot]: each+ /// one's Swarm and the unread Activity rows it tells of.+ final _replies = <String, ({String swarmId, Set<String> rows})>{};/// Posts [entry]'s notice, once: a reply in a thread of Swarm [swarmId]'s/// project [project] that the person is in ([SwarmActivityFeed.onReply])./// Names who replied and the project only, as [swarmNotice] does.+ ///+ /// One notification per thread, which the server's push for it shares+ /// (task #3248, the rule Tony approved): it sounds when nothing of that+ /// thread was unread; a newer reply only replaces it quietly. A thread a+ /// push still shows gets nothing: that push says so already.void announceReply({required String swarmId,required SwarmActivityEntry entry,@@ -211,11 +227,17 @@ class SwarmAnnouncer {if (quiet(null)) return;final key = 'reply:$swarmId:${entry.id}';if (!told.add(key)) return;- _replies[key] = (swarmId: swarmId, rowId: entry.id);+ final thread = entry.threadId;+ final slot = thread == null+ ? key+ : threadSlot(swarmId, entry.conversationId, thread);+ final earlier = _replies[slot];+ _replies[slot] = (swarmId: swarmId, rows: {...?earlier?.rows, entry.id});+ if (told.pushed(slot)) return;final who = entry.actorName.isEmpty ? 'Someone' : entry.actorName;unawaited(notices.showSwarm((- key: key,+ key: slot,title: '$who replied in a thread',subtitle: project,body: 'Open Harness to read it.',@@ -227,26 +249,33 @@ class SwarmAnnouncer {// A reply only in its thread is found there, not in the chat.threadId: entry.threadId,),+ quiet: earlier != null,)),);}- /// Swarm [swarmId]'s Activity was read and lists [rows]: a reply's notice- /// whose row is read now, or no longer listed, is taken down.+ /// Swarm [swarmId]'s Activity was read and lists [rows]: a thread's+ /// notification none of whose rows is unread now, or listed, is taken down,+ /// with the push it shares, and the thread's next reply sounds again.void repliesRead(String swarmId, Iterable<SwarmActivityEntry> rows) {final unread = {for (final row in rows)if (!row.read) row.id,};for (final MapEntry(:key, :value) in _replies.entries.toList()) {- if (value.swarmId == swarmId && !unread.contains(value.rowId)) {+ if (value.swarmId != swarmId) continue;+ final left = value.rows.intersection(unread);+ if (left.isEmpty) {_takeDownReply(key);+ } else {+ _replies[key] = (swarmId: swarmId, rows: left);}}}void _takeDownReply(String key) {_replies.remove(key);+ told.pushGone(key);unawaited(notices.cancelSwarm(key));}@@ -307,12 +336,34 @@ class SwarmTold {/// notification centre (task #2905).void addAll(Iterable<String> keys) => keys.forEach(add);+ /// The keys and notification slots of the pushes in the notification centre+ /// as the app last came back ([SwarmHost.toldElsewhere]).+ Set<String> _pushes = const {};++ /// The pushes in the notification centre now, by their keys and the slots+ /// they show in (task #3248: Android gives the slot alone). Each is told+ /// ([addAll]); [pushed] holds for each until the next call.+ void pushesShown(Iterable<String> keys) {+ final shown = {...keys};+ addAll(shown);+ _pushes = shown;+ }++ /// Whether a push still shows notification [slot].+ bool pushed(String slot) => _pushes.contains(slot);++ /// The app took notification [slot] down, and the push in it with it.+ void pushGone(String slot) {+ if (_pushes.contains(slot)) _pushes = {..._pushes}..remove(slot);+ }+/// Whose notices these are: another account, or none (Swarm turned off),/// forgets every key.set account(String? id) {if (id == _account) return;_account = id;_keys.clear();+ _pushes = const {};}@visibleForTestingdiff --git a/mobile/lib/swarm/swarm_session.dart b/mobile/lib/swarm/swarm_session.dartindex 93bbf7b35..db905cb72 100644--- a/mobile/lib/swarm/swarm_session.dart+++ b/mobile/lib/swarm/swarm_session.dart@@ -446,9 +446,10 @@ class SwarmHost extends ChangeNotifier {session?.foreground = value;}- /// Notices the person was already shown by a push while the app was away:- /// never posted again ([SwarmTold.addAll]).- void toldElsewhere(Iterable<String> keys) => _told.addAll(keys);+ /// Notices the person was already shown by a push while the app was away,+ /// by their keys and slots: never posted again, and a thread a push still+ /// shows gets no notice of its own ([SwarmTold.pushesShown]).+ void toldElsewhere(Iterable<String> keys) => _told.pushesShown(keys);/// A computer may have come up: a Swarm waiting for one reads at once.void _computersChanged() {diff --git a/mobile/test/notify/agent_announcer_test.dart b/mobile/test/notify/agent_announcer_test.dartindex b51cdbbc0..91e3c7995 100644--- a/mobile/test/notify/agent_announcer_test.dart+++ b/mobile/test/notify/agent_announcer_test.dart@@ -336,6 +336,20 @@ void main() {});});+ test('a finished turn sounds once until the person goes to the agent; '+ 'the next only replaces it quietly (task #3248)', () {+ front = false;+ const other = (ref: (machineId: 'm', agentId: 'b'), name: 'Docs', machine: 'MacBook');+ announcer.turnEnded(agent, news, watching: () => false);+ announcer.turnEnded(agent, news, watching: () => false);+ announcer.turnEnded(other, news, watching: () => false);+ expect([for (final n in system.shown) (n.agent.agentId, n.quiet)], [('a', false), ('a', true), ('b', false)]);++ announcer.seen(ref);+ announcer.turnEnded(agent, news, watching: () => false);+ expect(system.shown.last.quiet, isFalse, reason: 'seen: the next is news again');+ });+test('an agent is one mark however many turns it finished', () {announcer.turnEnded(agent, news, watching: () => false);announcer.turnEnded(agent, news, watching: () => false);diff --git a/mobile/test/notify/announcer_lifecycle_test.dart b/mobile/test/notify/announcer_lifecycle_test.dartindex 495af56ac..f871017ea 100644--- a/mobile/test/notify/announcer_lifecycle_test.dart+++ b/mobile/test/notify/announcer_lifecycle_test.dart@@ -54,11 +54,14 @@ void main() {tester.binding.handleAppLifecycleStateChanged(state);}expect(announcer.inFront, isFalse);+ // Pocketed, even on the agent last on screen: the notice is posted. The+ // first one is still up, unseen, so this one replaces it quietly (task #3248).expect(announcer.turnEnded(agent, news, watching: () => true),- AgentNotice.alert,+ AgentNotice.quiet,);expect(system.shown, hasLength(2));+ expect(system.shown.last.quiet, isTrue);expect(system.shown.last.body, 'Fixed the login screen.');tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);diff --git a/mobile/test/notify/local_system_notices_test.dart b/mobile/test/notify/local_system_notices_test.dartindex 1886baec8..bc95fc6d7 100644--- a/mobile/test/notify/local_system_notices_test.dart+++ b/mobile/test/notify/local_system_notices_test.dart@@ -84,13 +84,15 @@ void main() {subtitle: 'Mobile',body: 'Open Harness to answer.',target: target,+ quiet: false,);+ tearDown(() => debugDefaultTargetPlatformOverride = null);test('its own channel, where it is on the second line, replaced by its own key', () async {await notices.showSwarm(swarm);await notices.showSwarm(swarm);- expect(plugin.shown.map((n) => n.id).toSet(), {swarmNoticeIdFor('decision:d1')});+ expect(plugin.shown.map((n) => n.details!.android!.tag).toSet(), {'decision:d1'});final shown = plugin.shown.first;expect(shown.title, 'River asks you');expect(shown.body, 'Open Harness to answer.');@@ -148,9 +150,60 @@ void main() {expect(decodeSwarmPayload(encodeSwarmPayload(inThread)), inThread);});- test('taking it down cancels its own id', () async {+ // The server's push for the same thing shows in the same notification (task #3248): Android draws an FCM push under its+ // tag with id 0, iOS keys a push by its `apns-collapse-id`, this id in decimal. So the app's notice replaces the push.+ test('iOS: posted and taken down under the id the push collapses on', () async {+ debugDefaultTargetPlatformOverride = TargetPlatform.iOS;+ await notices.showSwarm(swarm);+ await notices.cancelSwarm('decision:d1');+ expect(plugin.shown.single.id, swarmNoticeIdFor('decision:d1'));+ expect(plugin.shown.single.details!.android!.tag, isNull);+ expect(plugin.cancelled, [(id: swarmNoticeIdFor('decision:d1'), tag: null)]);+ });++ test('Android: posted and taken down under its key as the tag, id 0, as FCM draws the push', () async {+ debugDefaultTargetPlatformOverride = TargetPlatform.android;+ await notices.showSwarm(swarm);await notices.cancelSwarm('decision:d1');- expect(plugin.cancelled, [swarmNoticeIdFor('decision:d1')]);+ expect(plugin.shown.single.id, 0);+ expect(plugin.shown.single.details!.android!.tag, 'decision:d1');+ expect(plugin.cancelled, [(id: 0, tag: 'decision:d1')]);+ });++ test('a quiet one replaces its notification with no sound, no vibration and no banner (task #3248)', () async {+ await notices.showSwarm((+ key: 'thread:tab-1:g9:root-1',+ title: 'Mia replied in a thread',+ subtitle: 'Mobile',+ body: 'Open Harness to read it.',+ target: target,+ quiet: true,+ ));+ final details = plugin.shown.single.details!;+ expect(details.android!.silent, isTrue);+ expect(details.iOS!.presentSound, isFalse);+ expect(details.iOS!.presentBanner, isFalse);+ expect(details.iOS!.interruptionLevel, InterruptionLevel.passive);+ // A notice with sound leaves them to the channel and the plugin.+ await notices.showSwarm(swarm);+ expect(plugin.shown.last.details!.android!.silent, isFalse);+ expect(plugin.shown.last.details!.iOS!.presentSound, isNull);+ });++ test('Android: the push channels exist before a push can arrive, the quiet one silent (task #3248)', () async {+ debugDefaultTargetPlatformOverride = TargetPlatform.android;+ await notices.preparePush();+ expect(plugin.android.channels.map((c) => (c.id, c.importance, c.playSound)), [+ ('swarm-needs-you', Importance.high, true),+ ('swarm-quiet', Importance.low, false),+ ]);+ expect(plugin.initialized, 0, reason: 'made without starting the centre');+ });++ test('iOS has no channels to make', () async {+ debugDefaultTargetPlatformOverride = TargetPlatform.iOS;+ await notices.preparePush();+ expect(plugin.android.channels, isEmpty);});test('a plugin that fails never throws into the Swarm', () async {@@ -242,7 +295,7 @@ void main() {test('taking a notice down cancels that agent\'s id', () async {await notices.cancel(ref);- expect(plugin.cancelled, [noticeIdFor(ref)]);+ expect(plugin.cancelled, [(id: noticeIdFor(ref), tag: null)]);});test('asking permission asks both platforms for alerts, sound and the icon count', () async {@@ -472,7 +525,7 @@ typedef _Shown = ({/// falls to [noSuchMethod] — and so fails the test, which is the point.class _FakePlugin implements FlutterLocalNotificationsPlugin {final shown = <_Shown>[];- final cancelled = <int>[];+ final cancelled = <({int id, String? tag})>[];final ios = _FakeIos();final android = _FakeAndroid();int initialized = 0;@@ -534,7 +587,7 @@ class _FakePlugin implements FlutterLocalNotificationsPlugin {@overrideFuture<void> cancel({required int id, String? tag}) async {if (failCancel) throw PlatformException(code: 'cancel');- cancelled.add(id);+ cancelled.add((id: id, tag: tag));}@override@@ -567,6 +620,11 @@ class _FakeIos implements IOSFlutterLocalNotificationsPlugin {class _FakeAndroid implements AndroidFlutterLocalNotificationsPlugin {int asked = 0;+ final channels = <AndroidNotificationChannel>[];++ @override+ Future<void> createNotificationChannel(AndroidNotificationChannel notificationChannel) async =>+ channels.add(notificationChannel);@overrideFuture<bool?> requestNotificationsPermission() async {diff --git a/mobile/test/swarm/swarm_chat_notices_test.dart b/mobile/test/swarm/swarm_chat_notices_test.dartindex d7d0befdd..18ef48248 100644--- a/mobile/test/swarm/swarm_chat_notices_test.dart+++ b/mobile/test/swarm/swarm_chat_notices_test.dart@@ -69,6 +69,8 @@ void main() {backend.move('g1', 5);await poll(session);expect(told(), [g1Notice, g1Notice]);+ // Sounds once until the person looks: the next one only replaces it (task #3248).+ expect([for (final n in notices.shown) n.quiet], [false, true]);// Read again with nothing new: nothing told again.backend.version++;@@ -143,6 +145,23 @@ void main() {expect(notices.cancelled, [g1Notice, 'chat:$tab:g2']);});+ test('read, the chat\'s next message sounds again (task #3248)', () async {+ backend.settings = {'g1': 'all'};+ final session = await start();+ backend.move('g1', 4);+ await poll(session);+ backend.move('g1', 5);+ await poll(session);+ session.inbox.reader(tab)!.readMarks!.markRead('g1', 5);+ backend.version++;+ await poll(session);+ expect(notices.cancelled, [g1Notice]);++ backend.move('g1', 6);+ await poll(session);+ expect([for (final n in notices.shown) n.quiet], [false, true, false]);+ });+test('signed out or Swarm turned off: every chat notice goes', () async {backend.settings = {'g1': 'all'};final session = await start(disposeAtEnd: false);diff --git a/mobile/test/swarm/swarm_notices_test.dart b/mobile/test/swarm/swarm_notices_test.dartindex 258aea459..12f00a9b2 100644--- a/mobile/test/swarm/swarm_notices_test.dart+++ b/mobile/test/swarm/swarm_notices_test.dart@@ -215,13 +215,13 @@ void main() {});group('a reply in a thread the person is in', () {- SwarmActivityEntry reply(String id, {bool read = false}) =>+ SwarmActivityEntry reply(String id, {bool read = false, String threadId = 'root-1'}) =>SwarmActivityEntry.fromJson({'id': id,'kind': 'reply','conversationId': 'g9','messageId': 'msg-$id',- 'threadId': 'root-1',+ 'threadId': threadId,'actor': {'kind': 'person', 'id': 'person-mia', 'name': 'Mia'},'text': "sounds good, I'll ship the copy today",'createdAt': DateTime.utc(2026, 11, 4, 9).toIso8601String(),@@ -282,7 +282,67 @@ void main() {project: 'M',);expect(notices.shown, hasLength(2));- expect(notices.shown[0].key, isNot(notices.shown[1].key));+ });++ test('shares one notification per thread, the push\'s too: a newer '+ 'reply replaces it quietly until the thread is read (task #3248)', () {+ final notices = _Recording();+ final announcer = SwarmAnnouncer(notices, quiet: (_) => false);+ announcer.announceReply(swarmId: 'tab-b', entry: reply('a1'), project: 'M');+ announcer.announceReply(swarmId: 'tab-b', entry: reply('a2'), project: 'M');+ final slot = threadSlot('tab-b', 'g9', 'root-1');+ expect(slot, 'thread:tab-b:g9:root-1', reason: 'the server\'s push slot (backend/src/push/notices.ts threadSlot)');+ expect([for (final n in notices.shown) (n.key, n.quiet)], [(slot, false), (slot, true)]);+ expect(notices.shown.last.target.messageId, 'msg-a2', reason: 'the tap opens the newest');++ // Read up to a1 only: the thread's notification stays for a2.+ announcer.repliesRead('tab-b', [reply('a1', read: true), reply('a2')]);+ expect(notices.cancelled, isEmpty);+ announcer.repliesRead('tab-b', [reply('a1', read: true), reply('a2', read: true)]);+ expect(notices.cancelled, [slot]);++ // Read, the next reply there sounds again; a reply in another thread is a notification of its own.+ announcer.announceReply(swarmId: 'tab-b', entry: reply('a3'), project: 'M');+ announcer.announceReply(swarmId: 'tab-b', entry: reply('b1', threadId: 'root-2'), project: 'M');+ expect([for (final n in notices.shown.skip(2)) (n.key, n.quiet)],+ [(slot, false), (threadSlot('tab-b', 'g9', 'root-2'), false)]);+ });++ test('is not posted for a thread a push shows: the push already says '+ 'so, and comes down once the thread is read (task #3248)', () {+ final notices = _Recording();+ final told = SwarmTold();+ final announcer = SwarmAnnouncer(notices, quiet: (_) => false, told: told);+ final slot = threadSlot('tab-b', 'g9', 'root-1');+ // Android's FCM push carries the thread's slot as its tag, iOS's the slot and the key it showed.+ told.pushesShown([slot, 'reply:tab-b:a1', 'decision:d1']);+ announcer.announceReply(swarmId: 'tab-b', entry: reply('a1'), project: 'M');+ announcer.announceReply(swarmId: 'tab-b', entry: reply('a2'), project: 'M');+ announcer.announce(decision());+ expect(notices.shown, isEmpty);++ // Read in the app: the push goes with the thread's notification, and the next reply there sounds.+ announcer.repliesRead('tab-b', [reply('a1', read: true), reply('a2', read: true)]);+ expect(notices.cancelled, [slot]);+ expect(told.pushed(slot), isFalse);+ announcer.announceReply(swarmId: 'tab-b', entry: reply('a3'), project: 'M');+ expect([for (final n in notices.shown) (n.key, n.quiet)], [(slot, false)]);+ });++ test('a thread whose push was swiped away unread only replaces quietly, '+ 'as the server does', () {+ final notices = _Recording();+ final told = SwarmTold();+ final announcer = SwarmAnnouncer(notices, quiet: (_) => false, told: told);+ final slot = threadSlot('tab-b', 'g9', 'root-1');+ told.pushesShown([slot]);+ announcer.announceReply(swarmId: 'tab-b', entry: reply('a1'), project: 'M');+ expect(notices.shown, isEmpty);++ // Back again with that push gone, and a1 still unread.+ told.pushesShown(const []);+ announcer.announceReply(swarmId: 'tab-b', entry: reply('a2'), project: 'M');+ expect([for (final n in notices.shown) (n.key, n.quiet)], [(slot, true)]);});test('is not posted again when its push is already in the notification '@@ -310,7 +370,7 @@ void main() {entry: reply('a2'),project: 'M',);- expect(notices.shown.single.key, 'reply:tab-b:a2');+ expect(notices.shown.single.key, threadSlot('tab-b', 'g9', 'root-1'));});test('is not posted while the person looks at the Swarm', () {@@ -338,16 +398,16 @@ void main() {);announcer.announceReply(swarmId: 'tab-b',- entry: reply('a2'),+ entry: reply('a2', threadId: 'root-2'),project: 'M',);final [first, second] = [for (final n in notices.shown) n.key];announcer.repliesRead('tab-other', const []);- announcer.repliesRead('tab-b', [reply('a1'), reply('a2')]);+ announcer.repliesRead('tab-b', [reply('a1'), reply('a2', threadId: 'root-2')]);expect(notices.cancelled, isEmpty, reason: 'both still unread');- announcer.repliesRead('tab-b', [reply('a1'), reply('a2', read: true)]);+ announcer.repliesRead('tab-b', [reply('a1'), reply('a2', threadId: 'root-2', read: true)]);expect(notices.cancelled, [second]);announcer.repliesRead('tab-b', const []);