Dough Git

commit

better ws

commit
0c29cdb24d2834b4609eaec5604089aa8b9f6b5b
author
Clove Twilight <[email protected]>
date
2026-07-14 13:52

diff --git a/README.md b/README.md
index aded091..d00e102 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
 # dough-restful
 
-A combined Discord **presence** (Lanyard-style) and **profile/badges** (dstn.to-style) API on a **single Cloudflare Worker + Durable Object**, powered by **one Discord bot**. It exposes a REST endpoint and a Lanyard-compatible WebSocket, returning a single unified JSON shape.
+A combined Discord **presence** (Lanyard-style) and **profile/badges** (dstn.to-style) API on a **single Cloudflare Worker + Durable Objects**, powered by **one Discord bot**. It also carries the Doughmination plural-system API (fronting, members, mental state, devices, guestbook). Everything returns one unified JSON shape, and all live updates go over a single WebSocket.
 
 ## Thanks
 This code wasn't just me. It took a good chunk of my own brain plus a lot of
@@ -9,6 +9,55 @@ the tricky parts: rate limits, caching, and getting Discord to actually trust
 your requests. Thanks Dustin! And credit to Phineas for Lanyard, which inspired
 the presence half of this.
 
+## What's in here
+
+Two Durable Objects behind the Worker router (`src/index.ts`):
+
+- **GATEWAY** (`GatewayManager`) — holds the single Discord gateway socket, ingests presences from `READY` / `GUILD_CREATE` / `PRESENCE_UPDATE`, and keeps an in-memory `userId → presence` map. It doesn't serve browser sockets; it relays each live presence change to the SYSTEM DO for fan-out.
+- **SYSTEM** (`SystemState`) — the old backend as one object: all persistent state (users, tags, statuses, mental state, devices) in DO storage, the visitor-log SQLite table, and the single realtime WebSocket hub.
+
+### Endpoints (all under `/v2`)
+
+- `/v2/ws` — **the one WebSocket** for all live updates (see below).
+- `/v2/lanyard/users`, `/v2/lanyard/users/:id`, `/v2/lanyard/status` — REST presence.
+- `/v2/discord/users/:id`, `/v2/discord/users?ids=…`, `/v2/discord/guilds/:invite`, `/v2/discord/girls/:idType/:id` — profiles, badges, guild/role info.
+- `/v2/minecraft/general/:uuid`, `/v2/minecraft/hypixel/:uuid`, `/v2/minecraft/capes` — Mojang + Hypixel.
+- `/v2/contribapi` — merged git contribution heatmaps.
+- `/v2/plural/*`, `/v2/devices/*`, `/v2/guestbook/*`, `/v2/system-data/*` — the plural system API.
+- `/docs` — full HTML API reference.
+
+## Realtime — the single `/v2/ws`
+
+There's exactly **one** socket now (the old `/v2/lanyard/ws` and `/v2/plural/ws` are gone). Every frame is a `{ type, data }` object.
+
+On connect you get `connection_established`. These are then pushed to **every** client automatically as they happen:
+
+- `fronters_update` — who's fronting changed
+- `mental_state_update` — mental state changed
+- `device_update` — a device/battery report changed
+- `force_refresh` — admin asked all clients to refresh
+
+Discord **presence is opt-in** (keeps traffic down). Send a subscribe frame:
+
+```jsonc
+{ "type": "subscribe", "all": true }              // every tracked user
+{ "type": "subscribe", "ids": ["123…", "456…"] }  // just these users
+```
+
+You immediately get an `init_state` snapshot of the presences you asked for, then `presence_update` frames for those users only. Subscriptions persist across DO hibernation. Send the string `ping` to get `pong`.
+
+Presence lives in the GATEWAY DO; when it changes, GATEWAY relays it to SYSTEM, which fans it out to the clients subscribed to that user.
+
+## Caching
+
+See the notes in each source file, but the short version:
+
+- **Presence is never cached** — it's live from the Discord gateway, held in memory in the GATEWAY DO and pushed over the socket in real time.
+- **PluralKit data** (system, members, fronters) — in-memory in the SYSTEM DO, `CACHE_TTL` seconds (default **30s**). Busted immediately on any switch / member / tag / status change.
+- **Discord profiles** — KV (`PROFILE_CACHE`), `PROFILE_CACHE_TTL_SECONDS` (default **300s**, min 60), jittered ±20% so batches don't all expire at once. Rich (userbot) fetches back off on a 429 via a shared cooldown key (30–300s).
+- **Guild invites** — KV, **300s**. **Memberships** — KV, **6h**. **Client-mod badges** (Equicord) — KV, **1h** with stale fallback. **Minecraft** general + Hypixel — KV, **5min**; the vanilla-cape registry is kept **permanently**.
+- **HTTP `Cache-Control`** — JSON API responses are `no-store` (never edge/browser cached). `/docs` and `/v2/contribapi` are `public, max-age=3600` (1h).
+
 ## Setup
 
 ### 1. Settings
