diff --git a/apps/link-service/chaos/run.mjs b/apps/link-service/chaos/run.mjs index 08e9a00082..b9c6e09c15 100644 --- a/apps/link-service/chaos/run.mjs +++ b/apps/link-service/chaos/run.mjs @@ -136,7 +136,7 @@ async function bringUp() { */ function createProbe(world) { const pings = [], gaps = []; - let live = null, lastEventAt = 0, stopped = false, timer = null, inFlight = 0, liveReq = null; + let live = null, lastEventAt = 0, openedAt = 0, stopped = false, timer = null, inFlight = 0, liveReq = null; const port = () => Number(new URL(world.app.origin()).port); const host = () => world.app.host(); function call(path, { method = "GET", body = null, timeoutMs = 8000, port: at = port(), host: name = host() } = {}) { @@ -180,6 +180,7 @@ function createProbe(world) { res.on("close", () => closed("closed")); }); liveReq = req; + openedAt = Date.now(); let done = false; function closed() { if (done) return; @@ -198,7 +199,10 @@ function createProbe(world) { const up = now - lastEventAt < 5000; if (!up && downSince === null) downSince = Math.max(lastEventAt, now - 5000); if (up && downSince !== null) { gaps.push({ from: downSince, to: now }); downSince = null; } - if (liveReq && now - lastEventAt > 20_000 && live) { liveReq.destroy(); } + // as the app does (src/lib/live-events.ts): a dial that sends nothing in LIVE_EVENTS_OPEN_MS (8 s) is dialled again, + // and a stream that went quiet after it sent something is dialled again after 20 s + const quietFor = now - Math.max(lastEventAt, openedAt); + if (liveReq && quietFor > (live ? 20_000 : 8_000)) { liveReq.destroy(); } }, 250); return { start() { timer = setInterval(tick, 500); openLive(); }, @@ -336,5 +340,6 @@ if (!process.env.DUSK_CHAOS_DIR) { } else { process.env.DUSK_CHAOS_PARENT = String(process.pid); for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => process.exit(130)); - main().catch((error) => { console.error(error); process.exit(2); }); + // the results are written by then; a socket or timer some scenario left open would otherwise hold the run until CI's job limit + main().then(() => process.exit(process.exitCode ?? 0), (error) => { console.error(error); process.exit(2); }); } diff --git a/apps/link-service/chaos/scenarios.mjs b/apps/link-service/chaos/scenarios.mjs index bf64921b90..4d70cf6fa9 100644 --- a/apps/link-service/chaos/scenarios.mjs +++ b/apps/link-service/chaos/scenarios.mjs @@ -2,6 +2,7 @@ // things route around it) and answers { clearedAt, pass, note, sees }. run.mjs measures the rest. import { createHash } from "node:crypto"; import { chmodSync } from "node:fs"; +import { Agent as HttpsAgent, request as httpsRequest } from "node:https"; import { join } from "node:path"; import { createTunnelAgent } from "../agent.mjs"; @@ -27,17 +28,43 @@ async function failover(world, { kill = true } = {}) { return { pass: moved !== home && moved !== null, note: `moved ${home} -> ${moved} in ${Math.round((workedAt - started) / 1000)} s`, clearedAt: started }; } -/** `count` more servers and apps on the default node, in this process: the agent's and the app's relay code each */ +/** a fetch that keeps to one connection of its own. Node's built-in fetch shares one pool for the whole process, and the + * chaos workflow runs without installing packages, so this uses node:https. `close()` ends the connection. */ +function fetchOverOwnConnection() { + const agent = new HttpsAgent({ keepAlive: true, maxSockets: 1 }); + const ownFetch = (url, { method = "GET", headers = {}, body, signal } = {}) => new Promise((resolve, reject) => { + const request = httpsRequest(url, { method, headers, agent, signal }, (answer) => { + const chunks = []; + answer.on("data", (chunk) => chunks.push(chunk)); + answer.on("error", reject); + answer.on("end", () => { + const noBody = [204, 205, 304].includes(answer.statusCode); + const answerHeaders = Object.entries(answer.headers).flatMap(([name, value]) => (Array.isArray(value) ? value.map((one) => [name, one]) : [[name, value]])); + resolve(new Response(noBody ? null : Buffer.concat(chunks), { status: answer.statusCode, headers: answerHeaders })); + }); + }); + request.on("error", reject); + request.end(body); + }); + return { fetch: ownFetch, close: () => agent.destroy() }; +} + +/** `count` more servers and apps on the default node, in this process: the agent's and the app's relay code each. Each + * sets up its link over its own connection, so the node's front gives it its own address, as `count` machines would have: + * on one connection they would be one address, over the node's limit on new links an address may make in a minute. */ async function crowd(world, count) { - const base = world.url("contabo"), relay = createRelayClient({ base }), out = []; + const base = world.url("contabo"), out = []; for (let i = 0; i < count; i += 1) { + const own = fetchOverOwnConnection(); + const ownFetch = own.fetch; const keys = newLinkKeys(); - const made = await relay.create({ verifier: keys.verifier, appPub: keys.pub }); + const made = await createRelayClient({ base, fetch: ownFetch }).create({ verifier: keys.verifier, appPub: keys.pub }); const vps = vpsTokenOf(keys.secret); - const post = (path, body) => fetch(`${base}/v1/sessions/${made.id}/${path}`, { method: "POST", headers: { authorization: `Bearer ${vps}`, "content-type": "application/json" }, body: JSON.stringify(body) }); + const post = (path, body) => ownFetch(`${base}/v1/sessions/${made.id}/${path}`, { method: "POST", headers: { authorization: `Bearer ${vps}`, "content-type": "application/json" }, body: JSON.stringify(body) }); await post("claim", {}); const tunnel = { key: randomBytes(32).toString("base64url"), vps: randomBytes(32).toString("base64url"), app: randomBytes(32).toString("base64url") }; const done = await post("result", { sealed: seal(Buffer.alloc(32), made.id, Buffer.from("{}")), vpsPub: keys.pub, tunnel: { vps: sha256hex(tunnel.vps), app: sha256hex(tunnel.app) } }); + await own.close(); if (!done.ok) throw new Error(`crowd link ${i} answered ${done.status}`); const agent = createTunnelAgent({ base, id: made.id, key: tunnel.key, token: tunnel.vps, server: { host: "127.0.0.1", port: world.bot.port }, log: () => {} }); const running = agent.run(); diff --git a/apps/link-service/src/push-relay.d.mts b/apps/link-service/src/push-relay.d.mts index a973b17b5a..26c1f31c29 100644 --- a/apps/link-service/src/push-relay.d.mts +++ b/apps/link-service/src/push-relay.d.mts @@ -17,4 +17,5 @@ export function activityBody(push: RelayActivityPush): object; export function alertBody(message: RelayPushMessage): object; export function fcmBody(token: string, message: RelayPushMessage, draws: boolean): object; export const SERVICE_TIMEOUT_MS: number; +export const BADGE_KIND: "badge"; export function createPushRelay(options?: Record): { services: string[]; route(...args: unknown[]): Promise }; diff --git a/apps/link-service/src/push-relay.mjs b/apps/link-service/src/push-relay.mjs index f026a87898..37943737e0 100644 --- a/apps/link-service/src/push-relay.mjs +++ b/apps/link-service/src/push-relay.mjs @@ -46,8 +46,12 @@ export function pushMessage(value) { const idsOf = ({ botName: _name, badge: _badge, ...ids }) => ids; +/** an iPhone's app icon count and nothing else, sent when a read elsewhere changes it; its ids are placeholders */ +export const BADGE_KIND = "badge"; + /** the APNs alert: stacked under its conversation, opened by the app's extension (mutable-content) to show the preview */ export function alertBody(message) { + if (message.kind === BADGE_KIND) return { aps: { badge: message.badge } }; const category = pushCategory(message); return { aps: { @@ -211,7 +215,7 @@ export function createPushRelay({ env = process.env, now = Date.now, fetch: fetc } function sendAlert(token, environment, message) { - return sendApns(token, environment, { "apns-topic": apns.topic, "apns-push-type": "alert", "apns-priority": "10" }, alertBody(message)); + return sendApns(token, environment, { "apns-topic": apns.topic, "apns-push-type": "alert", "apns-priority": message.kind === BADGE_KIND ? "5" : "10" }, alertBody(message)); } function sendActivity(token, environment, activity) { @@ -264,10 +268,11 @@ export function createPushRelay({ env = process.env, now = Date.now, fetch: fetc return { services, - /** GET /v1/push says which services it delivers; POST /v1/push {service, token, environment?, draws?, message | activity} - * sends one (an activity is APNs only; `draws`: FCM to an app that draws its own notification) */ + /** GET /v1/push says which services it delivers, and `badges`: it sends a badge-only push; POST /v1/push {service, + * token, environment?, draws?, message | activity} sends one (an activity and a badge are APNs only; `draws`: FCM to + * an app that draws its own notification) */ async route(req, res, { method, readJson, send, fail, ip }) { - if (method === "GET") return send(res, 200, { services }); + if (method === "GET") return send(res, 200, { services, badges: true }); if (method !== "POST") return fail(res, 405, "method not allowed"); const body = await readJson(req, 16_384); const service = SERVICES.has(body?.service) ? body.service : null; @@ -277,6 +282,7 @@ export function createPushRelay({ env = process.env, now = Date.now, fetch: fetc const activity = body?.activity !== undefined && service === "apns" ? activityMessage(body.activity) : null; const message = activity ? null : pushMessage(body?.message); if (!service || !token || (!message && !activity)) return fail(res, 400, "service, token and message are required", "invalid"); + if (message?.kind === BADGE_KIND && (service !== "apns" || message.badge === undefined)) return fail(res, 400, "a badge push is APNs only and carries its count", "invalid"); if (!services.includes(service)) return fail(res, 503, `this relay has no ${service === "apns" ? "APNs" : "FCM"} keys`, "not_configured"); if (!allowed(`ip:${ip}`, PER_IP_PER_MINUTE) || !allowed(`token:${token}`, PER_TOKEN_PER_MINUTE)) return fail(res, 429, "too many pushes", "rate_limited"); let outcome; diff --git a/apps/link-service/test/push-relay.test.mjs b/apps/link-service/test/push-relay.test.mjs index f71f0a69e3..3b47e379d8 100644 --- a/apps/link-service/test/push-relay.test.mjs +++ b/apps/link-service/test/push-relay.test.mjs @@ -43,7 +43,7 @@ afterEach(async () => { if (server) await new Promise((resolve) => server.close( describe("push relay", () => { it("says which services it delivers and refuses one it has no keys for", async () => { await start(createPushRelay({ env: {}, fetch: fakeFetch(), readFile })); - expect(await (await fetch(`${base}/v1/push`)).json()).toEqual({ services: [] }); + expect(await (await fetch(`${base}/v1/push`)).json()).toEqual({ services: [], badges: true }); const answer = await post({ service: "fcm", token: "fixture-token", message }); expect(answer.status).toBe(503); expect((await answer.json()).code).toBe("not_configured"); @@ -102,6 +102,29 @@ describe("push relay", () => { }); }); + it("sends an iPhone its icon's count alone, with no alert, at the low priority, and refuses one for FCM or with no count", async () => { + const requests = []; + const http2Connect = (origin) => { + const session = Object.assign(new EventEmitter(), { closed: false, destroyed: false, unref() {}, close() {}, destroy() {} }); + session.request = (headers) => { + const stream = Object.assign(new EventEmitter(), { setEncoding() {}, close() {} }); + stream.end = (body) => { requests.push({ origin, headers, body: JSON.parse(body) }); queueMicrotask(() => { stream.emit("response", { ":status": 200 }); stream.emit("end"); }); }; + return stream; + }; + return session; + }; + await start(createPushRelay({ env: { DUSK_APNS_KEY_FILE: "/keys/apns.p8", DUSK_APNS_KEY_ID: "key", DUSK_APNS_TEAM_ID: "team", DUSK_APNS_TOPIC: "com.example.omb" }, http2Connect, readFile })); + const badge = { id: "badge", kind: "badge", botId: "badge", botName: "dusk bot", threadId: "badge", badge: 0 }; + expect(await (await post({ service: "apns", token: "abcdef0123456789", message: badge })).json()).toEqual({ outcome: "sent" }); + expect(requests[0].headers["apns-push-type"]).toBe("alert"); + expect(requests[0].headers["apns-priority"]).toBe("5"); + expect(requests[0].body).toEqual({ aps: { badge: 0 } }); + expect((await post({ service: "fcm", token: "fixture-token", message: badge })).status).toBe(400); + const { badge: _count, ...noCount } = badge; + expect((await post({ service: "apns", token: "abcdef0123456789", message: noCount })).status).toBe(400); + expect(requests).toHaveLength(1); + }); + it("drops an APNs connection that stopped answering and sends on a new one, so later pushes do not wait on it", async () => { const sessions = []; const http2Connect = () => { diff --git a/docs/phone-push.md b/docs/phone-push.md index 56b4780cf2..cd4169d32e 100644 --- a/docs/phone-push.md +++ b/docs/phone-push.md @@ -30,7 +30,10 @@ stack together, one notification per conversation on Android with its lines in i Activity line's seal with the salt in `PUSH_PREVIEW_SEAL`), so only that phone can read it. Without a key (Android before 12, an older app) the line is "New message". - iPhone: an APNs alert with `mutable-content`, `thread-id` the conversation, `badge` the unread count and no collapse - id; the app's Notification Service Extension opens the preview and attaches the bot's picture. + id; the app's Notification Service Extension opens the preview and attaches the bot's picture. When notifications + are read on any device and the count changes, each iPhone gets a push with only its new count (no alert, no sound, + priority 5), within a second of the read. Through the push relay this goes only when the relay's `GET /v1/push` + answers `badges: true`, since an older relay would show it as a "New message" alert. - Android: a phone that registered with `draws: true` gets data-only high priority FCM messages, which Android hands to the app even when it is closed; the app draws the notification itself (MessagingStyle, the bot as the person). An older app gets the system-drawn notification on the `messages` channel. @@ -41,7 +44,7 @@ stack together, one notification per conversation on Android with its lines in i On the iPhone, a push that lands while the app is open shows as the system's own banner, unless it is about the conversation on screen, which shows nothing. Pushes already in Notification Center are removed once read: when that conversation opens, when a read arrives from another device while the app is open, and each time the app comes back. -An iPhone that stays locked keeps a push read elsewhere until the app next opens. +An iPhone that stays locked keeps a push read elsewhere until the app next opens; its icon's count follows the read. On Android, a conversation read anywhere (the desktop, another phone, "mark all read") also clears its notification on every other Android phone that was shown it, with the app closed too: once every line a phone got there is read, the diff --git a/scripts/testing/ci-retry-list.json b/scripts/testing/ci-retry-list.json index 070a6c47a0..90b819f616 100644 --- a/scripts/testing/ci-retry-list.json +++ b/scripts/testing/ci-retry-list.json @@ -70,6 +70,132 @@ "owner": "siddharth", "reason": "Failed once in the 0.2.33 release CI (run 45993068105, ubuntu shard 5 or parallel-threads, a different test each attempt); passes locally on a quiet machine.", "since": "2026-11-27" + }, + { + "file": "server/settings-sync.e2e.test.ts", + "test": "a setting changed in any one place reaches the others, and the last change wins", + "owner": "Yabuku-xD", + "reason": "Failed on Dec 1 in CI of PRs #479 (run 46726301408, all five), #481 (run 46636209589) and #483 (run 46637592516): a loopback request with no forwarding header was answered 403 'this request came through a proxy'. Passed in the other PR runs that day; passes locally (macOS, Node 26) alone, as four copies at once and in its full ubuntu shard 7/8 with 4 workers.", + "since": "2026-12-01" + }, + { + "file": "server/settings-sync.e2e.test.ts", + "test": "what belongs to one computer stays there", + "owner": "Yabuku-xD", + "reason": "Failed on Dec 1 in CI of PRs #479 (run 46726301408, all five), #481 (run 46636209589) and #483 (run 46637592516): a loopback request with no forwarding header was answered 403 'this request came through a proxy'. Passed in the other PR runs that day; passes locally (macOS, Node 26) alone, as four copies at once and in its full ubuntu shard 7/8 with 4 workers.", + "since": "2026-12-01" + }, + { + "file": "server/settings-sync.e2e.test.ts", + "test": "keys travel only over the person's own links, and a Team Cloud keeps no person's settings", + "owner": "Yabuku-xD", + "reason": "Failed on Dec 1 in CI of PRs #479 (run 46726301408, all five), #481 (run 46636209589) and #483 (run 46637592516): a loopback request with no forwarding header was answered 403 'this request came through a proxy'. Passed in the other PR runs that day; passes locally (macOS, Node 26) alone, as four copies at once and in its full ubuntu shard 7/8 with 4 workers.", + "since": "2026-12-01" + }, + { + "file": "server/settings-sync.e2e.test.ts", + "test": "the move to My Cloud and the way home keep settings level", + "owner": "Yabuku-xD", + "reason": "Failed on Dec 1 in CI of PRs #479 (run 46726301408, all five), #481 (run 46636209589) and #483 (run 46637592516): a loopback request with no forwarding header was answered 403 'this request came through a proxy'. Passed in the other PR runs that day; passes locally (macOS, Node 26) alone, as four copies at once and in its full ubuntu shard 7/8 with 4 workers.", + "since": "2026-12-01" + }, + { + "file": "server/settings-sync.e2e.test.ts", + "test": "a computer whose bots moved to My Cloud is left as it was, with nothing failing, until they come back", + "owner": "Yabuku-xD", + "reason": "Failed on Dec 1 in CI of PRs #479 (run 46726301408, all five), #481 (run 46636209589) and #483 (run 46637592516): a loopback request with no forwarding header was answered 403 'this request came through a proxy'. Passed in the other PR runs that day; passes locally (macOS, Node 26) alone, as four copies at once and in its full ubuntu shard 7/8 with 4 workers.", + "since": "2026-12-01" + }, + { + "file": "server/steer-e2e.test.ts", + "test": "mid-turn steering e2e > a steer the CLI runs as its next native turn keeps the turn, its busy state and its internal tool pass until that reply lands", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #477 (run 46623618361, ubuntu shard 8/8) and of the diag/connector-issues branch on Dec 1; passes locally on dev and on #477.", + "since": "2026-12-01" + }, + { + "file": "server/drivers/antigravity.test.ts", + "test": "starting Google sign-in again > hands back the same link while it is live, so a code from the first page still completes", + "owner": "Yabuku-xD", + "reason": "Failed in CI of main (run 46580994542), a release (run 46616055192) and PR #478 (run 46623629685) on Dec 1; failed 1 of 3 local runs on one commit.", + "since": "2026-12-01" + }, + { + "file": "server/connected-app-tools.e2e.test.ts", + "test": "a bot given Gmail by its app switch reaches gmail.search_emails by name on Claude and on an ACP engine alike", + "owner": "Yabuku-xD", + "reason": "Failed in CI of main (run 46615872847) and PR #478 (run 46623629685) on Dec 1; passes locally on dev.", + "since": "2026-12-01" + }, + { + "file": "server/direct-coordination.e2e.test.ts", + "test": "runs the owed direct follow-up while the same bot works in another thread", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #478 (run 46623629685) and of fix-app-trigger-restore-enabled (run 46370208019); passed 3 of 3 local runs.", + "since": "2026-12-01" + }, + { + "file": "server/index.test.ts", + "test": "harness HTTP API > reports a failed routine once, not twice", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PRs #480 (run 46636190164) and #481 (run 46636209589) on Dec 1, at about 10.7 s; passes locally on dev.", + "since": "2026-12-01" + }, + { + "file": "server/setup-connect-card.e2e.test.ts", + "test": "/setup connects an app through a Connect card, against the real server > names the switch, and mounts nothing to call, when the bot's connected apps are off", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #479 (run 46636167463) on Dec 1; passes locally on dev, twice.", + "since": "2026-12-01" + }, + { + "file": "server/host-lazy-claim.e2e.test.ts", + "test": "lazy host claim and pin on use (issue #1650) > a No is an answer, not a failure: the screen stays untouched and the bot is told to finish another way", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #482 (run 46636235332, windows shard 5/8, 'Fixture wait expired') on Dec 1; that PR changes only electron/main.mjs.", + "since": "2026-12-01" + }, + { + "file": "server/copilot-engine.e2e.test.ts", + "test": "creates and updates a routine through Copilot's launcher-owned tools", + "owner": "Yabuku-xD", + "reason": "Failed in CI of main (run 46615872847) on Dec 1.", + "since": "2026-12-01" + }, + { + "file": "server/usage-trace/recorder.test.ts", + "test": "trace recorder > records 2,000 tool calls in one turn without holding up the event loop", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #479 (run 46726301408, ubuntu shard 7/8) on Dec 1 at 53 ms against its 50 ms bound; that PR changes only src/lib/live-events.ts.", + "since": "2026-12-01" + }, + { + "file": "server/teammate-follow-ups.e2e.test.ts", + "test": "F4 keeps a second assignment Clive hands Mira in the same turn its own job, though the first is already running", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #479 (run 46726301408, ubuntu shard 7/8) on Dec 1 ('the first was running when the second was sent'); that PR changes only src/lib/live-events.ts.", + "since": "2026-12-01" + }, + { + "file": "server/drivers/chat-mcp-tools.test.ts", + "test": "Chat MCP shutdown verdict > an unconfirmed shutdown still fails close when a call was in flight", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #479 (run 46740020170, ubuntu shard 3/8) on Dec 1 ('Unexpected end of JSON input'); that PR changes only src/lib/live-events.ts. Passes locally.", + "since": "2026-12-01" + }, + { + "file": "server/memory-order.e2e.test.ts", + "test": "starts the person's own line ahead of a hand-off that was already waiting for memory, and the hand-off right after", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #479 (run 46740020170, ubuntu shard 5/8) on Dec 1; that PR changes only src/lib/live-events.ts. Passes locally.", + "since": "2026-12-01" + }, + { + "file": "server/workspace-backup-workflow.test.ts", + "test": "restores an encrypted workspace through the real server and continues its original chat", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #479 (run 46740020170, windows shard 5/8) on Dec 1; that PR changes only src/lib/live-events.ts. Passes locally.", + "since": "2026-12-01" } ] } diff --git a/server/cloud-personal.e2e.test.ts b/server/cloud-personal.e2e.test.ts index 73081ca1f2..781e7d3415 100644 --- a/server/cloud-personal.e2e.test.ts +++ b/server/cloud-personal.e2e.test.ts @@ -678,7 +678,14 @@ it("a guest's skill card enables only the exact text the owner reviewed, holds a const owner = await adminPairing(); await settleAll(owner); const botId = before.roomBot.id; - const skillMd = (name: string, body: string) => `---\nname: ${name}\ndescription: Checks the site for broken links.\n---\n\n# ${name}\n\n${body}\n`; + // kinds of work none of this file's other skills covers: a create that covers a skill already there is turned away + const work: Record = { + "reviewed-links": "Reviews pull requests for missing tests.", + "denied-links": "Drafts the weekly status email for the team.", + "lost-links": "Files expense receipts in the company portal.", + "deleted-links": "Renames vacation photos by the date taken.", + }; + const skillMd = (name: string, body: string) => `---\nname: ${name}\ndescription: ${work[name]}\n---\n\n# ${name}\n\n${body}\n`; const cards = async () => ((await api("GET", `/api/threads/${before.theirs}/messages`, { token: owner })).body.messages as any[]) .map((message) => message.card).filter((card) => card?.skillRequest); const respond = (route: "bot" | "thread", body: Record) => route === "bot" diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.json index 338d8ca056..6ebfb58711 100644 --- a/server/drivers/agents-catalog-goldens/full.tools-list.json +++ b/server/drivers/agents-catalog-goldens/full.tools-list.json @@ -2611,7 +2611,7 @@ }, { "name": "skill_manage", - "description": "Submit a new or updated SKILL.md for one kind of work. Update a learned skill when the person corrected how that work is done, asked you to revise it, or it misled you; never one the person wrote or imported unless they asked for that named skill. Create one only for recurring work with rules you'd get wrong without it, never for an automation, a one-off or a preference; omit what any model knows. If the result is pending, a create stays inactive and an update leaves the current version unchanged. Read the result: it applies immediately at every access level, and the person sees it with an Undo where possible. If applied, continue the work without another confirmation. Only a pending result (a Cloud conversation its owner did not drive) means ending the turn to wait for the owner. Never claim success without an applied result; report failures honestly. This does not elevate another bot's execution permissions.", + "description": "Submit a new or updated reusable SKILL.md for one kind of work. Update a learned skill when the person corrected how that work is done, asked you to revise it, or it misled you; never one the person wrote or imported unless they asked for that named skill. Create one only for recurring work with rules you'd get wrong without it, never for an automation, a one-off or a preference; omit what any model knows. If the result is pending, a create stays inactive and an update leaves the current version unchanged. Read the result: it applies immediately at every access level, and the person sees it with an Undo where possible. If applied, continue the work without another confirmation. Only a pending result (a Cloud conversation its owner did not drive) means ending the turn to wait for the owner. Never claim success without an applied result; report failures honestly. This does not elevate another bot's execution permissions.", "inputSchema": { "type": "object", "additionalProperties": false, diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.json index 232389816e..8da9b6b072 100644 --- a/server/drivers/agents-catalog-goldens/profiles.json +++ b/server/drivers/agents-catalog-goldens/profiles.json @@ -125,8 +125,8 @@ ] }, "skills": { - "bytes": 79704, - "sha256": "ab31ffbd342b3eff3b99849f6722cdc5002514b372e398e499d8bffcd9d5e3da", + "bytes": 79713, + "sha256": "a3ea87f686b9fc624c9aa68eaca93d2fa3d239d377854a7e788870336e8e944a", "tools": [ "set_status", "send_message", @@ -189,8 +189,8 @@ ] }, "skills+voice": { - "bytes": 80482, - "sha256": "72656e98d9324abd4a0a6fe99a0b5fd2d1cb6648b8a8789e50e7ee175bcff5c5", + "bytes": 80491, + "sha256": "5845b1830e6d0546c3f2c9ecbf0329faadd9e82c36769afad6148aa61b374b9a", "tools": [ "set_status", "send_message", @@ -369,8 +369,8 @@ ] }, "skills+non-chief": { - "bytes": 71686, - "sha256": "e033162122142bb14c5991c22b21fb182a049e75efe36f4452890496631c3e55", + "bytes": 71695, + "sha256": "0a31ffd3ed3a5803db43c317b810595a014d9f4d993e119a8b168ac620b6cceb", "tools": [ "set_status", "send_message", @@ -428,8 +428,8 @@ ] }, "skills+voice+non-chief": { - "bytes": 72464, - "sha256": "630045d61d6bdc00fd94bec0327599b38772069a9c2d6b7f982ce176d4bdbaba", + "bytes": 72473, + "sha256": "feacf12ae6edd3eb48ca5b9bc74241682851c3708e8f9a42954575c99523ed4f", "tools": [ "set_status", "send_message", @@ -488,8 +488,8 @@ ] }, "skills+voice+cloud-home": { - "bytes": 79458, - "sha256": "87046e3f1680cb3688a81e68c736e25fe4cc822a7c5c43848d57f732613d509f", + "bytes": 79467, + "sha256": "f19672a959c94ce7073ae118ce9d62172c4af6b88593191de7996a4fccb83165", "tools": [ "set_status", "send_message", @@ -552,8 +552,8 @@ ] }, "skills+voice+non-chief+cloud-home": { - "bytes": 71440, - "sha256": "158fe4d01fbb73b6f4c4a468868e7fe7dd4cd30bb92c6500fe448b0c8a8b542f", + "bytes": 71449, + "sha256": "c3be064722efa48c326150acf7529cf16993760a56bc6c3726915758b63b2e3e", "tools": [ "set_status", "send_message", @@ -611,8 +611,8 @@ ] }, "skills+voice+x": { - "bytes": 87140, - "sha256": "a57e0b4afbfa031a592ced1ab097100ec2a12f6c59535a7b2f2127e0fd3e3303", + "bytes": 87149, + "sha256": "62498a24d47f510cca1314d99605d4be581dab3c2763825ef2ecd5d0d09d79fa", "tools": [ "set_status", "send_message", @@ -684,8 +684,8 @@ ] }, "skills+voice+x+team": { - "bytes": 87556, - "sha256": "efd173cb43a931be63700ee55cf3798c55578d6603495d5353fa0391140ddf21", + "bytes": 87565, + "sha256": "e253321813dbe8fa0ea457f40401f68e92853fa5dacc5fd3f90f3323d2542563", "tools": [ "set_status", "send_message", @@ -758,8 +758,8 @@ ] }, "skills+skill-reader": { - "bytes": 80120, - "sha256": "e562baae663c0b9d238fc65d9a557019eae0e3a10c7cd986d42bec9227b9fcc9", + "bytes": 80129, + "sha256": "db617a90d6dec8a458a5678034198026d7bf2e69afd665d3bf122b4d4322cf99", "tools": [ "set_status", "send_message", @@ -949,8 +949,8 @@ ] }, "skills+voice+dusk": { - "bytes": 81133, - "sha256": "aecee531cd5dd67546525416ac925ec36db52b978777bbbb997718b51da4af69", + "bytes": 81142, + "sha256": "e48dad639cff9c24f7b605f54f443aa54c09d1081519d403df93be26de903f87", "tools": [ "set_status", "send_message", diff --git a/server/drivers/agents-catalog.ts b/server/drivers/agents-catalog.ts index 324a261bec..4f0077619e 100644 --- a/server/drivers/agents-catalog.ts +++ b/server/drivers/agents-catalog.ts @@ -808,7 +808,7 @@ const TOOL_DEFINITIONS = [ { name: "skill_manage", description: - "Submit a new or updated SKILL.md for one kind of work. Update a learned skill when the person corrected how that work is done, asked you to revise it, or it misled you; never one the person wrote or imported unless they asked for that named skill. Create one only for recurring work with rules you'd get wrong without it, never for an automation, a one-off or a preference; omit what any model knows. If the result is pending, a create stays inactive and an update leaves the current version unchanged." + APPLIES_OUTCOME, + "Submit a new or updated reusable SKILL.md for one kind of work. Update a learned skill when the person corrected how that work is done, asked you to revise it, or it misled you; never one the person wrote or imported unless they asked for that named skill. Create one only for recurring work with rules you'd get wrong without it, never for an automation, a one-off or a preference; omit what any model knows. If the result is pending, a create stays inactive and an update leaves the current version unchanged." + APPLIES_OUTCOME, inputSchema: { type: "object", additionalProperties: false, diff --git a/server/mobile/link.test.ts b/server/mobile/link.test.ts index 13cfff3e8a..6194d6abf0 100644 --- a/server/mobile/link.test.ts +++ b/server/mobile/link.test.ts @@ -10,7 +10,7 @@ import { SessionRegistry } from "../sessions.ts"; import { createDecipheriv, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, type KeyObject } from "node:crypto"; import { PUSH_PREVIEW_SEAL } from "../../shared/phone-activity.ts"; -import { createMobileLink, mobileLookupRelay, PUSH_GRACE_MS, pushPreview, typedCodeRelay } from "./link.ts"; +import { BADGE_SYNC_MS, createMobileLink, mobileLookupRelay, PUSH_GRACE_MS, pushPreview, typedCodeRelay } from "./link.ts"; import { PRESENCE_OVERDUE_MS } from "./presence.ts"; import { lookupKeys, openLookup } from "./lookup.ts"; import type { PushMessage, PushTarget } from "./push.ts"; @@ -462,6 +462,33 @@ describe("mobile link", () => { expect(sent).toHaveLength(2); }); + it("tells each iPhone its new count once a read anywhere changes it, so its icon never keeps a number nothing is behind", async () => { + vi.useFakeTimers(); + let unread = 2; + const badges: Array<{ token: string; badge: number }> = []; + const mobile = link({ + unreadCount: () => unread, + push: { + configured: ["apns"], + send: async (target, message) => { sent.push({ target, message }); return "sent"; }, + sendBadge: async (target, badge) => { badges.push({ token: target.token, badge }); return "sent"; }, + }, + }); + await pushPhone(mobile, "attempt-0114"); + await mobile.notify(note("n1")); + await vi.advanceTimersByTimeAsync(PUSH_GRACE_MS); + expect(sent.map((one) => one.message.badge)).toEqual([2]); + unread = 1; + mobile.read(["n1"]); + unread = 0; + mobile.read(["n2"]); + await vi.advanceTimersByTimeAsync(BADGE_SYNC_MS); + expect(badges).toEqual([{ token: "abcdef0123456789", badge: 0 }]); + mobile.read(["n3"]); + await vi.advanceTimersByTimeAsync(BADGE_SYNC_MS); + expect(badges).toHaveLength(1); + }); + it("never sends a read to a phone whose app does not draw its own notifications", async () => { vi.useFakeTimers(); const mobile = link(); diff --git a/server/mobile/link.ts b/server/mobile/link.ts index a34c1514c9..a9ed27c6fb 100644 --- a/server/mobile/link.ts +++ b/server/mobile/link.ts @@ -55,6 +55,8 @@ const MAX_DEVICES = 24; const PUSH_RETRY_MS = [10_000, 60_000, 300_000]; /** a notification waits this long before it pushes, so one read right away (on any device) never buzzes */ export const PUSH_GRACE_MS = 4_000; +/** the reads of one moment ("mark all read", a chat with several notifications) give each iPhone one new count */ +export const BADGE_SYNC_MS = 1_000; const relayId = () => Array.from(randomBytes(10), (byte) => B32[byte & 31]).join(""); @@ -223,10 +225,33 @@ export function createMobileLink(deps: MobileLinkDeps) { } } } + /** the count each iPhone's icon shows, as last sent to it; an iPhone changes its icon only when a push says so */ + const iconShows = new Map(); + let badgeSync: ReturnType | null = null; + function syncBadges() { + if (badgeSync || !push.sendBadge) return; + badgeSync = setTimeout(() => { + badgeSync = null; + const count = deps.unreadCount?.(); + if (count === undefined) return; + for (const device of devices) { + const registration = device.push; + if (registration?.service !== "apns" || iconShows.get(device.id) === count) continue; + void push.sendBadge!({ service: "apns", token: registration.token, ...(registration.environment ? { environment: registration.environment } : {}) }, count) + .catch(() => "failed" as const) + .then((outcome) => { + if (outcome === "sent") iconShows.set(device.id, count); + if (outcome === "gone" && device.push === registration) { device.push = null; persist(); } + }); + } + }, BADGE_SYNC_MS); + badgeSync.unref?.(); + } function read(ids: readonly string[]) { const done = new Set(ids); for (const [key, one] of waiting) if (done.has(one.id)) { clearTimeout(one.timer); waiting.delete(key); } clearElsewhere(done); + syncBadges(); } const activities = createTurnActivities({ now, @@ -254,12 +279,14 @@ export function createMobileLink(deps: MobileLinkDeps) { function deliver(device: DeviceRecord, message: PushMessage, preview: string, attempt = 0): Promise { const registration = device.push; if (!registration) return Promise.resolve(); + const shown = forPhone(registration, message, preview); return push.send({ service: registration.service, token: registration.token, ...(registration.environment ? { environment: registration.environment } : {}), ...(registration.draws ? { draws: true } : {}), - }, forPhone(registration, message, preview)) + }, shown) .catch(() => "failed" as const) .then((outcome) => { + if (outcome === "sent" && registration.service === "apns" && shown.badge !== undefined) iconShows.set(device.id, shown.badge); if (outcome === "gone" && device.push === registration) { device.push = null; persist(); } if (outcome === "sent" && registration.draws) remember(device, message); const wait = PUSH_RETRY_MS[attempt]; @@ -708,6 +735,7 @@ export function createMobileLink(deps: MobileLinkDeps) { const previewKey = typeof value.previewKey === "string" ? value.previewKey : undefined; const draws = service === "fcm" && value.draws === true; device.push = { service, token, ...(environment ? { environment } : {}), ...(previewKey ? { previewKey } : {}), ...(draws ? { draws } : {}), updatedAt: now() }; + iconShows.delete(device.id); for (const replaced of devices.filter((one) => one !== device && one.push?.service === service && one.push.token === token)) revoke(replaced.id); persist(); const delivering = push.delivers?.(service) ?? push.configured.includes(service); diff --git a/server/mobile/push.test.ts b/server/mobile/push.test.ts index 2eb35c4dd0..3b44da7502 100644 --- a/server/mobile/push.test.ts +++ b/server/mobile/push.test.ts @@ -130,6 +130,12 @@ describe("APNs push", () => { }); }); + it("sends an iPhone's count alone with its own keys: no alert, no sound, the low priority", async () => { + expect(await sender().sendBadge!(target, 0)).toBe("sent"); + expect(received[0].headers).toMatchObject({ "apns-push-type": "alert", "apns-priority": "5", "apns-topic": "com.example.dusk" }); + expect(JSON.parse(received[0].body)).toEqual({ aps: { badge: 0 } }); + }); + it("carries the sealed preview for the app's extension and the app icon's count", async () => { expect(await sender().send(target, { ...message, sealed: "s".repeat(90), badge: 3 })).toBe("sent"); const body = JSON.parse(received[0].body); @@ -451,6 +457,21 @@ describe("push relay", () => { expect(await push.sendActivity!({ service: "fcm", token: "abcdef0123456789" }, activity)).toBe("skipped"); }); + it("sends an iPhone's count alone through a relay that says it draws one, and never through one that does not", async () => { + const answers = (badges: boolean) => vi.fn(async (_url, init) => new Response(JSON.stringify(init?.method === "POST" ? { outcome: "sent" } : { services: ["apns"], ...(badges ? { badges: true } : {}) }), { status: 200 })); + const older = answers(false); + expect(await createPushSender({}, { fetch: older, relay: () => "https://relay.example" }).sendBadge!({ service: "apns", token: "abcdef0123456789" }, 0)).toBe("skipped"); + expect(older.mock.calls.filter(([, init]) => init?.method === "POST")).toHaveLength(0); + const current = answers(true); + const push = createPushSender({}, { fetch: current, relay: () => "https://relay.example" }); + expect(await push.sendBadge!({ service: "apns", token: "abcdef0123456789", environment: "sandbox" }, 3)).toBe("sent"); + expect(await push.sendBadge!({ service: "apns", token: "abcdef0123456789" }, 0)).toBe("sent"); + const posts = current.mock.calls.filter(([, init]) => init?.method === "POST").map(([, init]) => JSON.parse(String(init?.body))); + expect(posts[0]).toEqual({ service: "apns", token: "abcdef0123456789", environment: "sandbox", message: { id: "badge", kind: "badge", botId: "badge", botName: "dusk bot", threadId: "badge", badge: 3 } }); + expect(current.mock.calls.filter(([, init]) => init?.method !== "POST")).toHaveLength(1); + expect(await push.sendBadge!({ service: "fcm", token: "abcdef0123456789" }, 1)).toBe("skipped"); + }); + it("keeps its own keys ahead of the relay", async () => { const fetch = relayFetch(200, { outcome: "sent" }); const push = createPushSender(apnsEnv, { fetch, relay: () => "https://relay.example", http2Connect: (() => { throw new Error("no network"); }) as never }); diff --git a/server/mobile/push.ts b/server/mobile/push.ts index 7a965022fd..f87698997c 100644 --- a/server/mobile/push.ts +++ b/server/mobile/push.ts @@ -53,6 +53,8 @@ export interface PushSender { /** whether a push for this service leaves this server at all: its own keys, or a push relay */ delivers?(service: PushService): boolean; send(target: PushTarget, message: PushMessage): Promise; + /** APNs only: the app icon's count and nothing else, no alert and no sound */ + sendBadge?(target: PushTarget, badge: number): Promise; /** APNs only; `target.token` is the activity's own token, or the push-to-start one */ sendActivity?(target: PushTarget, push: ActivityPush): Promise; /** where pushes leave from now: this server's own keys, and the relay with the services it says it has (null when it @@ -108,7 +110,8 @@ function messageData(message: PushMessage): Record { }; } -const badgeOf = (message: PushMessage) => message.badge !== undefined && Number.isSafeInteger(message.badge) && message.badge >= 0 ? Math.min(message.badge, 9999) : undefined; +const iconCount = (badge: number | undefined) => badge !== undefined && Number.isSafeInteger(badge) && badge >= 0 ? Math.min(badge, 9999) : undefined; +const badgeOf = (message: PushMessage) => iconCount(message.badge); /** Each push stacks under its conversation (`thread-id`); the app's extension opens the sealed preview (`mutable-content`). */ export function apnsAlertBody(message: PushMessage): object { @@ -126,6 +129,11 @@ export function apnsAlertBody(message: PushMessage): object { /** A data-only push to an Android app that draws its own notifications: this conversation was read, up to `id`. */ export const READ_KIND = "read"; +/** An iPhone's count only. The relay is sent it as a message of this kind, with placeholder ids, only when it says it + * draws one (`badges` in GET /v1/push): an older relay would show it as a "New message" alert. */ +export const BADGE_KIND = "badge"; +export const badgeApnsBody = (badge: number): object => ({ aps: { badge } }); + /** The FCM message. An app that draws its own gets data only, which Android hands it even while it is closed; an older * app gets the system-drawn notification. */ export function fcmMessage(target: PushTarget, message: PushMessage): object { @@ -207,7 +215,7 @@ export function createPushSender(env: NodeJS.ProcessEnv = process.env, deps: { return current; } - async function sendApns(target: PushTarget, kind: { type: "alert" } | { type: "liveactivity"; priority: 5 | 10 }, payload: object, again = true): Promise { + async function sendApns(target: PushTarget, kind: { type: "alert"; priority?: 5 } | { type: "liveactivity"; priority: 5 | 10 }, payload: object, again = true): Promise { const credentials = apns!; const timestamp = now(); if (!providerToken || timestamp - providerToken.createdAt >= 50 * 60_000) { @@ -223,7 +231,7 @@ export function createPushSender(env: NodeJS.ProcessEnv = process.env, deps: { ":method": "POST", ":path": `/3/device/${target.token}`, authorization: `bearer ${providerToken!.value}`, ...(kind.type === "alert" - ? { "apns-topic": credentials.topic, "apns-push-type": "alert", "apns-priority": "10" } + ? { "apns-topic": credentials.topic, "apns-push-type": "alert", "apns-priority": String(kind.priority ?? 10) } : { "apns-topic": `${credentials.topic}.push-type.liveactivity`, "apns-push-type": "liveactivity", "apns-priority": String(kind.priority) }), }); let status = 0; @@ -331,10 +339,32 @@ export function createPushSender(env: NodeJS.ProcessEnv = process.env, deps: { const base = deps.relay?.() ?? null; return base && !relayLacks(base, service) ? base : null; }; + /** whether each relay draws a badge-only push, and when it was asked: asked again after RELAY_RECHECK_MS */ + const badgeRelays = new Map; at: number }>(); + const relayDrawsBadges = (base: string): Promise => { + const known = badgeRelays.get(base); + if (known && now() - known.at < RELAY_RECHECK_MS) return known.draws; + const draws = fetch(`${base}/v1/push`, { signal: AbortSignal.timeout(5_000) }) + .then(async (response) => response.ok && (await response.json().catch(() => null) as { badges?: unknown } | null)?.badges === true, () => false); + badgeRelays.set(base, { draws, at: now() }); + return draws; + }; let warned = false; return { configured, delivers: (service) => configured.includes(service) || relayFor(service) !== null, + async sendBadge(target, badge) { + const count = iconCount(badge); + if (target.service !== "apns" || count === undefined) return "skipped"; + const relay = relayFor("apns"); + try { + if (configured.includes("apns")) return await sendApns(target, { type: "alert", priority: 5 }, badgeApnsBody(count)); + if (!relay || !await relayDrawsBadges(relay)) return "skipped"; + return await sendRelay(relay, target, { message: { id: BADGE_KIND, kind: BADGE_KIND, botId: BADGE_KIND, botName: "dusk bot", threadId: BADGE_KIND, badge: count } }); + } catch { + return "failed"; + } + }, async send(target, message) { const base = configured.includes(target.service) ? null : deps.relay?.() ?? null; if (base && relayLacks(base, target.service)) return "skipped";