Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Phone push: no Team Cloud Live Activities, per-phone limits, truthful Cloud answer

milind-sonif3476a5a64c8
diff --git a/cloudflare/control-plane/README.md b/cloudflare/control-plane/README.md
index cd6c362462..62efed913b 100644
--- a/cloudflare/control-plane/README.md
+++ b/cloudflare/control-plane/README.md
@@ -328,9 +328,10 @@ that runs it checks the home's own signature and relays its calls here, keyed
by the home's machine id:
- `POST /v1/cloud-homes/<machine id>/push/register`, `unregister`, `send` and
- `activity` take exactly the installation routes' bodies, schemas, answers and
- limits (50 tokens, 120 registrations, 600 sends and 60 per token an hour,
- each per machine), and send through the same path to APNs and FCM. A send
+ `activity` take exactly the installation routes' bodies, schemas and answers,
+ and their limits per machine (50 tokens, 120 registrations and 60 sends per
+ token an hour) except sends: 200 an hour per machine (`CLOUD_HOME_SEND_LIMIT`,
+ 1% of the fleet's), not 600, and send through the same path to APNs and FCM. A send
reaches only a token registered under the same machine id (`404
push_device_unknown` otherwise), never an installation's.
- `POST /v1/cloud-homes/<machine id>/push/forget` deletes every token and rate
diff --git a/cloudflare/control-plane/src/push-cloud-homes.ts b/cloudflare/control-plane/src/push-cloud-homes.ts
index 1298f9add2..ac57344598 100644
--- a/cloudflare/control-plane/src/push-cloud-homes.ts
+++ b/cloudflare/control-plane/src/push-cloud-homes.ts
@@ -27,10 +27,13 @@ const SECRET_MIN_LENGTH = 32;
/** The fleet's row in machine_push_rate_limits: no machine id can be `*`. */
export const FLEET_ID = "*";
/** Across every Cloud home in an hour. A leaked Admin secret can name any machine id, so the per-machine limits alone
- * would not bound it; these do. They sit well above what the fleet sends today (each home's own limits are 600 sends
- * and 120 registrations an hour) and are the owner's to change. */
+ * would not bound it; these do. They sit well above what the fleet sends today (each home's own limits are
+ * CLOUD_HOME_SEND_LIMIT sends and 120 registrations an hour) and are the owner's to change. */
export const CLOUD_HOME_FLEET_SEND_LIMIT = 20_000;
export const CLOUD_HOME_FLEET_REGISTER_LIMIT = 6_000;
+/** One Cloud home's sends an hour: 1% of the fleet's, so no single home can use up what every other home shares. The
+ * Admin applies the same (openmaus-cloud server/cloud-push.ts PUSH_SEND_LIMIT). An installation keeps PUSH_SEND_LIMIT. */
+export const CLOUD_HOME_SEND_LIMIT = 200;
const FLEET_SENDS: PushLimit = { owner: FLEET_ID, action: "push_send", limit: CLOUD_HOME_FLEET_SEND_LIMIT };
const FLEET_REGISTERS: PushLimit = { owner: FLEET_ID, action: "push_register", limit: CLOUD_HOME_FLEET_REGISTER_LIMIT };
@@ -63,6 +66,7 @@ function sender(request: Request, env: Env, machineId: string): PushSender {
return {
store: MACHINE_PUSH_STORE,
fleet: [FLEET_SENDS],
+ sendLimit: CLOUD_HOME_SEND_LIMIT,
authenticate: async (read) => {
await requireCloudHomeRelay(request, env);
const row = read ? await read(machineId).first<DeviceRow>() : null;
diff --git a/cloudflare/control-plane/src/push.ts b/cloudflare/control-plane/src/push.ts
index ee8233c1a9..d1bcdaa0d8 100644
--- a/cloudflare/control-plane/src/push.ts
+++ b/cloudflare/control-plane/src/push.ts
@@ -401,6 +401,8 @@ export interface PushSender {
authenticate(read: ((ownerId: string) => D1PreparedStatement) | null): Promise<{ ownerId: string; row: DeviceRow | null }>;
/** More windows than the owner's own two (a Cloud home's fleet-wide limit). */
fleet: PushLimit[];
+ /** The owner's own sends an hour, when not PUSH_SEND_LIMIT (a Cloud home's smaller share of the fleet). */
+ sendLimit?: number;
}
/**
@@ -459,7 +461,7 @@ export async function sendAs<T extends { token: string }>(
const planned = await plan(body, row, config, now);
if (planned instanceof Response) return planned;
const limits = [
- { owner: ownerId, action: "push_send", limit: PUSH_SEND_LIMIT },
+ { owner: ownerId, action: "push_send", limit: sender.sendLimit ?? PUSH_SEND_LIMIT },
{ owner: ownerId, action: `push_send:${tokenHash.slice(0, 32)}`, limit: PUSH_DEVICE_SEND_LIMIT },
...sender.fleet,
];
diff --git a/cloudflare/control-plane/test/push-cloud-homes.test.ts b/cloudflare/control-plane/test/push-cloud-homes.test.ts
index 8c76811a02..fe6758f335 100644
--- a/cloudflare/control-plane/test/push-cloud-homes.test.ts
+++ b/cloudflare/control-plane/test/push-cloud-homes.test.ts
@@ -5,8 +5,8 @@ import { describe, expect, it } from "vitest";
import { createAuth } from "../src/auth";
import { readConfig } from "../src/config";
import { createWorker } from "../src/index";
-import { PUSH_DEVICE_LIMIT, PUSH_DEVICE_SEND_LIMIT, PUSH_REGISTER_LIMIT } from "../src/push";
-import { CLOUD_HOME_FLEET_SEND_LIMIT, FLEET_ID } from "../src/push-cloud-homes";
+import { PUSH_DEVICE_LIMIT, PUSH_DEVICE_SEND_LIMIT, PUSH_REGISTER_LIMIT, PUSH_SEND_LIMIT } from "../src/push";
+import { CLOUD_HOME_FLEET_SEND_LIMIT, CLOUD_HOME_SEND_LIMIT, FLEET_ID } from "../src/push-cloud-homes";
import fixture from "./fixtures/cloud-home-push.json";
const BASE_URL = "https://auth.openmausbot.test";
@@ -187,6 +187,22 @@ describe("phone push for Cloud homes (the Admin's machine routes)", () => {
expect(await count("SELECT COUNT(*) AS n FROM machine_push_rate_limits WHERE machine_id = ? AND action = 'push_send'", OTHER)).toBe(0);
});
+ it("gives each machine 1% of the fleet's sends an hour, below an installation's own limit", async () => {
+ expect(CLOUD_HOME_SEND_LIMIT).toBe(CLOUD_HOME_FLEET_SEND_LIMIT / 100);
+ expect(CLOUD_HOME_SEND_LIMIT).toBeLessThan(PUSH_SEND_LIMIT);
+ const worker = createWorker(fetch, fakeApns().fetch);
+ const testEnv = await pushEnv();
+ expect((await home(worker, testEnv, MACHINE, "register", registration())).status).toBe(200);
+ expect((await home(worker, testEnv, OTHER, "register", registration(TOKEN_B))).status).toBe(200);
+ const now = Date.now();
+ await env.DB.prepare("INSERT INTO machine_push_rate_limits (machine_id, action, window_started_at, attempts, updated_at) VALUES (?, 'push_send', ?, ?, ?)")
+ .bind(MACHINE, now, CLOUD_HOME_SEND_LIMIT - 1, now).run();
+ expect((await home(worker, testEnv, MACHINE, "send", alert())).status).toBe(202);
+ expect((await home(worker, testEnv, MACHINE, "send", alert())).status).toBe(429);
+ // Another home's share is its own.
+ expect((await home(worker, testEnv, OTHER, "send", alert(TOKEN_B))).status).toBe(202);
+ });
+
it("keeps at most 50 tokens a machine, as for an installation", async () => {
const worker = createWorker(fetch, fakeApns().fetch);
const testEnv = await pushEnv();
diff --git a/docs/phone-push.md b/docs/phone-push.md
index 8f4ed73de1..b18a1ec922 100644
--- a/docs/phone-push.md
+++ b/docs/phone-push.md
@@ -40,7 +40,11 @@ the computer's credential does.
On a Team Cloud each person's phone gets only the alerts that person's own
event stream would carry (their own private chats, rooms and bots they can
see), the same rule as the stream (`pushReaches` in `server/index.ts`, tested
-in `server/cloud-team-phone-push.e2e.test.ts`).
+in `server/cloud-team-phone-push.e2e.test.ts`). Live Activities and Android's
+ongoing notification are not offered on a Team Cloud: a bot's state there
+(working, waiting on an ask) is everyone's, not one person's, so it could show
+one person another's private work. A Team Cloud keeps no activity token and
+pushes no activity; closed-app alerts are unaffected.
**Switching it off.** `features.phonePush: false` in `config.json`, or
`OMB_PHONE_PUSH=0` in the server's environment, turns it off on that machine
@@ -87,7 +91,8 @@ person.
the event stream uses: bot visibility, rooms, admin-only frames, a Team
Cloud's per-person frames);
- has it had a push for the same kind and conversation in the last
- 10 seconds, or 30 pushes in the last 10 minutes.
+ 10 seconds, or 60 pushes in the last hour (40 for a finished reply; see
+ "Rate limits").
5. **The server asks the control plane to send**
(`POST /v1/installations/self/push/send`) with the kind, a title made from
names, ids, the phone's tag for this computer, and a notification
@@ -112,16 +117,16 @@ carry it (`400 invalid_request`, not silently dropped).
| Field | Example | Notes |
| --- | --- | --- |
| kind | `approval` | `approval`, `question`, `sign-in`, `done` |
-| title | `Scout needs approval` | the server's own notification line for that kind, from names only, in the conversation's language |
+| title | `Scout needs approval` | the server's own notification line for that kind, from the bot's name only (never the room's), in the conversation's language |
| bot id, bot name | `bot_…`, `Scout` | |
| thread id | `th_…` | which conversation to open |
-| room id, room name | `grp_…`, `Launch` | only in a room |
+| room id, room name | `grp_…`, `Launch` | only in a room; for the app once it is open, not on the lock screen |
| pairing | the phone's random tag for this computer | so a tap opens the right one of several saved computers |
| collapse id | `openmaus.<thread>.<seq>` | see "No duplicates" |
What the lock screen reads, by kind:
-- approval: "Scout needs approval" (in a room: "Scout in Launch needs approval")
+- approval: "Scout needs approval" (in a room too: the room is left out)
- question: "Scout has a question"
- sign-in: "Scout needs you to sign in to a website" (the website is left out)
- finished reply: "Scout finished"
@@ -214,23 +219,26 @@ phone then still gets "Scout finished" from that computer; a tap opens
nothing, because the computer is no longer saved.
**Rate limits.** On the server: one push per phone, kind and conversation in
-10 seconds, 30 per phone in 10 minutes. In the control plane: 600 sends per
-installation and 60 per token per hour, 120 registrations per hour, 50 tokens
-per installation; the same per Cloud home, plus 20,000 sends and 6,000
-registrations an hour across every Cloud home together. The Admin applies the
-same per-home and fleet limits before it forwards anything.
-
-With phone push on by default these stay as they are. Every limit but the
-fleet's is per phone, per installation or per home, so more machines with push
-on do not bring any of them closer. Only phones that registered cost anything,
-and a phone sends an unchanged registration again only about once a day, so
-the registration limits are far off. The fleet's 20,000 sends an hour are
-shared by every Cloud home: about 66 an hour each if 300 homes push at once,
-where one person's closed phone gets an alert per approval, question, sign-in
-or finished reply. That count is the one to watch as Clouds grow. One known
-mismatch is older than the default: a server allows a phone up to 180 pushes an
-hour (30 in 10 minutes), the control plane 60 per token, and its `429` pauses
-all of that server's pushes for a minute and drops the waiting ones.
+10 seconds, and 60 pushes per phone an hour, alerts and Live Activity changes
+together, the same as the control plane allows a token. Finished replies and
+activity changes stop at 40 in that hour, so a bot looping finished replies
+leaves the last 20 for approvals, questions and sign-ins. When the relay answers
+`429`, only that phone is left alone for the wait it names (a minute) and only
+its waiting pushes are dropped; every other phone's go on. In the control
+plane: 600 sends per installation and 60 per token per hour, 120 registrations
+per hour, 50 tokens per installation. A Cloud home gets 200 sends an hour (1% of
+the fleet's), 60 per token, 120 registrations and 50 tokens, and every Cloud
+home together 20,000 sends and 6,000 registrations an hour. The Admin applies
+the same per-home and fleet limits before it forwards anything, and alerts its
+operators once in an hour when the fleet reaches half of its sends.
+
+With phone push on by default, every limit but the fleet's is per phone, per
+installation or per home, so more machines with push on do not bring any of
+them closer. Only phones that registered cost anything, and a phone sends an
+unchanged registration again only about once a day, so the registration limits
+are far off. The fleet's 20,000 sends an hour are shared by every Cloud home;
+with each home held to 1%, it takes a hundred homes at their own limit to use
+them all, and the Admin's alert comes at fifty.
**Replay and forgery.** Every relay call needs the installation credential.
A send reaches only a token that the same installation registered, so a
@@ -274,9 +282,12 @@ on.
outbox, retries and back-off: `503 push_unavailable`, a `401` or a `404` (an
Admin with its switch off, or an older one) leaves it alone for an hour. On by
default like every server; `features.phonePush: false` or `OMB_PHONE_PUSH=0`
- on the home turns it off there. A home cannot see the Admin's switch, so while
- that switch is off it still tells its phones `on` and its pushes are refused.
- The Admin does not write `OMB_PHONE_PUSH` into a home's environment.
+ on the home turns it off there. When the Admin refuses (`404` other than
+ `push_device_unknown`, or `503 push_unavailable`), the home tells its phones
+ `off` for that hour, so a phone shows its "hasn't turned on" line and registers
+ again at each connect; once the hour is over the next registration tries the
+ Admin again. The Admin does not write `OMB_PHONE_PUSH` into a home's
+ environment.
- **The Admin** checks the signature, takes the machine id from it, checks the
body against the control plane's own strict schemas (no field for message
text), applies the limits, and forwards the parsed body. Its switch is
diff --git a/server/cloud-team-phone-push.e2e.test.ts b/server/cloud-team-phone-push.e2e.test.ts
index e484e0c5c2..0e2d6340e1 100644
--- a/server/cloud-team-phone-push.e2e.test.ts
+++ b/server/cloud-team-phone-push.e2e.test.ts
@@ -1,7 +1,9 @@
// Phone push on a Team Cloud, on by default (docs/phone-push.md): a stand-in Admin records what the Cloud asks it to relay.
// Acme's Owner Cleo and a member Ben each pair a phone and register it for closed-app alerts, with no switch set anywhere
// on the Cloud. A reply that finishes in one person's own private chat wakes only that person's phone, signed as this
-// Cloud's machine, with names only and never the words. Disposable homes; nothing leaves this machine.
+// Cloud's machine, with names only and never the words. Live Activities are not offered on a Team Cloud (a bot's state
+// there is everyone's, not one person's): a phone's activity tokens are neither kept nor registered, and no activity is
+// ever pushed. Disposable homes; nothing leaves this machine.
import { existsSync, rmSync, writeFileSync } from "node:fs";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
@@ -17,6 +19,8 @@ const BEN = { email: "[email protected]", role: "member" as const };
const TEAM_MACHINE = "0d9e8f7a-6b5c-4d3e-9f8a-7b6c5d4e3f2a";
const CLEO_TOKEN = "c1".repeat(32);
const BEN_TOKEN = "b2".repeat(32);
+const START_TOKEN = "5a".repeat(40);
+const ACTIVITY_TOKEN = "ac".repeat(40);
const ENGINE = `process.env.FAKE_CLAUDE_DUMP = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/dump.json";
process.env.FAKE_CLAUDE_REPLY_FILE = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/reply.txt";`;
@@ -99,6 +103,18 @@ it("with no switch set, both phones register through the Admin, signed as this C
]);
}, hostTimeout(60_000));
+it("offers no Live Activities: a phone's activity tokens are neither kept nor registered", async () => {
+ for (const token of [cleo, ben]) {
+ const put = await team.as(token, "PUT", "/api/push/activity", {
+ scheme: "openmausbot", headlines: { needsYou: "{name} needs you", working: "{name} is working" },
+ startToken: START_TOKEN, activities: [{ botId: scout.id, token: ACTIVITY_TOKEN }],
+ });
+ expect(put.status, JSON.stringify(put.body)).toBe(200);
+ expect(put.body).toEqual({ push: "on", activity: null });
+ }
+ expect(relayed.filter((call) => call.action !== "register" || call.body.purpose !== undefined)).toEqual([]);
+}, hostTimeout(60_000));
+
it("a reply finishing in one person's private chat wakes only that person's phone, with names and never the words", async () => {
const bensThread = await privateTurn(ben, "Ben and Scout", "Draft my resignation letter for Globex", "Here is the letter.");
await until(() => sends().length >= 1, 30_000);
@@ -115,4 +131,6 @@ it("a reply finishing in one person's private chat wakes only that person's phon
]);
expect(sends()[0]!.body.notification).toEqual({ kind: "done", title: "Scout finished", botId: scout.id, botName: "Scout", threadId: bensThread });
expect(relayed.map((call) => call.raw).join("")).not.toMatch(/resignation|Globex|letter|salary|summary|board|Ben and Scout|Cleo and Scout/);
+ // Neither person's phone was sent another's work, or anyone's, as a Live Activity.
+ expect(relayed.filter((call) => call.action === "activity")).toEqual([]);
}, hostTimeout(120_000));
diff --git a/server/index.ts b/server/index.ts
index c0cc5e72dd..3bbedc4efd 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -4568,7 +4568,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 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 });
+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, available: () => CLOUD_TEAM === null, /* a Team Cloud: a bot's state is everyone's, not one person's */ 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 {
diff --git a/server/phone-activity.test.ts b/server/phone-activity.test.ts
index 2850030d53..9504273d3f 100644
--- a/server/phone-activity.test.ts
+++ b/server/phone-activity.test.ts
@@ -4,7 +4,7 @@ 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";
+import { PhonePush, PUSH_DEVICE_LOW_MAX } from "./phone-push.ts";
const CREDENTIAL = `omb_install_${"a".repeat(22)}.${"b".repeat(43)}`;
const START = "5a".repeat(40);
@@ -23,7 +23,7 @@ beforeEach(() => {
});
afterEach(() => rmSync(dataDir, { recursive: true, force: true }));
-function harness(options: { enabled?: boolean; live?: Set<string>; openAsks?: Set<string>; answers?: Array<{ status: number; error?: string }> } = {}) {
+function harness(options: { enabled?: boolean; available?: 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) => {
@@ -49,6 +49,7 @@ function harness(options: { enabled?: boolean; live?: Set<string>; openAsks?: Se
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: () => {} },
+ ...(options.available === undefined ? {} : { available: () => options.available! }),
});
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. */
@@ -77,6 +78,16 @@ describe("registering a phone's activities", () => {
expect(calls).toEqual([]);
});
+ it("is not offered where a bot's state is everyone's (a Team Cloud): keeps nothing, registers nothing, pushes nothing", async () => {
+ const { activity, calls, step } = harness({ available: false, live: new Set() });
+ expect(await activity.register(IPHONE, registration({ startToken: START, activities: [{ botId: "bot_1", token: ACT }] }))).toBe("off");
+ expect(activity.registration(IPHONE)).toBeNull();
+ await step({ ask: true }, notify("approval"), everyone);
+ await step({ busy: true }, runtime("turn.started"), everyone);
+ await step({ busy: false, ask: false }, runtime("turn.completed"), everyone);
+ 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 } }));
@@ -168,6 +179,18 @@ describe("pushing a bot's activity while the app is closed", () => {
expect(activityCalls().map((body) => body.event)).toEqual(["end"]);
});
+ it("counts its pushes against the phone's hourly cap, at the lower priority, leaving the rest for its alerts", async () => {
+ const { push, activity, activityCalls, calls, step } = harness();
+ await push.register(ANDROID, { platform: "fcm", token: FCM });
+ await activity.register(ANDROID, registration({ ongoing: true }));
+ for (let change = 0; change < PUSH_DEVICE_LOW_MAX + 5; change += 1) await step({ busy: change % 2 === 0 }, runtime(change % 2 === 0 ? "turn.started" : "turn.completed"));
+ expect(activityCalls()).toHaveLength(PUSH_DEVICE_LOW_MAX);
+ // An approval still reaches the phone.
+ push.offer({ notification: { kind: "approval", botId: "bot_1", botName: "Scout", threadId: "th_1" }, seq: 1 }, everyone);
+ await push.flush();
+ expect(calls.filter((call) => call.path.endsWith("/push/send"))).toHaveLength(1);
+ });
+
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 }] }));
diff --git a/server/phone-activity.ts b/server/phone-activity.ts
index 71b6996d40..b1f93d56d9 100644
--- a/server/phone-activity.ts
+++ b/server/phone-activity.ts
@@ -1,7 +1,9 @@
// 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.
+// activity. Names, kind and the phone's headline only. It rides phone push's switch, store rules and relay access, and
+// its per-phone hourly cap. Not on a Team Cloud: a bot's state there (busy, waiting on an ask) is everyone's, not one
+// person's, so it would show one person another's private work.
import { mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { z } from "zod";
@@ -76,6 +78,8 @@ export interface PhoneActivityOptions {
bot: (botId: string) => { name: string; busy: boolean; threadId: string } | undefined;
/** The bot a conversation belongs to. */
botOfThread: (threadId: string) => string | undefined;
+ /** False where activities are not offered at all (a Team Cloud): nothing is kept and nothing is pushed. */
+ available?: () => boolean;
now?: () => number;
log?: (line: string) => void;
/** Frames for one bot gather this long before its state is read again. */
@@ -156,7 +160,7 @@ export class PhoneActivity {
/** 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";
+ if (this.options.push.status() === "off" || this.options.available?.() === false) 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 });
@@ -210,7 +214,7 @@ export class PhoneActivity {
*/
offer(payload: Record<string, unknown>, reaches: (key: string) => boolean): void {
try {
- if (!this.phones.length || this.options.push.status() !== "on") return;
+ if (!this.phones.length || this.options.push.status() !== "on" || this.options.available?.() === false) return;
const botId = this.botOf(payload);
if (!botId) return;
this.reach.set(botId, reaches);
@@ -376,8 +380,9 @@ export class PhoneActivity {
}
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 answer = await this.options.push.callFor(key, PHONE_ACTIVITY_RELAY_PATH, body);
const base = { key, botId, event: body.event, via } as const;
+ if (answer === "capped") return { ...base, result: "dropped" };
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") {
diff --git a/server/phone-push-admin.test.ts b/server/phone-push-admin.test.ts
index 7900685105..46ac1b369e 100644
--- a/server/phone-push-admin.test.ts
+++ b/server/phone-push-admin.test.ts
@@ -168,6 +168,46 @@ describe("a Cloud home's pushes through its Admin", () => {
}
});
+ it("tells its phones `off` while the Admin refuses (switch off, or no relay), and `on` again once it takes them", async () => {
+ for (const refusal of [{ status: 404, error: "Not found." }, { status: 503, error: "push_unavailable" }]) {
+ const { push, admin } = harness();
+ admin.answers.push(refusal);
+ // Refused at registration: the phone hears `off` (its "hasn't turned on" line) and registers again at its next sync.
+ expect(await push.register(PHONE, { platform: "apns", token: APNS })).toMatchObject({ push: "off", relay: "pending" });
+ expect(push.status()).toBe("off");
+ expect((await push.register(PHONE, { platform: "apns", token: APNS })).push).toBe("off");
+ push.offer({ notification: notification("th_1"), seq: 1 }, everyone);
+ await push.flush();
+ expect(admin.calls).toHaveLength(1);
+ await advance(push, RELAY_UNAVAILABLE_PAUSE_MS);
+ expect(push.status()).toBe("on");
+ expect(await push.register(PHONE, { platform: "apns", token: APNS })).toMatchObject({ push: "on", relay: "registered" });
+ rmSync(join(dataDir, "push-devices.json"), { force: true });
+ }
+ // Refused while sending: the same.
+ const { push, admin } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ admin.answers.push({ status: 404, error: "Not found." });
+ push.offer({ notification: notification("th_1"), seq: 1 }, everyone);
+ await push.flush();
+ expect(push.status()).toBe("off");
+ // A lost token (404 push_device_unknown) is not a refusal.
+ const other = harness();
+ await other.push.register(PHONE, { platform: "apns", token: APNS });
+ other.admin.answers.push({ status: 404, error: "push_device_unknown" });
+ other.push.offer({ notification: notification("th_1"), seq: 1 }, everyone);
+ await other.push.flush();
+ expect(other.push.status()).toBe("on");
+ });
+
+ it("an installation's refusal leaves the answer `on`: its relay's switch is the control plane's, as before", async () => {
+ const credential = { controlPlane: "https://accounts.openmausbot.com", credential: CREDENTIAL };
+ const { push, admin } = harness({ access: () => credential });
+ admin.answers.push({ status: 503, error: "push_unavailable" });
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ expect(push.status()).toBe("on");
+ });
+
it("registers again and retries once when the control plane has lost the token", async () => {
const { push, admin } = harness();
await push.register(PHONE, { platform: "apns", token: APNS });
diff --git a/server/phone-push.test.ts b/server/phone-push.test.ts
index a73c41be23..732cb671ce 100644
--- a/server/phone-push.test.ts
+++ b/server/phone-push.test.ts
@@ -9,7 +9,9 @@ import {
PHONE_PUSH_DESKTOP_MESSAGE,
PHONE_PUSH_FILE,
PUSH_COALESCE_MS,
+ PUSH_DEVICE_LOW_MAX,
PUSH_DEVICE_WINDOW_MAX,
+ PUSH_DEVICE_WINDOW_MS,
PUSH_MAX_AGE_MS,
PUSH_RETRY_MS,
PhonePush,
@@ -278,7 +280,7 @@ describe("offering a notify frame", () => {
]);
});
- it("names the room, and leaves a frame alone that is not a notification", async () => {
+ it("names the room beside the push but never in the lock screen's title, and leaves a frame alone that is not a notification", async () => {
const { push, relay } = harness({ room: () => ({ id: "grp_1", name: "Launch\nteam" }) });
await push.register(PHONE, { platform: "apns", token: APNS });
push.offer({ notification: notification(), seq: 1 }, everyone);
@@ -287,7 +289,7 @@ describe("offering a notify frame", () => {
push.offer({ notification: notification({ botId: "bad id" }), seq: 4 }, everyone);
await push.flush();
expect(relay.sends().map((call) => call.body.notification)).toEqual([
- { kind: "approval", title: "Scout in Launch team needs approval", botId: "bot_1", botName: "Scout", threadId: "th_1", roomId: "grp_1", roomName: "Launch team" },
+ { kind: "approval", title: "Scout needs approval", botId: "bot_1", botName: "Scout", threadId: "th_1", roomId: "grp_1", roomName: "Launch team" },
]);
});
@@ -305,12 +307,41 @@ describe("offering a notify frame", () => {
expect(relay.sends().map((call) => call.body.collapseId)).toEqual(["openmaus.th_1.1", "openmaus.th_1.3", "openmaus.th_1.4"]);
});
- it("stops a looping bot buzzing a pocket", async () => {
+ it("stops a looping bot buzzing a pocket: 60 an hour, as the relay allows a phone", async () => {
+ expect([PUSH_DEVICE_WINDOW_MAX, PUSH_DEVICE_WINDOW_MS]).toEqual([60, 60 * 60_000]);
const { push, relay } = harness();
await push.register(PHONE, { platform: "apns", token: APNS });
for (let seq = 0; seq < PUSH_DEVICE_WINDOW_MAX + 5; seq += 1) push.offer({ notification: notification({ threadId: `th_${seq}` }), seq }, everyone);
await push.flush();
expect(relay.sends()).toHaveLength(PUSH_DEVICE_WINDOW_MAX);
+ await advance(push, PUSH_DEVICE_WINDOW_MS);
+ push.offer({ notification: notification({ threadId: "th_later" }), seq: 99 }, everyone);
+ await push.flush();
+ expect(relay.sends()).toHaveLength(PUSH_DEVICE_WINDOW_MAX + 1);
+ });
+
+ it("near the cap, a finished reply gives way so approvals, questions and sign-ins still get through", async () => {
+ const { push, relay } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ for (let seq = 0; seq < PUSH_DEVICE_WINDOW_MAX; seq += 1) push.offer({ notification: notification({ kind: "done", threadId: `th_${seq}` }), seq }, everyone);
+ await push.flush();
+ expect(relay.sends()).toHaveLength(PUSH_DEVICE_LOW_MAX);
+ const asks = ["approval", "question", "sign-in"] as const;
+ for (let seq = 0; seq < PUSH_DEVICE_WINDOW_MAX; seq += 1) push.offer({ notification: notification({ kind: asks[seq % 3], threadId: `ask_${seq}` }), seq: 100 + seq }, everyone);
+ await push.flush();
+ expect(relay.sends()).toHaveLength(PUSH_DEVICE_WINDOW_MAX);
+ expect(relay.sends().slice(PUSH_DEVICE_LOW_MAX).every((call) => (call.body.notification as { kind: string }).kind !== "done")).toBe(true);
+ });
+
+ it("a Live Activity change counts against the same hour, at the lower priority", async () => {
+ const { push, relay } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ for (let index = 0; index < PUSH_DEVICE_LOW_MAX; index += 1) expect(await push.callFor(PHONE, "/v1/installations/self/push/activity", { v: 1 })).toMatchObject({ status: 200 });
+ expect(await push.callFor(PHONE, "/v1/installations/self/push/activity", { v: 1 })).toBe("capped");
+ push.offer({ notification: notification({ kind: "done" }), seq: 1 }, everyone);
+ push.offer({ notification: notification({ kind: "approval", threadId: "th_2" }), seq: 2 }, everyone);
+ await push.flush();
+ expect(relay.sends().map((call) => (call.body.notification as { kind: string }).kind)).toEqual(["approval"]);
});
});
@@ -374,15 +405,25 @@ describe("the outbox", () => {
expect(relay.sends()).toHaveLength(1);
await advance(push, 1);
expect(relay.sends()).toHaveLength(1);
+ });
+ it("over a limit, leaves only that phone alone for the relay's wait, and keeps every other phone's pushes", async () => {
+ const { push, relay } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ await push.register(OTHER, { platform: "fcm", token: FCM });
relay.answers.push({ status: 429, error: "rate_limited", retryAfter: 120 });
+ // The first send (PHONE's) is refused; OTHER's, waiting behind it, still goes.
push.offer({ notification: notification({ threadId: "th_3" }), seq: 3 }, everyone);
await push.flush();
+ expect(relay.sends().map((call) => call.body.token)).toEqual([APNS, FCM]);
push.offer({ notification: notification({ threadId: "th_4" }), seq: 4 }, everyone);
- await advance(push, 119_000);
- expect(relay.sends()).toHaveLength(2);
- await advance(push, 1_000);
- expect(relay.sends().at(-1)!.body.collapseId).toBe("openmaus.th_4.4");
+ await push.flush();
+ expect(relay.sends().map((call) => call.body.token)).toEqual([APNS, FCM, FCM]);
+ expect(push.pending()).toBe(0);
+ await advance(push, 120_000);
+ push.offer({ notification: notification({ threadId: "th_5" }), seq: 5 }, everyone);
+ await push.flush();
+ expect(relay.sends().slice(3).map((call) => [call.body.token, call.body.collapseId])).toEqual([[APNS, "openmaus.th_5.5"], [FCM, "openmaus.th_5.5"]]);
});
it("never throws into the server", async () => {
diff --git a/server/phone-push.ts b/server/phone-push.ts
index 95aa92aa1c..50588e5779 100644
--- a/server/phone-push.ts
+++ b/server/phone-push.ts
@@ -48,8 +48,14 @@ export const MAX_PUSH_DEVICES = 50;
/** One push per phone, kind and conversation in this window; the newest waiting one replaces an older one. */
export const PUSH_COALESCE_MS = 10_000;
-export const PUSH_DEVICE_WINDOW_MS = 10 * 60_000;
-export const PUSH_DEVICE_WINDOW_MAX = 30;
+/** Pushes one phone gets in an hour, alerts and Live Activity changes together: the relay's own per-phone limit. */
+export const PUSH_DEVICE_WINDOW_MS = 60 * 60_000;
+export const PUSH_DEVICE_WINDOW_MAX = 60;
+/** Finished replies and Live Activity changes stop here, so a noisy bot leaves the rest of the hour for approvals,
+ * questions and sign-ins. */
+export const PUSH_DEVICE_LOW_MAX = 40;
+/** How long one phone is left alone after the relay said it is over a limit, when the relay names no wait. */
+export const PUSH_DEVICE_THROTTLE_MS = 60_000;
/** A push still undelivered after this is dropped: the phone shows the news when it next connects. */
export const PUSH_MAX_AGE_MS = 10 * 60_000;
/** Waits before each retry of a push the relay could not take (network, 5xx). */
@@ -101,7 +107,9 @@ export interface InstallationPushAccess {
/** The control plane with an installation credential, or (a Cloud home) its Admin with its bootstrap secret. */
export type PhonePushAccess = InstallationPushAccess | CloudHomePushAccess;
-export type PushOutcome = "sent" | "dropped" | "stale" | "live" | "gone" | "failed" | "retry" | "paused";
+export type PushOutcome = "sent" | "dropped" | "stale" | "live" | "gone" | "failed" | "retry" | "paused" | "throttled";
+/** An ask wakes the person; a finished reply or a Live Activity change can wait for the app to open. */
+export type PushPriority = "ask" | "other";
export interface PhonePushOptions {
dataDir: string;
@@ -161,10 +169,10 @@ export function phonePushNotification(notification: PushableNotification, room?:
const botName = clip(notification.botName, PUSH_NAME_MAX) || "MausBot";
const roomName = room && PUSH_ID.test(room.id) ? clip(room.name, PUSH_NAME_MAX) : "";
const language = conversationLanguage(notification.threadId);
- const who = roomName ? serverLine(language, "server.notify.inRoom", { bot: botName, room: roomName }) : botName;
+ // The lock screen shows the title: the bot's name only, never the room's, which the app shows once it is open.
return {
kind: notification.kind,
- title: clip(serverLine(language, TITLES[notification.kind], { who }), PUSH_TITLE_MAX),
+ title: clip(serverLine(language, TITLES[notification.kind], { who: botName }), PUSH_TITLE_MAX),
botId: notification.botId,
botName,
threadId: notification.threadId,
@@ -183,6 +191,10 @@ export class PhonePush {
private readonly lastBySlot = new Map<string, number>();
private readonly outbox = new Map<string, Job>();
private pausedUntil = 0;
+ /** Phones the relay said were over a limit, until when. Other phones go on. */
+ private readonly phonePausedUntil = new Map<string, number>();
+ /** A Cloud home's Admin said it relays no push (its switch off, or no relay): until then this home answers `off`. */
+ private refusedUntil = 0;
private timer: unknown = null;
private draining: Promise<void> | null = null;
private readonly options: PhonePushOptions;
@@ -215,7 +227,12 @@ export class PhonePush {
status(): PhonePushState {
if (!this.options.enabled()) return "off";
- return this.options.access() ? "on" : "no-account";
+ const access = this.options.access();
+ if (!access) return "no-account";
+ // A Cloud home cannot see its Admin's switch; while the Admin refuses, saying `on` would tell the phone untruly that
+ // alerts arrive with the app closed.
+ if (!("credential" in access) && this.now() < this.refusedUntil) return "off";
+ return "on";
}
private publicDevice(key: string): PublicPushDevice | null {
@@ -239,6 +256,39 @@ export class PhonePush {
return this.relay(path, body);
}
+ /** One push for the phone behind `key` (a Live Activity or ongoing-notification change), under the same hourly cap as
+ * its alerts at the lower priority; "capped" when there is no room for it, or the relay asked to leave that phone alone. */
+ async callFor(key: string, path: string, body: unknown): Promise<RelayAnswer | "capped" | null> {
+ if (!this.roomFor(key, "other", this.now())) return "capped";
+ const answer = await this.relay(path, body);
+ if (answer && answer.status < 300) this.noteSent(key, this.now());
+ if (answer?.status === 429) this.throttle(key, answer.retryAfterMs);
+ return answer;
+ }
+
+ private recent(key: string, now: number): number[] {
+ const recent = (this.sent.get(key) ?? []).filter((at) => now - at < PUSH_DEVICE_WINDOW_MS);
+ if (recent.length) this.sent.set(key, recent);
+ else this.sent.delete(key);
+ return recent;
+ }
+
+ /** Whether one more push of this priority fits this phone's hour, and the relay has not asked to leave it alone. */
+ private roomFor(key: string, priority: PushPriority, now: number): boolean {
+ if ((this.phonePausedUntil.get(key) ?? 0) > now) return false;
+ return this.recent(key, now).length < (priority === "ask" ? PUSH_DEVICE_WINDOW_MAX : PUSH_DEVICE_LOW_MAX);
+ }
+
+ private noteSent(key: string, now: number): void {
+ this.sent.set(key, [...this.recent(key, now), now]);
+ }
+
+ /** The relay said this phone is over a limit: leave it alone for the wait it named, and drop what waits for it. */
+ private throttle(key: string, retryAfterMs: number | undefined): void {
+ this.phonePausedUntil.set(key, this.now() + Math.min(Math.max(retryAfterMs ?? PUSH_DEVICE_THROTTLE_MS, 1_000), 60 * 60_000));
+ for (const [slot, job] of this.outbox) if (job.key === key) this.outbox.delete(slot);
+ }
+
answer(key: string): PhonePushAnswer {
return { push: this.status(), device: this.publicDevice(key) };
}
@@ -269,6 +319,7 @@ export class PhonePush {
if (previous && previous.token !== next.token) this.dropFromRelay(previous);
if (this.status() !== "on") return { ...this.answer(key), relay: "off" };
const answer = await this.relay(PHONE_PUSH_RELAY_PATHS.register, this.registerBody(next));
+ // A Cloud home's Admin that refused makes the answer `off`, so the phone says so and registers again at its next sync.
return { ...this.answer(key), relay: answer && answer.status < 300 ? "registered" : "pending" };
}
@@ -315,7 +366,7 @@ export class PhonePush {
const collapseId = phonePushCollapseId(push.threadId, frame.seq);
const now = this.now();
for (const device of this.devices) {
- if (!device.kinds.includes(notification.kind) || this.options.live(device.key) || !reaches(device.key)) continue;
+ if (!device.kinds.includes(notification.kind) || (this.phonePausedUntil.get(device.key) ?? 0) > now || this.options.live(device.key) || !reaches(device.key)) continue;
const slot = `${device.key}|${push.kind}|${push.threadId}`;
const waiting = this.outbox.get(slot);
if (!waiting && now - (this.lastBySlot.get(slot) ?? -Infinity) < PUSH_COALESCE_MS) continue;
@@ -385,8 +436,8 @@ export class PhonePush {
if (now - job.queuedAt > PUSH_MAX_AGE_MS) return "stale";
// The phone connected while this waited: its stream delivers the frame itself.
if (this.options.live(job.key)) return "live";
- const recent = (this.sent.get(job.key) ?? []).filter((at) => now - at < PUSH_DEVICE_WINDOW_MS);
- if (recent.length >= PUSH_DEVICE_WINDOW_MAX) return "dropped";
+ // Near the hour's cap a finished reply gives way, so the asks still get through.
+ if (!this.roomFor(job.key, job.push.kind === "done" ? "other" : "ask", now)) return "dropped";
const body = { v: PHONE_PUSH_WIRE_VERSION, token: device.token, ...(device.pairing ? { pairing: device.pairing } : {}), ...(job.collapseId ? { collapseId: job.collapseId } : {}), notification: job.push };
let answer = await this.relay(PHONE_PUSH_RELAY_PATHS.send, body);
if (answer?.status === 404 && answer.code === PUSH_RELAY_ERRORS.unknownDevice) {
@@ -395,7 +446,7 @@ export class PhonePush {
}
if (!answer) return "retry";
if (answer.status < 300) {
- this.sent.set(job.key, [...recent, now]);
+ this.noteSent(job.key, now);
this.lastBySlot.set(job.slot, now);
if (this.lastBySlot.size > 2_000) this.lastBySlot.clear();
return "sent";
@@ -406,7 +457,11 @@ export class PhonePush {
return "gone";
}
if (answer.code === PUSH_RELAY_ERRORS.unavailable || answer.status === 401 || answer.status === 404) return this.pause(RELAY_UNAVAILABLE_PAUSE_MS);
- if (answer.status === 429) return this.pause(answer.retryAfterMs ?? 60_000);
+ // Over a limit: only this phone waits. Should the limit be the home's or the fleet's, each phone learns so once.
+ if (answer.status === 429) {
+ this.throttle(job.key, answer.retryAfterMs);
+ return "throttled";
+ }
if (answer.status >= 500) return "retry";
return "failed";
}
@@ -430,6 +485,10 @@ export class PhonePush {
const response = await this.fetchImpl(request.url, { ...request.init, redirect: "error", signal: AbortSignal.timeout(RELAY_TIMEOUT_MS) });
const payload = await response.json().catch(() => null) as { error?: unknown } | null;
const retryAfter = Number(response.headers.get("retry-after"));
+ const code = typeof payload?.error === "string" ? payload.error : undefined;
+ if (!("credential" in access) && (code === PUSH_RELAY_ERRORS.unavailable || (response.status === 404 && code !== PUSH_RELAY_ERRORS.unknownDevice))) {
+ this.refusedUntil = this.now() + RELAY_UNAVAILABLE_PAUSE_MS;
+ }
return {
status: response.status,
...(typeof payload?.error === "string" ? { code: payload.error } : {}),