@@ -21,26 +70,26 @@ the presence half of this.
 ### 2. Commands
 ```bash
 # REQUIRED
-pnpm install
+bun install
 
 # KV namespace for profile cache — paste the printed id into wrangler.jsonc
-pnpx wrangler kv namespace create PROFILE_CACHE
+bunx wrangler kv namespace create PROFILE_CACHE
 
 # Secrets
-pnpx wrangler secret put DISCORD_BOT_TOKEN
+bunx wrangler secret put DISCORD_BOT_TOKEN
 # Optional, ToS risk — only if you want the rich badges:
-pnpx wrangler secret put DISCORD_USER_TOKEN
+bunx wrangler secret put DISCORD_USER_TOKEN
 # Optional second userbot
-pnpx wrangler secret put DISCORD_USER_TOKEN2
+bunx wrangler secret put DISCORD_USER_TOKEN2
 # Optional 3rd userbot
-pnpx wrangler secret put DISCORD_USER_TOKEN2
+bunx wrangler secret put DISCORD_USER_TOKEN3
 
 # If you need to update the X-Super-Properties to latest version
-pnpm decode "X-Super-Properties: [BASE64 HERE]"
+bun decode "X-Super-Properties: [BASE64 HERE]"
 
 # Local test
-pnpm dev
+bun dev
 
 # Production
-pnpm deploy
-```
\ No newline at end of file
+bun deploy
+```
diff --git a/src/docs.ts b/src/docs.ts
index 16b3857..b3ccde4 100644
--- a/src/docs.ts
+++ b/src/docs.ts
@@ -229,8 +229,6 @@ var GROUPS = [
       { m: "GET", path: "/lanyard/users?ids=a,b,c", auth: "public",
         desc: "Live presence for up to 100 users at once. Returns a map of user ID → presence (or null).",
         params: [["ids", "Comma-separated Discord user IDs, max 100."]] },
-      { m: "WS", path: "/lanyard/ws", auth: "public",
-        desc: "WebSocket speaking the Lanyard socket protocol (op1 Hello, op2 Initialize, op3 Heartbeat, op0 INIT_STATE / PRESENCE_UPDATE)." },
       { m: "GET", path: "/lanyard/status", auth: "public",
         desc: "Live-presence connection health: whether it's connected, how many users are tracked, and recent reconnect activity." }
     ]
@@ -294,7 +292,7 @@ var GROUPS = [
       { m: "GET", path: "/plural/mental-state", auth: "public",
         desc: "Current mental state: { level, updated_at, notes }." },
       { m: "POST", path: "/plural/mental-state", auth: "admin",
-        desc: "Update mental state. Body { level, notes? }. Broadcasts a mental_state_update over /plural/ws." }
+        desc: "Update mental state. Body { level, notes? }. Broadcasts a mental_state_update over /ws." }
     ]
   },
   {
@@ -355,12 +353,12 @@ var GROUPS = [
     ]
   },
   {
-    id: "plural-realtime", name: "Plural — realtime & admin", blurb: "WebSocket + broadcast controls.",
+    id: "plural-realtime", name: "Plural — realtime & admin", blurb: "The unified WebSocket + broadcast controls.",
     endpoints: [
-      { m: "WS", path: "/plural/ws", auth: "public",
-        desc: "Realtime updates over WebSocket. On connect you get a connection_established message, then live fronters_update, mental_state_update, and force_refresh events as they happen. Send 'ping' to get 'pong'." },
+      { m: "WS", path: "/ws", auth: "public",
+        desc: "The single realtime socket for ALL live updates. On connect you get a connection_established message. Fronting (fronters_update), mental state (mental_state_update), device/battery (device_update) and force_refresh events are pushed to every client automatically. For live Discord presence, send a subscribe frame — either { \"type\": \"subscribe\", \"all\": true } or { \"type\": \"subscribe\", \"ids\": [\"<user id>\", …] }; you'll get an init_state snapshot immediately and presence_update events thereafter (only for the users you subscribed to). Every message is a { type, data } object. Send 'ping' to get 'pong'." },
       { m: "POST", path: "/plural/admin/refresh", auth: "admin",
-        desc: "Broadcast a force_refresh to every connected /plural/ws client." }
+        desc: "Broadcast a force_refresh to every connected /ws client." }
     ]
   },
   {
diff --git a/src/gateway.ts b/src/gateway.ts
index 72cc395..ac5ade9 100644
--- a/src/gateway.ts
+++ b/src/gateway.ts
@@ -5,9 +5,9 @@
  *   • holds ONE Discord gateway WebSocket (identify / heartbeat / resume),
  *   • ingests presences from READY/GUILD_CREATE/PRESENCE_UPDATE,
  *   • keeps an in-memory userId -> UnifiedPresence map,
- *   • accepts browser WebSockets and speaks the Lanyard socket protocol
- *     (op1 Hello, op2 Initialize, op3 Heartbeat, op0 INIT_STATE/PRESENCE_UPDATE),
- *   • broadcasts PRESENCE_UPDATE to subscribed clients.
+ *   • relays each live PRESENCE_UPDATE to the SystemState DO, which is the
+ *     single browser-facing realtime hub (/v2/ws). This DO no longer accepts
+ *     browser sockets of its own.
  *
  * State is in-memory: if the DO is evicted the gateway reconnects (via cron
  * or alarm) and GUILD_CREATE repopulates presences within a second or two.
@@ -15,14 +15,7 @@
 
 import type { Env, UnifiedPresence } from "./types";
 import { INTENTS, Op } from "./discord/constants";
-import { buildPresence, offlinePresence, type RawPresence } from "./presence";
-
-const CLIENT_HEARTBEAT_INTERVAL = 30_000;
-
-interface ClientSub {
-  all: boolean;
-  ids: Set<string>;
-}
+import { buildPresence, type RawPresence } from "./presence";
 
 export class GatewayManager implements DurableObject {
   private state: DurableObjectState;
@@ -40,8 +33,6 @@ export class GatewayManager implements DurableObject {
   private connectedSince: number | null = null;
 
   private presences = new Map<string, UnifiedPresence>();
-  private clients = new Map<WebSocket, ClientSub>();
-  private dispatchSeq = 0;
 
   constructor(state: DurableObjectState, env: Env) {
     this.state = state;
@@ -52,10 +43,6 @@ export class GatewayManager implements DurableObject {
   async fetch(req: Request): Promise<Response> {
     const url = new URL(req.url);
 
-    if (url.pathname === "/ws") {
-      return this.handleClientUpgrade(req);
-    }
-
     // Ensure the gateway is connected (cron / on-demand).
     await this.ensureConnected();
     await this.ensureAlarm();
@@ -196,7 +183,28 @@ export class GatewayManager implements DurableObject {
   private applyPresence(raw: RawPresence, broadcast: boolean): void {
     const presence = buildPresence(raw);
     this.presences.set(presence.user_id, presence);
-    if (broadcast) this.broadcast(presence);
+    if (broadcast) this.relayPresence(presence);
+  }
+
+  /** Push a live presence update to the SystemState DO, which fans it out to
+   *  the browser clients subscribed to that user over /v2/ws. Fire-and-forget:
+   *  a failed relay just means one dropped frame, corrected on the next update
+   *  or on the next subscribe's INIT_STATE snapshot. */
+  private relayPresence(presence: UnifiedPresence): void {
+    try {
+      const stub = this.env.SYSTEM.get(this.env.SYSTEM.idFromName("system"));
+      stub
+        .fetch("https://do/internal/presence", {
+          method: "POST",
+          headers: { "Content-Type": "application/json" },
+          body: JSON.stringify(presence),
+        })
+        .catch(() => {
+          /* dropped frame; ignore */
+        });
+    } catch {
+      /* binding unavailable; ignore */
+    }
   }
 
   // ---- heartbeat / identify / resume -----------------------------------
@@ -292,90 +300,4 @@ export class GatewayManager implements DurableObject {
     }
     setTimeout(() => this.ensureConnected(), 500);
   }
-
-  // ---- browser client sockets (Lanyard protocol) -----------------------
-  private handleClientUpgrade(req: Request): Response {
-    if (req.headers.get("Upgrade") !== "websocket") {
-      return new Response("expected websocket", { status: 426 });
-    }
-    const pair = new WebSocketPair();
-    const client = pair[0];
-    const server = pair[1];
-    server.accept();
-    this.clients.set(server, { all: false, ids: new Set() });
-
-    server.send(JSON.stringify({ op: 1, d: { heartbeat_interval: CLIENT_HEARTBEAT_INTERVAL } }));
-
-    server.addEventListener("message", (e) => this.onClientMessage(server, e));
-    server.addEventListener("close", () => this.clients.delete(server));
-    server.addEventListener("error", () => this.clients.delete(server));
-
-    // Make sure the gateway is alive once someone is listening.
-    this.ensureConnected();
-
-    return new Response(null, { status: 101, webSocket: client });
-  }
-
-  private onClientMessage(socket: WebSocket, e: MessageEvent): void {
-    let msg: any;
-    try {
-      msg = JSON.parse(typeof e.data === "string" ? e.data : "");
-    } catch {
-      socket.close(4006, "invalid_payload");
-      return;
-    }
-    if (msg.op === 3) return; // client heartbeat — nothing to ack
-
-    if (msg.op === 2) {
-      const d = msg.d || {};
-      const sub: ClientSub = { all: false, ids: new Set() };
-      if (d.subscribe_to_all === true) {
-        sub.all = true;
-      } else if (typeof d.subscribe_to_id === "string") {
-        sub.ids.add(d.subscribe_to_id);
-      } else if (Array.isArray(d.subscribe_to_ids)) {
-        for (const id of d.subscribe_to_ids) if (typeof id === "string") sub.ids.add(id);
-      } else {
-        socket.close(4005, "requires_data_object");
-        return;
-      }
-      this.clients.set(socket, sub);
-      this.sendInitState(socket, sub, typeof d.subscribe_to_id === "string" ? d.subscribe_to_id : null);
-      return;
-    }
-
-    socket.close(4004, "unknown_opcode");
-  }
-
-  private sendInitState(socket: WebSocket, sub: ClientSub, singleId: string | null): void {
-    let data: unknown;
-    if (singleId) {
-      data = this.presences.get(singleId) ?? offlinePresence(singleId);
-    } else if (sub.all) {
-      data = Object.fromEntries(this.presences);
-    } else {
-      const map: Record<string, UnifiedPresence> = {};
-      for (const id of sub.ids) map[id] = this.presences.get(id) ?? offlinePresence(id);
-      data = map;
-    }
-    socket.send(JSON.stringify({ op: 0, seq: ++this.dispatchSeq, t: "INIT_STATE", d: data }));
-  }
-
-  private broadcast(presence: UnifiedPresence): void {
-    const payload = JSON.stringify({
-      op: 0,
-      seq: ++this.dispatchSeq,
-      t: "PRESENCE_UPDATE",
-      d: presence,
-    });
-    for (const [socket, sub] of this.clients) {
-      if (sub.all || sub.ids.has(presence.user_id)) {
-        try {
-          socket.send(payload);
-        } catch {
-          this.clients.delete(socket);
-        }
-      }
-    }
-  }
 }
diff --git a/src/index.ts b/src/index.ts
index 2930f6b..4d73c97 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -2,7 +2,9 @@
  * index.ts — Worker entry: v2 router + cron keepalive.
  *
  * Namespaces
- *   /v2/lanyard/*     — live presence (Lanyard) + realtime socket
+ *   /v2/ws            — the single realtime socket for ALL live updates
+ *                       (presence, fronting, mental state, devices)  (SystemState DO)
+ *   /v2/lanyard/*     — live presence REST (users / status)
  *   /v2/discord/*     — general Discord info: profile, badges, guilds, girls
  *   /v2/plural/*      — Doughmination system API   (SystemState DO)
  *   /v2/devices/*     — device state (battery, etc.) (SystemState DO)
@@ -10,8 +12,9 @@
  *   /v2/system-data/* — visitor logs + viewer      (SystemState DO)
  *
  * Two Durable Objects:
- *   GATEWAY  — singleton holding the Discord gateway socket (presence).
- *   SYSTEM   — singleton running the Doughmination API + its realtime hub.
+ *   GATEWAY  — singleton holding the Discord gateway socket (presence). Relays
+ *              presence updates to SYSTEM for fan-out; no browser sockets.
+ *   SYSTEM   — singleton running the Doughmination API + the single /v2/ws hub.
  * ===================================================================== */
 
 import type {
@@ -103,6 +106,7 @@ const ID_RE = /^\d{16,21}$/;
 /** Paths owned by the SystemState Durable Object. */
 function isSystemPath(path: string): boolean {
   return (
+    path === "/v2/ws" ||
     path === "/v2/plural" ||
     path.startsWith("/v2/plural/") ||
     path === "/v2/devices" ||
@@ -147,9 +151,9 @@ export default {
 
     const path = url.pathname.replace(/\/+$/, "") || "/";
 
-    // ---- SystemState DO (plural / devices / system-data) -----------------
-    // Forwarded first, and untouched, so its Hono CORS + WebSocket upgrade
-    // (/v2/plural/ws) work end-to-end.
+    // ---- SystemState DO (plural / devices / system-data / realtime) ------
+    // Forwarded first, and untouched, so its Hono CORS + the single realtime
+    // WebSocket upgrade (/v2/ws) work end-to-end.
     if (isSystemPath(path)) {
       return systemStub(env).fetch(req);
     }
@@ -163,11 +167,6 @@ export default {
       });
     }
 
-    // ---- Lanyard realtime socket ----------------------------------------
-    if (path === "/v2/lanyard/ws") {
-      return gatewayStub(env).fetch(new Request("https://do/ws", req));
-    }
-
     // ---- Lanyard gateway status (debug) ----------------------------------
     if (path === "/v2/lanyard/status") {
       const res = await gatewayStub(env).fetch("https://do/status");
diff --git a/src/system/app.ts b/src/system/app.ts
index 59a9f85..955e8bb 100644
--- a/src/system/app.ts
+++ b/src/system/app.ts
@@ -14,7 +14,7 @@
  *   /v2/guestbook/*     — public guestbook (post/list/delete)  (misc)
  *   /v2/system-data/*   — visitor logging + log viewer (misc)
  *
- * The realtime socket /v2/plural/ws is handled by the DO before the request
+ * The single realtime socket /v2/ws is handled by the DO before the request
  * ever reaches this app (see do.ts).
  */
 
diff --git a/src/system/do.ts b/src/system/do.ts
index 95ebd00..ed69ffe 100644
--- a/src/system/do.ts
+++ b/src/system/do.ts
@@ -10,15 +10,25 @@
  *  - Holds all persistent state (users, tags, statuses, battery, mental
  *    state) in DO key-value storage via a small Store adapter.
  *  - Owns the visitor-log SQLite table (DO embedded SQLite).
- *  - Is the WebSocket hub for /v2/plural/ws, using the hibernatable
- *    WebSocket API so idle sockets don't keep the DO billed/awake.
+ *  - Is the SINGLE realtime WebSocket hub for the whole API, at /v2/ws,
+ *    using the hibernatable WebSocket API so idle sockets don't keep the DO
+ *    billed/awake. Every live update — presence, fronting, mental state,
+ *    device/battery, force-refresh — is delivered over this one socket as a
+ *    { type, data } envelope.
  *  - Delegates all HTTP to the Hono `systemApp`.
  *
+ * Presence lives in the GatewayManager DO (which owns the Discord gateway
+ * connection). Rather than expose a second browser-facing socket there, that
+ * DO relays each PRESENCE_UPDATE to us at POST /internal/presence, and we fan
+ * it out to the clients subscribed to that user. INIT_STATE snapshots are
+ * pulled from GatewayManager (GET /presences) on subscribe.
+ *
  * A single instance is used (idFromName("system")), so the module-level
  * runtime set in the constructor is safe.
  */
 
 import type { SystemEnv } from "./types";
+import type { UnifiedPresence } from "../types";
 import { setRuntime, type Store } from "./runtime";
 import { systemApp } from "./app";
 
@@ -39,13 +49,30 @@ class DoStore implements Store {
   }
 }
 
-const WS_PATH = "/v2/plural/ws";
+/** The single realtime socket path. */
+const WS_PATH = "/v2/ws";
+/** Internal DO-to-DO path GatewayManager relays presence updates to. */
+const PRESENCE_RELAY_PATH = "/internal/presence";
+
+/** Per-socket presence subscription, persisted on the hibernatable socket via
+ *  serializeAttachment so it survives eviction. Presence events are filtered
+ *  by this; all other event types go to every client regardless. */
+interface Sub {
+  /** Subscribed to every tracked user's presence. */
+  all: boolean;
+  /** Specific user ids this socket wants presence for. */
+  ids: string[];
+}
+
+const EMPTY_SUB: Sub = { all: false, ids: [] };
 
 export class SystemState implements DurableObject {
   private state: DurableObjectState;
+  private env: SystemEnv;
 
   constructor(state: DurableObjectState, env: SystemEnv) {
     this.state = state;
+    this.env = env;
     setRuntime({
       env,
       store: new DoStore(state.storage),
@@ -67,6 +94,14 @@ export class SystemState implements DurableObject {
       return this.handleWsUpgrade();
     }
 
+    // Presence relay from GatewayManager (DO-to-DO, never reaches here via the
+    // public Worker router).
+    if (url.pathname === PRESENCE_RELAY_PATH && req.method === "POST") {
+      const presence = (await req.json().catch(() => null)) as UnifiedPresence | null;
+      if (presence?.user_id) this.broadcastPresence(presence);
+      return new Response(null, { status: 204 });
+    }
+
     return systemApp.fetch(req, {} as never);
   }
 
@@ -76,6 +111,10 @@ export class SystemState implements DurableObject {
 
     // Hibernatable accept — the DO can be evicted while sockets stay open.
     this.state.acceptWebSocket(server);
+    // Start with no presence subscription; the client opts in by sending a
+    // { type: "subscribe" } message. Fronting / mental-state / device events
+    // are still delivered without any subscription.
+    server.serializeAttachment(EMPTY_SUB);
 
     try {
       server.send(
@@ -94,12 +133,22 @@ export class SystemState implements DurableObject {
 
   // ---- Hibernation WebSocket handlers -------------------------------------
 
-  webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): void {
-    const data = typeof message === "string" ? message : "";
-    if (data === "ping") {
+  async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
+    const raw = typeof message === "string" ? message : "";
+    if (raw === "ping") {
       ws.send("pong");
-    } else if (data === "subscribe") {
-      ws.send(JSON.stringify({ type: "subscribed", timestamp: new Date().toISOString() }));
+      return;
+    }
+
+    let msg: any;
+    try {
+      msg = JSON.parse(raw);
+    } catch {
+      return; // ignore non-JSON frames
+    }
+
+    if (msg?.type === "subscribe") {
+      await this.handleSubscribe(ws, msg);
     }
   }
 
@@ -115,7 +164,61 @@ export class SystemState implements DurableObject {
     // no-op; the runtime cleans the socket up
   }
 
-  /** Fan a JSON payload out to every connected client. */
+  // ---- presence subscription ----------------------------------------------
+
+  /** Accepts { type:"subscribe", all:true } or { type:"subscribe", ids:[...] }.
+   *  Also tolerates the Lanyard-ish aliases subscribe_to_all / subscribe_to_id
+   *  / subscribe_to_ids so older callers keep working. Replies with an
+   *  init_state snapshot of the requested presences. */
+  private async handleSubscribe(ws: WebSocket, msg: any): Promise<void> {
+    const sub: Sub = { all: false, ids: [] };
+
+    if (msg.all === true || msg.subscribe_to_all === true) {
+      sub.all = true;
+    } else {
+      const ids = new Set<string>();
+      if (typeof msg.subscribe_to_id === "string") ids.add(msg.subscribe_to_id);
+      for (const list of [msg.ids, msg.subscribe_to_ids]) {
+        if (Array.isArray(list)) for (const id of list) if (typeof id === "string") ids.add(id);
+      }
+      sub.ids = [...ids];
+    }
+
+    ws.serializeAttachment(sub);
+
+    const presences = await this.fetchPresences();
+    let data: Record<string, UnifiedPresence>;
+    if (sub.all) {
+      data = presences;
+    } else {
+      data = {};
+      for (const id of sub.ids) if (presences[id]) data[id] = presences[id];
+    }
+
+    try {
+      ws.send(JSON.stringify({ type: "init_state", data }));
+    } catch {
+      // socket went away mid-subscribe
+    }
+  }
+
+  /** Pull the current presence map from the GatewayManager DO. This also wakes
+   *  / keeps the Discord gateway connected (the /presences handler ensures it). */
+  private async fetchPresences(): Promise<Record<string, UnifiedPresence>> {
+    try {
+      const stub = this.env.GATEWAY.get(this.env.GATEWAY.idFromName("gateway"));
+      const res = await stub.fetch("https://do/presences");
+      if (!res.ok) return {};
+      return (await res.json()) as Record<string, UnifiedPresence>;
+    } catch {
+      return {};
+    }
+  }
+
+  // ---- fan-out ------------------------------------------------------------
+
+  /** Fan a { type, data } payload out to EVERY connected client. Used for
+   *  fronting / mental-state / device / force_refresh events. */
   private broadcast(data: unknown): void {
     const message = JSON.stringify(data);
     for (const ws of this.state.getWebSockets()) {
@@ -126,4 +229,18 @@ export class SystemState implements DurableObject {
       }
     }
   }
+
+  /** Fan a presence update out only to clients subscribed to that user. */
+  private broadcastPresence(presence: UnifiedPresence): void {
+    const message = JSON.stringify({ type: "presence_update", data: presence });
+    for (const ws of this.state.getWebSockets()) {
+      const sub = (ws.deserializeAttachment() as Sub | null) ?? EMPTY_SUB;
+      if (!sub.all && !sub.ids.includes(presence.user_id)) continue;
+      try {
+        ws.send(message);
+      } catch {
+        // drop dead sockets silently
+      }
+    }
+  }
 }
diff --git a/src/system/routes/admin.ts b/src/system/routes/admin.ts
index ae1cef6..ca26877 100644
--- a/src/system/routes/admin.ts
+++ b/src/system/routes/admin.ts
@@ -13,7 +13,7 @@ import { HttpError } from "../errors";
 
 export const adminRoutes = new Hono<Env>();
 
-/** Force every connected /v2/plural/ws client to refresh (admin only). */
+/** Force every connected /v2/ws client to refresh (admin only). */
 adminRoutes.post("/admin/refresh", requireAuth, requireAdmin, async (c) => {
   try {
     broadcastFrontendUpdate("force_refresh", { message: "Admin initiated refresh" });
diff --git a/src/system/routes/devices.ts b/src/system/routes/devices.ts
index 7bff261..8419ee8 100644
--- a/src/system/routes/devices.ts
+++ b/src/system/routes/devices.ts
@@ -24,6 +24,7 @@ import { Hono } from "hono";
 import type { Env } from "../hono";
 import { deleteDevice, getAllLevels, getDeviceLevel, setDeviceLevel } from "../services/devices";
 import { verifyBatteryAccess } from "../middleware/auth";
+import { broadcastDeviceUpdate } from "../ws";
 
 export const deviceRoutes = new Hono<Env>();
 
@@ -73,6 +74,7 @@ deviceRoutes.post("/", verifyBatteryAccess, async (c) => {
   }
 
   const record = await setDeviceLevel(device, patch);
+  broadcastDeviceUpdate(record);
   return c.json({ success: true, ...record });
 });
 
@@ -86,6 +88,7 @@ deviceRoutes.delete("/", verifyBatteryAccess, async (c) => {
   if (!deleted) {
     return c.json({ detail: `No state recorded for device '${device}'` }, 404);
   }
+  broadcastDeviceUpdate({ device, deleted: true });
   return c.json({ success: true, device, deleted: true });
 });
 
diff --git a/src/system/types.ts b/src/system/types.ts
index 96544b0..bc57292 100644
--- a/src/system/types.ts
+++ b/src/system/types.ts
@@ -13,8 +13,13 @@
  * first run any more.
  */
 export interface SystemEnv {
-  // ---- Durable Object binding (this DO, used for the singleton id) -------
+  // ---- Durable Object bindings -------------------------------------------
+  /** This DO, used for the singleton id. */
   SYSTEM: DurableObjectNamespace;
+  /** The GatewayManager DO (Discord presence). SystemState is the single
+   *  /v2/ws hub, so it pulls presence snapshots from here for INIT_STATE and
+   *  receives live PRESENCE_UPDATE relays from it. */
+  GATEWAY: DurableObjectNamespace;
 
   // ---- PluralKit ---------------------------------------------------------
   /** PluralKit system token (Authorization header for api.pluralkit.me). */
diff --git a/src/system/ws.ts b/src/system/ws.ts
index 3c52361..8ddf6af 100644
--- a/src/system/ws.ts
+++ b/src/system/ws.ts
@@ -7,7 +7,10 @@
 /**
  * Broadcast helpers. The old backend had a ConnectionManager holding a Set
  * of `ws` sockets; here the sockets live on the SystemState DO (hibernatable
- * WebSockets) and `rt().broadcast` fans a payload out to all of them.
+ * WebSockets) exposed at /v2/ws, and `rt().broadcast` fans a { type, data }
+ * payload out to every connected client. Presence updates are the one
+ * exception — they're relayed in from the GatewayManager DO and filtered per
+ * subscription (see do.ts), not sent through here.
  */
 
 import { rt } from "./runtime";
@@ -20,6 +23,11 @@ export function broadcastMentalStateUpdate(stateData: unknown): void {
   rt().broadcast({ type: "mental_state_update", data: stateData });
 }
 
+/** A device/battery state change ({ device, level, charging, ... }). */
+export function broadcastDeviceUpdate(deviceData: unknown): void {
+  rt().broadcast({ type: "device_update", data: deviceData });
+}
+
 export function broadcastFrontendUpdate(updateType: string, data: unknown): void {
   rt().broadcast({ type: updateType, data });
 }