Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Phone push on by default for anyone who pairs
milind-sonicff19344805b
diff --git a/cloudflare/control-plane/README.md b/cloudflare/control-plane/README.mdindex 7f5377b22a..cd6c362462 100644--- a/cloudflare/control-plane/README.md+++ b/cloudflare/control-plane/README.md@@ -194,6 +194,9 @@ Closed-app alerts for the phone app, on iPhone through APNs and on Androidthrough Firebase Cloud Messaging (HTTP v1). The design, the threat model andthe switch-on steps are in `docs/phone-push.md`; the harness side is`server/phone-push.ts`, its wire types `packages/phone-protocol/src/phone-push.ts`.+Every desktop, server and Cloud home has phone push on by default ("Who gets+it" in that document) and calls these routes only for a phone that paired and+registered; one with no paired phone never calls them.Apple accepts pushes for an App Store or TestFlight build only when they aresigned with the publishing team's key, and Google only from a service accountof the Firebase project the Android build is registered in. So the project'sdiff --git a/docs/ios-privacy.md b/docs/ios-privacy.mdindex 527b5261e5..e226c7a8ae 100644--- a/docs/ios-privacy.md+++ b/docs/ios-privacy.md@@ -52,7 +52,9 @@ account. A user may separately sign in on the desktop to enable the optionalthe hosted control-plane database.- Closed-app alerts: when the phone allows notifications, the app gives itspaired computer the Apple Push Notification service device token for this- app install. A computer with optional hosted access registers that token+ app install. A computer with optional hosted access, or a MausBot Cloud+ through its Admin, registers that token (phone push is on by default, and+ nothing is registered until a paired phone gives its token)with the OpenMausBot control plane, which stores it with the installationID, the APNs environment and timestamps so it can ask Apple to deliver analert. An alert carries only its kind, the bot's and room's names anddiff --git a/docs/phone-push.md b/docs/phone-push.mdindex e4cab33f71..8f4ed73de1 100644--- a/docs/phone-push.md+++ b/docs/phone-push.md@@ -9,8 +9,52 @@ swiped away, nothing arrives.This document describes real push: Apple's push service (APNs) on iPhone andFirebase Cloud Messaging (FCM) on Android wake the phone even when the app is-closed. The code for every part is in place and switched off. Nothing changes-until the owner supplies the keys and turns it on (see "Switching it on").+closed. It is on by default for anyone who pairs a phone: there is no setting+to find (see "Who gets it"). The keys are in place on iPhone; Android does not+have push yet (see "Switching it on").++## Who gets it++Phone push is on by default on every desktop, every Cloud home (My Cloud and+Team Cloud) and every `openmausbot serve` server. It does anything only for a+phone that is paired and registers: a computer with no paired phone keeps no+registration, makes no call to the control plane or the Admin, sets no timer and+holds no connection for it, at start or later.++What a paired phone gets, by how it was paired. "Anywhere" is+Settings → Devices → How your phone reaches this computer → Anywhere, through MausBot,+which signs the computer in with an emailed code and stores its installation+credential.++| Paired with | Closed-app alerts | The phone app says |+| --- | --- | --- |+| A desktop, over Anywhere (the relay) | Yes, with no further step: the relay itself needs the installation credential, so the computer already has it | on |+| A Cloud (My Cloud or Team Cloud) | Yes, with no further step: the Cloud's Admin relays for it (see "Cloud homes") | on |+| A desktop on the same Wi-Fi only, never signed in | No: the computer has no account to push as. Turning Anywhere on (and signing in) is the one step; the phone's registration is already kept, and the first push after the sign-in registers it with the control plane | no-account ("Your computer isn't signed in to a MausBot account…") |+| `openmausbot serve` on a person's own server | Yes once it holds an installation credential: `openmausbot account login`, `OMB_INSTALLATION_CREDENTIAL` or `OMB_PUSH_CREDENTIAL`. Without one, as the row above | on, or no-account |++A desktop that was ever signed in for Anywhere keeps its credential, so a phone+paired with it over Wi-Fi gets pushes too. The pairing route does not matter;+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`).++**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+(only an exact `0` or `1` is read; `1` turns it on over a `false` in+`config.json`). This is an operator's kill switch; there is no setting or dialog+for it. A phone then hears `off`, and the server keeps nothing and calls nobody.+For every Cloud home at once, the Admin's `OMB_CLOUD_PHONE_PUSH` switch is the+kill switch: off, its relay routes answer `404` and homes back off for an hour.++**A phone that registered while push was off.** The server kept nothing then.+The phone app registers again at each connect while its last answer was `off`+or `no-account`, so after the desktop or Cloud updates its next connect stores+the registration and registers it with the control plane, with no step from the+person.## How it works@@ -176,6 +220,18 @@ per installation; the same per Cloud home, plus 20,000 sends and 6,000registrations an hour across every Cloud home together. The Admin applies thesame 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.+**Replay and forgery.** Every relay call needs the installation credential.A send reaches only a token that the same installation registered, so astolen credential of one computer cannot reach another computer's phones. It@@ -200,11 +256,13 @@ accepts a previous secret beside the current one.## Cloud homes-A desktop has an installation credential once its owner turns on "Use your-phone anywhere", and `openmausbot serve` has one after `openmausbot account login` or+A desktop has an installation credential once its owner turns on Anywhere+(Settings → Devices → How your phone reaches this computer → Anywhere, through MausBot),+and `openmausbot serve` has one after `openmausbot account login` orfrom `OMB_INSTALLATION_CREDENTIAL` (or a push-only `OMB_PUSH_CREDENTIAL`). A-Cloud home has none. So **the Admin relays for its homes**: built, and off-until switched on.+Cloud home has none. So **the Admin relays for its homes**, My Clouds and Team+Clouds alike, keyed by the home's machine id. It is live: the Admin's switch is+on.- **The home** (`server/phone-push-admin.ts`): when the server runs as a Cloudhome and has no installation credential, every relay call goes to its Admin@@ -214,12 +272,15 @@ until switched on.`x-omb-cloud-signature: v1=<HMAC-SHA256 over "omb-phone-push-v1", the machineid, the action, the timestamp, the nonce and the body's SHA-256>`). Sameoutbox, 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. Still- gated by `features.phonePush` / `OMB_PHONE_PUSH`, off by default.+ 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.- **The Admin** checks the signature, takes the machine id from it, checks thebody against the control plane's own strict schemas (no field for messagetext), applies the limits, and forwards the parsed body. Its switch is- `OMB_CLOUD_PHONE_PUSH` (off by default); it forwards to+ `OMB_CLOUD_PHONE_PUSH` (a live switch, off when unset, on in production); it forwards to`OMB_CLOUD_PUSH_RELAY_URL` with `OMB_CLOUD_PUSH_RELAY_SECRET`. Retiring ordeleting a Cloud deletes its tokens at the control plane, switch on or off.- **The control plane** has the matching routes,@@ -239,7 +300,7 @@ No credential lives on the home beyond the bootstrap secret it already had,nothing needs rotating every 90 days, and the Admin keeps no device token.**Switching it on for Cloud homes**, after steps 1 to 10 of "Switching it on",-in order:+in order (all done; kept as the record and for a new environment):1. Apply the control plane's migration `0019_cloud_home_push.sql`.2. Set the control plane's `CLOUD_HOME_PUSH_SECRET` (random, 32 characters or@@ -247,12 +308,12 @@ in order:3. Ship an Admin image with the relay, then set the same value as the Admin's`OMB_CLOUD_PUSH_RELAY_SECRET`, and `OMB_CLOUD_PUSH_RELAY_URL` to the controlplane's origin, and restart the Admin.-4. Ship a Cloud home image with this code.-5. Turn phone push on in one test Cloud's home: `features.phonePush: true` in- its `config.json` (its owner's `PUT /api/config`; an `OMB_PHONE_PUSH` set by- hand in a home's environment is rewritten by the Admin at its next update),- then `OMB_CLOUD_PHONE_PUSH` on in the Admin's Cloud operations → Switches.-6. Run "Test plan on real devices" against that Cloud, then widen.+4. Ship a Cloud home image with this code. Homes have phone push on by+ default; to keep one test Cloud apart, set `features.phonePush: false` on the+ others first (its owner's `PUT /api/config`; an `OMB_PHONE_PUSH` set by hand+ in a home's environment is lost at its next update).+5. Turn `OMB_CLOUD_PHONE_PUSH` on in the Admin's Cloud operations → Switches.+6. Run "Test plan on real devices" against a Cloud.## Always-on and the grace period@@ -378,7 +439,11 @@ without any MausBot account at all.## Switching it on-What the owner provides and does, in order. Nothing here has been done.+What the owner provides and does, in order. Done for iPhone: the control plane+sends with the Apple key, the Admin relays for Cloud homes with its switch on,+the iPhone build 2.0.1 registers, and servers have phone push on by default+(step 10). Android does not have push yet. The steps stay as the record and for+a new environment.**Apple**@@ -424,22 +489,22 @@ What the owner provides and does, in order. Nothing here has been done.**Desktop and server**-10. Ship the server with phone push. It stays off until- `features.phonePush: true` is in `config.json`, or `OMB_PHONE_PUSH=1` is set- (`OMB_PHONE_PUSH=0` forces it off). This is the rollout flag: turn it on- for one machine first, then flip the default in a release.+10. Ship the server with phone push. It is on by default for anyone who pairs+ (see "Who gets it"); `features.phonePush: false` in `config.json` or+ `OMB_PHONE_PUSH=0` turns it off on one machine, and `OMB_PHONE_PUSH=1` turns+ it on over a `false`. There is no setting for it.11. For Cloud homes, follow "Switching it on for Cloud homes" under "Cloudhomes".-Deploy order: migration and secrets, then the control plane, then a server-with phone push on for one test machine, then a phone build with the switch on,-then widen.+Deploy order: migration and secrets, then the control plane, then a phone+build with the switch on, then servers (on by default).## Test plan on real devicesRun each on an iPhone (TestFlight build, production APNs) and an Android-phone (release build with Google Play services), paired with a desktop that-has "Use your phone anywhere" on and `features.phonePush: true`.+phone (release build with Google Play services, once it has push), paired with+a desktop that has Anywhere on (signed in), or with a Cloud. No switch is+needed.1. Pair, then `GET /api/push/device` from the phone (or check the server's`push-devices.json`) shows a registration with the right platform.@@ -462,8 +527,12 @@ has "Use your phone anywhere" on and `features.phonePush: true`.the service and pushes resume.11. Uninstall the app, trigger an alert: the server log shows the tokendropped after the provider's `410`/`UNREGISTERED`.-12. A computer with phone push left off: nothing in the control plane's logs,+12. A computer with phone push switched off (`features.phonePush: false` or+ `OMB_PHONE_PUSH=0`): nothing in the control plane's logs,`GET /api/push/device` says `off`.+13. A desktop paired only over Wi-Fi and never signed in: the phone's footer+ says the computer isn't signed in to a MausBot account; turn Anywhere on,+ lock the phone, trigger an approval: the push arrives.## What this does not do@@ -473,7 +542,7 @@ has "Use your phone anywhere" on and `features.phonePush: true`.- **Nothing arrives if the computer is off or asleep,** or offline. Thecomputer is what notices the event and asks for the push; a sleeping Macnotices nothing. A Cloud runs all the time, so a Cloud's phones get pushes- whenever its bots work (once its Admin relays for it, see "Cloud homes").+ whenever its bots work (its Admin relays for it, see "Cloud homes").- **No push for other kinds** (mentions, routine failures, waits, notices).They arrive as today while the app is connected.- **No badge counts from push.** The badge is updated when the app runs.diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex d15ea03232..88701b8a92 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -110,6 +110,7 @@ export const VITEST_SUBSETS = {"server/cloud-team-owners.e2e.test.ts","server/cloud-team-people.e2e.test.ts","server/cloud-team-per-person.e2e.test.ts",+ "server/cloud-team-phone-push.e2e.test.ts","server/cloud-team-phones.e2e.test.ts","server/cloud-team-pictures.e2e.test.ts","server/cloud-team-presence.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 2d12905090..747d8b26be 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -250,6 +250,7 @@ describe("CI outputs", () => {"server/cloud-team-owners.e2e.test.ts","server/cloud-team-people.e2e.test.ts","server/cloud-team-per-person.e2e.test.ts",+ "server/cloud-team-phone-push.e2e.test.ts","server/cloud-team-phones.e2e.test.ts","server/cloud-team-pictures.e2e.test.ts","server/cloud-team-presence.e2e.test.ts",diff --git a/server/cloud-team-phone-push.e2e.test.ts b/server/cloud-team-phone-push.e2e.test.tsnew file mode 100644index 0000000000..e484e0c5c2--- /dev/null+++ b/server/cloud-team-phone-push.e2e.test.ts@@ -0,0 +1,118 @@+// 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.+import { existsSync, rmSync, writeFileSync } from "node:fs";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { join } from "node:path";+import { afterAll, beforeAll, expect, it } from "vitest";++import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { CLOUD_HOME_PUSH_ADMIN_PATH } from "./phone-push-admin.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const CLEO = { email: "[email protected]", role: "owner" as const };+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 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";`;++type Bot = { id: string; name: string; threadId: string; busy?: boolean; activity?: string };+type Relayed = { action: string; raw: string; body: Record<string, any>; signed: boolean };+const relayed: Relayed[] = [];+let adminServer: Server, fx: CloudSendFixture, team: CloudTeamFixture;+let cleo = "", ben = "", scout: Bot;++const sends = () => relayed.filter((call) => call.action === "send");+const file = (name: string) => join(team.home, name);+const bots = async (token: string) => (await team.as(token, "GET", "/api/bots")).body.bots as Bot[];+async function until(done: () => Promise<boolean> | boolean, timeoutMs = 60_000): Promise<void> {+ const end = Date.now() + timeoutMs;+ while (!(await done())) {+ if (Date.now() > end) throw new Error("timed out waiting");+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+}+/** One finished reply in `token`'s own private chat with Scout; its thread id. */+async function privateTurn(token: string, title: string, text: string, reply: string): Promise<string> {+ const own = await team.as(token, "POST", `/api/bots/${scout.id}/tasks`, { title });+ expect(own.status, JSON.stringify(own.body)).toBe(201);+ const threadId = own.body.task.threadId as string;+ writeFileSync(file("reply.txt"), reply);+ rmSync(file("dump.json"), { force: true });+ const sent = await team.as(token, "POST", `/api/bots/${scout.id}/messages`, { text, threadId });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ await until(() => existsSync(file("dump.json")));+ await until(async () => (await bots(cleo)).every((bot) => !bot.busy && bot.activity !== "working")+ && ((await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages as { role: string; text?: string }[]).some((row) => row.role === "bot" && row.text === reply));+ return threadId;+}++beforeAll(async () => {+ adminServer = createServer((req, res) => {+ const chunks: Buffer[] = [];+ req.on("data", (chunk) => chunks.push(chunk));+ req.on("end", () => {+ const url = req.url ?? "";+ if (!url.startsWith(CLOUD_HOME_PUSH_ADMIN_PATH)) { res.writeHead(404, { "content-type": "application/json" }); res.end(JSON.stringify({ error: "Not found." })); return; }+ const raw = Buffer.concat(chunks).toString("utf8");+ const headers = req.headers as Record<string, string>;+ const action = url.slice(CLOUD_HOME_PUSH_ADMIN_PATH.length);+ relayed.push({ action, raw, body: JSON.parse(raw), signed: (headers["x-omb-cloud-signature"] ?? "").startsWith("v1=") && headers["x-omb-cloud-machine"] === TEAM_MACHINE });+ if (action === "unregister") { res.writeHead(204); res.end(); return; }+ res.writeHead(action === "register" ? 200 : 202, { "content-type": "application/json" });+ res.end("{}");+ });+ });+ await new Promise<void>((resolve) => adminServer.listen(0, "127.0.0.1", resolve));+ fx = await launchCloudSendFixture({ onePasswordToken: "ops_fake-team-push", team: { id: "team-acme-push", name: "Acme", engine: ENGINE, env: {+ OMB_BOT_BOX: "0", FIXTURE_ADMIN_STAND_IN: `http://127.0.0.1:${(adminServer.address() as AddressInfo).port}`,+ } } });+ team = fx.team!;+ cleo = (await team.pair(CLEO)).token!;+ ben = (await team.pair(BEN)).token!;+ await bots(ben);+ const created = await team.as(cleo, "POST", "/api/bots", { name: "Scout", visibility: "everyone" });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ scout = created.body.bot as Bot;+ expect((await team.as(cleo, "PATCH", `/api/bots/${scout.id}`, { notifications: true })).status).toBe(200);+}, hostTimeout(180_000));++afterAll(async () => {+ await fx?.close();+ await new Promise((resolve) => adminServer?.close(resolve));+});++it("with no switch set, both phones register through the Admin, signed as this Cloud", async () => {+ expect(relayed).toEqual([]);+ for (const [token, device] of [[cleo, CLEO_TOKEN], [ben, BEN_TOKEN]] as const) {+ const put = await team.as(token, "PUT", "/api/push/device", { platform: "apns", token: device });+ expect(put.status, JSON.stringify(put.body)).toBe(200);+ expect(put.body).toMatchObject({ push: "on", relay: "registered", device: { platform: "apns" } });+ }+ expect(relayed.map(({ action, body, signed }) => ({ action, token: body.token, signed }))).toEqual([+ { action: "register", token: CLEO_TOKEN, signed: true },+ { action: "register", token: BEN_TOKEN, signed: true },+ ]);+}, 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);+ await new Promise((resolve) => setTimeout(resolve, 1_500));+ expect(sends().map(({ body, signed }) => ({ token: body.token, kind: body.notification.kind, threadId: body.notification.threadId, signed }))).toEqual([+ { token: BEN_TOKEN, kind: "done", threadId: bensThread, signed: true },+ ]);++ const cleosThread = await privateTurn(cleo, "Cleo and Scout", "Summarise the salary review for the board", "Here is the summary.");+ await until(() => sends().length >= 2, 30_000);+ await new Promise((resolve) => setTimeout(resolve, 1_500));+ expect(sends().slice(1).map(({ body }) => ({ token: body.token, threadId: body.notification.threadId }))).toEqual([+ { token: CLEO_TOKEN, threadId: cleosThread },+ ]);+ 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/);+}, hostTimeout(120_000));diff --git a/server/config.ts b/server/config.tsindex 991c8c24ee..ecd80fbf3d 100644--- a/server/config.ts+++ b/server/config.ts@@ -226,7 +226,7 @@ const featureConfigSchema = z.object({/** Room jobs to several members run side by side, each in a thread of its own. On unless false. */parallelRoomJobs: z.boolean().optional(),acpPlanLines: z.boolean().optional(), // An ACP agent's plan as activity lines. Off unless true.-}).extend({ agentsToolBridge: z.boolean().optional(), savedSteps: z.boolean().optional(), usbPhoneTakeover: z.boolean().optional(), cloudComputerAutoReplace: z.boolean().optional(), phonePush: z.boolean().optional(), skillBurger: z.boolean().optional(), threadTabs: z.boolean().optional(), roomFeed: z.boolean().optional(), teamBoard: z.boolean().optional() }); // skillBurger: Skill Burgers in chat, the side menu and the bot panel, and the tools that run them, on unless false; threadTabs: a bot's threads as tabs above its chat, off unless true; roomFeed: a room's threads as one feed with the open thread beside it, off unless true; teamBoard: the Team Board on a Team Cloud (docs/team-board.md), off unless true; cloudComputerAutoReplace: set a dead or silent cloud computer aside (kept seven days with its files) and give its bot a new one by itself, on unless false (OMB_CLOUD_COMPUTER_AUTO_REPLACE wins); agentsToolBridge: the find_tool / use_tool bridge, off unless true; savedSteps: repeat a computer task from its saved steps, on unless false; usbPhoneTakeover: watch and take over the bots' USB phone, off unless true; phonePush: wake a paired phone whose app is closed through the hosted push relay, off unless true (OMB_PHONE_PUSH wins)+}).extend({ agentsToolBridge: z.boolean().optional(), savedSteps: z.boolean().optional(), usbPhoneTakeover: z.boolean().optional(), cloudComputerAutoReplace: z.boolean().optional(), phonePush: z.boolean().optional(), skillBurger: z.boolean().optional(), threadTabs: z.boolean().optional(), roomFeed: z.boolean().optional(), teamBoard: z.boolean().optional() }); // skillBurger: Skill Burgers in chat, the side menu and the bot panel, and the tools that run them, on unless false; threadTabs: a bot's threads as tabs above its chat, off unless true; roomFeed: a room's threads as one feed with the open thread beside it, off unless true; teamBoard: the Team Board on a Team Cloud (docs/team-board.md), off unless true; cloudComputerAutoReplace: set a dead or silent cloud computer aside (kept seven days with its files) and give its bot a new one by itself, on unless false (OMB_CLOUD_COMPUTER_AUTO_REPLACE wins); agentsToolBridge: the find_tool / use_tool bridge, off unless true; savedSteps: repeat a computer task from its saved steps, on unless false; usbPhoneTakeover: watch and take over the bots' USB phone, off unless true; phonePush: wake a paired phone whose app is closed through the hosted push relay, on unless false (OMB_PHONE_PUSH=0 or 1 wins)const onboardingConfigSchema = z.object({completedAt: z.string().trim().max(40).optional(),version: z.number().int().min(0).max(1000).optional(),diff --git a/server/phone-push-admin.test.ts b/server/phone-push-admin.test.tsindex d6a31fc144..7900685105 100644--- a/server/phone-push-admin.test.ts+++ b/server/phone-push-admin.test.ts@@ -5,8 +5,9 @@ import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";import { PHONE_ACTIVITY_RELAY_PATH, PHONE_PUSH_RELAY_PATHS } from "../shared/phone-push.ts";+import { cloudHomeConfiguration } from "./cloud-home.ts";import { CLOUD_HOME_PUSH_ACTIONS, cloudHomePushAccess, cloudHomePushRequest, cloudHomePushSignature } from "./phone-push-admin.ts";-import { PhonePush, PhonePushAccessSource, RELAY_UNAVAILABLE_PAUSE_MS, type PhonePushOptions } from "./phone-push.ts";+import { PhonePush, PhonePushAccessSource, RELAY_UNAVAILABLE_PAUSE_MS, phonePushEnabled, type PhonePushOptions } from "./phone-push.ts";/** The bodies and the signature vector the Admin's tests read from their own copy of this file (openmaus-cloud* tests/fixtures/cloud-home-push.json): both copies must hash to this. */@@ -176,6 +177,15 @@ describe("a Cloud home's pushes through its Admin", () => {expect(admin.calls.slice(1).map((call) => call.url.split("/").at(-1))).toEqual(["send", "register", "send"]);});+ it("on by default with no phone paired: asks the Admin nothing and sets no timer, however many alerts go by", async () => {+ const { push, admin } = harness({ enabled: () => phonePushEnabled({}, {}) });+ expect(push.status()).toBe("on");+ for (const threadId of ["th_1", "th_2", "th_3"]) push.offer({ notification: notification(threadId), seq: 1 }, everyone);+ await advance(push, 60 * 60_000);+ expect(admin.calls).toEqual([]);+ expect(timers).toEqual([]);+ });+it("switched off, keeps nothing and asks the Admin nothing", async () => {const { push, admin, setEnabled } = harness();setEnabled(false);@@ -202,4 +212,15 @@ describe("which transport a server uses", () => {writeFileSync(tunnelFile(), JSON.stringify({}));expect(source({}, HOME)).toEqual({ admin: ADMIN, machineId: MACHINE, secret: SECRET });});++ it("is the Admin for a Team Cloud as for a My Cloud, with the home's own machine id", () => {+ const secret = "s".repeat(43);+ const env = { OMB_CLOUD_MACHINE_ID: MACHINE, OMB_CLOUD_ADMIN_URL: ADMIN, OMB_PUBLIC_URL: "https://omb-t-1.fly.dev", OMB_CLOUD_BOOTSTRAP_SECRET: secret };+ const mine = cloudHomeConfiguration({ ...env, OMB_CLOUD_ROLE: "home" });+ const team = cloudHomeConfiguration({ ...env, OMB_CLOUD_ROLE: "team", OMB_CLOUD_TEAM_ID: "team-1", OMB_CLOUD_TEAM_NAME: "Acme" });+ expect(team?.team).toEqual({ id: "team-1", name: "Acme" });+ for (const home of [mine, team]) expect(source({}, home)).toEqual({ admin: ADMIN, machineId: MACHINE, secret });+ // A self-run server with no Admin and no credential has nothing to push as: it answers no-account and calls nobody.+ expect(source({}, null)).toBeNull();+ });});diff --git a/server/phone-push.e2e.test.ts b/server/phone-push.e2e.test.tsindex e717ab5335..35bda24d8a 100644--- a/server/phone-push.e2e.test.ts+++ b/server/phone-push.e2e.test.ts@@ -1,7 +1,9 @@// A real server in a temporary home with the fake engines and a stand-in control plane: two paired phones register for// closed-app alerts; a finished reply and a question reach, as content-free pushes carrying the stream's own// identifier, only the phone that holds no live event stream; signing a phone out unregisters its token; a phone whose-// stream closes gets the next one. A second server with phone push left off keeps nothing and calls nobody.+// stream closes gets the next one. Phone push is on by default, yet with no phone paired that server calls the control+// plane not once, at start or after an alert. Two more servers, switched off in config.json and by OMB_PHONE_PUSH=0, keep+// nothing and call nobody.import { spawn, type ChildProcess } from "node:child_process";import { chmodSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";@@ -25,16 +27,18 @@ const FCM_B = `fcmPhoneB_01:APA91b${"Q".repeat(140)}`;interface Fixture { child: ChildProcess; home: string; base: string; stderr: () => string }let stub: ControlPlaneStub;+let offStub: ControlPlaneStub;let on: Fixture;let off: Fixture;+let envOff: Fixture;const streams: SseRecorder[] = [];-async function boot(env: Record<string, string>): Promise<Fixture> {+async function boot(env: Record<string, string>, features: Record<string, boolean> = {}): Promise<Fixture> {const home = mkdtempSync(join(tmpdir(), "omb-phone-push-"));const data = join(home, ".openmausbot");mkdirSync(data, { recursive: true });writeFileSync(join(data, "config.json"), JSON.stringify({- features: { smartSetupChoices: false },+ features: { smartSetupChoices: false, ...features },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 } },@@ -97,34 +101,55 @@ const sends = () => stub.pushes.filter((push) => push.path.endsWith("/send"));beforeAll(async () => {chmodSync(FAKE_CLAUDE, 0o755);chmodSync(FAKE_ACP, 0o755);- stub = await startControlPlaneStub();+ [stub, offStub] = await Promise.all([startControlPlaneStub(), startControlPlaneStub()]);const credential = stub.seedInstallation("phone push fixture");- [on, off] = await Promise.all([- boot({ OMB_PHONE_PUSH: "1", OMB_CONTROL_PLANE_URL: stub.url, OMB_PUSH_CREDENTIAL: credential }),+ const offCredential = offStub.seedInstallation("phone push off fixture");+ // `on` has no switch at all: phone push is on by default.+ [on, off, envOff] = await Promise.all([boot({ OMB_CONTROL_PLANE_URL: stub.url, OMB_PUSH_CREDENTIAL: credential }),+ boot({ OMB_CONTROL_PLANE_URL: offStub.url, OMB_PUSH_CREDENTIAL: offCredential }, { phonePush: false }),+ boot({ OMB_PHONE_PUSH: "0", OMB_CONTROL_PLANE_URL: offStub.url, OMB_PUSH_CREDENTIAL: offCredential }),]);}, 60_000);afterAll(async () => {for (const stream of streams) stream.close();- for (const fixture of [on, off]) {+ for (const fixture of [on, off, envOff]) {if (!fixture) continue;await waitForExit(fixture.child, { signal: "SIGTERM" });await removeTempDir(fixture.home);}await stub?.close();+ await offStub?.close();});-describe("phone push left off", () => {- it("answers off, keeps nothing and calls no relay", async () => {- const phone = await pair(off, "Off phone");- expect(await api(off, "PUT", "/api/push/device", { platform: "apns", token: APNS_A }, phone.token)).toEqual({ status: 200, body: { push: "off", relay: "off", device: null } });- expect(await api(off, "GET", "/api/push/device", undefined, phone.token)).toEqual({ status: 200, body: { push: "off", device: null } });- expect(stub.pushes).toEqual([]);+describe("phone push on by default, with no phone paired", () => {+ it("calls the control plane not once, at start or after a finished reply", async () => {+ expect(stub.calls).toEqual([]);+ const watcher = await openSse(`${on.base}/api/events`, { origin: on.base });+ streams.push(watcher);+ await watcher.until((frame) => frame.kind === "hello", 10_000);+ const echo = await createBot(on, "Echo", "quick", "claude-sonnet-5");+ expect((await api(on, "POST", `/api/bots/${echo.id}/messages`, { text: "anyone there?" })).status).toBe(202);+ await watcher.until((frame) => frame.kind === "notify" && frame.notification?.kind === "done" && frame.notification?.botId === echo.id, 30_000);+ await new Promise((resolve) => setTimeout(resolve, 1_500));+ expect(stub.calls).toEqual([]);+ watcher.close();+ }, 60_000);+});++describe("phone push switched off", () => {+ it("in config.json or by OMB_PHONE_PUSH=0: answers off, keeps nothing and calls no relay", async () => {+ for (const fixture of [off, envOff]) {+ const phone = await pair(fixture, "Off phone");+ expect(await api(fixture, "PUT", "/api/push/device", { platform: "apns", token: APNS_A }, phone.token)).toEqual({ status: 200, body: { push: "off", relay: "off", device: null } });+ expect(await api(fixture, "GET", "/api/push/device", undefined, phone.token)).toEqual({ status: 200, body: { push: "off", device: null } });+ }+ expect(offStub.calls).toEqual([]);});});-describe("phone push switched on", () => {+describe("phone push on by default, with phones paired", () => {it("wakes only the phone that is not connected, without the reply's text, and stops when it signs out", async () => {const phoneA = await pair(on, "Phone A");const phoneB = await pair(on, "Phone B");diff --git a/server/phone-push.test.ts b/server/phone-push.test.tsindex 2497487d01..a73c41be23 100644--- a/server/phone-push.test.ts+++ b/server/phone-push.test.ts@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { PUSH_KINDS, phonePushCollapseId } from "../shared/phone-push.ts";+import { PUSH_KINDS, PUSH_RELAY_ERRORS, phonePushCollapseId } from "../shared/phone-push.ts";import {MAX_PUSH_DEVICES,PHONE_PUSH_DESKTOP_MESSAGE,@@ -109,12 +109,69 @@ const notification = (overrides: Record<string, unknown> = {}) => ({const everyone = () => true;describe("phone push switch", () => {- it("is off unless config or OMB_PHONE_PUSH turns it on, and the variable wins", () => {- expect(phonePushEnabled({}, {})).toBe(false);+ it("is on unless config or OMB_PHONE_PUSH turns it off, and the variable wins both ways", () => {+ expect(phonePushEnabled({}, {})).toBe(true);+ expect(phonePushEnabled({ features: {} }, {})).toBe(true);expect(phonePushEnabled({ features: { phonePush: true } }, {})).toBe(true);+ expect(phonePushEnabled({ features: { phonePush: false } }, {})).toBe(false);+ expect(phonePushEnabled({}, { OMB_PHONE_PUSH: "0" })).toBe(false);expect(phonePushEnabled({ features: { phonePush: true } }, { OMB_PHONE_PUSH: "0" })).toBe(false);- expect(phonePushEnabled({}, { OMB_PHONE_PUSH: "1" })).toBe(true);+ expect(phonePushEnabled({ features: { phonePush: false } }, { OMB_PHONE_PUSH: "1" })).toBe(true);+ // Only an exact 0 or 1 is the variable's word; anything else leaves config.json's.expect(phonePushEnabled({ features: { phonePush: false } }, { OMB_PHONE_PUSH: "yes" })).toBe(false);+ expect(phonePushEnabled({}, { OMB_PHONE_PUSH: "off" })).toBe(true);+ });++ it("with no paired phone, makes no relay call, sets no timer and reads no access, however many alerts go by", async () => {+ let accessReads = 0;+ const { push, relay } = harness({ access: () => { accessReads += 1; return ACCESS; } });+ expect(push.status()).toBe("on");+ accessReads = 0;+ for (const kind of PUSH_KINDS) push.offer({ notification: notification({ kind }), seq: 1 }, everyone);+ await advance(push, 60 * 60_000);+ expect(relay.calls).toEqual([]);+ expect(timers).toEqual([]);+ expect(accessReads).toBe(0);+ expect(push.pending()).toBe(0);+ expect(() => readFileSync(join(dataDir, PHONE_PUSH_FILE))).toThrow();+ });++ it("with no account to push as, keeps a phone's registration and queues nothing, then pushes once there is one", async () => {+ let access: typeof ACCESS | null = null;+ const { push, relay } = harness({ access: () => access });+ expect(await push.register(PHONE, { platform: "apns", token: APNS })).toMatchObject({ push: "no-account", relay: "off", device: { platform: "apns" } });+ push.offer({ notification: notification(), seq: 1 }, everyone);+ await advance(push, 5 * 60_000);+ expect(relay.calls).toEqual([]);+ expect(timers).toEqual([]);+ expect(push.pending()).toBe(0);+ // The person signs in ("Anywhere, through MausBot", or `openmausbot account login`): the kept phone is registered with+ // the relay at its first push, which the relay did not know yet.+ access = ACCESS;+ relay.answers.push({ status: 404, error: PUSH_RELAY_ERRORS.unknownDevice });+ push.offer({ notification: notification({ threadId: "th_2" }), seq: 2 }, everyone);+ await push.flush();+ expect(relay.calls.map((call) => call.path.split("/").at(-1))).toEqual(["send", "register", "send"]);+ expect(relay.calls[1]!.body).toEqual({ v: 1, platform: "apns", token: APNS, environment: "production" });+ });++ it("a phone that registered while push was off is kept and used once an update turns it on by default", async () => {+ const { push, relay, setEnabled } = harness();+ setEnabled(false);+ expect(await push.register(PHONE, { platform: "fcm", token: FCM, pairing: "pair-tag-0001" })).toEqual({ push: "off", device: null, relay: "off" });+ // The update: a new process on the same data folder, with no switch in config.json.+ const relayAfter = fakeRelay();+ const upgraded = new PhonePush({ dataDir, access: () => ACCESS, enabled: () => phonePushEnabled({}, {}), live: () => false, room: () => undefined, fetchImpl: relayAfter.fetchImpl, now: () => clock, log: () => {} });+ expect(upgraded.answer(PHONE)).toEqual({ push: "on", device: null });+ // The phone app registers again at its next connect, because the last answer was off.+ expect(await upgraded.register(PHONE, { platform: "fcm", token: FCM, pairing: "pair-tag-0001" })).toMatchObject({ push: "on", relay: "registered", device: { platform: "fcm" } });+ const restarted = new PhonePush({ dataDir, access: () => ACCESS, enabled: () => phonePushEnabled({}, {}), live: () => false, room: () => undefined, fetchImpl: relayAfter.fetchImpl, now: () => clock, log: () => {} });+ restarted.offer({ notification: notification({ kind: "done" }), seq: 4 }, everyone);+ await restarted.flush();+ expect(relayAfter.sends().map((call) => call.body)).toEqual([+ { v: 1, token: FCM, pairing: "pair-tag-0001", collapseId: "openmaus.th_1.4", notification: { kind: "done", title: "Scout finished", botId: "bot_1", botName: "Scout", threadId: "th_1" } },+ ]);+ expect(relay.calls).toEqual([]);});it("switched off, keeps nothing, sends nothing and says so", async () => {diff --git a/server/phone-push.ts b/server/phone-push.tsindex e71284d5f2..95aa92aa1c 100644--- a/server/phone-push.ts+++ b/server/phone-push.ts@@ -2,7 +2,8 @@// sign-in request or a finished reply would reach a phone that holds no live event stream, this asks the push relay in// the hosted control plane to wake it, with the installation credential this server already has; a Cloud home, which has// none, asks its Admin to relay instead (phone-push-admin.ts). The push is content-free: kind, a title from names alone,-// opaque ids. Off unless `features.phonePush` (or OMB_PHONE_PUSH=1).+// opaque ids. On unless `features.phonePush: false` (or OMB_PHONE_PUSH=0). Nothing leaves this server until a paired phone+// registers: with no registered phone there is no relay call, no timer and no connection.import { mkdirSync, readFileSync } from "node:fs";import { dirname, join } from "node:path";import { z } from "zod";@@ -64,11 +65,13 @@ const TITLES: Record<PushKind, ServerLineKey> = {done: "server.notify.done",};-/** On only when switched on: OMB_PHONE_PUSH=1 or 0 wins over `features.phonePush` in config.json. */+/** On for every desktop, Cloud home (My Cloud and Team Cloud) and server unless switched off: OMB_PHONE_PUSH=0 or 1 wins+ * over `features.phonePush` in config.json, and `features.phonePush: false` turns it off. Both are an operator's kill+ * switch; there is no setting for it. */export function phonePushEnabled(cfg: { features?: { phonePush?: boolean } }, env: NodeJS.ProcessEnv = process.env): boolean {if (env[PHONE_PUSH_ENV] === "1") return true;if (env[PHONE_PUSH_ENV] === "0") return false;- return cfg.features?.phonePush === true;+ return cfg.features?.phonePush !== false;}const kindsSchema = z.array(z.enum(PUSH_KINDS)).max(PUSH_KINDS.length);@@ -299,11 +302,12 @@ export class PhonePush {/*** A `notify` frame left this server as frame `seq`. Each registered phone that holds no live stream, wants this kind* and would have been shown the frame (`reaches`, the event stream's own audience rule) gets a push queued. Never- * throws, and does nothing at all while switched off.+ * throws, and does nothing at all while switched off or with no account to push as (the phone's registration is kept,+ * and a later send registers it with the relay first).*/offer(frame: { notification: unknown; seq: number }, reaches: (key: string) => boolean): void {try {- if (!this.devices.length || !this.options.enabled()) return;+ if (!this.devices.length || this.status() !== "on") return;const notification = pushableOf(frame.notification);if (!notification || !isPushKind(notification.kind)) return;const push = phonePushNotification(notification, this.options.room(notification));