Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Server: Live Activities and Android ongoing notification by push while the app is closed (#5989)
Milind Soni67ad9ff503df
diff --git a/companion/src/routes.ts b/companion/src/routes.tsindex c0f7c926bc..bdba698a78 100644--- a/companion/src/routes.ts+++ b/companion/src/routes.ts@@ -221,6 +221,9 @@ const ALLOWED: ReadonlyArray<{ method: string; path: RegExp }> = [{ method: "PUT", path: /^\/api\/push\/device$/ },{ method: "GET", path: /^\/api\/push\/device$/ },{ method: "DELETE", path: /^\/api\/push\/device$/ },+ { method: "PUT", path: /^\/api\/push\/activity$/ },+ { method: "GET", path: /^\/api\/push\/activity$/ },+ { method: "DELETE", path: /^\/api\/push\/activity$/ },// The harness records only the owner's activation; a guest's is answered and// dropped.diff --git a/companion/test/routes.test.ts b/companion/test/routes.test.tsindex 1d37c5666a..c494d11ae4 100644--- a/companion/test/routes.test.ts+++ b/companion/test/routes.test.ts@@ -34,6 +34,9 @@ describe("what the app may do", () => {["PUT", "/api/push/device"],["GET", "/api/push/device"],["DELETE", "/api/push/device"],+ ["PUT", "/api/push/activity"],+ ["GET", "/api/push/activity"],+ ["DELETE", "/api/push/activity"],["GET", "/api/config"],["GET", "/api/events"],["GET", "/api/instances"],diff --git a/packages/phone-protocol/src/phone-push.ts b/packages/phone-protocol/src/phone-push.tsindex bafc6f6bfb..5cb364c380 100644--- a/packages/phone-protocol/src/phone-push.ts+++ b/packages/phone-protocol/src/phone-push.ts@@ -122,3 +122,54 @@ export function isPushKind(kind: string): kind is PushKind {export function validPushToken(platform: PushPlatform, token: string): boolean {return platform === "apns" ? APNS_TOKEN.test(token) : FCM_TOKEN.test(token);}++/** The phone's Live Activity and ongoing-notification registration on its computer or Cloud: `PUT` replaces it whole,+ * `GET` reads it back, `DELETE` removes it. Keyed like `PHONE_PUSH_ROUTE`. */+export const PHONE_ACTIVITY_ROUTE = "/api/push/activity";+export const PHONE_ACTIVITY_RELAY_PATH = "/v1/installations/self/push/activity";++/** What a bot's activity shows: it needs the person, or it is working. */+export type ActivityKind = "needsYou" | "working";+export type ActivityEvent = "start" | "update" | "end";++/** How the phone draws a bot: its colour, body gradient and mascot body, as its own widgets do. */+export interface ActivityVisual {+ color: string;+ gradient: string[];+ body: string;+}++/** `PUT /api/push/activity`, from the phone. */+export interface PhoneActivityRegistration {+ /** The app's URL scheme, for the chat link a pushed activity opens. */+ scheme: "openmausbot" | "openmausbot-dev" | "openmausbot-next";+ /** The phone's own words, with `{name}` where the bot's name goes: "{name} needs you", "{name} is working". */+ headlines: Record<ActivityKind, string>;+ /** iOS: the app's Live Activity push-to-start token (hex). */+ startToken?: string;+ /** iOS: each running Live Activity's own update token (hex), by bot. */+ activities?: Array<{ botId: string; token: string }>;+ /** iOS: how each bot the phone knows is drawn, so a pushed activity looks like the app's own. */+ visuals?: Record<string, ActivityVisual>;+ fallbackVisual?: ActivityVisual;+ /** Android: send the device's FCM token the ongoing "working" notification's data messages. */+ ongoing?: boolean;+ /** Which kinds the phone wants, from its Settings switches. Absent: both. */+ kinds?: ActivityKind[];+}++/** What the server sends the relay for one activity change. */+export interface PushRelayActivityRequest {+ v: typeof PHONE_PUSH_WIRE_VERSION;+ token: string;+ event: ActivityEvent;+ alert?: boolean;+ activity: {+ botId: string;+ botName: string;+ kind: ActivityKind;+ headline: string;+ since: number;+ link: string;+ } & ActivityVisual;+}diff --git a/server/index.ts b/server/index.tsindex 146108ead9..2421ba01a7 100644--- a/server/index.ts+++ b/server/index.ts@@ -102,7 +102,7 @@ import { removeRetiredAppFiles } from "./retired-apps.ts"; import { createEmailRimport { createPhones } from "./host/phones.ts";import { NOT_THE_OWNER } from "./phones/owner.ts";import { PHONE_INTERNAL_MCP_PATH } from "./phones/rpc.ts";-import { isLongPollPath, phoneKey } from "./routes/phones.ts"; import { createPhonePushRoutes } from "./routes/phone-push.ts"; import { PhonePush, PhonePushAccessSource, phonePushEnabled } from "./phone-push.ts"; import { DEFAULT_COMPANION_CONTROL_PLANE_URL } from "../electron/companion-account-service.mjs"; import { TUNNEL_CREDENTIALS_FILE } from "./tunnel.ts";+import { isLongPollPath, phoneKey } from "./routes/phones.ts"; import { createPhoneActivityRoutes, createPhonePushRoutes } from "./routes/phone-push.ts"; import { PhoneActivity } from "./phone-activity.ts"; import { PhonePush, PhonePushAccessSource, phonePushEnabled } from "./phone-push.ts"; import { DEFAULT_COMPANION_CONTROL_PLANE_URL } from "../electron/companion-account-service.mjs"; import { TUNNEL_CREDENTIALS_FILE } from "./tunnel.ts";import { createDataRoutes } from "./data/routes.ts";import { DataSheetRegistry } from "./data/sheet.ts";import { DataFailure } from "./data/types.ts";@@ -4639,7 +4639,7 @@ interface SseClient {/** Stops the heartbeat and leaves `sseClients` before ending the response; every way a stream ends goes through it. */close: () => void;}-const { streams: sseClients, ...teamPresence } = createTeamPresenceHost<SseClient>({ people: teamOwners.people, broadcast, audienceOf: (threadId) => teamHost.audienceOf(threadId), sharedWithOne: (threadId) => conversationShares.readers(threadId) !== null, store: () => store, visibleTo }); type StreamView = Pick<SseClient, "admin" | "person" | "viewer" | "seen" | "ask">; const phonePush = new PhonePush({ dataDir: DATA_DIR, access: () => phonePushAccess.current(), enabled: () => phonePushEnabled(cfg), live: (key) => [...sseClients].some((client) => client.pushKey === key), room: (notification) => { const group = (notification.groupId ? store.group(notification.groupId) : undefined) ?? store.groupByThread(notification.threadId); return group && !group.dm ? { id: group.id, name: group.name } : undefined; } });+const { streams: sseClients, ...teamPresence } = createTeamPresenceHost<SseClient>({ people: teamOwners.people, broadcast, audienceOf: (threadId) => teamHost.audienceOf(threadId), sharedWithOne: (threadId) => conversationShares.readers(threadId) !== null, store: () => store, visibleTo }); type StreamView = Pick<SseClient, "admin" | "person" | "viewer" | "seen" | "ask">; const phonePush = new PhonePush({ dataDir: DATA_DIR, access: () => phonePushAccess.current(), enabled: () => phonePushEnabled(cfg), live: (key) => [...sseClients].some((client) => client.pushKey === key), room: (notification) => { const group = (notification.groupId ? store.group(notification.groupId) : undefined) ?? store.groupByThread(notification.threadId); return group && !group.dm ? { id: group.id, name: group.name } : undefined; } }); const phoneActivity = new PhoneActivity({ dataDir: DATA_DIR, push: phonePush, hasOpenAsk: (botId) => openCardRows().some((row) => row.fromBotId === botId || store.botByThread(row.threadId)?.id === botId), bot: (botId) => { const bot = store.bot(botId); const working = bot ? store.tasks(botId).find((task) => threadBusy(botId, task.threadId)) : undefined; return bot ? { name: bot.name, busy: Boolean(working), threadId: working?.threadId ?? bot.threadId } : undefined; }, botOfThread: (threadId) => store.botByThread(threadId)?.id });let audienceChangedAt = 0;function audienceChanged(): void {@@ -4744,7 +4744,7 @@ function broadcast(payload: Record<string, unknown>, options: { adminOnly?: bool// Members get config as configured-or-not and every bot without its server alias.const clientPayload = options.adminOnly ? null : kind === "config" ? configForAccess(payload as ReturnType<typeof configStatus>, false) : memberFramePayload(payload);const clientFrame = clientPayload === null ? null : clientPayload === payload ? frame : `id: ${STREAM_ID}:${seq}\ndata: ${JSON.stringify({ ...clientPayload, seq })}\n\n`;- replayBuffer.push({ seq, kind, frame, clientFrame, payload, ...(options.person ? { person: options.person } : {}) }); if (kind === "notify") phonePush.offer({ notification: payload.notification, seq }, (key) => pushReaches(key, payload, seq, options));+ replayBuffer.push({ seq, kind, frame, clientFrame, payload, ...(options.person ? { person: options.person } : {}) }); if (kind === "notify") phonePush.offer({ notification: payload.notification, seq }, (key) => pushReaches(key, payload, seq, options)); if (kind === "notify" || kind === "bot" || kind === "runtime") phoneActivity.offer(payload, (key) => pushReaches(key, payload, seq, options));const ownGroups: OwnGroupFrames = new Map();for (const client of Array.from(sseClients)) {if (!wants(client, kind) || !teamOwners.reaches(client.ask, payload) || !streamFor(client, options.person)) continue;@@ -12493,7 +12493,7 @@ const liveCalls = new LiveCallController({},log: (line) => console.log(line),});-sessions.onSessionRevoked((sessionId) => liveCalls.sessionRevoked(sessionId)); sessions.onSessionRevoked((sessionId) => phonePush.forget(`session:${sessionId}`)); ROUTES.push(createPhonePushRoutes({ push: phonePush, live: (auth) => auth.kind === "loopback" || sessions.isLive(auth.session.id) }));+sessions.onSessionRevoked((sessionId) => liveCalls.sessionRevoked(sessionId)); sessions.onSessionRevoked((sessionId) => { phonePush.forget(`session:${sessionId}`); phoneActivity.forget(`session:${sessionId}`); }); ROUTES.push(createPhonePushRoutes({ push: phonePush, live: (auth) => auth.kind === "loopback" || sessions.isLive(auth.session.id) }), createPhoneActivityRoutes({ push: phonePush, activity: phoneActivity, live: (auth) => auth.kind === "loopback" || sessions.isLive(auth.session.id) }));ROUTES.push(createDataRoutes({bot: (id) => store.bot(id),engine: dataEngine,@@ -12502,7 +12502,7 @@ ROUTES.push(createDataRoutes({exportRoots: dataExportRoots,}));ROUTES.push(createLiveRoutes({- calls: liveCalls, deviceRevoked: (device) => phonePush.forget(`companion:${device}`),+ calls: liveCalls, deviceRevoked: (device) => { phonePush.forget(`companion:${device}`); phoneActivity.forget(`companion:${device}`); },resolveTarget: (botId, threadId) => {const bot = store.bot(botId);if (!bot) return null;diff --git a/server/phone-activity.test.ts b/server/phone-activity.test.tsnew file mode 100644index 0000000000..cdada36057--- /dev/null+++ b/server/phone-activity.test.ts@@ -0,0 +1,204 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { activityRegistrationSchema, FALLBACK_VISUAL, PhoneActivity } from "./phone-activity.ts";+import { PhonePush } from "./phone-push.ts";++const CREDENTIAL = `omb_install_${"a".repeat(22)}.${"b".repeat(43)}`;+const START = "5a".repeat(40);+const ACT = "ac".repeat(40);+const FCM = `fcmInstance_1:APA91b${"x".repeat(140)}`;+const IPHONE = "session:iphone";+const ANDROID = "companion:android";+const VISUAL = { color: "#7C5CFF", gradient: ["#B9A9FF", "#7C5CFF", "#48369A"], body: "round" };+const HEADLINES = { needsYou: "{name} needs you", working: "{name} is working" };++interface Call { path: string; body: Record<string, unknown> }++let dataDir: string;+beforeEach(() => {+ dataDir = mkdtempSync(join(tmpdir(), "omb-phone-activity-"));+});+afterEach(() => rmSync(dataDir, { recursive: true, force: true }));++function harness(options: { enabled?: boolean; live?: Set<string>; openAsks?: Set<string>; answers?: Array<{ status: number; error?: string }> } = {}) {+ const calls: Call[] = [];+ const answers = [...(options.answers ?? [])];+ const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {+ const path = new URL(String(input)).pathname;+ calls.push({ path, body: JSON.parse(String(init?.body)) });+ const answer = path.endsWith("/activity") ? answers.shift() : undefined;+ const status = answer?.status ?? (path.endsWith("/unregister") ? 204 : path.endsWith("/register") ? 200 : 202);+ return new Response(answer?.error ? JSON.stringify({ error: answer.error }) : status === 204 ? null : "{}", { status });+ }) as typeof fetch;+ const live = options.live ?? new Set<string>();+ const push = new PhonePush({+ dataDir,+ access: () => ({ controlPlane: "https://accounts.openmausbot.test", credential: CREDENTIAL }),+ enabled: () => options.enabled ?? true,+ live: (key) => live.has(key),+ room: () => undefined,+ fetchImpl,+ log: () => {},+ });+ const openAsks = options.openAsks ?? new Set<string>();+ const bots = new Map<string, { name: string; busy: boolean; threadId: string }>([["bot_1", { name: "Scout", busy: false, threadId: "th_1" }]]);+ let clock = 1_000_000;+ const activity = new PhoneActivity({+ dataDir, push, hasOpenAsk: (botId) => openAsks.has(botId), bot: (botId) => bots.get(botId), botOfThread: (threadId) => (threadId.startsWith("th_") ? "bot_1" : undefined),+ now: () => clock, log: () => {}, timers: { set: () => ({}), clear: () => {} },+ });+ const activityCalls = () => calls.filter((call) => call.path.endsWith("/push/activity")).map((call) => call.body);+ /** The bot works (or stops), a frame says so, and its frames settle. */+ const step = async (change: { busy?: boolean; ask?: boolean; name?: string }, payload: Record<string, unknown> = { kind: "bot", bot: { id: "bot_1" } }, reaches: (key: string) => boolean = () => true) => {+ const bot = bots.get("bot_1")!;+ bots.set("bot_1", { ...bot, ...(change.busy === undefined ? {} : { busy: change.busy }), ...(change.name ? { name: change.name } : {}) });+ if (change.ask === true) openAsks.add("bot_1");+ if (change.ask === false) openAsks.delete("bot_1");+ activity.offer(payload, reaches);+ await activity.flushNow();+ };+ return { push, activity, calls, activityCalls, live, openAsks, step, tick: (ms: number) => { clock += ms; } };+}++const registration = (extra: Record<string, unknown> = {}) => activityRegistrationSchema.parse({ scheme: "openmausbot", headlines: HEADLINES, ...extra });+const notify = (kind: string) => ({ kind: "notify", notification: { kind, botId: "bot_1", botName: "Scout", threadId: "th_ask", title: "Scout needs approval", body: "PRIVATE run cat ~/payroll.csv" } });+const runtime = (type: string) => ({ kind: "runtime", event: { type, threadId: "th_1", eventId: "e1", provider: "claudeAgent", createdAt: "" } });+const everyone = () => true;++describe("registering a phone's activities", () => {+ it("keeps nothing while phone push is off", async () => {+ const { activity, calls, step } = harness({ enabled: false });+ expect(await activity.register(IPHONE, registration({ startToken: START }))).toBe("off");+ expect(activity.registration(IPHONE)).toBeNull();+ await step({ busy: true });+ expect(calls).toEqual([]);+ });++ it("registers the push-to-start and activity tokens with their purpose, never echoes them, and drops replaced ones", async () => {+ const { activity, calls } = harness();+ await activity.register(IPHONE, registration({ startToken: START, activities: [{ botId: "bot_1", token: ACT }], visuals: { bot_1: VISUAL } }));+ expect(calls.map((call) => call.body)).toEqual([+ { v: 1, platform: "apns", purpose: "activity-start", token: START, environment: "production" },+ { v: 1, platform: "apns", purpose: "activity", token: ACT, environment: "production" },+ ]);+ expect(activity.registration(IPHONE)).toEqual({ scheme: "openmausbot", headlines: HEADLINES, ongoing: false, kinds: ["needsYou", "working"], activities: ["bot_1"], canStart: true });+ expect(JSON.stringify(activity.registration(IPHONE))).not.toContain(ACT);+ await activity.register(IPHONE, registration({ startToken: START }));+ expect(calls.at(-1)).toEqual({ path: "/v1/installations/self/push/unregister", body: { v: 1, platform: "apns", token: ACT } });+ });++ it("takes only its own words with a place for the name, and well-formed tokens and colours", () => {+ for (const bad of [+ { headlines: { needsYou: "needs you", working: "{name} is working" } },+ { headlines: { needsYou: "{name}\nneeds you", working: "{name} is working" } },+ { startToken: FCM },+ { visuals: { bot_1: { ...VISUAL, color: "purple" } } },+ { scheme: "https" },+ { activities: Array.from({ length: 11 }, (_, index) => ({ botId: `b${index}`, token: ACT })) },+ { line: "text" },+ ]) expect(activityRegistrationSchema.safeParse({ scheme: "openmausbot", headlines: HEADLINES, ...bad }).success, JSON.stringify(bad)).toBe(false);+ });+});++describe("pushing a bot's activity while the app is closed", () => {+ it("updates a running activity as the bot starts and stops working, once per change, then forgets its token", async () => {+ const { activity, activityCalls, calls, step } = harness();+ await activity.register(IPHONE, registration({ activities: [{ botId: "bot_1", token: ACT }], visuals: { bot_1: VISUAL } }));+ await step({ busy: true }, runtime("turn.started"));+ await step({}, runtime("turn.started"));+ await step({ busy: false }, runtime("turn.completed"));+ expect(activityCalls()).toEqual([+ { v: 1, token: ACT, event: "update", activity: { botId: "bot_1", botName: "Scout", kind: "working", headline: "Scout is working", since: 1_000_000, link: "openmausbot://chat/th_1", ...VISUAL } },+ { v: 1, token: ACT, event: "end", activity: { botId: "bot_1", botName: "Scout", kind: "working", headline: "Scout is working", since: 1_000_000, link: "openmausbot://chat/th_1", ...VISUAL } },+ ]);+ expect(calls.at(-1)).toMatchObject({ path: "/v1/installations/self/push/unregister", body: { token: ACT } });+ expect(activity.registration(IPHONE)?.activities).toEqual([]);+ });++ it("rings when a bot starts needing the person, and starts an activity remotely only then", async () => {+ const { activity, activityCalls, step } = harness();+ await activity.register(IPHONE, registration({ startToken: START }));+ await step({ busy: true });+ await step({ ask: true }, notify("approval"));+ await step({}, notify("done"));+ expect(activityCalls()).toEqual([+ { v: 1, token: START, event: "start", alert: true, activity: { botId: "bot_1", botName: "Scout", kind: "needsYou", headline: "Scout needs you", since: 1_000_000, link: "openmausbot://chat/th_ask", ...FALLBACK_VISUAL } },+ ]);+ expect(JSON.stringify(activityCalls())).not.toContain("payroll");+ });++ it("drives Android's ongoing notification through the phone's FCM token", async () => {+ const { push, activity, activityCalls, step } = harness();+ await push.register(ANDROID, { platform: "fcm", token: FCM });+ await activity.register(ANDROID, registration({ ongoing: true }));+ await step({ busy: true });+ await step({ ask: true }, runtime("request.opened"));+ await step({ ask: false, busy: false }, runtime("turn.completed"));+ expect(activityCalls().map((body) => [body.token === FCM, body.event, (body.activity as { kind: string }).kind, body.alert ?? false])).toEqual([+ [true, "update", "working", false],+ [true, "update", "needsYou", true],+ [true, "end", "needsYou", false],+ ]);+ });++ it("leaves a connected phone to its own app, and a phone that may not see the bot alone", async () => {+ const { activity, activityCalls, live, step } = harness();+ await activity.register(IPHONE, registration({ activities: [{ botId: "bot_1", token: ACT }] }));+ live.add(IPHONE);+ await step({ busy: true });+ live.delete(IPHONE);+ await step({}, undefined, () => false);+ expect(activityCalls()).toEqual([]);+ await step({});+ expect(activityCalls()).toHaveLength(1);+ await step({}, { kind: "runtime", event: { type: "content.delta", threadId: "th_1" } });+ await step({}, { kind: "message", threadId: "th_1" });+ expect(activityCalls()).toHaveLength(1);+ });++ it("honours the kinds the phone asked for", async () => {+ const { activity, activityCalls, step } = harness();+ await activity.register(IPHONE, registration({ kinds: ["needsYou"], activities: [{ botId: "bot_1", token: ACT }] }));+ await step({ busy: true });+ await step({ busy: true }, runtime("turn.started"));+ // Never an update for a kind the phone did not ask for; only the one end for what its app may have drawn.+ expect(activityCalls().map((body) => body.event)).toEqual(["end"]);+ });++ it("drops an activity token the provider calls dead", async () => {+ const { activity, step } = harness({ answers: [{ status: 410, error: "push_device_unregistered" }] });+ await activity.register(IPHONE, registration({ activities: [{ botId: "bot_1", token: ACT }] }));+ await step({ busy: true });+ expect(activity.registration(IPHONE)?.activities).toEqual([]);+ });++ it("forgets a phone and its tokens when it is unpaired", async () => {+ const { activity, calls } = harness();+ await activity.register(IPHONE, registration({ startToken: START, activities: [{ botId: "bot_1", token: ACT }] }));+ await activity.remove(IPHONE);+ expect(calls.filter((call) => call.path.endsWith("/unregister")).map((call) => call.body.token)).toEqual([START, ACT]);+ expect(activity.registration(IPHONE)).toBeNull();+ });++ it("never throws into the server", () => {+ const { activity } = harness();+ expect(() => activity.offer({ kind: "bot", bot: null }, everyone)).not.toThrow();+ expect(() => activity.offer({ kind: "notify", notification: "x" }, everyone)).not.toThrow();+ });++ it("ends what the app drew for a bot that went quiet after the phone's stream closed, once", async () => {+ const { push, activity, activityCalls, live, step } = harness();+ await push.register(ANDROID, { platform: "fcm", token: FCM });+ await activity.register(ANDROID, registration({ ongoing: true }));+ await activity.register(IPHONE, registration({}));+ live.add(ANDROID);+ await step({ busy: true });+ live.delete(ANDROID);+ await step({ busy: false });+ await step({ busy: false });+ expect(activityCalls().map((body) => [body.token === FCM, body.event])).toEqual([[true, "end"]]);+ });+});diff --git a/server/phone-activity.ts b/server/phone-activity.tsnew file mode 100644index 0000000000..9ba5cb0709--- /dev/null+++ b/server/phone-activity.ts@@ -0,0 +1,384 @@+// A paired phone's Live Activities (iPhone) and ongoing "working" notification (Android) while its app is closed. The+// phone registers its activity tokens and its own words; when a bot it would see starts needing the person, starts or+// stops working, and the phone holds no live stream, this asks the push relay to start, update or end that bot's+// activity. Names, kind and the phone's headline only. It rides phone push's switch, store rules and relay access.+import { mkdirSync, readFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { z } from "zod";++import {+ APNS_TOKEN,+ FCM_TOKEN,+ PHONE_ACTIVITY_RELAY_PATH,+ PHONE_PUSH_RELAY_PATHS,+ PHONE_PUSH_WIRE_VERSION,+ PUSH_ID,+ PUSH_NAME_MAX,+ PUSH_RELAY_ERRORS,+ type ActivityEvent,+ type ActivityKind,+ type ActivityVisual,+ type PhoneActivityRegistration,+ type PushRelayActivityRequest,+} from "../shared/phone-push.ts";+import { writeFileAtomic } from "./atomic.ts";+import { PUSH_DEVICE_KEY, type PhonePush } from "./phone-push.ts";++export const PHONE_ACTIVITY_FILE = "push-activity.json";+export const MAX_ACTIVITY_PHONES = 50;+export const MAX_ACTIVITIES = 10;+export const MAX_VISUALS = 60;+const HEADLINE_MAX = 120;+const NEEDS_YOU_KINDS: ReadonlySet<string> = new Set(["approval", "question", "sign-in"]);++const hex = z.string().regex(/^#[0-9A-Fa-f]{6}$/);+const visualSchema = z.object({ color: hex, gradient: z.array(hex).min(1).max(4), body: z.string().regex(/^[a-z][a-z0-9-]{0,39}$/) }).strict();+const headline = z.string().min(1).max(HEADLINE_MAX).refine((value) => value.includes("{name}") && !/[\p{Cc}\u2028\u2029]/u.test(value));++export const activityRegistrationSchema = z.object({+ scheme: z.enum(["openmausbot", "openmausbot-dev", "openmausbot-next"]),+ headlines: z.object({ needsYou: headline, working: headline }).strict(),+ startToken: z.string().trim().toLowerCase().regex(APNS_TOKEN).optional(),+ activities: z.array(z.object({ botId: z.string().regex(PUSH_ID), token: z.string().trim().toLowerCase().regex(APNS_TOKEN) }).strict()).max(MAX_ACTIVITIES).optional(),+ visuals: z.record(z.string().regex(PUSH_ID), visualSchema).refine((value) => Object.keys(value).length <= MAX_VISUALS).optional(),+ fallbackVisual: visualSchema.optional(),+ ongoing: z.boolean().optional(),+ kinds: z.array(z.enum(["needsYou", "working"])).max(2).optional(),+}).strict();++const storedSchema = z.object({ version: z.literal(1), phones: z.array(z.object({ key: z.string().regex(PUSH_DEVICE_KEY), registration: activityRegistrationSchema, updatedAt: z.number() })).max(MAX_ACTIVITY_PHONES) });+type Stored = z.infer<typeof storedSchema>["phones"][number];++/** The neutral look of a pushed activity for a bot the phone never drew. */+export const FALLBACK_VISUAL: ActivityVisual = { color: "#7C5CFF", gradient: ["#B9A9FF", "#7C5CFF", "#48369A"], body: "cursor" };++interface BotState {+ kind: ActivityKind;+ since: number;+ name: string;+ threadId: string;+}++export interface PhoneActivityOptions {+ dataDir: string;+ push: PhonePush;+ /** Whether a bot has an approval, question or sign-in card waiting on the person. */+ hasOpenAsk: (botId: string) => boolean;+ /** The bot as it is now: its name, whether any of its conversations is working, and which. */+ bot: (botId: string) => { name: string; busy: boolean; threadId: string } | undefined;+ /** The bot a conversation belongs to. */+ botOfThread: (threadId: string) => string | undefined;+ now?: () => number;+ log?: (line: string) => void;+ /** Frames for one bot gather this long before its state is read again. */+ settleMs?: number;+ timers?: { set(run: () => void, ms: number): unknown; clear(handle: unknown): void };+}++/** The runtime events that change whether a bot is working or waiting on the person. */+const STATE_EVENTS: ReadonlySet<string> = new Set(["turn.started", "turn.completed", "turn.retrying", "turn.wait_started", "turn.wait_ended", "request.opened", "request.resolved", "session.exited"]);++export type ActivityOutcome = { key: string; botId: string; event: ActivityEvent; via: "apns" | "fcm"; result: "sent" | "dropped" | "failed" };++function headlineFor(template: string, name: string): string {+ const filled = template.replace("{name}", name).replace(/[\p{Cc}\u2028\u2029]/gu, " ").trim();+ const points = [...filled];+ return points.length > HEADLINE_MAX ? `${points.slice(0, HEADLINE_MAX - 1).join("")}…` : filled;+}++function clipName(name: string): string {+ const points = [...name.replace(/[\p{Cc}\u2028\u2029]/gu, " ").trim()];+ return (points.length > PUSH_NAME_MAX ? `${points.slice(0, PUSH_NAME_MAX - 1).join("")}…` : points.join("")) || "MausBot";+}++export class PhoneActivity {+ private phones: Stored[] = [];+ private readonly file: string;+ private readonly options: PhoneActivityOptions;+ private readonly now: () => number;+ private readonly log: (line: string) => void;+ /** What each bot is doing now, from the frames that passed. */+ private readonly bots = new Map<string, BotState>();+ /** Each bot's last known name and conversation, for an end that comes after its state is gone. */+ private readonly seen = new Map<string, { name: string; threadId: string }>();+ /** What each phone was last sent per bot, so only a change goes out. */+ private readonly shown = new Map<string, Map<string, ActivityKind>>();+ /** The bots each phone has been told about since its app last connected; any other may still show what the app drew. */+ private readonly told = new Map<string, Set<string>>();+ private queue: Promise<unknown> = Promise.resolve();+ private readonly pending = new Map<string, unknown>();+ private readonly reach = new Map<string, (key: string) => boolean>();+ private readonly askThread = new Map<string, string>();++ constructor(options: PhoneActivityOptions) {+ this.options = options;+ this.file = join(options.dataDir, PHONE_ACTIVITY_FILE);+ this.now = options.now ?? Date.now;+ this.log = options.log ?? ((line) => console.log(line));+ let raw: unknown;+ try {+ raw = JSON.parse(readFileSync(this.file, "utf8"));+ } catch {+ return;+ }+ const parsed = storedSchema.safeParse(raw);+ if (parsed.success) this.phones = parsed.data.phones;+ }++ private persist(): void {+ mkdirSync(dirname(this.file), { recursive: true, mode: 0o700 });+ writeFileAtomic(this.file, `${JSON.stringify({ version: 1, phones: this.phones }, null, 2)}\n`, { mode: 0o600 });+ }++ /** A registration as the phone may read it back: never a token. */+ registration(key: string): { scheme: string; headlines: Record<ActivityKind, string>; ongoing: boolean; kinds: ActivityKind[]; activities: string[]; canStart: boolean } | null {+ const found = this.phones.find((phone) => phone.key === key)?.registration;+ if (!found) return null;+ return {+ scheme: found.scheme,+ headlines: found.headlines,+ ongoing: found.ongoing === true,+ kinds: found.kinds ?? ["needsYou", "working"],+ activities: (found.activities ?? []).map(({ botId }) => botId),+ canStart: Boolean(found.startToken),+ };+ }++ /** Replaces this phone's registration. Switched off, nothing is kept. Tokens it no longer lists are unregistered. */+ async register(key: string, input: z.infer<typeof activityRegistrationSchema>): Promise<"off" | "saved"> {+ if (!PUSH_DEVICE_KEY.test(key)) throw new Error("not a phone");+ if (this.options.push.status() === "off") return "off";+ const previous = this.phones.find((phone) => phone.key === key);+ const others = this.phones.filter((phone) => phone.key !== key);+ if (!previous && others.length >= MAX_ACTIVITY_PHONES) throw Object.assign(new Error("Too many phones"), { status: 409 });+ this.phones = [...others, { key, registration: input, updatedAt: this.now() }];+ this.persist();+ const environment = this.options.push.deviceOf(key)?.environment ?? "production";+ const tokens = (registration: PhoneActivityRegistration | undefined) => new Map<string, "activity" | "activity-start">([+ ...(registration?.startToken ? [[registration.startToken, "activity-start"] as const] : []),+ ...(registration?.activities ?? []).map(({ token }) => [token, "activity"] as const),+ ]);+ const before = tokens(previous?.registration);+ const after = tokens(input);+ for (const token of before.keys()) {+ if (!after.has(token)) void this.options.push.call(PHONE_PUSH_RELAY_PATHS.unregister, { v: PHONE_PUSH_WIRE_VERSION, platform: "apns", token });+ }+ if (this.options.push.status() === "on") {+ for (const [token, purpose] of after) {+ if (!before.has(token)) await this.options.push.call(PHONE_PUSH_RELAY_PATHS.register, { v: PHONE_PUSH_WIRE_VERSION, platform: "apns", purpose, token, environment });+ }+ }+ // The phone said which activities it holds: anything it no longer lists is not on screen.+ const listed = new Set((input.activities ?? []).map(({ botId }) => botId));+ const shown = this.shown.get(key);+ if (shown) for (const botId of shown.keys()) if (!listed.has(botId) && !input.ongoing) shown.delete(botId);+ return "saved";+ }++ async remove(key: string): Promise<void> {+ const previous = this.phones.find((phone) => phone.key === key);+ if (!previous) return;+ this.phones = this.phones.filter((phone) => phone.key !== key);+ this.shown.delete(key);+ this.persist();+ const tokens = [previous.registration.startToken, ...(previous.registration.activities ?? []).map(({ token }) => token)].filter((token): token is string => Boolean(token));+ await Promise.all(tokens.map((token) => this.options.push.call(PHONE_PUSH_RELAY_PATHS.unregister, { v: PHONE_PUSH_WIRE_VERSION, platform: "apns", token })));+ }++ forget(key: string): void {+ void this.remove(key).catch((error) => this.log(`[phone-activity] could not forget a phone: ${error instanceof Error ? error.message : String(error)}`));+ }++ /** Resolves once every change offered so far has been sent (or given up). */+ async flush(): Promise<void> {+ await this.queue;+ }++ /**+ * A `bot`, `notify` or `runtime` frame left the server. After its bot's frames settle, what the bot is doing is read+ * again and, for each registered phone with no live stream that would have seen the frame, the change is pushed.+ * Never throws, and does nothing while phone push is off.+ */+ offer(payload: Record<string, unknown>, reaches: (key: string) => boolean): void {+ try {+ if (!this.phones.length || this.options.push.status() !== "on") return;+ const botId = this.botOf(payload);+ if (!botId) return;+ this.reach.set(botId, reaches);+ if (this.pending.has(botId)) return;+ const timers = this.options.timers ?? { set: (run: () => void, ms: number) => setTimeout(run, ms).unref(), clear: (handle: unknown) => clearTimeout(handle as ReturnType<typeof setTimeout>) };+ this.pending.set(botId, timers.set(() => {+ this.pending.delete(botId);+ this.settle(botId);+ }, this.options.settleMs ?? 250));+ } catch (error) {+ this.log(`[phone-activity] could not queue: ${error instanceof Error ? error.message : String(error)}`);+ }+ }++ /** The bot a frame is about, noting the conversation an ask came from; null for a frame that changes no activity. */+ private botOf(payload: Record<string, unknown>): string | null {+ if (payload.kind === "notify") {+ const notification = payload.notification as Record<string, unknown> | undefined;+ const botId = notification?.botId, threadId = notification?.threadId, kind = notification?.kind;+ if (typeof botId !== "string" || typeof kind !== "string" || !PUSH_ID.test(botId) || !NEEDS_YOU_KINDS.has(kind)) return null;+ if (typeof threadId === "string") this.askThread.set(botId, threadId);+ return botId;+ }+ if (payload.kind === "bot") {+ const botId = (payload.bot as Record<string, unknown> | undefined)?.id;+ return typeof botId === "string" && PUSH_ID.test(botId) ? botId : null;+ }+ if (payload.kind === "runtime") {+ const event = payload.event as Record<string, unknown> | undefined;+ if (typeof event?.type !== "string" || !STATE_EVENTS.has(event.type) || typeof event.threadId !== "string") return null;+ const botId = this.options.botOfThread(event.threadId);+ return botId && PUSH_ID.test(botId) ? botId : null;+ }+ return null;+ }++ /** Reads what the bot is doing now and pushes each phone the change, if any. */+ private settle(botId: string): void {+ try {+ if (this.options.push.status() !== "on") return;+ const now = this.now();+ const bot = this.options.bot(botId);+ const previous = this.bots.get(botId);+ const kind: ActivityKind | undefined = !bot ? undefined : this.options.hasOpenAsk(botId) ? "needsYou" : bot.busy ? "working" : undefined;+ if (bot) this.remember(botId, bot.name, kind === "needsYou" ? this.askThread.get(botId) ?? bot.threadId : bot.threadId);+ if (kind && bot) this.bots.set(botId, { kind, since: previous?.kind === kind ? previous.since : now, name: bot.name, threadId: this.seen.get(botId)?.threadId ?? bot.threadId });+ else this.bots.delete(botId);+ if (kind !== "needsYou") this.askThread.delete(botId);+ const reaches = this.reach.get(botId) ?? (() => false);+ for (const phone of this.phones) {+ if (this.options.push.isLive(phone.key)) {+ // Its app draws its own activities while connected; after, the server starts from nothing.+ this.shown.delete(phone.key);+ this.told.delete(phone.key);+ continue;+ }+ if (!reaches(phone.key)) continue;+ const shown = this.shown.get(phone.key) ?? new Map<string, ActivityKind>();+ this.shown.set(phone.key, shown);+ const told = this.told.get(phone.key) ?? new Set<string>();+ this.told.set(phone.key, told);+ const firstNews = !told.has(botId);+ told.add(botId);+ const wanted = kind && (phone.registration.kinds ?? ["needsYou", "working"]).includes(kind) ? kind : undefined;+ const was = shown.get(botId);+ if (wanted === was) {+ // The app may have drawn this bot before it went quiet: end what it left, once.+ const drawn = phone.registration.ongoing === true || phone.registration.activities?.some((entry) => entry.botId === botId) === true;+ if (firstNews && !wanted && drawn) this.enqueue(phone, botId, undefined, "working");+ continue;+ }+ if (wanted) shown.set(botId, wanted);+ else shown.delete(botId);+ this.enqueue(phone, botId, wanted, was);+ }+ } catch (error) {+ this.log(`[phone-activity] could not push: ${error instanceof Error ? error.message : String(error)}`);+ }+ }++ /** Runs every settle that is waiting now, then waits for the sends. */+ async flushNow(): Promise<void> {+ const timers = this.options.timers;+ for (const [botId, handle] of this.pending) {+ timers?.clear(handle);+ this.pending.delete(botId);+ this.settle(botId);+ }+ await this.queue;+ }++ private remember(botId: string, name: string, threadId: string): void {+ this.seen.delete(botId);+ this.seen.set(botId, { name, threadId });+ for (const oldest of this.seen.keys()) {+ if (this.seen.size <= 500) break;+ this.seen.delete(oldest);+ }+ }++ private enqueue(phone: Stored, botId: string, wanted: ActivityKind | undefined, was: ActivityKind | undefined): void {+ const state = this.bots.get(botId);+ this.queue = this.queue.then(() => this.send(phone, botId, wanted, was, state)).catch((error: unknown) => {+ this.log(`[phone-activity] could not push: ${error instanceof Error ? error.message : String(error)}`);+ });+ }++ private activityBody(phone: Stored, botId: string, kind: ActivityKind, state: BotState | undefined, fallbackName: string): PushRelayActivityRequest["activity"] {+ const registration = phone.registration;+ const visual = registration.visuals?.[botId] ?? registration.fallbackVisual ?? FALLBACK_VISUAL;+ const known = state ?? this.seen.get(botId);+ const name = clipName(known?.name ?? fallbackName);+ return {+ botId,+ botName: name,+ kind,+ headline: headlineFor(registration.headlines[kind], name),+ since: state?.since ?? this.now(),+ link: `${registration.scheme}://chat/${encodeURIComponent(known?.threadId ?? botId)}`,+ ...visual,+ };+ }++ private async send(phone: Stored, botId: string, wanted: ActivityKind | undefined, was: ActivityKind | undefined, state: BotState | undefined): Promise<ActivityOutcome[]> {+ const outcomes: ActivityOutcome[] = [];+ const registration = phone.registration;+ const kind = wanted ?? was;+ if (!kind) return outcomes;+ const activity = this.activityBody(phone, botId, kind, state, botId);+ const alert = wanted === "needsYou" && was !== "needsYou";+ const event: ActivityEvent = wanted ? "update" : "end";++ const running = registration.activities?.find((entry) => entry.botId === botId);+ if (running) {+ outcomes.push(await this.post(phone.key, botId, { v: PHONE_PUSH_WIRE_VERSION, token: running.token, event, ...(alert ? { alert } : {}), activity }, "apns"));+ if (event === "end") this.dropActivity(phone.key, botId);+ } else if (wanted === "needsYou" && registration.startToken && alert) {+ // Only a bot that starts needing the person is started remotely: a working bot is news the app shows when opened.+ outcomes.push(await this.post(phone.key, botId, { v: PHONE_PUSH_WIRE_VERSION, token: registration.startToken, event: "start", alert: true, activity }, "apns"));+ }++ const device = this.options.push.deviceOf(phone.key);+ if (registration.ongoing && device?.platform === "fcm" && FCM_TOKEN.test(device.token)) {+ outcomes.push(await this.post(phone.key, botId, { v: PHONE_PUSH_WIRE_VERSION, token: device.token, event, ...(alert ? { alert } : {}), activity }, "fcm"));+ }+ return outcomes;+ }++ private async post(key: string, botId: string, body: PushRelayActivityRequest, via: "apns" | "fcm"): Promise<ActivityOutcome> {+ const answer = await this.options.push.call(PHONE_ACTIVITY_RELAY_PATH, body);+ const base = { key, botId, event: body.event, via } as const;+ if (answer && answer.status < 300) return { ...base, result: "sent" };+ if (answer && (answer.status === 410 || answer.code === PUSH_RELAY_ERRORS.unregistered || answer.code === PUSH_RELAY_ERRORS.unknownDevice)) {+ if (via === "apns") {+ if (body.event === "start") this.dropStartToken(key);+ else this.dropActivity(key, botId);+ }+ return { ...base, result: "dropped" };+ }+ return { ...base, result: "failed" };+ }++ private dropActivity(key: string, botId: string): void {+ const phone = this.phones.find((candidate) => candidate.key === key);+ const activities = phone?.registration.activities;+ if (!phone || !activities?.some((entry) => entry.botId === botId)) return;+ const removed = activities.filter((entry) => entry.botId === botId);+ phone.registration = { ...phone.registration, activities: activities.filter((entry) => entry.botId !== botId) };+ this.persist();+ for (const { token } of removed) void this.options.push.call(PHONE_PUSH_RELAY_PATHS.unregister, { v: PHONE_PUSH_WIRE_VERSION, platform: "apns", token });+ }++ private dropStartToken(key: string): void {+ const phone = this.phones.find((candidate) => candidate.key === key);+ if (!phone?.registration.startToken) return;+ const { startToken: _dropped, ...rest } = phone.registration;+ phone.registration = rest;+ this.persist();+ }+}diff --git a/server/phone-push.e2e.test.ts b/server/phone-push.e2e.test.tsindex f34b6e4718..4781efb5e9 100644--- a/server/phone-push.e2e.test.ts+++ b/server/phone-push.e2e.test.ts@@ -37,6 +37,7 @@ async function boot(env: Record<string, string>): Promise<Fixture> {features: { smartSetupChoices: false },instances: {quick: { driver: "claudeAgent", displayName: "Quick fixture", environment: { FAKE_CLAUDE_MODE: "happy", FAKE_CLAUDE_REPLIES: JSON.stringify(Array.from({ length: 8 }, () => SECRET_REPLY)) }, config: { cli: FAKE_CLAUDE } },+ slow: { driver: "claudeAgent", displayName: "Slow fixture", environment: { FAKE_CLAUDE_MODE: "slow", FAKE_CLAUDE_SLOW_FINISH_GATE: join(home, "finish-gate") }, config: { cli: FAKE_CLAUDE } },curious: { driver: "grokAgent", displayName: "Curious fixture", environment: { FAKE_ACP_MODE: "question" }, config: { cli: FAKE_ACP, fullAuto: true } },},}));@@ -175,3 +176,35 @@ describe("phone push switched on", () => {expect(on.stderr()).not.toContain(FCM_B);}, 120_000);});++describe("Live Activities by push", () => {+ it("updates and ends a closed phone's activity for a bot as it works, with the phone's own words and no reply text", async () => {+ const ACTIVITY = "ac".repeat(40);+ const phone = await pair(on, "Phone C");+ const pip = await createBot(on, "Pip", "slow", "claude-sonnet-5");+ expect((await api(on, "PUT", "/api/push/device", { platform: "apns", token: "c3".repeat(32) }, phone.token)).status).toBe(200);+ const registered = await api(on, "PUT", "/api/push/activity", {+ scheme: "openmausbot",+ headlines: { needsYou: "{name} braucht dich", working: "{name} arbeitet" },+ activities: [{ botId: pip.id, token: ACTIVITY }],+ visuals: { [pip.id]: { color: "#7C5CFF", gradient: ["#B9A9FF", "#7C5CFF"], body: "round" } },+ }, phone.token);+ expect(registered.body).toMatchObject({ push: "on", activity: { activities: [pip.id], canStart: false } });+ expect(JSON.stringify(registered.body)).not.toContain(ACTIVITY);+ expect(stub.pushes.at(-1)!.body).toEqual({ v: 1, platform: "apns", purpose: "activity", token: ACTIVITY, environment: "production" });++ const activityPushes = () => stub.pushes.filter((push) => push.path.endsWith("/push/activity")).map((push) => push.body);+ expect((await api(on, "POST", `/api/bots/${pip.id}/messages`, { text: "go" })).status).toBe(202);+ await expect.poll(() => activityPushes().map((body) => body.event), { timeout: 30_000 }).toEqual(["update"]);+ writeFileSync(join(on.home, "finish-gate"), "");+ await expect.poll(() => activityPushes().map((body) => body.event), { timeout: 30_000 }).toEqual(["update", "end"]);+ expect(activityPushes()[0]).toEqual({+ v: 1,+ token: ACTIVITY,+ event: "update",+ activity: { botId: pip.id, botName: "Pip", kind: "working", headline: "Pip arbeitet", since: expect.any(Number), link: `openmausbot://chat/${pip.threadId}`, color: "#7C5CFF", gradient: ["#B9A9FF", "#7C5CFF"], body: "round" },+ });+ expect(JSON.stringify(activityPushes())).not.toContain("PRIVATE-REPLY-TEXT");+ await expect.poll(() => stub.pushes.at(-1), { timeout: 10_000 }).toEqual({ path: "/v1/installations/self/push/unregister", body: { v: 1, platform: "apns", token: ACTIVITY } });+ }, 90_000);+});diff --git a/server/phone-push.ts b/server/phone-push.tsindex 304021bed1..d622015d69 100644--- a/server/phone-push.ts+++ b/server/phone-push.ts@@ -129,7 +129,7 @@ interface Job {attempts: number;}-interface RelayAnswer {+export interface RelayAnswer {status: number;code?: string;retryAfterMs?: number;@@ -217,6 +217,21 @@ export class PhonePush {return { platform: device.platform, environment: device.environment, ...(device.pairing ? { pairing: device.pairing } : {}), kinds: [...device.kinds], updatedAt: device.updatedAt };}+ /** The device token a phone registered, for the Live Activity and ongoing-notification pushes that share its relay. */+ deviceOf(key: string): { platform: "apns" | "fcm"; token: string; environment: "production" | "sandbox" } | undefined {+ const device = this.devices.find((candidate) => candidate.key === key);+ return device ? { platform: device.platform, token: device.token, environment: device.environment } : undefined;+ }++ isLive(key: string): boolean {+ return this.options.live(key);+ }++ /** One relay call, as this server's installation; null when the relay could not be reached or there is no account. */+ call(path: string, body: unknown): Promise<RelayAnswer | null> {+ return this.relay(path, body);+ }+answer(key: string): PhonePushAnswer {return { push: this.status(), device: this.publicDevice(key) };}diff --git a/server/request-auth.ts b/server/request-auth.tsindex 89ff128b7d..8097e14335 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -328,8 +328,8 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg{ methods: ["GET", "PUT", "DELETE"], path: /^\/api\/phones\/self$/ },{ methods: ["GET"], path: /^\/api\/phones\/self\/jobs$/ },{ methods: ["POST"], path: /^\/api\/phones\/self\/jobs\/[\w-]+\/(?:lease|result)$/ },- // This phone's own closed-app alert registration, keyed by its session (routes/phone-push.ts).- { methods: ["GET", "PUT", "DELETE"], path: /^\/api\/push\/device$/ },+ // This phone's own push registrations, alerts and Live Activities, keyed by its session (routes/phone-push.ts).+ { methods: ["GET", "PUT", "DELETE"], path: /^\/api\/push\/(?:device|activity)$/ },{ methods: ["GET"], path: /^\/api\/health$/ },{ methods: ["GET"], path: /^\/api\/edition$/ },{ methods: ["GET"], path: /^\/api\/brand$/ },diff --git a/server/routes/phone-push.ts b/server/routes/phone-push.tsindex 45d52f5a41..04e38de78c 100644--- a/server/routes/phone-push.ts+++ b/server/routes/phone-push.ts@@ -1,6 +1,7 @@// /api/push/device: a paired phone registers, reads back or removes its own closed-app alert registration. The phone is// known by what authenticated the request (a paired session, or the device the companion vouched for), never the body.-import { PHONE_PUSH_ROUTE } from "../../shared/phone-push.ts";+import { PHONE_ACTIVITY_ROUTE, PHONE_PUSH_ROUTE } from "../../shared/phone-push.ts";+import { activityRegistrationSchema, type PhoneActivity } from "../phone-activity.ts";import { registrationSchema, type PhonePush } from "../phone-push.ts";import type { RequestAuth } from "../request-auth.ts";import { phoneKey } from "./phones.ts";@@ -38,3 +39,38 @@ export function createPhonePushRoutes(deps: PhonePushRouteDeps): RouteHandler {}};}++export interface PhoneActivityRouteDeps {+ push: PhonePush;+ activity: PhoneActivity;+ live: (auth: RequestAuth) => boolean;+}++/** /api/push/activity: the calling phone's Live Activity tokens, its words and its Android ongoing switch. */+export function createPhoneActivityRoutes(deps: PhoneActivityRouteDeps): RouteHandler {+ return async ({ req, res, path, method, auth, json, readBody }: RouteContext): Promise<typeof PASS | void> => {+ if (path !== PHONE_ACTIVITY_ROUTE) return PASS;+ res.setHeader("Cache-Control", "no-store");+ if (!deps.live(auth)) return json(res, 401, { error: "Session expired" });+ const key = phoneKey(auth);+ if (!key) return json(res, 403, { error: SELF_ONLY });+ const answer = () => ({ push: deps.push.status(), activity: deps.activity.registration(key) });+ if (method === "GET") return json(res, 200, answer());+ if (method === "DELETE") {+ await deps.activity.remove(key);+ return json(res, 200, answer());+ }+ if (method !== "PUT") return json(res, 405, { error: "Method not allowed" });+ if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) return json(res, 415, { error: "JSON required" });+ const parsed = activityRegistrationSchema.safeParse(await readBody(req, 32_768));+ if (!deps.live(auth)) return json(res, 401, { error: "Session expired" });+ if (!parsed.success) return json(res, 400, { error: "Invalid activity registration" });+ try {+ await deps.activity.register(key, parsed.data);+ return json(res, 200, answer());+ } catch (error) {+ const status = (error as { status?: unknown }).status === 409 ? 409 : 500;+ return json(res, status, { error: error instanceof Error ? error.message : "Could not save the registration" });+ }+ };+}diff --git a/server/testing/control-plane-stub.ts b/server/testing/control-plane-stub.tsindex 97eb24444a..8f214c65bd 100644--- a/server/testing/control-plane-stub.ts+++ b/server/testing/control-plane-stub.ts@@ -149,7 +149,7 @@ export async function startControlPlaneStub(options: { otp?: string; endpointUrl}if (method === "DELETE") return send(204);}- const push = /^\/v1\/installations\/self\/push\/(register|unregister|send)$/.exec(path);+ const push = /^\/v1\/installations\/self\/push\/(register|unregister|send|activity)$/.exec(path);if (push && method === "POST") {const inst = byCredential();if (!inst) return send(401, { error: "unauthorized" });