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 i1150: #3071 #3077 (#3079)
0xken15d01f6cc5b16b
diff --git a/backend/integration/pushDevices.test.ts b/backend/integration/pushDevices.test.tsnew file mode 100644index 000000000..07d4ddbd9--- /dev/null+++ b/backend/integration/pushDevices.test.ts@@ -0,0 +1,82 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import type { PrismaClient } from '@prisma/client'+import { planDatabase, profiled, reads, plan } from './plans.test-support.js'+import { PUSH_DEVICES_PER_PERSON, devicesOf, dropPushDevice, forgetPushDevice, markSandbox, registerPushDevice } from '../src/push/devices.js'++// A fresh loopback replica set with the schema pushed; never DATABASE_URL.+let replica: MongoMemoryReplSet+let db: PrismaClient+beforeAll(async () => { ({ replica, db } = await planDatabase('push_devices_test')) })+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})++const NOW = Date.UTC(2026, 10, 5, 9)+let next = 0+const person = () => `person-${++next}`+const token = (n: number) => `${'ab'.repeat(32)}${n}`++describe('Push devices: a phone token belongs to whoever registered it last (task #2905)', () => {+ it('keeps a registered token for its person', async () => {+ const a = person()+ await registerPushDevice(db, a, { platform: 'ios', token: token(1) }, NOW)+ expect(await devicesOf(db, [a])).toEqual([expect.objectContaining({ userId: a, platform: 'ios', token: token(1), sandbox: false })])+ })++ it('moves a token to the next person who signs in on that phone, so the first stops hearing the second\'s notices', async () => {+ const a = person(), b = person()+ await registerPushDevice(db, a, { platform: 'android', token: token(2) }, NOW)+ await registerPushDevice(db, b, { platform: 'android', token: token(2) }, NOW + 1000)+ expect(await devicesOf(db, [a])).toEqual([])+ expect((await devicesOf(db, [b])).map(d => d.token)).toEqual([token(2)])+ })++ it('registering the same token again keeps one row', async () => {+ const a = person()+ await registerPushDevice(db, a, { platform: 'ios', token: token(3) }, NOW)+ await registerPushDevice(db, a, { platform: 'ios', token: token(3) }, NOW + 1000)+ expect(await devicesOf(db, [a])).toHaveLength(1)+ })++ it(`keeps the ${PUSH_DEVICES_PER_PERSON} phones registered last`, async () => {+ const a = person()+ for (let i = 0; i <= PUSH_DEVICES_PER_PERSON; i++) await registerPushDevice(db, a, { platform: 'ios', token: token(100 + i) }, NOW + i * 1000)+ const kept = (await devicesOf(db, [a])).map(d => d.token).sort()+ expect(kept).toHaveLength(PUSH_DEVICES_PER_PERSON)+ expect(kept).not.toContain(token(100))+ })++ it('drops a token only for the person it belongs to', async () => {+ const a = person(), b = person()+ await registerPushDevice(db, a, { platform: 'ios', token: token(4) }, NOW)+ expect(await dropPushDevice(db, b, { platform: 'ios', token: token(4) })).toBe(false)+ expect(await devicesOf(db, [a])).toHaveLength(1)+ expect(await dropPushDevice(db, a, { platform: 'ios', token: token(4) })).toBe(true)+ expect(await devicesOf(db, [a])).toEqual([])+ })++ it('forgets a dead token and remembers a sandbox one', async () => {+ const a = person()+ await registerPushDevice(db, a, { platform: 'ios', token: token(5) }, NOW)+ await registerPushDevice(db, a, { platform: 'ios', token: token(6) }, NOW)+ const [first, second] = (await devicesOf(db, [a])).sort((x, y) => x.token.localeCompare(y.token))+ await forgetPushDevice(db, first!.id)+ await markSandbox(db, second!.id)+ expect(await devicesOf(db, [a])).toEqual([expect.objectContaining({ token: token(6), sandbox: true })])+ })++ it('reads nothing for nobody', async () => {+ expect(await devicesOf(db, [])).toEqual([])+ })++ it('reads the told people\'s devices through the userId index', async () => {+ const people = Array.from({ length: 5 }, person)+ for (const [i, p] of people.entries()) await registerPushDevice(db, p, { platform: 'ios', token: token(200 + i) }, NOW)+ const rows = reads(await profiled(db, () => devicesOf(db, people.slice(0, 2))), 'push_devices', ['userId'])+ expect(rows).toHaveLength(1)+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ userId: 1/)+ expect(rows[0]!.docsExamined).toBe(2)+ })+})diff --git a/backend/integration/schemaRelease.test.ts b/backend/integration/schemaRelease.test.tsindex 52ea69ca9..dc79518c5 100644--- a/backend/integration/schemaRelease.test.ts+++ b/backend/integration/schemaRelease.test.ts@@ -35,6 +35,7 @@ const EXPIRY: Array<[string, string, Record<string, number>, number]> = ['agent_daily_presence', 'analytics_daily_buckets', 'analytics_daily_machines'].map(c => [c, 'product_usage_expiry', { dayUtc: 1 }, 35 * DAY] as [string, string, Record<string, number>, number]),['product_usage_activity', 'product_usage_expiry', { expiresAt: 1 }, 0],['harness_sessions', 'harness_session_expiry', { expiresAt: 1 }, 30 * DAY],+ ['push_devices', 'push_device_expiry', { seenAt: 1 }, 90 * DAY],]type Profiled = { ts: Date; ns: string; errCode?: number; command?: Record<string, unknown>; locks?: Record<string, { acquireCount?: Record<string, number> }> }diff --git a/backend/integration/superTabActivity.test.ts b/backend/integration/superTabActivity.test.tsindex 9aafdb2ac..7ef9cf196 100644--- a/backend/integration/superTabActivity.test.ts+++ b/backend/integration/superTabActivity.test.ts@@ -21,6 +21,7 @@ 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 { 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.@@ -32,6 +33,8 @@ let store: SuperTabStorelet measured: PrismaClientlet measuredStore: SuperTabStorelet tally: Record<string, number> | null = null+// What each write would tell phones, after its commit (push/notices.ts, task #2905).+const phones: PhoneNotice[] = []const user = (actor: { userId: string; email: string }): AuthUser => ({ sub: actor.userId, email: actor.email, autonomousEnv: 'prod', role: 'user' })const [owner, peer, outsider] = [ownerActor, peerActor, outsiderActor].map(user) as [AuthUser, AuthUser, AuthUser]const ownerTeam: AuthUser = { ...owner, harnessSessionId: 'owner-team-session', harnessSessionKind: 'team' }@@ -49,7 +52,7 @@ beforeAll(async () => {db = new PrismaClient({ datasources: { db: { url: uri } } })for (const each of [owner, peer, outsider]) await db.user.create({ data: { id: each.sub, externalId: `fixture-${each.sub}`, email: each.email, autonomousEnv: 'prod' } })await db.machine.create({ data: { machineId: 'host', userId: owner.sub, apiKey: 'fixture-only', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })- store = new SuperTabStore(db)+ store = new SuperTabStore(db, Date.now, null, { phoneNotices: notices => { phones.push(...notices) } })measured = new PrismaClient({ datasources: { db: { url: uri } }, log: [{ emit: 'event', level: 'query' }] })measuredStore = new SuperTabStore(measured)measured.$on('query', (event: { query: string }) => {@@ -181,6 +184,37 @@ describe('Activity: replies to a person\'s messages', () => {})})+describe('Phone push: a write tells the phones of whoever its rows tell (task #2905)', () => {+ 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 string+ const told = async (write: () => Promise<unknown>) => {+ phones.length = 0+ await write()+ return phones.map(n => ({ personId: n.personId, kind: n.key.split(':')[0], link: n.link, title: n.title }))+ }++ it('tells the thread\'s starter of a reply, linking the reply in its thread, and nobody of a message outside threads', async () => {+ const s = await scene()+ let root = ''+ expect(await told(async () => { root = await send(s.tabId, s.web, 'Owner root') })).toEqual([])+ let reply = ''+ const notices = await told(async () => { reply = await send(s.tabId, s.web, 'Peer answers', peer, root) })+ expect(notices).toEqual([{ personId: owner.sub, kind: 'reply', link: `swarm:${s.tabId}/${s.web}/message/${reply}/thread/${root}`, title: expect.stringMatching(/ replied in a thread$/) }])+ const row = await db.superTabActivity.findFirst({ where: { tabId: s.tabId, personId: owner.sub, messageId: reply } })+ expect(phones[0]!.key).toBe(`reply:${s.tabId}:${row!.id}`)+ })++ it('tells a person who muted the chat of a tag alone, never of a reply', async () => {+ const s = await scene()+ const root = await send(s.tabId, s.web, 'Peer root', peer)+ expect((await notify(s.tabId, s.web, 'muted', peer)).status).toBe(200)+ expect(await told(() => send(s.tabId, s.web, 'Owner answers', owner, root))).toEqual([])+ let tag = ''+ expect(await told(async () => { tag = await tagging(s.tabId, s.web, 'Peer, please check', owner, root, [peer.sub]) }))+ .toEqual([{ personId: peer.sub, kind: 'mention', link: `swarm:${s.tabId}/${s.web}/message/${tag}/thread/${root}`, title: expect.stringMatching(/ tagged you$/) }])+ })+})+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/prisma/schema.prisma b/backend/prisma/schema.prismaindex 154ff0e7e..1906bed5a 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -2323,3 +2323,25 @@ model GitHubApprovalRefusal {@@unique([autonomousEnv, tabId, repository, projectId, userId])@@index([tabId])}++/// A phone's push token (task #2905): where the server sends a thread reply or a tag for its person while the app is closed+/// (push/devices.ts). One row per token, `_id` the SHA-256 of platform and token, so a phone signed in as someone else moves+/// to them. Removed: by the phone at sign-out, when Apple or Google call the token dead, past the 10 newest of a person, and by+/// the TTL index 90 days after `seenAt` (push_device_expiry); a signed-in phone registers again at every launch. About 300 bytes+/// a row, at most 10 a person.+model PushDevice {+ id String @id @map("_id")+ userId String+ /// ios | android+ platform String+ token String+ /// An iOS token from a development build, which only Apple's sandbox host accepts (push/apns.ts).+ sandbox Boolean @default(false)+ seenAt DateTime++ /// A command's told people's phones (devicesOf), and a person's newest ten.+ @@index([userId])+ /// Expires these rows (push/devices.ts ensurePushDeviceExpiry, made before the push). Declared so db push keeps it.+ @@index([seenAt], map: "push_device_expiry")+ @@map("push_devices")+}diff --git a/backend/src/config/env.ts b/backend/src/config/env.tsindex e4020abf3..c3d695f78 100644--- a/backend/src/config/env.ts+++ b/backend/src/config/env.ts@@ -308,6 +308,18 @@ const envSchema = z.object({GITHUB_APP_CLIENT_ID: z.string().default(''),GITHUB_APP_CLIENT_SECRET: z.string().default(''),+ // Phone push (push/keys.ts, task #2905): a thread reply or a tag reaches a phone whose app is closed. APNs for iPhones: the+ // key Apple generated in the developer account (the .p8 file, with its line breaks as \n, or base64 of it), its Key ID and+ // the Team ID; all three or none. FCM for Android: base64 of the Firebase service account's JSON key. Unset: that platform+ // gets no push, and each one skipped is counted and logged. A value that cannot be right stops the backend at startup, with+ // a message that never shows it.+ APNS_KEY_ID: z.string().default(''),+ APNS_TEAM_ID: z.string().default(''),+ APNS_PRIVATE_KEY: z.string().default(''),+ // The iPhone app's bundle id, which Apple sends to.+ APNS_TOPIC: z.string().default('ai.autonomous.harness.ios'),+ FCM_SERVICE_ACCOUNT: z.string().default(''),+// TTL for the in-memory subdomain→machineId cache on the public app-proxy hot path// (avoids a Mongo lookup per request). Bounds staleness after a cross-instance app teardown.// 60 min default (mapping is stable; a same-instance delete evicts immediately).diff --git a/backend/src/lib/db/schemaRelease.ts b/backend/src/lib/db/schemaRelease.tsindex fee37342f..71b539181 100644--- a/backend/src/lib/db/schemaRelease.ts+++ b/backend/src/lib/db/schemaRelease.ts@@ -7,6 +7,7 @@ import { ensureMentionExpiry } from '../../superTabs/mentions.js'import { ensureReadMarkExpiry } from '../../superTabs/readMarks.js'import { ensurePartExpiry } from '../../superTabs/sweeps.js'import { ensureOperationExpiry } from '../../superTabs/operations.js'+import { ensurePushDeviceExpiry } from '../../push/devices.js'import { ensureSchema, type SchemaTarget } from './migrate.js'/** What a release's index work left for the worker to do: remove old read marks itself where their expiry was refused. */@@ -19,6 +20,7 @@ export async function releaseSchema(db: PrismaClient = prisma, target: SchemaTar// at once and the push keeps it; built by the push, it would need collMod for its expiry, which production's app user may// not run (10-29). The indexes below were made before they were declared, so the push has always found them.await ensureOperationExpiry(db)+ await ensurePushDeviceExpiry(db)await ensureSchema(target)await ensureProductUsageExpiry(db)await ensureHarnessSessionExpiry(db)diff --git a/backend/src/lib/metrics.ts b/backend/src/lib/metrics.tsindex 93384f88a..2247cefa1 100644--- a/backend/src/lib/metrics.ts+++ b/backend/src/lib/metrics.ts@@ -37,6 +37,8 @@ export function createMetrics(hour: LastHour = createLastHour()) {labelNames: ['work'] as const, registers: [registry] })const workBusy = new Counter({ name: 'work_busy_seconds_total', help: 'Main-thread busy time, by kind of work, while CPU_SELF_PROFILE=1',labelNames: ['work'] as const, registers: [registry] })+ const phonePushes = new Counter({ name: 'phone_pushes_total', help: 'Pushes to phones (push/send.ts), by platform and outcome',+ labelNames: ['platform', 'outcome'] as const, registers: [registry] })const works = new Set<string>()const work = (kind: string) => {if (works.has(kind)) return kind@@ -62,6 +64,8 @@ export function createMetrics(hour: LastHour = createLastHour()) {}hour.db(window)},+ /** One push to one phone: sent, gone (a dead token), sandbox, failed, or unconfigured (no keys for its platform). */+ phonePush(platform: string, outcome: string) { phonePushes.inc({ platform, outcome }) },/** A minute of `cpu by kind`, every kind of work's busy ms. */busyWindow(window: BusyWindow) {for (const [kind, ms] of window) workBusy.inc({ work: work(kind) }, ms / 1000)diff --git a/backend/src/push/apns.test.ts b/backend/src/push/apns.test.tsnew file mode 100644index 000000000..e82ab711c--- /dev/null+++ b/backend/src/push/apns.test.ts@@ -0,0 +1,124 @@+import { createPublicKey, generateKeyPairSync, verify } from 'node:crypto'+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'++const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' })+const keys = { keyId: 'ABC123DEFG', teamId: 'TEAM123456', privateKey, topic: 'ai.autonomous.harness.ios' }+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' }+const NOW = Date.UTC(2026, 10, 5, 9)++/** A transport that answers each request in turn and remembers what it was asked. */+function scripted(...answers: Array<ApnsAnswer | 'hang'>) {+ const asked: ApnsRequest[] = []+ const transport = (request: ApnsRequest) => {+ asked.push(request)+ const answer = answers.shift() ?? { status: 200, reason: null }+ return answer === 'hang' ? new Promise<ApnsAnswer>(() => {}) : Promise.resolve(answer)+ }+ return { asked, transport }+}+const jwtOf = (request: ApnsRequest) => request.headers.authorization!.replace(/^bearer /, '')+const part = (jwt: string, i: number) => JSON.parse(Buffer.from(jwt.split('.')[i]!, 'base64url').toString())++describe('APNs sender (task #2905)', () => {+ it('sends an alert for the app\'s topic, signed with the team\'s key, that says who and where and nothing written', async () => {+ const { asked, transport } = scripted({ status: 200, reason: null })+ expect(await apnsSender(keys, { transport, now: () => NOW }).send(device, notice)).toEqual({ outcome: 'sent' })+ const [request] = asked+ expect(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(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,+ })+ const jwt = jwtOf(request!)+ expect(part(jwt, 0)).toEqual({ alg: 'ES256', kid: 'ABC123DEFG' })+ expect(part(jwt, 1)).toEqual({ iss: 'TEAM123456', iat: NOW / 1000 })+ const [head, claims, signature] = jwt.split('.')+ expect(verify('sha256', Buffer.from(`${head}.${claims}`), { key: createPublicKey(privateKey), dsaEncoding: 'ieee-p1363' }, Buffer.from(signature!, 'base64url'))).toBe(true)+ })++ it('signs again only after 50 minutes', async () => {+ let now = NOW+ const { asked, transport } = scripted()+ const sender = apnsSender(keys, { transport, now: () => now })+ await sender.send(device, notice)+ now += 49 * 60_000+ await sender.send(device, notice)+ now += 2 * 60_000+ await sender.send(device, notice)+ expect(jwtOf(asked[1]!)).toBe(jwtOf(asked[0]!))+ expect(jwtOf(asked[2]!)).not.toBe(jwtOf(asked[0]!))+ })++ it('calls a token Apple no longer knows gone', async () => {+ for (const answer of [{ status: 410, reason: 'Unregistered' }, { status: 400, reason: 'DeviceTokenNotForTopic' }]) {+ const { transport } = scripted(answer)+ expect(await apnsSender(keys, { transport }).send(device, notice)).toEqual({ outcome: 'gone', reason: answer.reason })+ }+ })++ it('tries a development build\'s token on the sandbox host once, and says so when it is taken there', async () => {+ const { asked, transport } = scripted({ status: 400, reason: 'BadDeviceToken' }, { status: 200, reason: null })+ expect(await apnsSender(keys, { transport }).send(device, notice)).toEqual({ outcome: 'sandbox' })+ expect(asked.map(r => r.sandbox)).toEqual([false, true])+ })++ it('calls a token neither host takes gone', async () => {+ const { transport } = scripted({ status: 400, reason: 'BadDeviceToken' }, { status: 400, reason: 'BadDeviceToken' })+ expect(await apnsSender(keys, { transport }).send(device, notice)).toEqual({ outcome: 'gone', reason: 'BadDeviceToken' })+ })++ it('sends a sandbox token to the sandbox host alone', async () => {+ const { asked, transport } = scripted({ status: 200, reason: null })+ expect(await apnsSender(keys, { transport }).send({ ...device, sandbox: true }, notice)).toEqual({ outcome: 'sent' })+ expect(asked.map(r => r.sandbox)).toEqual([true])+ })++ it('fails on Apple\'s error, a broken connection, or no answer in time', async () => {+ expect(await apnsSender(keys, { transport: scripted({ status: 500, reason: 'InternalServerError' }).transport }).send(device, notice))+ .toEqual({ outcome: 'failed', reason: 'InternalServerError' })+ expect(await apnsSender(keys, { transport: () => Promise.reject(new Error('ECONNRESET')) }).send(device, notice))+ .toEqual({ outcome: 'failed', reason: 'ECONNRESET' })+ expect(await apnsSender(keys, { transport: scripted('hang').transport, timeoutMs: 20 }).send(device, notice))+ .toEqual({ outcome: 'failed', reason: 'timeout' })+ })+})++describe('APNs over HTTP/2', () => {+ const seen: Array<{ headers: http2.IncomingHttpHeaders; body: string }> = []+ const server = http2.createServer((request, response) => {+ let body = ''+ request.on('data', chunk => { body += chunk })+ request.on('end', () => {+ seen.push({ headers: request.headers, body })+ if (request.headers['apns-topic'] === 'gone') {+ response.writeHead(410, { 'content-type': 'application/json' })+ response.end(JSON.stringify({ reason: 'Unregistered', timestamp: 1 }))+ } else {+ response.writeHead(200, { 'apns-id': 'x' })+ response.end()+ }+ })+ })+ afterAll(() => new Promise<void>(resolve => server.close(() => resolve())))++ it('posts to the path with the headers, and reads Apple\'s reason', async () => {+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))+ const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`+ const transport = http2Transport({ production: origin, sandbox: origin })+ try {+ expect(await transport({ sandbox: false, path: '/3/device/abc', headers: { 'apns-topic': 'ok' }, body: '{"a":1}' }, 5_000)).toEqual({ status: 200, reason: null })+ expect(await transport({ sandbox: true, path: '/3/device/def', headers: { 'apns-topic': 'gone' }, body: '{}' }, 5_000)).toEqual({ status: 410, reason: 'Unregistered' })+ } finally {+ transport.close()+ }+ expect(seen.map(s => [s.headers[':method'], s.headers[':path'], s.body])).toEqual([['POST', '/3/device/abc', '{"a":1}'], ['POST', '/3/device/def', '{}']])+ })+})diff --git a/backend/src/push/apns.ts b/backend/src/push/apns.tsnew file mode 100644index 000000000..3dd132961--- /dev/null+++ b/backend/src/push/apns.ts@@ -0,0 +1,91 @@+import { sign } from 'node:crypto'+import http2 from 'node:http2'+import type { 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'++/** 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 }+export interface ApnsAnswer { status: number; reason: string | null }+export type ApnsTransport = (request: ApnsRequest, timeoutMs: number) => Promise<ApnsAnswer>++/** Apple takes a token at most an hour old and refuses one renewed more often than every 20 minutes. */+const JWT_RENEW_MS = 50 * 60_000+/** Apple's answers for a token that is no longer this app's on any phone. */+const GONE = new Set(['Unregistered', 'DeviceTokenNotForTopic', 'BadDeviceToken'])++const base64url = (value: string | Buffer) => Buffer.from(value).toString('base64url')++/**+ * Sends to iPhones through Apple's HTTP/2 API with a token signed by the team's key (task #2905). An Xcode build's token is+ * known only to the sandbox host: production calls it bad, so it is tried there once, and the device is marked (`sandbox`).+ */+export function apnsSender(keys: ApnsKeys, options: { transport?: ApnsTransport; now?: () => number; timeoutMs?: number } = {}): Sender {+ const transport = options.transport ?? http2Transport(), now = options.now ?? Date.now, timeoutMs = options.timeoutMs ?? SEND_TIMEOUT_MS+ let jwt: { value: string; at: number } | null = null+ const bearer = () => {+ const at = now()+ if (!jwt || at - jwt.at >= JWT_RENEW_MS) {+ const signed = `${base64url(JSON.stringify({ alg: 'ES256', kid: keys.keyId }))}.${base64url(JSON.stringify({ iss: keys.teamId, iat: Math.floor(at / 1000) }))}`+ jwt = { value: `${signed}.${base64url(sign('sha256', Buffer.from(signed), { key: keys.privateKey, dsaEncoding: 'ieee-p1363' }))}`, at }+ }+ return jwt.value+ }+ const ask = async (device: PushDevice, notice: PhoneNotice, sandbox: boolean): Promise<ApnsAnswer> => withTimeout(transport({+ sandbox, path: `/3/device/${device.token}`,+ headers: { authorization: `bearer ${bearer()}`, '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 }),+ }, timeoutMs), timeoutMs)+ const judged = (answer: ApnsAnswer, sandboxNow: boolean): SendResult => {+ if (answer.status === 200) return { outcome: sandboxNow ? 'sandbox' : 'sent' }+ if (answer.status === 410 || (answer.status === 400 && GONE.has(answer.reason ?? ''))) return { outcome: 'gone', reason: answer.reason ?? String(answer.status) }+ return { outcome: 'failed', reason: answer.reason ?? String(answer.status) }+ }+ return {+ async send(device, notice) {+ try {+ const answer = await ask(device, notice, device.sandbox)+ if (device.sandbox || answer.status !== 400 || answer.reason !== 'BadDeviceToken') return judged(answer, false)+ return judged(await ask(device, notice, true), true)+ } catch (error) {+ return { outcome: 'failed', reason: (error as Error).message === 'timeout' ? 'timeout' : (error as NodeJS.ErrnoException).code ?? (error as Error).message }+ }+ },+ }+}++/** Apple's two hosts, one HTTP/2 connection each, made when first needed and again once closed. */+export function http2Transport(origins = { production: 'https://api.push.apple.com', sandbox: 'https://api.sandbox.push.apple.com' }): ApnsTransport & { close(): void } {+ const sessions = new Map<string, http2.ClientHttp2Session>()+ const sessionFor = (origin: string) => {+ const open = sessions.get(origin)+ if (open && !open.closed && !open.destroyed) return open+ const session = http2.connect(origin)+ // A connection that fails is dropped here; the request on it fails by itself, and the next one connects again.+ session.on('error', () => sessions.delete(origin))+ session.on('close', () => { if (sessions.get(origin) === session) sessions.delete(origin) })+ session.unref()+ sessions.set(origin, session)+ return session+ }+ const transport = (request: ApnsRequest, timeoutMs: number) => new Promise<ApnsAnswer>((resolve, reject) => {+ const stream = sessionFor(request.sandbox ? origins.sandbox : origins.production)+ .request({ ':method': 'POST', ':path': request.path, ...request.headers })+ stream.setTimeout(timeoutMs, () => stream.close(http2.constants.NGHTTP2_CANCEL))+ let status = 0, body = ''+ stream.on('response', headers => { status = Number(headers[':status']) })+ stream.setEncoding('utf8')+ stream.on('data', (chunk: string) => { body += chunk })+ stream.on('end', () => {+ let reason: string | null = null+ try { reason = body ? (JSON.parse(body) as { reason?: string }).reason ?? null : null } catch { reason = null }+ resolve({ status, reason })+ })+ stream.on('error', reject)+ stream.on('close', () => { if (!status) reject(new Error('timeout')) })+ stream.end(request.body)+ })+ return Object.assign(transport, { close: () => { for (const session of sessions.values()) session.close(); sessions.clear() } })+}diff --git a/backend/src/push/devices.ts b/backend/src/push/devices.tsnew file mode 100644index 000000000..22468563a--- /dev/null+++ b/backend/src/push/devices.ts@@ -0,0 +1,66 @@+import { createHash } from 'node:crypto'+import type { PrismaClient } from '@prisma/client'+import { ensureIndex } from '../lib/db/indexes.js'++/**+ * The phones a person signed in on, by their push tokens (task #2905): where a thread reply or a tag goes while the app is+ * closed (push/send.ts). A token is the person's who registered it last, so a phone signed in as someone else stops hearing+ * the first person's notices; a sign-out drops it, and a token Apple or Google call dead is forgotten.+ */+export type PushPlatform = 'ios' | 'android'+export interface PushDevice { id: string; userId: string; platform: PushPlatform; token: string; sandbox: boolean }++/** Phones kept per person: the ones registered last. A person has a phone or two; ten leaves room for old ones. */+export const PUSH_DEVICES_PER_PERSON = 10+/** A phone that has not opened the app signed in for this long is forgotten (push_device_expiry). */+export const PUSH_DEVICE_EXPIRY_MS = 90 * 24 * 60 * 60_000++/** Made before the schema push (lib/db/schemaRelease.ts), so the push finds it with its expiry and keeps it. */+export async function ensurePushDeviceExpiry(db: PrismaClient): Promise<void> {+ await ensureIndex(db, 'push_devices', { key: { seenAt: 1 }, name: 'push_device_expiry', expireAfterSeconds: PUSH_DEVICE_EXPIRY_MS / 1000 })+}++/** One row per token, whoever holds it: the token itself is never the key. */+const deviceId = (platform: PushPlatform, token: string) => createHash('sha256').update(`${platform}\n${token}`).digest('hex')++type Row = { _id: string; userId: string; platform: PushPlatform; token: string; sandbox?: boolean; seenAt?: { $date: string } }++/** By the userId index, as a plain $match: Prisma sends `in` as $expr, which no index bounds (backend/AGENTS.md rule 3). */+async function rowsOf(db: PrismaClient, userIds: string[]): Promise<Row[]> {+ return await db.pushDevice.aggregateRaw({ pipeline: [{ $match: { userId: { $in: userIds } } }] }) as unknown as Row[]+}++/** Keeps `device` for `userId`, taking it from whoever had it, and lets go of the person's phones past the newest ten. */+export async function registerPushDevice(db: PrismaClient, userId: string, device: { platform: PushPlatform; token: string }, now: number): Promise<void> {+ const id = deviceId(device.platform, device.token)+ await db.pushDevice.upsert({ where: { id }, create: { id, userId, platform: device.platform, token: device.token, seenAt: new Date(now) },+ update: { userId, seenAt: new Date(now) } })+ const rows = await rowsOf(db, [userId])+ if (rows.length <= PUSH_DEVICES_PER_PERSON) return+ const seen = (row: Row) => Date.parse(row.seenAt?.$date ?? '') || 0+ const old = rows.sort((a, b) => seen(b) - seen(a)).slice(PUSH_DEVICES_PER_PERSON).map(row => row._id)+ // A plain $in by _id: Prisma's `in` goes as $expr, which no index bounds (backend/AGENTS.md rule 3).+ await db.$runCommandRaw({ delete: 'push_devices', deletes: [{ q: { _id: { $in: old }, userId }, limit: 0 }] })+}++/** Removes `device` if it is `userId`'s: false when it is not (another person's phone, or already gone). */+export async function dropPushDevice(db: PrismaClient, userId: string, device: { platform: PushPlatform; token: string }): Promise<boolean> {+ const { count } = await db.pushDevice.deleteMany({ where: { id: deviceId(device.platform, device.token), userId } })+ return count > 0+}++/** The phones of `userIds`, in one read. */+export async function devicesOf(db: PrismaClient, userIds: string[]): Promise<PushDevice[]> {+ if (!userIds.length) return []+ return (await rowsOf(db, userIds)).map(row => ({ id: row._id, userId: row.userId, platform: row.platform, token: row.token, sandbox: row.sandbox === true }))+}++/** A token Apple or Google answered is dead: never sent to again. */+export async function forgetPushDevice(db: PrismaClient, id: string): Promise<void> {+ await db.pushDevice.deleteMany({ where: { id } })+}++/** An iOS token only Apple's sandbox host accepts (push/apns.ts): sent there from now on. */+export async function markSandbox(db: PrismaClient, id: string): Promise<void> {+ await db.pushDevice.updateMany({ where: { id }, data: { sandbox: true } })+}diff --git a/backend/src/push/fcm.test.ts b/backend/src/push/fcm.test.tsnew file mode 100644index 000000000..3e5fb7729--- /dev/null+++ b/backend/src/push/fcm.test.ts@@ -0,0 +1,83 @@+import { createPublicKey, generateKeyPairSync, verify } from 'node:crypto'+import { describe, expect, it } from 'vitest'+import { fcmSender } from './fcm.js'+import type { PushDevice } from './devices.js'+import type { PhoneNotice } from './sender.js'++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' }+const NOW = Date.UTC(2026, 10, 5, 9)++type Call = { url: string; init: RequestInit }+/** A fetch that answers Google's token endpoint with a one-hour token and FCM with `send` in turn. */+function google(...send: Array<{ status: number; body?: unknown } | 'hang'>) {+ const calls: Call[] = []+ let issued = 0+ const fetcher = (async (url: string, init: RequestInit) => {+ calls.push({ url, init })+ if (url === account.tokenUri) return new Response(JSON.stringify({ access_token: `access-${++issued}`, expires_in: 3600, token_type: 'Bearer' }), { status: 200 })+ const answer = send.shift() ?? { status: 200, body: { name: 'projects/harness-push/messages/1' } }+ if (answer === 'hang') return await new Promise<Response>((_, reject) => init.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'TimeoutError'))))+ return new Response(JSON.stringify(answer.body ?? {}), { status: answer.status })+ }) as unknown as typeof fetch+ return { calls, fetcher, sends: () => calls.filter(c => c.url !== account.tokenUri) }+}+const unregistered = { status: 404, body: { error: { code: 404, status: 'NOT_FOUND', details: [{ '@type': 'type.googleapis.com/google.firebase.fcm.v1.FcmError', errorCode: 'UNREGISTERED' }] } } }++describe('FCM sender (task #2905)', () => {+ it('signs in as the service account and sends a notification that says who and where and nothing written', async () => {+ const { calls, fetcher } = google()+ expect(await fcmSender(account, { fetcher, now: () => NOW }).send(device, notice)).toEqual({ outcome: 'sent' })+ const [grant, send] = calls+ const form = new URLSearchParams(String(grant!.init.body))+ expect(form.get('grant_type')).toBe('urn:ietf:params:oauth:grant-type:jwt-bearer')+ const [head, claims, signature] = form.get('assertion')!.split('.')+ expect(JSON.parse(Buffer.from(head!, 'base64url').toString())).toEqual({ alg: 'RS256', typ: 'JWT' })+ expect(JSON.parse(Buffer.from(claims!, 'base64url').toString())).toEqual({ iss: account.clientEmail, scope: 'https://www.googleapis.com/auth/firebase.messaging',+ aud: account.tokenUri, iat: NOW / 1000, exp: NOW / 1000 + 3600 })+ expect(verify('sha256', Buffer.from(`${head}.${claims}`), createPublicKey(privateKey), Buffer.from(signature!, 'base64url'))).toBe(true)+ expect(send!.url).toBe('https://fcm.googleapis.com/v1/projects/harness-push/messages:send')+ expect((send!.init.headers as Record<string, string>).authorization).toBe('Bearer access-1')+ expect(JSON.parse(String(send!.init.body))).toEqual({ message: {+ 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 },+ } })+ })++ it('keeps its access token until five minutes before it runs out', async () => {+ let now = NOW+ const { calls, fetcher } = google()+ const sender = fcmSender(account, { fetcher, now: () => now })+ await sender.send(device, notice)+ now += 54 * 60_000+ await sender.send(device, notice)+ now += 2 * 60_000+ await sender.send(device, notice)+ expect(calls.filter(c => c.url === account.tokenUri)).toHaveLength(2)+ })++ it('calls a token Firebase no longer knows gone', async () => {+ const { fetcher } = google(unregistered)+ expect(await fcmSender(account, { fetcher }).send(device, notice)).toEqual({ outcome: 'gone', reason: 'UNREGISTERED' })+ })++ it('signs in again after a refused access token, and fails that send', async () => {+ const { calls, fetcher } = google({ status: 401, body: { error: { status: 'UNAUTHENTICATED' } } })+ const sender = fcmSender(account, { fetcher })+ expect(await sender.send(device, notice)).toEqual({ outcome: 'failed', reason: 'UNAUTHENTICATED' })+ await sender.send(device, notice)+ expect(calls.filter(c => c.url === account.tokenUri)).toHaveLength(2)+ })++ it('fails on Google\'s error or no answer in time', async () => {+ expect(await fcmSender(account, { fetcher: google({ status: 503, body: { error: { status: 'UNAVAILABLE' } } }).fetcher }).send(device, notice))+ .toEqual({ outcome: 'failed', reason: 'UNAVAILABLE' })+ expect(await fcmSender(account, { fetcher: google('hang').fetcher, timeoutMs: 20 }).send(device, notice))+ .toEqual({ outcome: 'failed', reason: 'timeout' })+ })+})diff --git a/backend/src/push/fcm.ts b/backend/src/push/fcm.tsnew file mode 100644index 000000000..0ba01e435--- /dev/null+++ b/backend/src/push/fcm.ts@@ -0,0 +1,62 @@+import { sign } from 'node:crypto'+import type { FcmAccount } from './keys.js'+import { SEND_TIMEOUT_MS, SWARM_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. */+const RENEW_BEFORE_MS = 5 * 60_000++const base64url = (value: string | Buffer) => Buffer.from(value).toString('base64url')++type GoogleError = { error?: { status?: string; details?: Array<{ errorCode?: string }> } }++/**+ * Sends to Android phones through FCM's HTTP v1 API, signed in as the service account with a JWT grant (task #2905). The+ * message is a notification Android draws itself while the app is closed, in the channel of the app's own Swarm notices, and+ * never draws while the app is in front: there the app's own notices decide.+ */+export function fcmSender(account: FcmAccount, options: { fetcher?: typeof fetch; now?: () => number; timeoutMs?: number } = {}): Sender {+ const fetcher = options.fetcher ?? fetch, now = options.now ?? Date.now, timeoutMs = options.timeoutMs ?? SEND_TIMEOUT_MS+ let access: { token: string; until: number } | null = null+ const call = (url: string, init: RequestInit) => withTimeout(fetcher(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }), timeoutMs)+ const accessToken = async () => {+ const at = now()+ if (access && at < access.until - RENEW_BEFORE_MS) return access.token+ const iat = Math.floor(at / 1000)+ const signed = `${base64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }))}.${base64url(JSON.stringify({ iss: account.clientEmail, scope: SCOPE,+ aud: account.tokenUri, iat, exp: iat + 3600 }))}`+ const assertion = `${signed}.${base64url(sign('sha256', Buffer.from(signed), account.privateKey))}`+ const answer = await call(account.tokenUri, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion }).toString() })+ if (!answer.ok) throw new Error(`sign-in ${answer.status}`)+ const granted = await answer.json() as { access_token?: string; expires_in?: number }+ if (!granted.access_token) throw new Error('sign-in gave no token')+ access = { token: granted.access_token, until: at + (granted.expires_in ?? 3600) * 1000 }+ return access.token+ }+ return {+ async send(device, notice) {+ try {+ const answer = await call(`https://fcm.googleapis.com/v1/projects/${account.projectId}/messages:send`, {+ method: 'POST', headers: { authorization: `Bearer ${await accessToken()}`, 'content-type': 'application/json' },+ body: JSON.stringify({ message: {+ token: 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 },+ } }),+ })+ if (answer.ok) return { outcome: 'sent' }+ const error = (await answer.json().catch(() => ({})) as GoogleError).error+ if (answer.status === 401) access = null+ const code = error?.details?.find(d => d.errorCode)?.errorCode+ if (code === 'UNREGISTERED') return { outcome: 'gone', reason: code }+ return { outcome: 'failed', reason: code ?? error?.status ?? String(answer.status) }+ } catch (error) {+ const name = (error as Error).name, message = (error as Error).message+ return { outcome: 'failed', reason: message === 'timeout' || name === 'TimeoutError' ? 'timeout' : message }+ }+ },+ }+}diff --git a/backend/src/push/keys.test.ts b/backend/src/push/keys.test.tsnew file mode 100644index 000000000..c6976dad0--- /dev/null+++ b/backend/src/push/keys.test.ts@@ -0,0 +1,46 @@+import { generateKeyPairSync } from 'node:crypto'+import { describe, expect, it } from 'vitest'+import { pushKeysFromEnv } from './keys.js'++const ec = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).privateKey.export({ type: 'pkcs8', format: 'pem' }).toString()+const rsa = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ type: 'pkcs8', format: 'pem' }).toString()+const account = { type: 'service_account', project_id: 'harness-push', client_email: '[email protected]',+ private_key: rsa, token_uri: 'https://oauth2.googleapis.com/token' }+const none = { APNS_KEY_ID: '', APNS_TEAM_ID: '', APNS_PRIVATE_KEY: '', APNS_TOPIC: 'ai.autonomous.harness.ios', FCM_SERVICE_ACCOUNT: '' }+const apns = { ...none, APNS_KEY_ID: 'ABC123DEFG', APNS_TEAM_ID: 'TEAM123456', APNS_PRIVATE_KEY: ec.replace(/\n/g, '\\n') }+const fcm = { ...none, FCM_SERVICE_ACCOUNT: Buffer.from(JSON.stringify(account)).toString('base64') }++describe('push keys from the server\'s secret store (task #2905)', () => {+ it('is off for both platforms with nothing set', () => {+ expect(pushKeysFromEnv(none)).toEqual({ apns: null, fcm: null })+ })++ it('reads the APNs key as Apple hands it out, with its line breaks as \\n or as base64 of the .p8 file', () => {+ for (const key of [apns.APNS_PRIVATE_KEY, Buffer.from(ec).toString('base64')]) {+ const keys = pushKeysFromEnv({ ...apns, APNS_PRIVATE_KEY: key })+ expect(keys.apns).toMatchObject({ keyId: 'ABC123DEFG', teamId: 'TEAM123456', topic: 'ai.autonomous.harness.ios' })+ expect(keys.apns!.privateKey.asymmetricKeyType).toBe('ec')+ }+ })++ it('reads the Firebase service account from base64 of its JSON file', () => {+ expect(pushKeysFromEnv(fcm).fcm).toMatchObject({ projectId: 'harness-push', clientEmail: account.client_email, tokenUri: account.token_uri })+ })++ it('stops the server when the APNs values are set in part, naming what is missing', () => {+ expect(() => pushKeysFromEnv({ ...apns, APNS_TEAM_ID: '' })).toThrow(/APNS_TEAM_ID/)+ expect(() => pushKeysFromEnv({ ...none, APNS_PRIVATE_KEY: apns.APNS_PRIVATE_KEY })).toThrow(/APNS_KEY_ID/)+ })++ it('stops the server on a key that cannot be right, and never repeats it', () => {+ const cases = [{ ...apns, APNS_PRIVATE_KEY: 'not-a-key-SECRET' }, { ...apns, APNS_PRIVATE_KEY: rsa.replace(/\n/g, '\\n') },+ { ...none, FCM_SERVICE_ACCOUNT: 'SECRETnotbase64json' }, { ...none, FCM_SERVICE_ACCOUNT: Buffer.from(JSON.stringify({ ...account, private_key: 'SECRET' })).toString('base64') },+ { ...none, FCM_SERVICE_ACCOUNT: Buffer.from(JSON.stringify({ ...account, project_id: '' })).toString('base64') }]+ for (const env of cases) {+ let message = ''+ try { pushKeysFromEnv(env) } catch (error) { message = (error as Error).message }+ expect(message).toMatch(/APNS_PRIVATE_KEY|FCM_SERVICE_ACCOUNT/)+ expect(message).not.toMatch(/SECRET|BEGIN/)+ }+ })+})diff --git a/backend/src/push/keys.ts b/backend/src/push/keys.tsnew file mode 100644index 000000000..49ed8fb3a--- /dev/null+++ b/backend/src/push/keys.ts@@ -0,0 +1,49 @@+import { createPrivateKey, type KeyObject } from 'node:crypto'++/** Apple's push key (a .p8 from the developer account), the ids it is signed with, and the app it sends to. */+export interface ApnsKeys { keyId: string; teamId: string; privateKey: KeyObject; topic: string }+/** The Firebase service account that sends to Android phones. */+export interface FcmAccount { projectId: string; clientEmail: string; privateKey: KeyObject; tokenUri: string }++export interface PushEnv { APNS_KEY_ID: string; APNS_TEAM_ID: string; APNS_PRIVATE_KEY: string; APNS_TOPIC: string; FCM_SERVICE_ACCOUNT: string }++/** A PEM private key with its line breaks as `\n`, or base64 of the file. Errors name the variable, never the value. */+function readKey(name: string, value: string, type: 'ec' | 'rsa'): KeyObject {+ let pem = value.trim().replace(/\\n/g, '\n')+ if (!pem.includes('-----BEGIN')) {+ const decoded = /^[A-Za-z0-9+/=\s]+$/.test(pem) ? Buffer.from(pem, 'base64').toString('utf8') : ''+ if (!decoded.includes('-----BEGIN')) throw new Error(`${name} is not a PEM private key or base64 of one.`)+ pem = decoded.trim()+ }+ let key: KeyObject+ try { key = createPrivateKey(pem) } catch { throw new Error(`${name} could not be read as a private key.`) }+ if (key.asymmetricKeyType !== type) throw new Error(`${name} must be the ${type === 'ec' ? 'P-256 key Apple generated (.p8)' : 'RSA key of the service account'}.`)+ return key+}++function readAccount(value: string): FcmAccount {+ let account: Record<string, unknown>+ try { account = JSON.parse(Buffer.from(value.trim(), 'base64').toString('utf8')) as Record<string, unknown> } catch {+ throw new Error('FCM_SERVICE_ACCOUNT must be base64 of the service account\'s JSON key file.')+ }+ const field = (name: string) => typeof account[name] === 'string' && account[name] ? account[name] as string : null+ const projectId = field('project_id'), clientEmail = field('client_email'), key = field('private_key')+ if (!projectId || !clientEmail || !key) throw new Error('FCM_SERVICE_ACCOUNT must hold project_id, client_email and private_key.')+ return { projectId, clientEmail, privateKey: readKey('FCM_SERVICE_ACCOUNT', key, 'rsa'), tokenUri: field('token_uri') ?? 'https://oauth2.googleapis.com/token' }+}++/**+ * The push keys in the server's secret store (task #2905). Nothing set: that platform's push is off, and each push it skips+ * is counted (push/send.ts). The APNs values set in part, or a key that cannot be right, stops the server at start rather+ * than failing the first notice.+ */+export function pushKeysFromEnv(env: PushEnv): { apns: ApnsKeys | null; fcm: FcmAccount | null } {+ const keyId = env.APNS_KEY_ID.trim(), teamId = env.APNS_TEAM_ID.trim(), key = env.APNS_PRIVATE_KEY.trim()+ let apns: ApnsKeys | null = null+ if (keyId || teamId || key) {+ const missing = [['APNS_KEY_ID', keyId], ['APNS_TEAM_ID', teamId], ['APNS_PRIVATE_KEY', key]].filter(([, v]) => !v).map(([n]) => n)+ if (missing.length) throw new Error(`Set APNS_KEY_ID, APNS_TEAM_ID and APNS_PRIVATE_KEY for phone push, or none: ${missing.join(', ')} missing.`)+ apns = { keyId, teamId, privateKey: readKey('APNS_PRIVATE_KEY', key, 'ec'), topic: env.APNS_TOPIC.trim() }+ }+ return { apns, fcm: env.FCM_SERVICE_ACCOUNT.trim() ? readAccount(env.FCM_SERVICE_ACCOUNT) : null }+}diff --git a/backend/src/push/notices.test.ts b/backend/src/push/notices.test.tsnew file mode 100644index 000000000..dc7662da4--- /dev/null+++ b/backend/src/push/notices.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it } from 'vitest'+import { phoneNotices } from './notices.js'+import { swarm, owner, peer } from '../superTabs/read/fixture.test-support.js'+import { shownNameOf } from '../superTabs/personNames.js'+import type { MessageDraft } from '../superTabs/model.js'+import { openSwarmBuddyChat } from '../superTabs/buddies.js'++function scene() {+ const s = swarm()+ s.join(peer)+ const project = s.run({ type: 'project.create', name: 'Web launch', visibility: 'public', brief: '' }).projectId as string+ const web = s.group('Web', project)+ const worker = s.add('worker-harness', web)+ return { state: s.state, web, worker }+}+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' })++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])+ 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` }])+ })++ it('words a tag as the phone does, and links the message, in its thread only when it is only there', () => {+ const { state, web, worker } = scene()+ const agent = { kind: 'agent' as const, id: worker, name: 'worker-harness', membershipGeneration: 'g' }+ const inChat = draft({ id: 'm1', conversationId: web, author: agent, mentions: [owner.userId] })+ const inThread = draft({ id: 'm2', conversationId: web, author: person(peer), mentions: [owner.userId], thread: 'root2' })+ 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])+ 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`],+ ['mention:t3', `${shownNameOf(state, peer.userId)} tagged you`, 'Web launch', `swarm:tab/${web}/message/m3`],+ ])+ expect(notices.every(n => n.body === 'Open Harness to read it.')).toBe(true)+ })++ it('tells of a reply in a person\'s Swarm Buddy chat, which belongs to no project, without failing (security review 2)', () => {+ const { state } = scene()+ const buddy = openSwarmBuddyChat(state, state.people.find(p => p.id === peer.userId)!).id+ 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])+ expect(notices).toEqual([expect.objectContaining({ personId: peer.userId, subtitle: '', link: `swarm:tab/${buddy}/message/r1/thread/root1` })])+ })++ it('pushes no tag held back for a quiet chat', () => {+ const { state, web } = scene()+ const held = draft({ id: 'm1', conversationId: web, author: person(peer), mentions: [owner.userId], holdMentions: true })+ expect(phoneNotices('tab', state, { replies: [], tags: [{ id: 't1', personId: owner.userId, conversationId: web, messageId: 'm1', holdUntil: new Date() }] }, [held])).toEqual([])+ })++ it('escapes the link\'s parts as the phone reads them', () => {+ 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])+ expect(notice!.link).toBe(`swarm:tab%3Ax/${web}/message/r%2F1/thread/root%201`)+ })++ it('never carries what was written', () => {+ 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])+ expect(JSON.stringify(notices)).not.toContain('never in a notice')+ })+})diff --git a/backend/src/push/notices.ts b/backend/src/push/notices.tsnew file mode 100644index 000000000..a30b461b5--- /dev/null+++ b/backend/src/push/notices.ts@@ -0,0 +1,51 @@+import type { MessageDraft, SuperTabState } from '../superTabs/model.js'+import { actorName } from '../superTabs/activity.js'+import { taggerName } from '../superTabs/mentions.js'+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 }+/** 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 }++/** 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.'++/** 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 = encodeURIComponent+ return `swarm:${e(tabId)}/${e(conversationId)}/message/${e(messageId)}${threadId ? `/thread/${e(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.+ */+export function phoneNotices(tabId: string, state: SuperTabState, written: { replies: ReplyRow[]; tags: TagRow[] }, 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).+ const project = (conversationId: string) => {+ const group = state.conversations.find(c => c.id === conversationId)+ if (!group || isSwarmBuddyChat(group)) return ''+ return projectsOf(state).find(p => p.id === (group.projectId ?? 'lead'))?.name ?? ''+ }+ const replies = written.replies.map(row => ({+ 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),+ }))+ const tags = written.tags.filter(row => !row.holdUntil).flatMap(row => {+ 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) }]+ })+ return [...replies, ...tags]+}diff --git a/backend/src/push/send.test.ts b/backend/src/push/send.test.tsnew file mode 100644index 000000000..1572dd61c--- /dev/null+++ b/backend/src/push/send.test.ts@@ -0,0 +1,67 @@+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() }))+vi.mock('./devices.js', () => ({ devicesOf: m.devicesOf, forgetPushDevice: m.forget, markSandbox: m.sandbox }))+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'+import type { PushDevice } from './devices.js'+import type { PhoneNotice, Sender, SendResult } from './sender.js'++const db = { fixture: 'db' } as never+const 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' })+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]> = []+ const sender: Sender = { send: async (device, n) => { sent.push([device.id, n.key]); return results[device.id] ?? { outcome: 'sent' } } }+ return { sender, sent }+}++describe('sendPhoneNotices (task #2905)', () => {+ beforeEach(() => vi.resetAllMocks())++ 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')])+ const ios = answering({}), android = answering({})+ await sendPhoneNotices(db, { ios: ios.sender, android: android.sender }, [notice('a'), notice('b'), notice('a', 'mention:t1')])+ expect(m.devicesOf).toHaveBeenCalledTimes(1)+ expect(m.devicesOf).toHaveBeenCalledWith(db, ['a', 'b'])+ expect(ios.sent.sort()).toEqual([['a1', 'mention:t1'], ['a1', 'reply:tab:a'], ['b1', 'reply:tab:b']])+ expect(android.sent.sort()).toEqual([['a2', 'mention:t1'], ['a2', 'reply:tab:a']])+ expect(m.count).toHaveBeenCalledWith('ios', 'sent')+ })++ it('forgets a dead token, sends a sandbox one there from now on, and logs a failure without the token', async () => {+ m.devicesOf.mockResolvedValue([phone('dead', 'a'), phone('dev', 'a'), phone('down', 'a')])+ const ios = answering({ dead: { outcome: 'gone', reason: 'Unregistered' }, dev: { outcome: 'sandbox' }, down: { outcome: 'failed', reason: 'InternalServerError' } })+ await sendPhoneNotices(db, { ios: ios.sender, android: null }, [notice('a')])+ expect(m.forget).toHaveBeenCalledWith(db, 'dead')+ expect(m.sandbox).toHaveBeenCalledWith(db, 'dev')+ expect(m.count.mock.calls.sort()).toEqual([['ios', 'failed'], ['ios', 'gone'], ['ios', 'sandbox']])+ expect(m.warn).toHaveBeenCalledWith('phone push failed', expect.objectContaining({ platform: 'ios', reason: 'InternalServerError' }))+ expect(JSON.stringify([m.warn.mock.calls, m.info.mock.calls])).not.toContain('secret-token')+ })++ it('counts and logs a push it cannot send for want of the platform\'s keys', async () => {+ m.devicesOf.mockResolvedValue([phone('a2', 'a', 'android')])+ await sendPhoneNotices(db, { ios: null, android: null }, [notice('a')])+ expect(m.count).toHaveBeenCalledWith('android', 'unconfigured')+ expect(m.warn).toHaveBeenCalledWith('phone push off: no keys for this platform', expect.objectContaining({ platform: 'android', skipped: 1 }))+ })++ it('reads nothing when nobody is told, and never throws', async () => {+ await sendPhoneNotices(db, { ios: null, android: null }, [])+ expect(m.devicesOf).not.toHaveBeenCalled()+ m.devicesOf.mockRejectedValue(new Error('db down'))+ await expect(sendPhoneNotices(db, { ios: null, android: null }, [notice('a')])).resolves.toBeUndefined()+ expect(m.warn).toHaveBeenCalledWith('phone push failed', expect.objectContaining({ error: 'db down' }))+ })++ it('sends at most 8 at once', async () => {+ m.devicesOf.mockResolvedValue(Array.from({ length: 30 }, (_, i) => phone(`p${i}`, 'a')))+ let open = 0, most = 0+ const sender: Sender = { send: async () => { open++; most = Math.max(most, open); await Promise.resolve(); await Promise.resolve(); open--; return { outcome: 'sent' } } }+ await sendPhoneNotices(db, { ios: sender, android: null }, [notice('a')])+ expect(most).toBe(8)+ })+})diff --git a/backend/src/push/send.ts b/backend/src/push/send.tsnew file mode 100644index 000000000..ef2028471--- /dev/null+++ b/backend/src/push/send.ts@@ -0,0 +1,64 @@+import type { PrismaClient } from '@prisma/client'+import { logger } from '../utils/logger.js'+import { metrics } from '../lib/metrics.js'+import { devicesOf, forgetPushDevice, markSandbox, type PushDevice, type PushPlatform } from './devices.js'+import { apnsSender } from './apns.js'+import { fcmSender } from './fcm.js'+import { pushKeysFromEnv, type PushEnv } from './keys.js'+import type { PhoneNotice, Sender } from './sender.js'++/** A platform's sender, or null when the server has no keys for it. */+export type PhoneSenders = Record<PushPlatform, Sender | null>++/** Sends to Apple and Google at once: a 100-person thread's reply is done in a few rounds without opening 100 streams. */+const AT_ONCE = 8++/** The senders the server's secret store allows (push/keys.ts); a bad key throws, which stops the server at start. */+export function phoneSendersFromEnv(env: PushEnv): PhoneSenders {+ const keys = pushKeysFromEnv(env)+ const senders = { ios: keys.apns && apnsSender(keys.apns), android: keys.fcm && fcmSender(keys.fcm) }+ logger.info('phone push', { ios: senders.ios ? 'on' : 'off: no APNs key', android: senders.android ? 'on' : 'off: no FCM service account' })+ return senders+}++/**+ * Sends `notices` to the phones of the people they are for (task #2905), after the write that made them committed. One read+ * 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+ const started = Date.now()+ try {+ 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 })))+ const skipped: Partial<Record<PushPlatform, number>> = {}+ const counts: Record<string, number> = {}+ let next = 0+ const lane = async () => {+ while (next < sends.length) {+ const { notice, device } = sends[next++]!+ const sender = senders[device.platform]+ if (!sender) {+ skipped[device.platform] = (skipped[device.platform] ?? 0) + 1+ metrics.phonePush(device.platform, 'unconfigured')+ continue+ }+ const result = await sender.send(device, notice)+ counts[result.outcome] = (counts[result.outcome] ?? 0) + 1+ metrics.phonePush(device.platform, result.outcome)+ if (result.outcome === 'gone') await forgetPushDevice(db, device.id)+ if (result.outcome === 'sandbox') await markSandbox(db, device.id)+ if (result.outcome === 'failed') logger.warn('phone push failed', { platform: device.platform, reason: result.reason })+ }+ }+ await Promise.all(Array.from({ length: Math.min(AT_ONCE, sends.length) }, lane))+ for (const [platform, count] of Object.entries(skipped)) {+ logger.warn('phone push off: no keys for this platform', { platform, skipped: count, fix: 'set the APNs or FCM keys in the backend secret store (config/env.ts)' })+ }+ if (sends.length) logger.info('phone push', { notices: notices.length, phones: sends.length, ...counts, ms: Date.now() - started })+ } catch (error) {+ logger.warn('phone push failed', { notices: notices.length, error: error instanceof Error ? error.message : String(error) })+ }+}diff --git a/backend/src/push/sender.ts b/backend/src/push/sender.tsnew file mode 100644index 000000000..bd133d275--- /dev/null+++ b/backend/src/push/sender.ts@@ -0,0 +1,28 @@+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.+ */+export interface PhoneNotice { personId: string; key: string; title: string; subtitle: string; body: string; link: string }++/** sent; gone: the token is dead, forget it; sandbox: taken by Apple's sandbox host, send there from now on; failed. */+export type SendOutcome = 'sent' | 'gone' | 'sandbox' | 'failed'+/** `reason` is Apple's or Google's word for it, or `timeout`: never the token. */+export interface SendResult { outcome: SendOutcome; reason?: string }++export interface Sender { send(device: PushDevice, notice: PhoneNotice): Promise<SendResult> }++/** Every call to Apple or Google waits at most this long. */+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'++/** `promise`, or a rejection with `timeout` after `ms`. */+export function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {+ let timer: NodeJS.Timeout | undefined+ const late = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('timeout')), ms) })+ return Promise.race([promise, late]).finally(() => clearTimeout(timer))+}diff --git a/backend/src/routes/control.ts b/backend/src/routes/control.tsindex 344aaaa1e..1e3ad8b79 100644--- a/backend/src/routes/control.ts+++ b/backend/src/routes/control.ts@@ -15,6 +15,7 @@ import { communityNotificationRoutes } from './communityNotifications.js'import { communityReportRoutes } from './communityReports.js'import { communityEditRoutes } from './communityEdit.js'import { deviceKeyRoutes } from './deviceKeys.js'+import { pushDeviceRoutes } from './pushDevices.js'import { qrSignInRoutes } from './qrSignIn.js'import { deskRoutes } from './desk.js'import { connectorRoutes } from './connectors.js'@@ -67,6 +68,7 @@ export async function registerControlRoutes(app: FastifyInstance, opts: {await app.register(communityTranslateRoutes) // a Hub draft's words in English, for its author to reviewawait app.register(qrSignInRoutes) // sign a computer in by scanning its QR with a signed-in phoneawait app.register(deviceKeyRoutes) // the account's device key log: signing in is what trusts a device+ await app.register(pushDeviceRoutes) // a signed-in phone's push token: replies and tags reach it while the app is closedawait app.register(deskRoutes) // the account's tabs, the same on every computer (lib/desk.ts)await app.register(connectorRoutes) // sign-in to GitHub, Slack, Google… for local agents (lib/connectorGateway.ts)await app.register(connectorVaultRoutes) // those connections sealed for the account's computers, which keep them in stepdiff --git a/backend/src/routes/pushDevices.test.ts b/backend/src/routes/pushDevices.test.tsnew file mode 100644index 000000000..bf69cfe9b--- /dev/null+++ b/backend/src/routes/pushDevices.test.ts@@ -0,0 +1,72 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'+const m = vi.hoisted(() => ({ auth: vi.fn(), register: vi.fn(), drop: vi.fn() }))+vi.mock('../push/devices.js', () => ({ registerPushDevice: m.register, dropPushDevice: m.drop }))+vi.mock('../lib/prisma.js', () => ({ prisma: { fixture: 'db' } }))+vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof import('../lib/ssoAuth.js')>(), authenticateAccessToken: m.auth }))+import { pushDeviceRoutes } from './pushDevices.js'+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'+import { errorHandler } from '../middlewares/errorHandler.js'++const user = { sub: 'user-1', email: '[email protected]', role: 'user', autonomousEnv: 'prod' as const }+const auth = { authorization: 'Bearer fixture' }+const token = 'ab'.repeat(32)++describe('push device routes (task #2905)', () => {+ let app: FastifyInstance+ beforeEach(async () => {+ vi.resetAllMocks()+ m.auth.mockResolvedValue({ ...user, sub: `user-${Math.random()}` })+ m.drop.mockResolvedValue(true)+ app = Fastify(); app.setErrorHandler(errorHandler); registerAuthMiddleware(app, m.auth)+ await app.register(pushDeviceRoutes); await app.ready()+ })+ afterEach(async () => { await app.close() })+ const post = (url: string, payload: unknown) => app.inject({ method: 'POST', url, headers: auth, payload: payload as never })++ it('needs a sign-in', async () => {+ expect((await app.inject({ method: 'POST', url: '/api/push-devices', payload: { platform: 'ios', token } })).statusCode).toBe(401)+ })++ it('keeps the phone\'s token for the signed-in person', async () => {+ m.auth.mockResolvedValue(user)+ const r = await post('/api/push-devices', { platform: 'ios', token })+ expect(r.statusCode).toBe(200)+ expect(m.register).toHaveBeenCalledWith({ fixture: 'db' }, 'user-1', { platform: 'ios', token }, expect.any(Number))+ })++ it('takes an Android token as Firebase writes it', async () => {+ const fcm = `dGVzdA:APA91b${'x_-'.repeat(50)}`+ expect((await post('/api/push-devices', { platform: 'android', token: fcm })).statusCode).toBe(200)+ })++ it('refuses a team session: a teammate\'s work never gets the person\'s notices', async () => {+ m.auth.mockResolvedValue({ ...user, harnessSessionId: 's', harnessSessionKind: 'team' })+ const r = await post('/api/push-devices', { platform: 'ios', token })+ expect(r.statusCode).toBe(403)+ expect(r.json().error.code).toBe('TEAM_SESSION_LIMITED')+ expect(m.register).not.toHaveBeenCalled()+ })++ it('refuses another platform, a token with other characters, and one too long', async () => {+ for (const payload of [{ platform: 'web', token }, { platform: 'ios', token: 'ab cd' }, { platform: 'ios', token: 'a/b' },+ { platform: 'ios', token: 'a'.repeat(4097) }, { platform: 'ios', token: '' }, { platform: 'ios', token, extra: 1 }]) {+ expect((await post('/api/push-devices', payload)).statusCode, JSON.stringify(payload).slice(0, 60)).toBe(400)+ }+ expect(m.register).not.toHaveBeenCalled()+ })++ it('drops only the caller\'s token, and says whether it was there', async () => {+ m.auth.mockResolvedValue(user)+ const r = await post('/api/push-devices/drop', { platform: 'ios', token })+ expect(r.statusCode).toBe(200)+ expect(r.json().data).toEqual({ dropped: true })+ expect(m.drop).toHaveBeenCalledWith({ fixture: 'db' }, 'user-1', { platform: 'ios', token })+ })++ it('answers 429 past 20 changes a minute', async () => {+ m.auth.mockResolvedValue({ ...user, sub: 'busy' })+ for (let i = 0; i < 20; i++) expect((await post('/api/push-devices', { platform: 'ios', token })).statusCode).toBe(200)+ expect((await post('/api/push-devices/drop', { platform: 'ios', token })).statusCode).toBe(429)+ })+})diff --git a/backend/src/routes/pushDevices.ts b/backend/src/routes/pushDevices.tsnew file mode 100644index 000000000..af6553e6c--- /dev/null+++ b/backend/src/routes/pushDevices.ts@@ -0,0 +1,39 @@+import type { FastifyInstance } from 'fastify'+import { z } from 'zod'+import { prisma } from '../lib/prisma.js'+import { dropPushDevice, registerPushDevice } from '../push/devices.js'+import { validateBody } from '../middlewares/validation.js'+import { sendError, sendSuccess } from '../utils/response.js'+import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'+import { createRateLimiter } from '../lib/rateLimit.js'++/** A phone registers at each signed-in launch and when its token changes, and drops it at sign-out: a loop meets this, nothing else. */+const CHANGES_PER_MINUTE = 20+const allowChange = createRateLimiter('push-devices', 60_000, CHANGES_PER_MINUTE)++/** An APNs token is hex; an FCM token is base64url with a colon. Either fits in 4096 characters. */+const body = z.object({+ platform: z.enum(['ios', 'android']),+ token: z.string().min(1).max(4096).regex(/^[A-Za-z0-9:_-]+$/),+}).strict()++/**+ * A phone's push token for the signed-in person (push/devices.ts, task #2905): kept at sign-in, so a thread reply or a tag+ * reaches the phone while the app is closed, and dropped at sign-out, while the sign-in still works to say so. Never a team+ * session's (lib/teamSession.ts): a teammate's work on the person's Mac never gets the person's notices.+ */+export async function pushDeviceRoutes(app: FastifyInstance): Promise<void> {+ app.post<{ Body: z.infer<typeof body> }>('/api/push-devices', { preHandler: validateBody(body) }, async (req, reply) => {+ const user = req.user!+ if (isTeamSession(user)) return sendError(reply, TEAM_SESSION_MESSAGE, TEAM_SESSION_LIMITED, 403)+ if (!(await allowChange.allows(user.sub))) return sendError(reply, 'Too many changes to this phone\'s notifications. Try again in a minute.', 'RATE_LIMITED', 429)+ await registerPushDevice(prisma, user.sub, req.body, Date.now())+ sendSuccess(reply, { ok: true })+ })++ app.post<{ Body: z.infer<typeof body> }>('/api/push-devices/drop', { preHandler: validateBody(body) }, async (req, reply) => {+ const user = req.user!+ if (!(await allowChange.allows(user.sub))) return sendError(reply, 'Too many changes to this phone\'s notifications. Try again in a minute.', 'RATE_LIMITED', 429)+ sendSuccess(reply, { dropped: await dropPushDevice(prisma, user.sub, req.body) })+ })+}diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex a46c2c2b7..0c8bccd97 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -3,6 +3,7 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'import { z, ZodError } from 'zod'import { prisma, prismaSecondary } from '../lib/prisma.js'import { env } from '../config/env.js'+import { phoneSendersFromEnv, sendPhoneNotices } from '../push/send.js'import multipart from '@fastify/multipart'import { attachmentsFromEnv, formFileBody, FORM_TOO_LARGE_MESSAGE, MAX_FORM_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, stopUnpacking, unpackFailed } from '../superTabs/attachments.js'import { validateBody, validateParams, validateQuery } from '../middlewares/validation.js'@@ -248,9 +249,12 @@ async function productionStore(github: GitHubTokens | null): Promise<SuperTabSto{ VoiceQuotaExceededError, voiceQuotaService }, { pickWavLang, transcribeWavWithDeepgram }] = await Promise.all([import('../lib/bus.js'), import('../lib/swarmDeliveryPushes.js'), import('../lib/swarmHostPushes.js'), import('../lib/swarmClientPushes.js'),import('./harnessLinks.js'), import('../lib/voiceQuota.js'), import('../lib/deepgramWav.js')])+ const phones = phoneSendersFromEnv(env)return new SuperTabStore(prisma, Date.now, attachmentsFromEnv(env),// Older history pages and the costs report read the secondaries (lib/prisma.ts, task #2970).{ replica: prismaSecondary,+ // Thread replies and tags reach the phones of whoever they tell, while the app is closed (push/send.ts, task #2905).+ phoneNotices: notices => { void sendPhoneNotices(prisma, phones, notices) },// A task that ends revokes the token it was given; a revoke that fails is logged inside and never blocks the write.workEnded: (tabId, ended) => { void github?.release(tabId, ended).catch(error => logger.warn('[github] release failed', { tabId, error: String(error) })) },workStarted: (tabId, started) => { void github?.resume(tabId, started).catch(error => logger.warn('[github] resume failed', { tabId, error: String(error) })) },diff --git a/backend/src/superTabs/activity.ts b/backend/src/superTabs/activity.tsindex 99693aef4..437ee1e39 100644--- a/backend/src/superTabs/activity.ts+++ b/backend/src/superTabs/activity.ts@@ -22,6 +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 { shownNameOf } from './personNames.js'import { FIELDS, readable, row as messageRow, type Row } from './read/inbox.js'@@ -85,9 +86,9 @@ export interface ReplyFanout { state: SuperTabState; threads: ReadonlyMap<string* Reads: the roots and quoted messages by id, the people's thread marks by id and their chat settings by id: three reads* whatever the thread's length, the last two only when someone is told. Writes: one row per person told, in one createMany. */export async function writeReplyActivity(tx: Tx, tabId: string, messages: MessageDraft[], sequences: ReadonlyMap<string, number>, now: number,- fanout?: ReplyFanout): Promise<void> {+ fanout?: ReplyFanout): Promise<ReplyRow[]> {const replies = messages.filter(m => m.thread && m.thread !== m.id && !agentOnly(m.source ?? null, m.recipients) && m.source?.kind !== SESSION_ENDED_KIND)- if (!replies.length) return+ if (!replies.length) return []const ids = [...new Set(replies.flatMap(m => [m.thread!, ...(m.replyTo ? [m.replyTo] : [])]))]// By id through its index, as a plain $in (parts/indexed.ts): Prisma's `in` plans slowly.const found = new Map((await readBy(tx, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: ids }, tabId } }, { $project: { conversationId: 1, author: 1 } }]))@@ -114,7 +115,7 @@ export async function writeReplyActivity(tx: Tx, tabId: string, messages: Messag})const markIds = [...new Set(recipients.flatMap(({ message, people }) => people.map(personId =>stableId(tabId, message.conversationId, message.thread!, personId))))]- if (!markIds.length) return+ if (!markIds.length) return []const marks = await tx.superTabThreadMark.aggregateRaw({ pipeline: [{ $match: { _id: { $in: markIds } } }, { $project: { _id: 1, follow: 1 } },] }) as unknown as Array<{ _id: string; follow?: boolean | null }>@@ -132,6 +133,7 @@ export async function writeReplyActivity(tx: Tx, tabId: string, messages: Messag...sequences.has(m.id) ? { sequence: sequences.get(m.id)! } : {}, ...m.alsoInChat ? { alsoInChat: true } : {} }))})if (data.length) await tx.superTabActivity.createMany({ data })+ return data}/** 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 71f7b84e3..1d6c33b41 100644--- a/backend/src/superTabs/mentions.ts+++ b/backend/src/superTabs/mentions.ts@@ -158,7 +158,8 @@ export function checkMentions(state: SuperTabState, actor: Actor, group: Conversreturn ids}-export async function writeMentions(tx: Tx, tabId: string, state: SuperTabState, messages: MessageDraft[], now: number): Promise<void> {+/** Writes the tags `messages` carry, and answers the rows it wrote (push/notices.ts tells their phones). */+export async function writeMentions(tx: Tx, tabId: string, state: SuperTabState, messages: MessageDraft[], now: number): Promise<MentionRow[]> {const data = messages.flatMap(message => (message.mentions ?? []).map(personId => ({id: stableId(tabId, message.id, personId), tabId, personId, projectId: state.conversations.find(c => c.id === message.conversationId)!.projectId ?? 'lead',conversationId: message.conversationId, messageId: message.id, authorAgentId: message.author.id,@@ -166,6 +167,14 @@ export async function writeMentions(tx: Tx, tabId: string, state: SuperTabState,})))if (data.length) await tx.superTabMention.createMany({ data })await bringBackUnfollowed(tx, tabId, messages, now)+ return data+}+type MentionRow = { id: string; personId: string; conversationId: string; messageId: string; holdUntil?: Date }++/** Who tagged, as the inbox and a phone notice name them: a person by the name the Swarm shows for them (a person's name in a+ * message is their email, personNames.ts), an agent by its own. */+export function taggerName(state: SuperTabState, author: { kind?: string; id?: string; name?: string; displayName?: string } | undefined): string {+ return author?.kind === 'person' ? shownNameOf(state, author.id ?? '') ?? 'Someone' : author?.displayName ?? author?.name ?? 'Lead'}/** A tag in a thread reply puts the thread back on the tagged person's Threads page, as in Slack: their Unfollow of it is cleared@@ -345,8 +354,7 @@ export async function listMentions(tx: Tx, tabId: string, state: SuperTabState,return tagged.map(({ row, group }) => {const message = messages.find(m => m.id === row.messageId)const author = message?.author as { kind?: string; name?: string; displayName?: string } | undefined- // A person's name in a message is their email: the inbox shows the name the Swarm shows for them (personNames.ts).- const authorName = author?.kind === 'person' ? shownNameOf(state, row.authorAgentId) ?? 'Someone' : author?.displayName ?? author?.name ?? 'Lead'+ const authorName = taggerName(state, author && { ...author, id: row.authorAgentId })return { id: row.id, projectId: row.projectId, projectName: projectOf(state, group.projectId ?? 'lead').name,conversationId: row.conversationId, conversationTitle: group.title, messageId: row.messageId,leadId: row.authorAgentId, leadName: authorName, text: (message?.text ?? '').slice(0, 200),diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 95539f179..f0a79b83e 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1,5 +1,7 @@import { refusalLogFields, type DeclaredClient } from './refusalLog.js'import { writeReactionActivity, writeReplyActivity } from './activity.js'+import { phoneNotices, type ReplyRow, type TagRow } from '../push/notices.js'+import type { PhoneNotice } from '../push/sender.js'import { 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 { authorForAgent, lazyUsernames, namesPerson, rowForAgent, shownNameOf } from './personNames.js'import { readingClearsSuspensions, suspendedEngines } from './engineHealth.js'@@ -376,6 +378,9 @@ export interface SuperTabStoreHooks {/** A delivery now waits for this agent, committed: its machine's daemon socket tells its host to read it at once* (lib/swarmDeliveryPushes.ts). Called after the write commits; it must not throw. */deliveriesWaiting?: (waiting: DeliveriesWaiting) => void+ /** What a write tells people's phones (push/notices.ts, task #2905): its thread replies and tags. Called after the write+ * commits; it must not throw. */+ phoneNotices?: (notices: PhoneNotice[]) => void/** A terminal request waits for this machine (spec 2026-11-02 poll cost, Part 4.2), once its write commits. */terminalWaiting?: (waiting: DeliveriesWaiting) => void/** A commit changed what these machines' hosts read (parts/commit.ts hostsToTell): each machine's daemon socket tells its@@ -1980,9 +1985,10 @@ export class SuperTabStore {const ledId = 'conversationId' in command ? command.conversationId : command.type === 'agent.start' ? command.request.conversationId : undefinedconst leadAt = (state: SuperTabState) => state.conversations.find(c => c.id === ledId)?.leadAction?.atif (ledId && leadAt(effects.state) !== undefined && leadAt(effects.state) !== leadAt(original)) await dropHeldTags(tx, tabId, ledId, context.now)- await writeMentions(tx, tabId, effects.state, effects.messages, context.now)+ const tags = await writeMentions(tx, tabId, effects.state, effects.messages, context.now)// Everyone in each thread replied in, from the summaries just computed: no read of the threads' rows (task #2745).- await writeReplyActivity(tx, tabId, effects.messages, sequences, context.now, { state: effects.state, threads })+ const replies = await writeReplyActivity(tx, tabId, effects.messages, sequences, context.now, { state: effects.state, threads })+ this.tellPhones(tx, tabId, effects.state, { replies, tags }, effects.messages)// Their own message leaves the chat read for them on every app, in the same commit its read answers from (task #2265). A reply// only in a thread is not in the chat, and a Team session has no marks (read/service.ts markRead).if (command.type === 'message.send' && actor.kind === 'person' && !isTeamSession(user)) {@@ -4394,11 +4400,26 @@ export class SuperTabStore {// A finished step's too: its task handed on again since the load must not lose the step it will need.await this.save(tx, loaded, state, clock.next(), group.reviewOf ? [{ kind: 'group', key: group.reviewOf }] : [])await this.writeMessages(tx, tabId, state, rows, sequences)- await writeMentions(tx, tabId, state, rows, now)+ this.tellPhones(tx, tabId, state, { replies: [], tags: await writeMentions(tx, tabId, state, rows, now) }, rows)return true})}+ /** 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 {+ const tell = this.hooks.phoneNotices+ if (!tell || (!written.replies.length && !written.tags.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 {+ notices = phoneNotices(tabId, state, written, messages)+ } catch (error) {+ logger.warn('phone push failed', { tabId, error: error instanceof Error ? error.message : String(error) })+ return+ }+ if (notices.length) afterCommit(tx, () => tell(notices))+ }+/** Ends, as cancelled, those of this Swarm's open deliveries `rows` (as the delivery pass read them) that can no longer move* (deliverySettle.ts). Each only as it was read: one its host acknowledged since, or a claim with no hold its host claimed* again since, is kept. A held claim its host claims again still ends once its hold is over; it keeps its hold's reason,diff --git a/backend/src/worker.ts b/backend/src/worker.tsindex a5beec716..f1ee1da90 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -32,6 +32,7 @@ import { announceSwarmHostChanges } from './lib/swarmHostPushes.js'import { announceSwarmChanges } from './lib/swarmClientPushes.js'import { GitHubApp, githubAppConfig } from './github/app.js'import { env } from './config/env.js'+import { phoneSendersFromEnv, sendPhoneNotices } from './push/send.js'import { machineBillingWorkerService } from './services/MachineBillingWorkerService.js'import { productUsagePeopleRollupService } from './services/ProductUsagePeopleRollupService.js'import { startReceiptSweep } from './lib/productUsageReceiptSweep.js'@@ -131,8 +132,10 @@ async function start(): Promise<void> {configureSwarmStamps(redisSwarmStamps(), { reads: false })// Archive notes and Workspace removals write messages too: their recipients' hosts hear of them at once, and of the// groups they changed.+ // Their tags reach the tagged person's phones too (push/send.ts, task #2905).+ const phones = phoneSendersFromEnv(env)const swarms = new SuperTabStore(prisma, Date.now, null, { deliveriesWaiting: announceSwarmDeliveries, terminalWaiting: announceSwarmTerminal, hostsChanged: announceSwarmHostChanges,- swarmChanged: announceSwarmChanges })+ swarmChanged: announceSwarmChanges, phoneNotices: notices => { void sendPhoneNotices(prisma, phones, notices) } })// Decisions still waiting in work that was over before #2454 closed them where work ends: they counted toward the open// limit and came back on a reopen (store.ts withdrawEndedDecisions). Remove in the release after the one that runs it.logger.info('[swarm-decisions] closed waiting decisions of finished work', { closed: await swarms.withdrawEndedDecisions() })diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex f6fc59c00..a4e4a328c 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -8,5 +8,5 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts','integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabPersonalLead.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts','integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/overdueDecisions.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts','integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabPmSchedule.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',- 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],+ 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts', 'integration/pushDevices.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/desktop/lib/shared/widgets/app_menu.dart b/desktop/lib/shared/widgets/app_menu.dartindex ace114cad..233ca7055 100644--- a/desktop/lib/shared/widgets/app_menu.dart+++ b/desktop/lib/shared/widgets/app_menu.dart@@ -1,3 +1,4 @@+import 'dart:async';import 'dart:math' as math;import 'package:harness/shared/theme/app_icons.dart';@@ -626,6 +627,7 @@ class _AppDropdownState extends State<AppDropdown> {MenuController? _own;final _searchFocus = FocusNode(debugLabel: 'Dropdown search');final _searchText = TextEditingController();+ final _pointer = _AppMenuPointer();String _query = '';MenuController get _controller =>@@ -633,6 +635,7 @@ class _AppDropdownState extends State<AppDropdown> {@overridevoid dispose() {+ _pointer.dispose();_searchFocus.dispose();_searchText.dispose();super.dispose();@@ -780,10 +783,23 @@ class _AppDropdownState extends State<AppDropdown> {),),),- for (final child in shown)+ for (final (index, child) in shown.indexed)SizedBox(width: width,- child: _AppMenuRoot(controller: root, glyphs: glyphs, child: child),+ // The pointer arriving on a row tells the submenu row beside it to+ // let go ([AppSubmenuItem]).+ child: MouseRegion(+ onEnter: (_) => _pointer.enter(index),+ child: _AppMenuRow(+ index: index,+ pointer: _pointer,+ child: _AppMenuRoot(+ controller: root,+ glyphs: glyphs,+ child: child,+ ),+ ),+ ),),],builder: widget.builder,@@ -844,16 +860,67 @@ class AppSubmenuItem extends StatefulWidget {}class _AppSubmenuItemState extends State<AppSubmenuItem> {+ /// How long a sibling row may hold the pointer before the submenu lets go:+ /// the time a hand needs to cut a corner on its way into the submenu, as+ /// macOS and Slack allow.+ static const _grace = Duration(milliseconds: 120);+MenuController? _own;bool _open = false;+ Timer? _letGo;+ _AppMenuRow? _row;MenuController get _controller =>widget.controller ?? (_own ??= MenuController());+ /// A cancelled [Timer] stays in the field: clear it, or the `??=` below+ /// would never start another.+ void _keepOpen() {+ _letGo?.cancel();+ _letGo = null;+ }+void _openMenu() {+ _keepOpen();if (!_controller.isOpen) _controller.open();}+ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ final row = _AppMenuRow.maybeOf(context);+ if (row?.pointer == _row?.pointer) {+ _row = row;+ return;+ }+ _row?.pointer.removeListener(_pointerMoved);+ row?.pointer.addListener(_pointerMoved);+ _row = row;+ }++ @override+ void dispose() {+ _keepOpen();+ _row?.pointer.removeListener(_pointerMoved);+ super.dispose();+ }++ /// The pointer arrived on a row of the panel. On this row it stays; on+ /// another, the submenu closes unless the pointer reaches it first.+ void _pointerMoved() {+ final row = _row;+ if (row == null) return;+ if (row.pointer.row == row.index) {+ _keepOpen();+ return;+ }+ if (!_controller.isOpen) return;+ _letGo ??= Timer(_grace, () {+ _letGo = null;+ if (mounted && _controller.isOpen) _controller.close();+ });+ }+@overrideWidget build(BuildContext context) {return AppDropdown(@@ -868,10 +935,19 @@ class _AppSubmenuItemState extends State<AppSubmenuItem> {widget.onOpen?.call();},onClose: () {+ _keepOpen();if (mounted) setState(() => _open = false);widget.onClose?.call();},- children: widget.menuChildren,+ children: [+ // Reaching the submenu ends the grace.+ // Rows only: AppDropdown sizes its panel from a list of rows and+ // dividers it can see through, and a divider is not a place to rest.+ for (final child in widget.menuChildren)+ child is AppMenuDivider+ ? child+ : MouseRegion(onEnter: (_) => _keepOpen(), child: child),+ ],child: MouseRegion(onHover: (_) => _openMenu(),child: AppMenuItem(@@ -891,6 +967,36 @@ class _AppSubmenuItemState extends State<AppSubmenuItem> {}}+/// Which row of a panel the pointer last arrived on.+class _AppMenuPointer extends ChangeNotifier {+ int? row;++ void enter(int index) {+ row = index;+ notifyListeners();+ }+}++/// A row's place in its panel, handed down so a submenu row can tell when the+/// pointer is on a sibling.+class _AppMenuRow extends InheritedWidget {+ const _AppMenuRow({+ required this.index,+ required this.pointer,+ required super.child,+ });++ final int index;+ final _AppMenuPointer pointer;++ static _AppMenuRow? maybeOf(BuildContext context) =>+ context.dependOnInheritedWidgetOfExactType<_AppMenuRow>();++ @override+ bool updateShouldNotify(_AppMenuRow old) =>+ index != old.index || pointer != old.pointer;+}+/// The top menu of an [AppDropdown] chain, handed down to its rows.class _AppMenuRoot extends InheritedWidget {const _AppMenuRoot({diff --git a/desktop/test/app_submenu_hover_test.dart b/desktop/test/app_submenu_hover_test.dartnew file mode 100644index 000000000..5b50dc0b3--- /dev/null+++ b/desktop/test/app_submenu_hover_test.dart@@ -0,0 +1,151 @@+import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart';+import 'package:harness/shared/widgets/app_menu.dart';++/// A pointer over [AppSubmenuItem], as Slack and macOS menus treat it: pointing+/// at a sibling row closes the open submenu and clears the parent row's+/// highlight, while crossing into the submenu keeps it open.+void main() {+ const notifyKey = ValueKey('notify-row');+ final menu = MenuController();++ Future<TestGesture> open(WidgetTester tester) async {+ tester.view.physicalSize = const Size(900, 700);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);+ await tester.pumpWidget(+ MaterialApp(+ theme: buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: Align(+ alignment: Alignment.topLeft,+ child: AppDropdown(+ controller: menu,+ width: 200,+ children: [+ AppMenuItem(label: 'Status', onPressed: () {}),+ AppSubmenuItem(+ itemKey: notifyKey,+ label: 'Notifications',+ menuChildren: [+ AppMenuItem(label: 'All new messages', onPressed: () {}),+ AppMenuItem(label: 'Muted', onPressed: () {}),+ ],+ ),+ AppMenuItem(label: 'Sharing', onPressed: () {}),+ ],+ builder: (context, controller, _) => TextButton(+ onPressed: controller.open,+ child: const Text('Open menu'),+ ),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open menu'));+ await tester.pumpAndSettle();+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ addTearDown(mouse.removePointer);+ await mouse.addPointer(location: const Offset(800, 600));+ await tester.pump();+ return mouse;+ }++ bool submenuOpen(WidgetTester tester) =>+ find.text('All new messages').evaluate().isNotEmpty;++ bool rowHighlighted(WidgetTester tester) =>+ tester.widget<AppMenuItem>(find.byKey(notifyKey)).highlighted;++ testWidgets('pointing at a sibling row closes the submenu and clears the '+ 'highlight', (tester) async {+ final mouse = await open(tester);+ await mouse.moveTo(tester.getCenter(find.text('Notifications')));+ await tester.pumpAndSettle();+ expect(submenuOpen(tester), isTrue);+ expect(rowHighlighted(tester), isTrue);++ await mouse.moveTo(tester.getCenter(find.text('Sharing')));+ await tester.pumpAndSettle();++ expect(submenuOpen(tester), isFalse);+ expect(rowHighlighted(tester), isFalse);+ });++ testWidgets('pointing at a row above closes it too', (tester) async {+ final mouse = await open(tester);+ await mouse.moveTo(tester.getCenter(find.text('Notifications')));+ await tester.pumpAndSettle();++ await mouse.moveTo(tester.getCenter(find.text('Status')));+ await tester.pumpAndSettle();++ expect(submenuOpen(tester), isFalse);+ expect(rowHighlighted(tester), isFalse);+ });++ testWidgets('moving into the submenu keeps it open', (tester) async {+ final mouse = await open(tester);+ final row = tester.getCenter(find.text('Notifications'));+ await mouse.moveTo(row);+ await tester.pumpAndSettle();++ final choice = tester.getCenter(find.text('All new messages'));+ // Across the gap between the panels, as a hand crosses it.+ await mouse.moveTo(Offset(choice.dx - 60, row.dy));+ await tester.pump(const Duration(milliseconds: 30));+ await mouse.moveTo(choice);+ await tester.pump(const Duration(seconds: 1));++ expect(submenuOpen(tester), isTrue);+ expect(rowHighlighted(tester), isTrue);+ });++ testWidgets('cutting across a sibling row on the way in keeps it open', (+ tester,+ ) async {+ final mouse = await open(tester);+ await mouse.moveTo(tester.getCenter(find.text('Notifications')));+ await tester.pumpAndSettle();++ // A diagonal path clips the row below before it reaches the submenu.+ await mouse.moveTo(tester.getCenter(find.text('Sharing')));+ await tester.pump(const Duration(milliseconds: 30));+ await mouse.moveTo(tester.getCenter(find.text('All new messages')));+ await tester.pump(const Duration(seconds: 1));++ expect(submenuOpen(tester), isTrue);++ // The grace ended with the pointer in the submenu; a sibling row still+ // closes it afterwards.+ await mouse.moveTo(tester.getCenter(find.text('Sharing')));+ await tester.pumpAndSettle();+ expect(submenuOpen(tester), isFalse);+ expect(rowHighlighted(tester), isFalse);+ });++ testWidgets('coming back to the row after leaving it keeps it open', (+ tester,+ ) async {+ final mouse = await open(tester);+ final row = tester.getCenter(find.text('Notifications'));+ await mouse.moveTo(row);+ await tester.pumpAndSettle();++ await mouse.moveTo(tester.getCenter(find.text('Sharing')));+ await tester.pump(const Duration(milliseconds: 30));+ await mouse.moveTo(row);+ await tester.pump(const Duration(seconds: 1));++ expect(submenuOpen(tester), isTrue);++ // Back on the row, the grace is over: the next sibling closes it again.+ await mouse.moveTo(tester.getCenter(find.text('Sharing')));+ await tester.pumpAndSettle();+ expect(submenuOpen(tester), isFalse);+ expect(rowHighlighted(tester), isFalse);+ });+}diff --git a/docs/plans/2026-11-05-phone-push-plan.md b/docs/plans/2026-11-05-phone-push-plan.mdnew file mode 100644index 000000000..c48c687a6--- /dev/null+++ b/docs/plans/2026-11-05-phone-push-plan.md@@ -0,0 +1,215 @@+# Phone Push Implementation Plan++Task #2905, requested by anh Dee (#2745). Written by the task's Engineer by the writing-plans skill, implemented by the same+Engineer task by task, test first; the review step on the pull request is the one independent review.++**Goal:** A thread reply to someone in the thread, and a tag, reach that person's phone as a system notification while the+app is closed, and a tap opens the thread at the reply.++**Architecture:** The server already decides who hears a reply (`writeReplyActivity`, #2954) and a tag (`writeMentions`) in+the reply's own transaction. After that transaction commits, a new `push/` module turns those rows into phone notices and+sends each to the person's registered phones: APNs (HTTP/2, a JWT signed with the team's .p8 key) for iOS, FCM HTTP v1 (an+OAuth token from the service account) for Android. The phone registers its push token when signed in and drops it when+signing out, through two routes beside the device keys. The phone's native code (iOS AppDelegate, Android MainActivity) gets+the token and hands a tapped notification's link to Dart, which opens it as it opens a local Swarm notice today.++**Tech Stack:** TypeScript (Fastify, Prisma on MongoDB, node:http2 and node:crypto, no new npm dependency); Flutter (Dart),+Swift, Kotlin with `com.google.firebase:firebase-messaging` on Android only.++**Spec:** the task's brief (task #2905), and #2954's design `docs/plans/2026-11-04-thread-reply-notifications-design.md`+for who is told.++## Global Constraints++- Push for the same events #2954 notifies about: a reply to someone in the thread (its Activity row) and a tag (its mention+ row). Muted chats and Unfollow stay as #2954 has them: they decide the rows, and push follows the rows.+- The open-thread rule stays on the phone: a push that arrives while the app is in front shows nothing; the app's own+ notices (`SwarmAnnouncer`, with its `quiet` check) decide there.+- A notice says who and where, never what was written: the same title, subtitle and body as the phone's local notices+ (`swarm_notices.dart`: "X replied in a thread" / "X tagged you", the project, "Open Harness to read it."). Message text+ never goes to Apple or Google.+- Push keys live only in the server's environment (the secret store): `APNS_KEY_ID`, `APNS_TEAM_ID`, `APNS_PRIVATE_KEY`,+ `APNS_TOPIC` (default `ai.autonomous.harness.ios`), `FCM_SERVICE_ACCOUNT` (base64 of the JSON key). One APNs value+ without the others, or a key that cannot be read, stops the server at start with a message that never shows the key.+ None set: push is off and each skipped push is counted and logged, never silent.+- A token is the person's who registered it last; a sign-out drops it; a token Apple or Google call dead is deleted. A team+ session registers no token.+- Tokens never reach logs, metrics or errors. Metrics carry platform and outcome only.+- No new npm dependency. On the phone, Firebase only on Android, configured at build time; a build without its values+ has Android push off and says so in the app log.+- Swarm code stays out of `cli/src/core`. Two security reviews (tokens).++## Design++- growth: `PushDevice` rows. Deleted on sign-out, on a dead-token answer, at most 10 per person (the oldest go when an 11th+ registers), and by a TTL index 90 days after `seenAt`; the phone registers again at every signed-in launch.+- concurrency: one row per token (`_id` = SHA-256 of platform and token); register is an upsert by id, so two at once end+ with one row, the last owner's.+- read cost: one indexed read of the told people's devices per command that tells anyone (`userId $in`, at most 105+ people: 100 reply fan-out and 5 tags); nothing when nobody is told. No polling.+- scale: 10x people in a thread is still capped by `REPLY_FANOUT`; sends run 8 at a time with a 10-second timeout. What+ warns first: `phone_pushes_total{outcome="failed"}` and the send time in the `phone push` log line.+- compatibility: new routes and a new collection; an older phone never registers and keeps its open-app notices. A phone+ with this change against an older server gets 404 on register, logged and ignored.+- migration + rollback: none to run. The TTL index is made before the push (`releaseSchema`); rolling back stops sends,+ and the rows expire in 90 days or can be dropped with the collection.+- audience: rows are written only for people who may read the chat (#2954); push goes only to the tokens of those people.+- identity: tokens are per signed-in person (`req.user.sub`); team sessions are refused.+- failure: a send that fails is logged with platform and APNs/FCM reason and counted; push never blocks or fails the+ reply's write (it runs after the commit, its errors caught).+- platforms: backend; iOS and Android phone app.++## Review Focus++1. The same phone signed in as another person: the token must move to the new person, so the first stops getting the+ second's notices. Test: register as A then B, push for A sends nothing (Task 1).+2. Sign-out on a phone with no network: the drop fails and the token stays on the server. The phone does not retry it; the+ app is signed out, so a push it gets opens the welcome screen and shows no content beyond the notice. The next person+ signing in on that phone takes the token over (1), and Apple or Google calling it dead deletes it. Tested by (1).+3. A development build (Xcode) has a sandbox token: production APNs answers `BadDeviceToken`, and the server retries once+ on the sandbox host and remembers it. Test in Task 3.+4. A push while the app is in front must not show twice (push and local notice): iOS presents nothing for a remote Swarm+ push in the foreground, FCM does not draw a notification message in the foreground. And a push already in the tray is+ not posted again by the app when it comes back: the app marks the keys of delivered pushes told (Task 7 test).+5. A tag held back for 20 minutes (no worker yet, `holdMentions`) does not push at the time it is written. Test in Task 4.++---++### Task 1: Push devices, stored++**Files:**+- Modify: `backend/prisma/schema.prisma` (model `PushDevice`, `@@map("push_devices")`)+- Create: `backend/src/push/devices.ts`+- Modify: `backend/src/lib/db/schemaRelease.ts` (`ensurePushDeviceExpiry` before `ensureSchema`)+- Modify: `backend/integration/schemaRelease.test.ts` (the new expiry index in its list)+- Test: `backend/integration/pushDevices.test.ts` (a real replica set, with the plan check; listed in `vitest.super-tabs.config.ts`)++**Interfaces:**+- Produces: `type PushPlatform = 'ios' | 'android'`; `interface PushDevice { id: string; userId: string; platform: PushPlatform; token: string; sandbox: boolean }`;+ `registerPushDevice(db, userId: string, device: { platform: PushPlatform; token: string }, now: number): Promise<void>`;+ `dropPushDevice(db, userId: string, device: { platform; token }): Promise<boolean>`;+ `devicesOf(db, userIds: string[]): Promise<PushDevice[]>`; `forgetPushDevice(db, id: string): Promise<void>`;+ `markSandbox(db, id: string): Promise<void>`; `ensurePushDeviceExpiry(db)`; `PUSH_DEVICES_PER_PERSON = 10`;+ `PUSH_DEVICE_EXPIRY_MS = 90 days`.++- [ ] Step 1: tests: register then `devicesOf([A])` returns it; register as A then B: `devicesOf([A])` is empty and B has it;+ the 11th register keeps the 10 newest; `dropPushDevice` by another person returns false and keeps the row; by the owner+ deletes it; `devicesOf([])` reads nothing.+- [ ] Step 2: run `npx vitest run --config vitest.super-tabs.config.ts integration/pushDevices.test.ts`: FAIL (module missing). Commit the test.+- [ ] Step 3: implement. `_id` = hex SHA-256 of `platform + '\n' + token`. `devicesOf` is an `aggregateRaw` `$match` on+ `userId $in` (rule 3: Prisma's `in` is `$expr`). The cap deletes beyond the 10 newest `seenAt` of that person.+- [ ] Step 4: run it: PASS. Integration plan test: `devicesOf` is an IXSCAN on `userId`. Commit.++### Task 2: Register and drop routes++**Files:**+- Create: `backend/src/routes/pushDevices.ts`; Modify: `backend/src/routes/control.ts` (register it)+- Test: `backend/src/routes/pushDevices.test.ts`++**Interfaces:**+- Consumes: Task 1. Produces: `POST /api/push-devices` `{platform, token}` → `{ok: true}`; `POST /api/push-devices/drop`+ `{platform, token}` → `{dropped: boolean}`.++- [ ] Step 1: tests: a signed-in person registers (row for `req.user.sub`); a team session gets 403 `TEAM_SESSION_LIMITED`;+ a token with characters outside `[A-Za-z0-9:_-]` or longer than 4096 gets 400; drop removes only the caller's; the 21st+ call in a minute gets 429.+- [ ] Step 2: FAIL; commit. Step 3: implement with `validateBody` (zod, strict) and `createRateLimiter('push-devices', 60_000, 20)`.+- [ ] Step 4: PASS; commit.++### Task 3: Senders (APNs and FCM)++**Files:**+- Create: `backend/src/push/sender.ts` (the shared types), `backend/src/push/apns.ts`, `backend/src/push/fcm.ts`, `backend/src/push/keys.ts`+- Modify: `backend/src/config/env.ts` (the five variables, read through `push/keys.ts`)+- Test: `backend/src/push/apns.test.ts`, `backend/src/push/fcm.test.ts`, `backend/src/push/keys.test.ts`++**Interfaces:**+- Produces: `interface PhoneNotice { personId: string; key: string; title: string; subtitle: string; body: string; link: string }`;+ `type SendOutcome = 'sent' | 'gone' | 'sandbox' | 'failed'`; `interface SendResult { outcome: SendOutcome; reason?: string }`;+ `interface Sender { send(device: PushDevice, notice: PhoneNotice): Promise<SendResult> }`;+ `apnsSender(keys: ApnsKeys, options?: { transport?; now?; timeoutMs? }): Sender`; `fcmSender(account: FcmAccount, options?: { fetcher?; now?; timeoutMs? }): Sender`;+ `pushKeysFromEnv(env): { apns: ApnsKeys | null; fcm: FcmAccount | null }` (throws a message without the key on a bad one).++- [ ] Step 1: tests. APNs: the request has `:path /3/device/<token>`, `apns-topic`, `apns-push-type: alert`, priority 10,+ `authorization: bearer <JWT>` whose ES256 signature verifies with the key's public half and whose `iss`/`kid` are the team+ and key ids; the body is `{aps: {alert: {title, subtitle, body}, sound: 'default', 'thread-id', category: 'swarm-needs-you'}, key, link}`+ and holds no other text; 200 → `sent`; 410 or 400 `Unregistered` → `gone`; 400 `BadDeviceToken` on production → retried+ on the sandbox host, 200 there → `sandbox`; 500 → `failed`; a hung transport → `failed` after the timeout; the JWT is+ reused within 50 minutes. FCM: the token request is a JWT bearer grant signed RS256 by the service account; the message+ is `{message: {token, notification: {title, body}, android: {priority: 'high', notification: {channel_id: 'swarm-needs-you', tag: key}}, data: {key, link}}}`;+ 404 or `UNREGISTERED` → `gone`; the access token is reused until near its expiry. Keys: none set → both null; APNs+ partly set → throws naming the missing variable; a malformed key → throws, and the message does not contain the key.+- [ ] Step 2: FAIL; commit. Step 3: implement with `node:http2` (one session per host, reconnect when closed) and+ `node:crypto` `sign`. 10-second timeout on every call. Step 4: PASS; commit.++### Task 4: What a command tells phones, and sending it after commit++**Files:**+- Create: `backend/src/push/notices.ts`, `backend/src/push/send.ts`+- Modify: `backend/src/superTabs/activity.ts` (`writeReplyActivity` returns the rows it wrote),+ `backend/src/superTabs/mentions.ts` (`writeMentions` returns its rows), `backend/src/superTabs/store.ts` (hook+ `phoneNotices` after commit), `backend/src/routes/superTabs.ts` and `backend/src/worker.ts` (wire it),+ `backend/src/lib/metrics.ts` (`phone_pushes_total{platform,outcome}`)+- Test: `backend/src/push/notices.test.ts`, `backend/src/push/send.test.ts`, `backend/integration/superTabActivity.test.ts` (the store's hook)++**Interfaces:**+- Consumes: Tasks 1 and 3; `actorName`, `threadOf`-like rule (a thread-only message links its thread).+- Produces: `phoneNotices(tabId: string, state: SuperTabState, written: { replies: ReplyRow[]; tags: TagRow[] }, messages: MessageDraft[]): PhoneNotice[]`;+ `sendPhoneNotices(db, senders: { ios: Sender | null; android: Sender | null }, notices: PhoneNotice[]): Promise<void>`;+ `phoneSendersFromEnv(env): PhoneSenders`;+ `SuperTabStoreHooks.phoneNotices?: (notices: PhoneNotice[]) => void`.++- [ ] Step 1: tests. `phoneNotices`: a reply row → title `Mia replied in a thread`, subtitle the conversation's project+ name, body `Open Harness to read it.`, key `reply:<tab>:<row id>`, link `swarm:<tab>/<conversation>/message/<message>/thread/<root>`;+ a tag → `Mia tagged you`, key `mention:<mention id>`, link to the message (with its thread when only in the thread); a+ held tag → nothing. `sendPhoneNotices`: one devices read for all people; each device sent once; `gone` deletes the row;+ `sandbox` marks it; no sender for a platform → counted `unconfigured` and logged. Store (`superTabActivity.test.ts`): a reply+ by B in A's thread calls the hook once with A's notice after commit, keyed by A's Activity row; a muted A gets no reply+ notice but gets a tag. A write that fails calls nothing because the hook runs through `afterCommit`.+- [ ] Step 2: FAIL; commit. Step 3: implement; the hook runs `sendPhoneNotices` unawaited with its errors caught and+ logged. Step 4: PASS, plus the existing `activity`, `mentions` and `replyAudience` tests; commit.++### Task 5: The phone registers and drops its token (Dart)++**Files:**+- Create: `mobile/lib/notify/push_registration.dart`+- Modify: `mobile/lib/api/api_client.dart` (`registerPushToken`, `dropPushToken`), `mobile/lib/state/app_state.dart`+ (register when signed in, drop in `_endSession` before the session goes, as the device log leaves)+- Test: `mobile/test/notify/push_registration_test.dart`++**Interfaces:**+- Produces: `class PushRegistration { PushRegistration({MethodChannel channel, required Future<bool> Function(String platform, String token) register, required Future<bool> Function(String platform, String token) drop, required void Function(SwarmNoticeTarget) open}); Future<void> signedIn(); Future<void> signedOut(); Future<Set<String>> deliveredKeys(); }`+ over the channel `harness/push`: Dart calls `token` (→ `{platform, token}` or null) and `delivered` (→ keys); native+ calls `token` (refreshed) and `opened` (`{link}`).++- [ ] Step 1: tests: `signedIn` sends the channel's token once; a refreshed token from native is sent again while signed+ in and not after `signedOut`; `signedOut` drops the token it registered and gives up after 5 seconds; a null token sends+ nothing; `opened` with a `swarm:` link calls `open` with the decoded target; a malformed link opens nothing.+- [ ] Step 2: FAIL; commit. Step 3: implement. Step 4: `flutter test test/notify/push_registration_test.dart`: PASS; commit.++### Task 6: Native: iOS (APNs) and Android (FCM)++**Files:**+- Modify: `mobile/ios/Runner/AppDelegate.swift` (`PushChannel`), `mobile/ios/Runner/Runner.entitlements` (`aps-environment`)+- Modify: `mobile/android/app/build.gradle.kts` (firebase-messaging; `FCM_*` build values to `BuildConfig`),+ `mobile/android/app/src/main/AndroidManifest.xml` (the service), `.../MainActivity.kt` (the channel, a tapped intent's link)+- Create: `mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/PushService.kt`++- iOS: `registerForRemoteNotifications` on `token`; the token as hex; `willPresent` answers `[]` for a push carrying `link`;+ `didReceive` hands its `link` to Dart (held until Dart is listening, for a tap that launched the app); `delivered` lists+ the `key` of delivered pushes. Android: Firebase app from `BuildConfig` values (none: `token` answers null and logs why);+ `onNewToken` → Dart; a launch intent with a `link` extra → Dart; `delivered` lists active notifications' tags.+- [ ] Verify: `flutter build ios --no-codesign --debug` and `flutter build apk --debug` compile. PR CI builds neither and+ the Engineer's account has no Xcode or Android SDK, so this and the device behavior are the Tester's, on Tony's Mac+ with a Tony-approved build. Here: `swiftc -parse`, `plutil -lint` and the manifest's XML only.++### Task 7: No second notice for a push already shown++**Files:**+- Modify: `mobile/lib/swarm/swarm_notices.dart` (`SwarmTold.addAll(Iterable<String> keys)`),+ `mobile/lib/swarm/swarm_session.dart` (`SwarmHost.toldElsewhere`), `mobile/lib/phone/phone_shell.dart` (back in front:+ `pushDeliveredKeys()` first, then Swarm reads)+- Test: `mobile/test/swarm/swarm_notices_test.dart`++- [ ] Step 1: test: keys marked told elsewhere are not announced (a reply row and a tag with those keys post nothing);+ others still are. Step 2: FAIL; commit. Step 3: implement. Step 4: PASS; commit.