Skip to content

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

feat(phone-push): a phone can mute single bots' closed-app alerts

AdityaUmale38cefc094eb9
diff --git a/docs/phone-push.md b/docs/phone-push.md
index bafaff8bd7..23f1d8461b 100644
--- a/docs/phone-push.md
+++ b/docs/phone-push.md
@@ -69,7 +69,7 @@ person.
2. **The phone gives the token to its computer or Cloud,** over the link it
already uses and with the credential it already has:
`PUT /api/push/device {platform, token, environment?, pairing, kinds,
- botChannels?}`. The
+ botChannels?, mutedBots?}`. The
server knows which phone is asking from what authenticated the request (the
phone's paired session, or the device the desktop's companion vouched for),
never from the body. The phone does this after it connects, whenever the
@@ -363,6 +363,14 @@ in order (all done; kept as the record and for a new environment):
lists the registered `botChannels` (empty when none) on a computer that
takes the field; an older one answers without it, and the phone then leaves
the list out, since that computer refuses fields it does not know.
+- A phone can mute single bots (`mutedBots`, ids, on both platforms). The
+ server then sends that phone no alert push for those bots (Live Activity and
+ ongoing-notification updates still go); its other bots, and
+ other phones of the same person, are not affected. A push already waiting for
+ a retry is dropped once its bot is muted. The answer's `device` lists the
+ muted bots (empty when none) on a computer that takes the field, and the
+ phone sends its list only to a computer that answers with it, as with
+ `botChannels`.
- The categories (Allow and Deny on an approval, Answer on a question) are the
ones the app registers today.
diff --git a/packages/phone-protocol/src/phone-push.ts b/packages/phone-protocol/src/phone-push.ts
index 871567e43f..27999f9944 100644
--- a/packages/phone-protocol/src/phone-push.ts
+++ b/packages/phone-protocol/src/phone-push.ts
@@ -32,8 +32,11 @@ export const PAIRING_TAG = /^[A-Za-z0-9_-]{8,64}$/;
export const PUSH_COLLAPSE_ID = /^[A-Za-z0-9._:-]{1,64}$/;
export const PUSH_ID = /^[\w-]{1,120}$/;
export const PUSH_NAME_MAX = 80;
-/** The most bots one registration can name in `botChannels`: a full list of UUID ids stays well inside the 16 KB body. */
+/** The most bots one registration can name in `botChannels`. Both full lists of UUID ids and the longest FCM token stay
+ * inside the 32 KB body the computer takes. */
export const PUSH_BOT_CHANNELS_MAX = 200;
+/** The most bots one registration can mute in `mutedBots`, the same bound as `botChannels`. */
+export const PUSH_MUTED_BOTS_MAX = 200;
export const PUSH_TITLE_MAX = 200;
/** The kinds a closed app is woken for: a bot waits on the person (approval, question, sign-in), or a reply is ready.
@@ -54,6 +57,9 @@ export interface PhonePushRegistration {
/** FCM only: the bots (ids) that have a notification channel of their own on this phone, `bot_messages.<botId>`.
* A push for one of them is sent on it, so the person can give that bot its own sound. Absent: none. */
botChannels?: string[];
+ /** The bots (ids) whose alerts the person switched off on this phone. No alert push is sent for them (Live Activity
+ * and ongoing-notification updates still are). Absent: none. */
+ mutedBots?: string[];
}
/** Whether pushes can leave this server at all: `off` until the owner switches phone push on, `no-account` while it
@@ -69,6 +75,9 @@ export interface PublicPushDevice {
/** FCM only: the bots registered with a channel of their own. A computer that takes `botChannels` always lists it
* (maybe empty), so a phone sends its list only to one that answers with it. */
botChannels?: string[];
+ /** The bots muted on this phone. A computer that takes `mutedBots` always lists it (maybe empty), so a phone sends
+ * its list only to one that answers with it. */
+ mutedBots?: string[];
updatedAt: number;
}
diff --git a/server/phone-push.test.ts b/server/phone-push.test.ts
index 8cce4d70e0..c2fcc301c2 100644
--- a/server/phone-push.test.ts
+++ b/server/phone-push.test.ts
@@ -192,7 +192,7 @@ describe("registering a phone", () => {
it("keeps the token on this computer only (0600), registers it at the relay and never echoes it", async () => {
const { push, relay } = harness();
const answer = await push.register(PHONE, { platform: "apns", token: APNS, environment: "sandbox", pairing: "pair-tag-0001" });
- expect(answer).toEqual({ push: "on", relay: "registered", device: { platform: "apns", environment: "sandbox", pairing: "pair-tag-0001", kinds: [...PUSH_KINDS], updatedAt: clock } });
+ expect(answer).toEqual({ push: "on", relay: "registered", device: { platform: "apns", environment: "sandbox", pairing: "pair-tag-0001", kinds: [...PUSH_KINDS], mutedBots: [], updatedAt: clock } });
expect(JSON.stringify(answer)).not.toContain(APNS);
expect(relay.calls).toEqual([{ path: "/v1/installations/self/push/register", body: { v: 1, platform: "apns", token: APNS, environment: "sandbox" }, authorization: `Bearer ${CREDENTIAL}` }]);
const file = join(dataDir, PHONE_PUSH_FILE);
@@ -238,6 +238,9 @@ describe("registering a phone", () => {
it("takes only a well-formed registration", () => {
expect(registrationSchema.safeParse({ platform: "apns", token: APNS.toUpperCase() }).data).toEqual({ platform: "apns", token: APNS, environment: "production" });
+ for (const platform of ["apns", "fcm"] as const) {
+ expect(registrationSchema.safeParse({ platform, token: platform === "apns" ? APNS : FCM, mutedBots: ["bot_1"] }).data?.mutedBots).toEqual(["bot_1"]);
+ }
for (const body of [
{ platform: "apns", token: FCM },
{ platform: "fcm", token: "short" },
@@ -248,11 +251,46 @@ describe("registering a phone", () => {
{ platform: "webpush", token: FCM },
{ platform: "apns", token: APNS, botChannels: ["bot_1"] },
{ platform: "fcm", token: FCM, botChannels: ["not a bot id"] },
+ { platform: "apns", token: APNS, mutedBots: ["not a bot id"] },
+ { platform: "fcm", token: FCM, mutedBots: Array.from({ length: 201 }, (_, index) => `bot_${index}`) },
]) expect(registrationSchema.safeParse(body).success, JSON.stringify(body)).toBe(false);
});
});
describe("offering a notify frame", () => {
+ it("sends no push for a bot muted on that phone, while its other bots and other phones still get theirs", async () => {
+ const { push, relay } = harness();
+ expect((await push.register(PHONE, { platform: "apns", token: APNS, mutedBots: ["bot_1", "bot_1"] })).device?.mutedBots).toEqual(["bot_1"]);
+ expect((await push.register(OTHER, { platform: "fcm", token: FCM })).device?.mutedBots).toEqual([]);
+ push.offer({ notification: notification({ threadId: "th_a" }), seq: 1 }, everyone);
+ push.offer({ notification: notification({ botId: "bot_2", botName: "Atlas", threadId: "th_b" }), seq: 2 }, everyone);
+ await push.flush();
+ expect(relay.sends().map((call) => [call.body.token, (call.body.notification as { botId: string }).botId])).toEqual([
+ [FCM, "bot_1"],
+ [APNS, "bot_2"],
+ [FCM, "bot_2"],
+ ]);
+ const restarted = new PhonePush({ dataDir, access: () => ACCESS, enabled: () => true, live: () => false, room: () => undefined, fetchImpl: relay.fetchImpl, log: () => {} });
+ expect(restarted.answer(PHONE).device?.mutedBots).toEqual(["bot_1"]);
+ expect((await push.register(PHONE, { platform: "apns", token: APNS })).device?.mutedBots).toEqual([]);
+ push.offer({ notification: notification({ threadId: "th_c" }), seq: 3 }, everyone);
+ await push.flush();
+ expect(relay.sends().filter((call) => call.body.token === APNS).map((call) => (call.body.notification as { botId: string }).botId)).toEqual(["bot_2", "bot_1"]);
+ });
+
+ it("drops a push still waiting for a retry once the person mutes its bot", async () => {
+ const { push, relay } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ relay.answers.push("unreachable");
+ push.offer({ notification: notification(), seq: 1 }, everyone);
+ await push.flush();
+ expect(push.pending()).toBe(1);
+ await push.register(PHONE, { platform: "apns", token: APNS, mutedBots: ["bot_1"] });
+ for (const wait of PUSH_RETRY_MS) await advance(push, wait);
+ expect(relay.sends()).toHaveLength(1);
+ expect(push.pending()).toBe(0);
+ });
+
it("tells the relay a bot's push may use the bot's own Android channel, only for bots the phone made one for", async () => {
const { push, relay } = harness();
expect((await push.register(OTHER, { platform: "fcm", token: FCM, botChannels: ["bot_1", "bot_1"] })).device?.botChannels).toEqual(["bot_1"]);
diff --git a/server/phone-push.ts b/server/phone-push.ts
index a79322c36c..dd0edc5ad1 100644
--- a/server/phone-push.ts
+++ b/server/phone-push.ts
@@ -19,6 +19,7 @@ import {
PUSH_BOT_CHANNELS_MAX,
PUSH_ID,
PUSH_KINDS,
+ PUSH_MUTED_BOTS_MAX,
PUSH_NAME_MAX,
PUSH_RELAY_ERRORS,
PUSH_TITLE_MAX,
@@ -83,10 +84,11 @@ export function phonePushEnabled(cfg: { features?: { phonePush?: boolean } }, en
const kindsSchema = z.array(z.enum(PUSH_KINDS)).max(PUSH_KINDS.length);
const botChannelsSchema = z.array(z.string().regex(PUSH_ID)).max(PUSH_BOT_CHANNELS_MAX);
+const mutedBotsSchema = z.array(z.string().regex(PUSH_ID)).max(PUSH_MUTED_BOTS_MAX);
export const registrationSchema = z.discriminatedUnion("platform", [
- z.object({ platform: z.literal("apns"), token: z.string().trim().toLowerCase().regex(APNS_TOKEN), environment: z.enum(["production", "sandbox"]).default("production"), pairing: z.string().regex(PAIRING_TAG).optional(), kinds: kindsSchema.optional() }).strict(),
- z.object({ platform: z.literal("fcm"), token: z.string().trim().regex(FCM_TOKEN), environment: z.literal("production").optional(), pairing: z.string().regex(PAIRING_TAG).optional(), kinds: kindsSchema.optional(), botChannels: botChannelsSchema.optional() }).strict(),
+ z.object({ platform: z.literal("apns"), token: z.string().trim().toLowerCase().regex(APNS_TOKEN), environment: z.enum(["production", "sandbox"]).default("production"), pairing: z.string().regex(PAIRING_TAG).optional(), kinds: kindsSchema.optional(), mutedBots: mutedBotsSchema.optional() }).strict(),
+ z.object({ platform: z.literal("fcm"), token: z.string().trim().regex(FCM_TOKEN), environment: z.literal("production").optional(), pairing: z.string().regex(PAIRING_TAG).optional(), kinds: kindsSchema.optional(), botChannels: botChannelsSchema.optional(), mutedBots: mutedBotsSchema.optional() }).strict(),
]);
const storedDevice = z.object({
@@ -97,6 +99,7 @@ const storedDevice = z.object({
pairing: z.string().regex(PAIRING_TAG).optional(),
kinds: kindsSchema,
botChannels: botChannelsSchema.optional(),
+ mutedBots: mutedBotsSchema.optional(),
createdAt: z.number(),
updatedAt: z.number(),
}).refine((device) => validPushToken(device.platform, device.token));
@@ -241,7 +244,7 @@ export class PhonePush {
private publicDevice(key: string): PublicPushDevice | null {
const device = this.devices.find((candidate) => candidate.key === key);
if (!device) return null;
- return { platform: device.platform, environment: device.environment, ...(device.pairing ? { pairing: device.pairing } : {}), kinds: [...device.kinds], ...(device.platform === "fcm" ? { botChannels: [...(device.botChannels ?? [])] } : {}), updatedAt: device.updatedAt };
+ return { platform: device.platform, environment: device.environment, ...(device.pairing ? { pairing: device.pairing } : {}), kinds: [...device.kinds], ...(device.platform === "fcm" ? { botChannels: [...(device.botChannels ?? [])] } : {}), mutedBots: [...(device.mutedBots ?? [])], updatedAt: device.updatedAt };
}
/** The device token a phone registered, for the Live Activity and ongoing-notification pushes that share its relay. */
@@ -315,6 +318,7 @@ export class PhonePush {
...(input.pairing ? { pairing: input.pairing } : {}),
kinds: [...new Set(input.kinds ?? PUSH_KINDS)],
...(input.platform === "fcm" && input.botChannels?.length ? { botChannels: [...new Set(input.botChannels)] } : {}),
+ ...(input.mutedBots?.length ? { mutedBots: [...new Set(input.mutedBots)] } : {}),
createdAt: previous?.createdAt ?? now,
updatedAt: now,
};
@@ -370,7 +374,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.phonePausedUntil.get(device.key) ?? 0) > now || this.options.live(device.key) || !reaches(device.key)) continue;
+ if (!device.kinds.includes(notification.kind) || device.mutedBots?.includes(push.botId) || (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;
@@ -437,6 +441,8 @@ export class PhonePush {
private async attempt(job: Job, now: number): Promise<PushOutcome> {
const device = this.devices.find((candidate) => candidate.key === job.key);
if (!device || !this.options.enabled()) return "gone";
+ // The person muted this bot on the phone while the push waited.
+ if (device.mutedBots?.includes(job.push.botId)) return "dropped";
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";
diff --git a/server/routes/phone-push.test.ts b/server/routes/phone-push.test.ts
index 45c4e42f39..57b45d157e 100644
--- a/server/routes/phone-push.test.ts
+++ b/server/routes/phone-push.test.ts
@@ -81,6 +81,14 @@ describe("/api/push/device", () => {
}
});
+ it("takes the largest registration a phone may send: the longest FCM token with a full channel list and a full mute list", async () => {
+ const { call } = await setup();
+ const ids = (from: number) => Array.from({ length: 200 }, (_, index) => `00000000-0000-4000-8000-${String(from + index).padStart(12, "0")}`);
+ const put = await call("PUT", "/api/push/device", { platform: "fcm", token: `a:${"x".repeat(4094)}`, pairing: "pair-tag-0001", kinds: ["approval", "question", "sign-in", "done"], botChannels: ids(0), mutedBots: ids(200) });
+ expect(put.status).toBe(200);
+ expect((put.body.device as { mutedBots: string[] }).mutedBots).toEqual(ids(200));
+ });
+
it("answers off and keeps nothing while phone push is switched off", async () => {
const { call, push } = await setup({ enabled: false });
expect(await call("PUT", "/api/push/device", { platform: "apns", token: APNS })).toEqual({ status: 200, body: { push: "off", relay: "off", device: null } });
diff --git a/server/routes/phone-push.ts b/server/routes/phone-push.ts
index 04e38de78c..7373e57891 100644
--- a/server/routes/phone-push.ts
+++ b/server/routes/phone-push.ts
@@ -28,7 +28,7 @@ export function createPhonePushRoutes(deps: PhonePushRouteDeps): RouteHandler {
}
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 = registrationSchema.safeParse(await readBody(req, 16_384));
+ const parsed = registrationSchema.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 push registration" });
try {