Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(discord): ship a Discord Activity with a shared Forge room
nirholas8e7ab13c769d
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex e10bb29c1..c358fbeff 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -411,6 +411,7 @@ surface-map row already covers:| [workers/pump-fun-mcp/](workers/pump-fun-mcp) | Cloudflare Workers mirror of the canonical pump.fun MCP server || Account linking | Telegram sign-in [api/auth/telegram/](api/auth/telegram), link codes [api/auth/link-codes/](api/auth/link-codes), external wallets [api/auth/external-wallet/](api/auth/external-wallet), shared logic [api/_lib/account-link/](api/_lib/account-link), device page [pages/link-device.html](pages/link-device.html) `→ /link-device` + [src/link-device.js](src/link-device.js), account panels [src/dashboard-next/pages/account-linking.js](src/dashboard-next/pages/account-linking.js), CLI `three-ws link` [packages/three-ws-cli/src/link-code.js](packages/three-ws-cli/src/link-code.js) | Live | One-time, rate-limited, owner-confirmed linking of Telegram, phones, desktop apps, the CLI and chats, plus signed-message Solana/EVM wallets with step-up and a 24h payout cooldown. Docs: [docs/account-linking.md](docs/account-linking.md), [docs/chat-gateways.md](docs/chat-gateways.md). || [workers/agent-gateway/](workers/agent-gateway) | Chat gateway worker: drains `gateway_inbox` (filled by the webhook receivers in [api/gateway/](api/gateway)) through `handleEvent` in [api/_lib/gateway/core.js](api/_lib/gateway/core.js) and delivers replies, approval previews, signed approval requests and notifications back to the chat. Leased per-chat claims, platform-aware retries and dead letters, a `/healthz` endpoint, and operator commands for the bots and the inbox. Built and tested, not deployed: deliveries wait in the inbox until it runs. Docs: [workers/agent-gateway/README.md](workers/agent-gateway/README.md). Tests: [workers/agent-gateway/tests/](workers/agent-gateway/tests) |+| Discord Activity (Forge Room) | Page [pages/discord-activity.html](pages/discord-activity.html) `→ /discord-activity` + [src/discord-activity/app.js](src/discord-activity/app.js), config [api/gateway/discord-activity-config.js](api/gateway/discord-activity-config.js), OAuth [api/gateway/discord-activity-token.js](api/gateway/discord-activity-token.js) + [api/gateway/discord-activity-session.js](api/gateway/discord-activity-session.js), auth/session lib [api/_lib/gateway/discord-activity-auth.js](api/_lib/gateway/discord-activity-auth.js), room API [api/gateway/discord-activity-room/[id].js](api/gateway/discord-activity-room/%5Bid%5D.js), store [api/_lib/gateway/discord-activity-store.js](api/_lib/gateway/discord-activity-store.js), agent reactions [api/_lib/gateway/discord-activity-agent.js](api/_lib/gateway/discord-activity-agent.js), migration [api/_lib/migrations/20261015050000_discord_activity_rooms.sql](api/_lib/migrations/20261015050000_discord_activity_rooms.sql) | Built and tested, not live: needs a registered Discord application (`DISCORD_CLIENT_ID`/`DISCORD_CLIENT_SECRET`), owner-gated | An embedded Discord Activity for a voice channel: the group shares one Forge room, prompting and voting together on a single generation via the real `/api/forge` pipeline and `forge_votes` table. No coin, wallet, or purchase path. Docs: [docs/discord-activity.md](docs/discord-activity.md). Submission packet: [marketing/growth/submissions/discord-activity.md](marketing/growth/submissions/discord-activity.md) || [workers/signal-bridge/](workers/signal-bridge) | Signal leg of the chat gateway: the signal-cli REST bridge with its registration snapshotted to a Cloud Storage bucket so it survives redeploys. Single instance by design. Builds and runs locally, not deployed || [services/agent-screen-caster/](services/agent-screen-caster) | Self-hosted Playwright caster: an agent owner runs it on their own host with their agent id + key, and it streams the browser it drives into the agent-screen feed. No managed instance exists (the platform's own casting runs in `workers/agent-screen-pool` and `workers/agent-screen-worker`). Tests: [tests/agent-screen-caster.test.js](tests/agent-screen-caster.test.js) || [services/fleet-console/](services/fleet-console) | Health console for an open-source fleet: enumerates a GitHub owner's repositories, probes every deployment URL and npm package they advertise, and scores what each one actually delivers. Ships an HTTP dashboard, a CLI (`scan --attention` exits 1 when anything is broken, so cron can gate on it) and an MCP server over the same snapshot. Not deployed and not meant to be: it runs from a terminal, a cron job, or beside an agent. Tests: [tests/fleet-console.test.js](tests/fleet-console.test.js), [tests/fleet-console-server.test.js](tests/fleet-console-server.test.js) |diff --git a/api/_lib/gateway/discord-activity-agent.js b/api/_lib/gateway/discord-activity-agent.jsnew file mode 100644index 000000000..7c4a562f7--- /dev/null+++ b/api/_lib/gateway/discord-activity-agent.js@@ -0,0 +1,67 @@+// The three.ws agent's reaction line inside the shared Discord Activity Forge+// room (work order 088-partners-05). One short sentence, written by the+// platform LLM chain from the event that just happened and nothing else, the+// same validated-note pattern api/_lib/scout-notes.js uses for the Sentiment+// Scout: a model will happily invent a detail, so a line that fails the checks+// below is dropped and the deterministic template runs instead. Kept free of+// $THREE or any other coin/wallet mention: this room ships with no purchases.++import { llmComplete } from '../llm.js';++export const MAX_LINE_CHARS = 180;+const REACT_TIMEOUT_MS = 12_000;++const PROMISE_RE = /\b(guarantee[ds]?|guaranteed|risk[- ]free|can'?t lose|cannot lose|buy now|not financial advice|nfa)\b/i;+const URL_RE = /(https?:\/\/|www\.)/i;+const TICKER_RE = /\$[A-Za-z][A-Za-z0-9]{1,15}\b/;+const WALLET_RE = /\b(wallet|mint|token|coin|airdrop|solana|sol\b)\b/i;++export const REACTION_SYSTEM = `You are the three.ws agent sitting in a Discord voice-channel group Activity where the group is generating a shared 3D model together with Forge.++Write ONE short reaction sentence, under ${MAX_LINE_CHARS - 20} characters, in a warm and encouraging voice. React only to the fact you are given. Do not invent any detail (no object count, no technical claim) that is not in the fact. Never mention money, a coin, a token, a wallet or a price. No links, no hashtags, no emoji spam (zero or one is fine).++Reply with the sentence and nothing else.`;++function validateReaction(text) {+ if (typeof text !== 'string') return false;+ const trimmed = text.trim();+ if (!trimmed || trimmed.length > MAX_LINE_CHARS) return false;+ if (PROMISE_RE.test(trimmed) || URL_RE.test(trimmed) || TICKER_RE.test(trimmed) || WALLET_RE.test(trimmed)) return false;+ return true;+}++function fallbackReaction(event) {+ if (event.kind === 'prompt') return `Generating "${event.prompt.slice(0, 60)}" now, hang tight.`;+ if (event.kind === 'creation') return `Here it is! What does everyone think?`;+ if (event.kind === 'vote') return `${event.voteCount} vote${event.voteCount === 1 ? '' : 's'} so far.`;+ return 'Nice work, everyone.';+}++/**+ * One reaction line for a room event. Never throws: an LLM failure or a line+ * that fails validation falls back to the deterministic template above, so the+ * room always has something to show. `complete` is injectable for tests.+ */+export async function reactToEvent(event, { complete = llmComplete } = {}) {+ const fallback = fallbackReaction(event);+ let fact;+ if (event.kind === 'prompt') fact = `Someone just asked Forge to make: "${event.prompt}".`;+ else if (event.kind === 'creation') fact = `Forge just finished generating the model for the prompt: "${event.prompt}".`;+ else if (event.kind === 'vote') fact = `The group's current model now has ${event.voteCount} vote${event.voteCount === 1 ? '' : 's'}.`;+ else fact = 'Something happened in the room.';++ try {+ const res = await complete({+ system: REACTION_SYSTEM,+ user: fact,+ maxTokens: 80,+ timeoutMs: REACT_TIMEOUT_MS,+ track: { tool: 'discord_activity_agent' },+ });+ const text = res?.text?.trim();+ if (validateReaction(text)) return { text, model: res?.model || null, provider: res?.provider || null };+ } catch {+ // fall through to the deterministic line+ }+ return { text: fallback, model: null, provider: null };+}diff --git a/api/_lib/gateway/discord-activity-auth.js b/api/_lib/gateway/discord-activity-auth.jsnew file mode 100644index 000000000..efd2f8320--- /dev/null+++ b/api/_lib/gateway/discord-activity-auth.js@@ -0,0 +1,90 @@+// Auth for the Discord Activity (work order 088-partners-05): the OAuth2+// authorization-code exchange the Embedded App SDK's `authorize()` hands off+// to a server (Discord never lets the client hold the client secret), plus a+// short-lived HMAC-signed session that maps a verified Discord identity to one+// Activity instance. Mirrors forge-job-token.js's `f1.<payload>.<sig>` codec+// and signing key (server JWT_SECRET) rather than inventing a second scheme.++import { createHmac, timingSafeEqual } from 'node:crypto';++import { env } from '../env.js';++const DISCORD_TOKEN_URL = 'https://discord.com/api/oauth2/token';+const DISCORD_USER_URL = 'https://discord.com/api/users/@me';+const SESSION_TTL_S = 4 * 3600;++export function discordActivityConfigured() {+ return Boolean(process.env.DISCORD_CLIENT_ID && process.env.DISCORD_CLIENT_SECRET);+}++export class DiscordActivityAuthError extends Error {+ constructor(code, message, status = 400) {+ super(message);+ this.code = code;+ this.status = status;+ }+}++/**+ * Exchange the authorization code the client got from `discordSdk.commands.authorize()`+ * for an access token. Discord's own documented Activity flow: the client never+ * sees the client secret, so this round trip has to happen on a server.+ */+export async function exchangeActivityCode(code) {+ const clientId = process.env.DISCORD_CLIENT_ID;+ const clientSecret = process.env.DISCORD_CLIENT_SECRET;+ if (!clientId || !clientSecret) throw new DiscordActivityAuthError('not_configured', 'the Discord Activity is not configured', 503);+ if (typeof code !== 'string' || !code) throw new DiscordActivityAuthError('bad_code', 'code is required', 400);++ const resp = await fetch(DISCORD_TOKEN_URL, {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({ client_id: clientId, client_secret: clientSecret, grant_type: 'authorization_code', code }),+ });+ const data = await resp.json().catch(() => null);+ if (!resp.ok || !data?.access_token) {+ throw new DiscordActivityAuthError('token_exchange_failed', data?.error_description || data?.error || 'Discord rejected the authorization code', 502);+ }+ return { accessToken: data.access_token, scope: data.scope || null };+}++/** Verify an access token is real by asking Discord who it belongs to. */+export async function fetchDiscordUser(accessToken) {+ if (typeof accessToken !== 'string' || !accessToken) throw new DiscordActivityAuthError('bad_token', 'access_token is required', 400);+ const resp = await fetch(DISCORD_USER_URL, { headers: { Authorization: `Bearer ${accessToken}` } });+ const data = await resp.json().catch(() => null);+ if (!resp.ok || !data?.id) {+ throw new DiscordActivityAuthError('user_fetch_failed', data?.message || 'Discord rejected the access token', 502);+ }+ return { id: String(data.id), username: data.username, globalName: data.global_name || null, avatar: data.avatar || null };+}++function sign(payload) {+ return createHmac('sha256', env.JWT_SECRET).update(payload).digest('base64url');+}++/** `da1.<payload>.<sig>`, same shape family as forge-job-token.js's `f1.*`. */+export function signActivitySession({ discordUserId, username, globalName, roomId, guildId, channelId }) {+ const exp = Math.floor(Date.now() / 1000) + SESSION_TTL_S;+ const payload = Buffer.from(JSON.stringify({ u: discordUserId, n: username, g: globalName, r: roomId, gid: guildId, cid: channelId, exp }), 'utf8').toString('base64url');+ return `da1.${payload}.${sign(payload)}`;+}++export function verifyActivitySession(token) {+ if (typeof token !== 'string' || !token.startsWith('da1.')) return null;+ const parts = token.split('.');+ if (parts.length !== 3) return null;+ const [, payload, sig] = parts;+ if (!payload || !sig) return null;+ try {+ const expected = Buffer.from(sign(payload), 'utf8');+ const actual = Buffer.from(sig, 'utf8');+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return null;+ const obj = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));+ if (!obj?.u || !obj?.r || !obj?.exp) return null;+ if (obj.exp < Math.floor(Date.now() / 1000)) return null;+ return { discordUserId: obj.u, username: obj.n, globalName: obj.g || null, roomId: obj.r, guildId: obj.gid, channelId: obj.cid };+ } catch {+ return null;+ }+}diff --git a/api/_lib/gateway/discord-activity-store.js b/api/_lib/gateway/discord-activity-store.jsnew file mode 100644index 000000000..7f98607a3--- /dev/null+++ b/api/_lib/gateway/discord-activity-store.js@@ -0,0 +1,96 @@+// Persistence for the Discord Activity shared Forge room (work order+// 088-partners-05). One room per Discord Activity instance (a voice-channel+// session); state is derived from an append-only event log so every+// participant's SSE tail and every fresh snapshot agree with each other.+// Tables: 20261015050000_discord_activity_rooms.sql.++import { sql } from '../db.js';++export const EVENT_KINDS = ['join', 'prompt', 'creation', 'vote', 'agent_say'];+const MAX_RECENT_EVENTS = 200;++export async function ensureRoom({ roomId, guildId, channelId }) {+ const [row] = await sql`+ INSERT INTO discord_activity_rooms (id, guild_id, channel_id)+ VALUES (${roomId}, ${guildId}, ${channelId})+ ON CONFLICT (id) DO UPDATE SET last_active_at = now()+ RETURNING *`;+ return row;+}++export async function getRoom(roomId) {+ const [row] = await sql`SELECT * FROM discord_activity_rooms WHERE id = ${roomId}`;+ return row || null;+}++export async function upsertParticipant({ roomId, discordUserId, username, globalName }) {+ const [row] = await sql`+ INSERT INTO discord_activity_participants (room_id, discord_user_id, username, global_name)+ VALUES (${roomId}, ${discordUserId}, ${username}, ${globalName ?? null})+ ON CONFLICT (room_id, discord_user_id)+ DO UPDATE SET username = ${username}, global_name = ${globalName ?? null}, last_seen_at = now()+ RETURNING *`;+ return row;+}++export async function listParticipants(roomId) {+ return sql`+ SELECT discord_user_id, username, global_name, joined_at, last_seen_at+ FROM discord_activity_participants+ WHERE room_id = ${roomId}+ ORDER BY joined_at ASC`;+}++export async function appendEvent({ roomId, kind, actorDiscordId = null, payload = {} }) {+ if (!EVENT_KINDS.includes(kind)) throw new Error(`unknown event kind: ${kind}`);+ const [row] = await sql`+ INSERT INTO discord_activity_events (room_id, kind, actor_discord_id, payload)+ VALUES (${roomId}, ${kind}, ${actorDiscordId}, ${JSON.stringify(payload)}::jsonb)+ RETURNING *`;+ await sql`UPDATE discord_activity_rooms SET last_active_at = now() WHERE id = ${roomId}`;+ return row;+}++export async function listEvents({ roomId, afterId = 0, limit = MAX_RECENT_EVENTS }) {+ return sql`+ SELECT id, kind, actor_discord_id, payload, created_at+ FROM discord_activity_events+ WHERE room_id = ${roomId} AND id > ${afterId}+ ORDER BY id ASC+ LIMIT ${Math.min(limit, MAX_RECENT_EVENTS)}`;+}++/**+ * The current scene, folded from the event log: the latest prompt, the latest+ * completed creation, the vote tally for that creation, and the last few agent+ * lines. One fold keeps the GET snapshot and every SSE reconnect's "catch me up"+ * read in agreement, since both derive from the same rows.+ */+export async function getRoomSnapshot(roomId) {+ const [participants, events] = await Promise.all([+ listParticipants(roomId),+ sql`SELECT id, kind, actor_discord_id, payload, created_at FROM discord_activity_events WHERE room_id = ${roomId} ORDER BY id DESC LIMIT ${MAX_RECENT_EVENTS}`,+ ]);+ const ordered = [...events].reverse();+ let prompt = null;+ let creation = null;+ const votes = new Map();+ const agentLines = [];+ for (const ev of ordered) {+ if (ev.kind === 'prompt') prompt = { text: ev.payload.text, actorDiscordId: ev.actor_discord_id, createdAt: ev.created_at };+ else if (ev.kind === 'creation') {+ creation = { id: ev.payload.id, glbUrl: ev.payload.glb_url, previewImageUrl: ev.payload.preview_image_url, prompt: ev.payload.prompt, actorDiscordId: ev.actor_discord_id, createdAt: ev.created_at };+ votes.clear();+ } else if (ev.kind === 'vote') votes.set(ev.actor_discord_id, ev.payload.voted !== false);+ else if (ev.kind === 'agent_say') agentLines.push({ text: ev.payload.text, createdAt: ev.created_at });+ }+ return {+ roomId,+ participants: participants.map((p) => ({ discordUserId: p.discord_user_id, username: p.username, globalName: p.global_name })),+ prompt,+ creation,+ voteCount: [...votes.values()].filter(Boolean).length,+ agentLines: agentLines.slice(-5),+ lastEventId: events[0]?.id || 0,+ };+}diff --git a/api/_lib/migrations/20261015050000_discord_activity_rooms.sql b/api/_lib/migrations/20261015050000_discord_activity_rooms.sqlnew file mode 100644index 000000000..8230b5b81--- /dev/null+++ b/api/_lib/migrations/20261015050000_discord_activity_rooms.sql@@ -0,0 +1,38 @@+-- Discord Activity shared state (work order 088-partners-05): one row per+-- Discord Activity instance (a voice-channel session), an append-only event+-- log participants poll/stream for the shared scene, and the roster of who is+-- in it. instance_id is Discord's own opaque activity-instance id, so it is+-- text, not a uuid; guild_id/channel_id are Discord snowflakes (text, they+-- exceed JS safe-integer range).+create table if not exists discord_activity_rooms (+ id text primary key,+ guild_id text not null,+ channel_id text not null,+ created_at timestamptz not null default now(),+ last_active_at timestamptz not null default now()+);++create table if not exists discord_activity_participants (+ room_id text not null references discord_activity_rooms(id) on delete cascade,+ discord_user_id text not null,+ username text not null,+ global_name text,+ joined_at timestamptz not null default now(),+ last_seen_at timestamptz not null default now(),+ primary key (room_id, discord_user_id)+);++-- kind: 'join' | 'prompt' | 'creation' | 'vote' | 'agent_say'. payload shape+-- depends on kind; the store module is the only reader/writer so the shape+-- lives there, not in a check constraint.+create table if not exists discord_activity_events (+ id bigserial primary key,+ room_id text not null references discord_activity_rooms(id) on delete cascade,+ kind text not null,+ actor_discord_id text,+ payload jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now()+);++create index if not exists discord_activity_events_room_idx+ on discord_activity_events (room_id, id);diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex e9b8965bb..630b6acd0 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -1111,6 +1111,12 @@ export const limits = {// caps real influence at one vote each). Non-critical: a Redis blip must// never block a vote — the vote itself is idempotent.forgeVote: (key) => getLimiter('forge:vote', { limit: 120, window: '10 m' }).limit(key),+ // Discord Activity shared Forge room (api/gateway/discord-activity-room):+ // one group of up to a voice channel's worth of people posting prompts,+ // creations and votes into one room. Keyed per Discord user id so a bored+ // participant can't flood the room's event log for the whole call; a real+ // voice channel session comfortably fits inside this.+ discordActivityWrite: (discordUserId) => getLimiter('discord:activity:write', { limit: 60, window: '10 m' }).limit(discordUserId),// Free text→3D lane (api/v1/ai/text-to-3d) — each generation drives one real// NVIDIA NIM TRELLIS GPU inference, so the free tier is a per-IP daily quota// (10/day). Above it the endpoint returns 429 + a pointer to the paiddiff --git a/api/gateway/discord-activity-config.js b/api/gateway/discord-activity-config.jsnew file mode 100644index 000000000..c36f59ac5--- /dev/null+++ b/api/gateway/discord-activity-config.js@@ -0,0 +1,27 @@+// GET /api/gateway/discord-activity-config: the handful of public values the+// Activity's client bundle needs before it can call discordSdk.ready(): the+// OAuth client id (public by design, Discord's own authorize() call sends it)+// and the CDN host Discord must proxy for R2-hosted previews. Baking these into+// the build would mean a rebuild every time the Developer Portal app changes;+// reading them from the Cloud Run service's env lets the owner wire a real+// Discord application without touching code.++import { cors, json, method, error, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const clientId = process.env.DISCORD_CLIENT_ID;+ if (!clientId) return error(res, 503, 'not_configured', 'the Discord Activity is not configured');++ let cdnHost = null;+ try {+ cdnHost = new URL(env.S3_PUBLIC_DOMAIN).host;+ } catch {+ cdnHost = null;+ }++ return json(res, 200, { client_id: clientId, cdn_host: cdnHost }, { 'cache-control': 'public, max-age=60' });+});diff --git a/api/gateway/discord-activity-room/[id].js b/api/gateway/discord-activity-room/[id].jsnew file mode 100644index 000000000..6dc8680a8--- /dev/null+++ b/api/gateway/discord-activity-room/[id].js@@ -0,0 +1,175 @@+// /api/gateway/discord-activity-room/:id GET room snapshot+// /api/gateway/discord-activity-room/:id/stream GET SSE tail of room events+// /api/gateway/discord-activity-room/:id/prompt POST { text }, announce the prompt the group just sent to Forge+// /api/gateway/discord-activity-room/:id/creation POST { creation_id }, a submitted Forge job finished; share it with the room+// /api/gateway/discord-activity-room/:id/vote POST { vote }, vote on the room's current creation+//+// :id is a Discord Activity instance id. Every call needs the Bearer session+// token minted by discord-activity-session.js, and the token's own room id+// must match :id: a session can only act in the room it was issued for.+// Forge generation itself stays on the real /api/forge and /api/forge-vote+// endpoints (called by the client through Discord's `/.proxy/` mapping); this+// handler only shares the result with everyone in the call. No coin, wallet or+// purchase path: this room is free, per the order's own scope decision.++import { cors, json, method, error, readJson, wrap } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';+import { isUuid } from '../../_lib/validate.js';+import { verifyActivitySession } from '../../_lib/gateway/discord-activity-auth.js';+import { getRoom, getRoomSnapshot, appendEvent, listEvents } from '../../_lib/gateway/discord-activity-store.js';+import { reactToEvent } from '../../_lib/gateway/discord-activity-agent.js';+import { getPublicCreation, castVote, removeVote, hashClient } from '../../_lib/forge-store.js';++const INSTANCE_RE = /^[A-Za-z0-9_-]{1,128}$/;+const HEARTBEAT_MS = 15_000;+const POLL_MS = 2_000;+const MAX_DURATION_MS = 280_000;++function voterKeyFor(discordUserId) {+ return hashClient(`discord:${discordUserId}`);+}++// The stream sub-route is read by the browser's native EventSource, which+// cannot attach an Authorization header, so it carries the session token as a+// query param instead; every other sub-route uses the real header. Both are+// the same short-lived HMAC token, scoped to one room, over HTTPS only.+function bearerToken(req, url) {+ const header = req.headers.authorization || '';+ const m = /^Bearer\s+(.+)$/i.exec(header);+ if (m) return m[1];+ return url.searchParams.get('token');+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const url = new URL(req.url, 'http://x');+ const parts = url.pathname.split('/').filter(Boolean); // ['api','gateway','discord-activity-room', ':id', sub?]+ const roomId = parts[3] || '';+ const sub = parts[4] || null;+ if (!INSTANCE_RE.test(roomId)) return error(res, 404, 'not_found', 'room not found');++ const session = verifyActivitySession(bearerToken(req, url));+ if (!session || session.roomId !== roomId) return error(res, 401, 'unauthorized', 'a valid Activity session for this room is required');++ const room = await getRoom(roomId);+ if (!room) return error(res, 404, 'not_found', 'room not found');++ if (sub === null && req.method === 'GET') return json(res, 200, { data: await getRoomSnapshot(roomId) }, { 'cache-control': 'no-store' });+ if (sub === 'stream' && req.method === 'GET') return streamRoom(req, res, roomId);+ if (sub === 'prompt' && req.method === 'POST') return submitPrompt(req, res, roomId, session);+ if (sub === 'creation' && req.method === 'POST') return shareCreation(req, res, roomId, session);+ if (sub === 'vote' && req.method === 'POST') return voteOnCreation(req, res, roomId, session);+ return error(res, 404, 'not_found', 'not found');+});++async function writeGate(res, session) {+ const rl = await limits.discordActivityWrite(session.discordUserId);+ if (!rl.success) {+ res.statusCode = 429;+ json(res, 429, { error: 'rate_limited', message: 'Slow down a little, the room can only take so many actions a minute.' });+ return false;+ }+ return true;+}++async function reactAndBroadcast(roomId, actorDiscordId, reactionEvent) {+ const { text } = await reactToEvent(reactionEvent);+ await appendEvent({ roomId, kind: 'agent_say', actorDiscordId, payload: { text } });+}++async function submitPrompt(req, res, roomId, session) {+ if (!(await writeGate(res, session))) return;+ const body = (await readJson(req, 4_096)) || {};+ const text = typeof body.text === 'string' ? body.text.trim() : '';+ if (!text) return error(res, 400, 'empty_prompt', 'text is required');+ if (text.length > 400) return error(res, 400, 'prompt_too_long', 'Keep the prompt under 400 characters.');++ await appendEvent({ roomId, kind: 'prompt', actorDiscordId: session.discordUserId, payload: { text } });+ await reactAndBroadcast(roomId, session.discordUserId, { kind: 'prompt', prompt: text });+ return json(res, 200, { data: await getRoomSnapshot(roomId) });+}++async function shareCreation(req, res, roomId, session) {+ if (!(await writeGate(res, session))) return;+ const body = (await readJson(req, 4_096)) || {};+ const creationId = typeof body.creation_id === 'string' ? body.creation_id.trim() : '';+ if (!isUuid(creationId)) return error(res, 400, 'bad_creation', 'creation_id must be a uuid');++ const creation = await getPublicCreation({ id: creationId });+ if (!creation) return error(res, 404, 'not_found', 'that creation is not a finished, public Forge result');++ await appendEvent({+ roomId,+ kind: 'creation',+ actorDiscordId: session.discordUserId,+ payload: { id: creation.id, glb_url: creation.glb_url, preview_image_url: creation.preview_image_url, prompt: creation.prompt },+ });+ await reactAndBroadcast(roomId, session.discordUserId, { kind: 'creation', prompt: creation.prompt });+ return json(res, 200, { data: await getRoomSnapshot(roomId) });+}++async function voteOnCreation(req, res, roomId, session) {+ if (!(await writeGate(res, session))) return;+ const snapshot = await getRoomSnapshot(roomId);+ if (!snapshot.creation?.id) return error(res, 409, 'no_creation', 'nothing has been shared with the room yet');++ const body = (await readJson(req, 4_096)) || {};+ const removing = body?.vote === false;+ const voterKey = voterKeyFor(session.discordUserId);+ const result = removing+ ? await removeVote({ creationId: snapshot.creation.id, voterKey })+ : await castVote({ creationId: snapshot.creation.id, voterKey });+ if (!result) return error(res, 409, 'vote_failed', 'that creation can no longer be voted on');++ await appendEvent({ roomId, kind: 'vote', actorDiscordId: session.discordUserId, payload: { voted: !removing, vote_count: result.voteCount } });+ await reactAndBroadcast(roomId, session.discordUserId, { kind: 'vote', voteCount: result.voteCount });+ return json(res, 200, { data: await getRoomSnapshot(roomId) });+}++function openSse(res) {+ res.writeHead(200, {+ 'Content-Type': 'text/event-stream; charset=utf-8',+ 'Cache-Control': 'no-cache, no-transform',+ 'X-Accel-Buffering': 'no',+ Connection: 'keep-alive',+ });+ const hb = setInterval(() => {+ try { res.write(':hb\n\n'); } catch { clearInterval(hb); }+ }, HEARTBEAT_MS);+ res.on('close', () => clearInterval(hb));+ return () => clearInterval(hb);+}++async function streamRoom(req, res, roomId) {+ const url = new URL(req.url, 'http://x');+ let cursor = Number(req.headers['last-event-id'] || url.searchParams.get('after') || 0) || 0;++ const close = openSse(res);+ let stopped = false;+ const stop = () => {+ if (stopped) return;+ stopped = true;+ clearInterval(timer);+ clearTimeout(deadline);+ close();+ if (!res.writableEnded) res.end();+ };+ const pump = async () => {+ if (stopped) return;+ try {+ const events = await listEvents({ roomId, afterId: cursor, limit: 100 });+ for (const ev of events) {+ cursor = ev.id;+ res.write(`id: ${ev.id}\ndata: ${JSON.stringify({ id: ev.id, kind: ev.kind, actor_discord_id: ev.actor_discord_id, payload: ev.payload, created_at: ev.created_at })}\n\n`);+ }+ } catch (e) {+ console.warn('[discord-activity-room] stream poll failed', e?.message);+ }+ };+ const timer = setInterval(pump, POLL_MS);+ const deadline = setTimeout(stop, MAX_DURATION_MS);+ req.on('close', stop);+ await pump();+}diff --git a/api/gateway/discord-activity-session.js b/api/gateway/discord-activity-session.jsnew file mode 100644index 000000000..a968e8646--- /dev/null+++ b/api/gateway/discord-activity-session.js@@ -0,0 +1,43 @@+// POST /api/gateway/discord-activity-session: maps a verified Discord identity+// to a three.ws session scoped to one Activity instance. The client sends the+// access_token discordSdk.commands.authenticate() returned plus the instance's+// guild/channel/instance ids (all from discordSdk.instanceId etc., never+// trusted as identity on their own); this handler re-checks the token against+// Discord's own /users/@me before minting anything, so a forged client claim+// can never seat an impostor in someone else's room.++import { cors, json, method, error, readJson, wrap } from '../_lib/http.js';+import { fetchDiscordUser, signActivitySession, discordActivityConfigured, DiscordActivityAuthError } from '../_lib/gateway/discord-activity-auth.js';+import { ensureRoom, upsertParticipant, appendEvent } from '../_lib/gateway/discord-activity-store.js';++const SNOWFLAKE_RE = /^\d{1,24}$/;+const INSTANCE_RE = /^[A-Za-z0-9_-]{1,128}$/;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ if (!discordActivityConfigured()) return error(res, 503, 'not_configured', 'the Discord Activity is not configured');++ const body = (await readJson(req, 4_096)) || {};+ const instanceId = typeof body.instance_id === 'string' ? body.instance_id : '';+ const guildId = typeof body.guild_id === 'string' ? body.guild_id : '';+ const channelId = typeof body.channel_id === 'string' ? body.channel_id : '';+ if (!INSTANCE_RE.test(instanceId)) return error(res, 400, 'bad_instance', 'instance_id is required');+ if (!SNOWFLAKE_RE.test(guildId) || !SNOWFLAKE_RE.test(channelId)) return error(res, 400, 'bad_ids', 'guild_id and channel_id are required');++ let user;+ try {+ user = await fetchDiscordUser(body.access_token);+ } catch (e) {+ if (e instanceof DiscordActivityAuthError) return error(res, e.status, e.code, e.message);+ throw e;+ }++ await ensureRoom({ roomId: instanceId, guildId, channelId });+ await upsertParticipant({ roomId: instanceId, discordUserId: user.id, username: user.username, globalName: user.globalName });+ await appendEvent({ roomId: instanceId, kind: 'join', actorDiscordId: user.id, payload: { username: user.username } });++ const sessionToken = signActivitySession({ discordUserId: user.id, username: user.username, globalName: user.globalName, roomId: instanceId, guildId, channelId });+ return json(res, 200, { session_token: sessionToken, user: { id: user.id, username: user.username, global_name: user.globalName, avatar: user.avatar } });+});diff --git a/api/gateway/discord-activity-token.js b/api/gateway/discord-activity-token.jsnew file mode 100644index 000000000..899c02e22--- /dev/null+++ b/api/gateway/discord-activity-token.js@@ -0,0 +1,24 @@+// POST /api/gateway/discord-activity-token: the OAuth2 code-for-token swap the+// Discord Embedded App SDK's `authorize()` hands off to a server (Discord+// never lets the client hold DISCORD_CLIENT_SECRET). The client calls this+// right after authorize(), then feeds the returned access_token into its own+// `discordSdk.commands.authenticate({ access_token })`.++import { cors, json, method, error, readJson, wrap } from '../_lib/http.js';+import { exchangeActivityCode, discordActivityConfigured, DiscordActivityAuthError } from '../_lib/gateway/discord-activity-auth.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ if (!discordActivityConfigured()) return error(res, 503, 'not_configured', 'the Discord Activity is not configured');++ const body = (await readJson(req, 4_096)) || {};+ try {+ const { accessToken } = await exchangeActivityCode(body.code);+ return json(res, 200, { access_token: accessToken });+ } catch (e) {+ if (e instanceof DiscordActivityAuthError) return error(res, e.status, e.code, e.message);+ throw e;+ }+});diff --git a/data/changelog.json b/data/changelog.jsonindex 09b951ffb..4bb545ff2 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,17 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-13",+ "title": "A Discord Activity brings a shared Forge room into any voice channel",+ "link": "/docs/discord-activity",+ "summary": "Open the new Activity from a Discord voice channel and everyone in the call shares one Forge room: one prompt, one in-progress generation, one finished model with a shared vote count, and an agent that reacts in text to what just happened. Auth maps a verified Discord identity (re-checked against Discord's own /users/@me, never trusted from the client) to a room-scoped session; generation and voting reuse the real /api/forge pipeline and forge_votes table rather than a separate throwaway pipeline. No coin, wallet, or purchase path. Docs: /docs/discord-activity. Submission packet for Developer Portal setup and Discovery copy: marketing/growth/submissions/discord-activity.md.",+ "tags": [+ "feature",+ "integrations",+ "docs"+ ]+ },{"date": "2026-10-13","title": "A three.ws avatar now lipsyncs to any LiveKit Agents or Pipecat voice pipeline",diff --git a/data/pages.json b/data/pages.jsonindex be6dd8833..0a3a8b69a 100644--- a/data/pages.json+++ b/data/pages.json@@ -377,6 +377,15 @@"added": "2026-08-28","showcase": true},+ {+ "path": "/discord-activity",+ "title": "Forge Room (Discord Activity)",+ "description": "A shared Forge room that runs embedded inside a Discord voice channel: everyone in the call prompts, watches the same 3D model generate, and votes together.",+ "priority": 0.3,+ "changefreq": "monthly",+ "added": "2026-10-13",+ "indexable": false+ },{"path": "/knock","title": "Knock",@@ -6706,6 +6715,14 @@"changefreq": "monthly","added": "2026-10-13"},+ {+ "path": "/docs/discord-activity",+ "title": "Docs: Discord Activity (Forge Room)",+ "description": "How the three.ws Discord Activity works: the OAuth2 auth flow, Discord's /.proxy/ URL mapping and CSP, the shared event-sourced room state, and why it ships with no purchases.",+ "priority": 0.6,+ "changefreq": "monthly",+ "added": "2026-10-13"+ },{"path": "/docs/rig-doctor","title": "Rig Doctor reference",diff --git a/docs/discord-activity.md b/docs/discord-activity.mdnew file mode 100644index 000000000..098fe6361--- /dev/null+++ b/docs/discord-activity.md@@ -0,0 +1,103 @@+# Discord Activity: Forge Room++three.ws ships a [Discord Activity](https://discord.com/developers/docs/activities/overview):+an embedded web app that opens inside a Discord voice channel, visible to+everyone in the call. Ours is a **shared Forge room**: the group writes one+prompt together, watches the same 3D model generate, and votes on it, live,+without leaving Discord.++**On this page:** [How it works](#how-it-works) · [Auth flow](#auth-flow) · [Proxy and CSP](#proxy-and-csp) · [Shared state](#shared-state) · [Purchases](#purchases) · [Owner setup](#owner-setup)++---++## How it works++Open the Activity from a voice channel's Activities launcher and everyone in+the call sees the same room:++1. One person types a prompt. The room shows "`<name>` prompted: ...".+2. The prompt goes straight to the real `/api/forge` generation pipeline+ (the same endpoint [the Forge Studio](/forge) uses) and the room polls it+ to completion.+3. The finished model (preview image + an "Open in 3D" link) posts to+ everyone in the room at once, with a shared like/vote count.+4. An agent reacts in text to what just happened, grounded only in the real+ prompt and vote count (see [Agent reactions](#agent-reactions)).++No account creation, no wallet, no purchase: the room is free to use for+anyone already in the voice channel.++## Auth flow++The Activity never holds a Discord client secret. The flow, per+[Discord's documented OAuth2 flow for Activities](https://discord.com/developers/docs/activities/development-guides/networking):++1. The client calls `discordSdk.commands.authorize({ scope: ['identify'] })`+ and gets back an authorization `code`.+2. The client POSTs that code to `POST /api/gateway/discord-activity-token`,+ which exchanges it for an `access_token` server-side+ (`api/_lib/gateway/discord-activity-auth.js`, `exchangeActivityCode`).+3. The client calls `discordSdk.commands.authenticate({ access_token })` to+ finish authenticating the SDK itself.+4. The client POSTs the access token plus the Activity's `instance_id`,+ `guild_id`, and `channel_id` to `POST /api/gateway/discord-activity-session`,+ which re-verifies the token against Discord's own `/users/@me` (never+ trusting the client's claimed identity), creates or updates the room, and+ mints a short-lived (4 hour) HMAC-signed session token scoped to that one+ room.++Every room API call after that carries `Authorization: Bearer <session token>`+(the SSE stream carries it as `?token=` instead, since the browser's native+`EventSource` cannot set custom headers).++## Proxy and CSP++Everything inside the Activity iframe runs under Discord's `/.proxy/` network+model: same-origin calls (`/api/forge`, `/api/gateway/...`) are proxied+automatically by Discord's root URL mapping, no configuration needed. Any+*other* domain the client fetches, loads an image from, or opens a script+against needs an explicit URL Mapping in the Discord Developer Portal, or+Discord's CSP blocks it.++This app has exactly one such cross-origin dependency: the R2 CDN that serves+Forge preview images and GLBs. The client calls+`patchUrlMappings([{ prefix: 'cdn', target: cdnHost }], { patchFetch: true, patchXhr: true, patchSrcAttributes: true })`+once at startup (`src/discord-activity/app.js`), which transparently rewrites+any request to that host through Discord's proxy. The matching Developer+Portal mapping is listed in+[`marketing/growth/submissions/discord-activity.md`](https://github.com/nirholas/three.ws/blob/main/marketing/growth/submissions/discord-activity.md).++Deliberately kept out of the iframe: a full WebGL `<model-viewer>`. This+codebase only ever loads `<model-viewer>` from an external CDN script tag, and+that would mean a second URL Mapping plus a `script-src` CSP exception for a+cramped voice-channel panel. The room instead shows the 2D preview image and+an `openExternalLink` button to the model's real `/forge/share/:id` page,+which opens full 3D in the user's normal browser.++## Shared state++One room per Discord Activity `instance_id` (one room per voice-channel+session). State lives server-side as an append-only event log+(`discord_activity_events`, migration+`api/_lib/migrations/20261015050000_discord_activity_rooms.sql`), folded into+one snapshot (`getRoomSnapshot` in `api/_lib/gateway/discord-activity-store.js`)+that both a fresh `GET` and a reconnecting `EventSource` agree on. Voting+reuses the platform's real `forge_votes` table (`castVote`/`removeVote` in+`api/_lib/forge-store.js`), so a room's vote count is the same tally the+public Forge gallery shows, not a separate throwaway count.++## Purchases++None. This Activity does not sell anything, so it registers no SKUs and never+calls `discordSdk.commands.startPurchase`. If a paid room tier is added later,+it goes through Discord's own IAP flow (SKUs configured in the Developer+Portal, `startPurchase` client-side) rather than our own payment rails, since+Discord requires Activity purchases to go through its own commerce API.++## Owner setup++The Activity needs a registered Discord application before any of this runs+live. Exact Developer Portal settings, the URL Mapping list, and the+Discovery listing copy are written out in+[`marketing/growth/submissions/discord-activity.md`](https://github.com/nirholas/three.ws/blob/main/marketing/growth/submissions/discord-activity.md).+Owner action is tracked in `prompts/finish/_context/production-100-OWNER-ACTIONS.md`.diff --git a/marketing/growth/submissions/discord-activity.md b/marketing/growth/submissions/discord-activity.mdnew file mode 100644index 000000000..605db80db--- /dev/null+++ b/marketing/growth/submissions/discord-activity.md@@ -0,0 +1,168 @@+# Discord Activity submission: Forge Room++Target: [Discord Developer Portal](https://discord.com/developers/applications)+(create the application) and, once live, [Discord Activity Discovery](https://discord.com/developers/docs/activities/discovery)+(order 939).++Ready for owner order 939. Built and tested in work order 088; the account+creation, env vars, and Discovery submission are owner actions (CLAUDE.md+gate 2 and the "Never blocked" rule for a step that needs a third-party+account only the owner can create). This Evolve session confirmed no Discord+application exists in production yet: `DISCORD_CLIENT_ID` /+`DISCORD_CLIENT_SECRET` are unset, and even `DISCORD_PUBLIC_KEY` (used by the+pre-existing interactions webhook, `api/gateway/discord.js`) has never been+provisioned.++## What ships++- `pages/discord-activity.html` + `src/discord-activity/app.js`: the+ Activity's client, built on `@discord/embedded-app-sdk` v2.5.0.+- `api/gateway/discord-activity-config.js`: public runtime config+ (`client_id`, `cdn_host`), 503 until the owner sets the env vars below.+- `api/gateway/discord-activity-token.js`, `api/gateway/discord-activity-session.js`,+ `api/_lib/gateway/discord-activity-auth.js`: the OAuth2 code exchange and+ session minting, verified against Discord's own `/users/@me`.+- `api/gateway/discord-activity-room/[id].js`, `api/_lib/gateway/discord-activity-store.js`:+ the shared room (snapshot, SSE stream, prompt/creation/vote), backed by+ `api/_lib/migrations/20261015050000_discord_activity_rooms.sql`.+- `api/_lib/gateway/discord-activity-agent.js`: grounded agent reaction lines.+- Docs: `docs/discord-activity.md`. Changelog and `STRUCTURE.md` wired.++## Step 1: create the Discord application++1. Go to <https://discord.com/developers/applications> → **New Application**.+2. Name: `three.ws` (or `three.ws Forge Room` if that name is taken by+ another of the owner's apps).+3. Under **General Information**, copy the **Application ID** (this is+ `DISCORD_CLIENT_ID`) and the **Public Key** (this is `DISCORD_PUBLIC_KEY`,+ needed by the existing `api/gateway/discord.js` interactions webhook,+ currently also unset).+4. Under **OAuth2 → General**, click **Reset Secret**, copy it+ (`DISCORD_CLIENT_SECRET`). This value is shown once.++## Step 2: enable Activities++1. In the application sidebar, open **Activities → Settings**.+2. Toggle **Enable Activities** on.+3. **Supported Platforms**: enable Desktop and Mobile (the room UI is+ responsive; it has been reviewed for a narrow mobile Activity panel width).+4. **Root Mapping**: set the Activity's root URL to the production three.ws+ origin (`https://three.ws`), with the entry path `/discord-activity`.+ Discord auto-proxies this root domain; no explicit URL Mapping entry is+ needed for it.+5. **URL Mappings** (additional mappings, beyond the root): add one row:+ - Prefix: `cdn`+ - Target: the live value of `S3_PUBLIC_DOMAIN` without the scheme, e.g.+ `pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev` (confirm the exact live+ value with `node scripts/read-service-env.mjs '^S3_PUBLIC_DOMAIN$' --raw`+ before saving; it must match exactly, no trailing slash).++ This is the CDN that serves Forge preview images; the client calls+ `patchUrlMappings([{ prefix: 'cdn', target: cdnHost }], ...)` on boot+ (`src/discord-activity/app.js`) to route through it. Do not add a mapping+ for `/api/forge` or `/api/gateway/*`: those are same-origin and already+ covered by the root mapping.++## Step 3: OAuth2 redirect and scopes++1. Under **OAuth2 → General → Redirects**, add:+ `https://three.ws/discord-activity` (the client only uses the+ authorization-code grant inside the SDK's `authorize()` call, which does+ not perform a browser redirect, but Discord requires at least one+ registered redirect URI to issue a client secret).+2. No additional OAuth2 scopes need to be pre-approved; the Activity requests+ `identify` only, at runtime, via `discordSdk.commands.authorize()`.++## Step 4: set the environment on Cloud Run++Use `--update-env-vars` (never `--set-env-vars`, which replaces the entire+env set):++```bash+gcloud run services update three-ws-api --region us-central1 \+ --update-env-vars DISCORD_CLIENT_ID=<application id>,DISCORD_CLIENT_SECRET=<client secret>,DISCORD_PUBLIC_KEY=<public key>+```++## Step 5: run the migration++```bash+npm run db:status # confirm the pending migration is the one expected+npm run db:migrate # applies immediately, no dry run+```++This creates `discord_activity_rooms`, `discord_activity_participants`, and+`discord_activity_events`.++## Step 6: verify in a real Discord client++1. In the Developer Portal, add a **Test Server** the owner controls (or use+ an existing server where the owner has **Manage Server**).+2. Open that server's voice channel in the actual Discord desktop or mobile+ client (Activities do not run in a browser tab outside Discord; this+ Evolve session's build cannot verify this step because no Discord+ application has ever been registered, so there is nothing to launch+ against yet).+3. Click the Activities launcher (rocket icon) in the voice channel and+ select the three.ws Activity.+4. Have a second account join the same voice channel and open the Activity.+5. From account A, type a prompt and submit. Confirm account B's panel shows+ the same prompt line, the same "Generating..." status, and the same+ finished model + vote count once it completes, without refreshing.+6. Screenshot both accounts' panels side by side as the completion evidence+ for this Definition of Done line.++## Step 7: Discovery submission++Once Step 6 passes, submit for Activity Discovery per+<https://discord.com/developers/docs/activities/discovery>. Suggested listing+copy:++**Name:** Forge Room++**Tagline:** Prompt, generate, and vote on a 3D model together, live in your+voice channel.++**Description:**++> Forge Room turns your voice channel into a tiny shared 3D studio. Anyone in+> the call can type a prompt, and everyone watches the same model generate in+> real time, powered by three.ws's free Forge pipeline. When it's done, vote+> on it as a group and open the full interactive 3D view in your browser with+> one tap. No sign-up, no wallet, nothing to buy: just the group, a prompt,+> and a model everyone made together.++**Category:** Creativity / Social++**Age rating:** Discord's standard Activity rating applies; no user-generated+content beyond the text prompt and the resulting 3D model is stored outside+the room's own event log, and prompts flow through the same content+validation the public Forge studio already uses.++## Verification packet++- Source: this repository, `pages/discord-activity.html`,+ `src/discord-activity/`, `api/gateway/discord-activity-*`,+ `api/_lib/gateway/discord-activity-*`.+- OAuth2 code-exchange wiring proven live: a POST to Discord's real+ `https://discord.com/api/oauth2/token` with a placeholder client id/secret+ and an invalid code returns Discord's own documented `invalid_client`+ error, confirming the exchange path reaches Discord's real API rather than+ a mock (see the Evolve session's closing report for the exact response).+- Local tests: `tests/discord-activity-store.test.js`,+ `tests/discord-activity-auth.test.js` (pglite-backed, no mocks of the+ store's own SQL).+- `npm run check:rules` passes on every touched file.++## Owner steps (not automatable here)++1. Create the Discord application and copy its three credentials (Step 1).+2. Enable Activities, set the root mapping and the `cdn` URL Mapping (Step 2).+3. Add the OAuth2 redirect (Step 3).+4. Set `DISCORD_CLIENT_ID` / `DISCORD_CLIENT_SECRET` / `DISCORD_PUBLIC_KEY` on+ Cloud Run with `--update-env-vars` (Step 4).+5. Run `npm run db:migrate` for `20261015050000_discord_activity_rooms.sql`+ (Step 5).+6. Add a test server, open the Activity from two real Discord accounts in a+ voice channel, and capture the two-accounts-same-state screenshots+ (Step 6).+7. Submit the Discovery listing using the copy above (Step 7).diff --git a/package-lock.json b/package-lock.jsonindex 4650972b0..b71e2d42e 100644--- a/package-lock.json+++ b/package-lock.json@@ -99,6 +99,7 @@"@coinbase/x402": "^2.1.0","@coral-xyz/anchor": "^0.32.1","@dimforge/rapier3d-compat": "^0.19.3",+ "@discord/embedded-app-sdk": "^2.5.0","@elevenlabs/elevenlabs-js": "^2.68.0","@ellipsis-labs/rise": "^0.5.26","@ethereum-attestation-service/eas-sdk": "^2.10.0",@@ -5909,6 +5910,35 @@"version": "0.19.3","license": "Apache-2.0"},+ "node_modules/@discord/embedded-app-sdk": {+ "version": "2.5.0",+ "resolved": "https://registry.npmjs.org/@discord/embedded-app-sdk/-/embedded-app-sdk-2.5.0.tgz",+ "integrity": "sha512-FNoe5PbSkoKEbqPubaBmq6tlEMOftMjR3gu55YrdrrKmBfKKM4i9P/Z+Zxl0RZdJcKviBwVcTyYMMPM/aGex/w==",+ "license": "MIT",+ "dependencies": {+ "@types/lodash.transform": "^4.6.6",+ "@types/uuid": "^10.0.0",+ "big-integer": "^1.6.48",+ "decimal.js-light": "^2.5.0",+ "eventemitter3": "^5.0.0",+ "lodash.transform": "^4.6.0",+ "uuid": "^11.0.0",+ "zod": "^3.9.8"+ }+ },+ "node_modules/@discord/embedded-app-sdk/node_modules/uuid": {+ "version": "11.1.1",+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz",+ "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==",+ "funding": [+ "https://github.com/sponsors/broofa",+ "https://github.com/sponsors/ctavan"+ ],+ "license": "MIT",+ "bin": {+ "uuid": "dist/esm/bin/uuid"+ }+ },"node_modules/@dnsquery/dns-packet": {"version": "6.1.1","license": "MIT",@@ -28361,6 +28391,21 @@"@types/node": "*"}},+ "node_modules/@types/lodash": {+ "version": "4.17.26",+ "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.26.tgz",+ "integrity": "sha512-48NWfiY6oNcKOh47Z4h+sIvwcQR91h6KPhaYKgeMIrkT2jV82Gy90SErj60vW8jQbeMSOSbhIv3bZ7JoqPPVhA==",+ "license": "MIT"+ },+ "node_modules/@types/lodash.transform": {+ "version": "4.6.9",+ "resolved": "https://registry.npmjs.org/@types/lodash.transform/-/lodash.transform-4.6.9.tgz",+ "integrity": "sha512-1iIn+l7Vrj8hsr2iZLtxRkcV9AtjTafIyxKO9DX2EEcdOgz3Op5dhwKQFhMJgdfIRbYHBUF+SU97Y6P+zyLXNg==",+ "license": "MIT",+ "dependencies": {+ "@types/lodash": "*"+ }+ },"node_modules/@types/lru-cache": {"version": "5.1.1","license": "MIT"@@ -43702,6 +43747,12 @@"version": "4.7.0","license": "MIT"},+ "node_modules/lodash.transform": {+ "version": "4.6.0",+ "resolved": "https://registry.npmjs.org/lodash.transform/-/lodash.transform-4.6.0.tgz",+ "integrity": "sha512-LO37ZnhmBVx0GvOU/caQuipEh4GN82TcWv3yHlebGDgOxbxiwwzW5Pcx2AcvpIv2WmvmSMoC492yQFNhy/l/UQ==",+ "license": "MIT"+ },"node_modules/lodash.union": {"version": "4.6.0","resolved": "https://registry.npmjs.org/lodash.union/-/lodash.union-4.6.0.tgz",diff --git a/package.json b/package.jsonindex 6aa12f92b..8d49c6ab9 100644--- a/package.json+++ b/package.json@@ -581,6 +581,7 @@"@coinbase/x402": "^2.1.0","@coral-xyz/anchor": "^0.32.1","@dimforge/rapier3d-compat": "^0.19.3",+ "@discord/embedded-app-sdk": "^2.5.0","@elevenlabs/elevenlabs-js": "^2.68.0","@ellipsis-labs/rise": "^0.5.26","@ethereum-attestation-service/eas-sdk": "^2.10.0",diff --git a/pages/discord-activity.html b/pages/discord-activity.htmlnew file mode 100644index 000000000..72058bdc1--- /dev/null+++ b/pages/discord-activity.html@@ -0,0 +1,121 @@+<!doctype html>+<html lang="en">+ <head>+ <style>/* three.ws hidden-guard - make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>+ <script>/* three.ws theme boot */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />+ <title>Forge Room · three.ws Discord Activity</title>+ <meta name="description" content="A shared Forge room for a Discord voice channel: everyone prompts, watches the same 3D model generate, and votes together." />+ <meta name="robots" content="noindex" />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <style>+ :root {+ --bg: #0d0d0d; --card: #181818; --line: rgba(255,255,255,0.08); --line-2: rgba(255,255,255,0.14);+ --text: #e7e9ee; --muted: rgba(231,233,238,0.6); --dim: rgba(231,233,238,0.4);+ --accent: #5865f2; --green: #22c55e;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; height: 100%; }+ body {+ background: var(--bg); color: var(--text); font: 14px/1.5 'Inter', system-ui, -apple-system, sans-serif;+ -webkit-font-smoothing: antialiased; display: flex; flex-direction: column;+ }+ .da-shell { max-width: 720px; width: 100%; margin: 0 auto; padding: 16px; display: flex; flex-direction: column; gap: 12px; flex: 1; min-height: 100%; }+ .da-center { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; flex: 1; text-align: center; padding: 24px; }+ .da-spinner { width: 28px; height: 28px; border-radius: 50%; border: 3px solid var(--line-2); border-top-color: var(--accent); animation: da-spin 0.8s linear infinite; }+ @keyframes da-spin { to { transform: rotate(360deg); } }+ @media (prefers-reduced-motion: reduce) { .da-spinner { animation: none; } }+ .da-error-box { border: 1px solid rgba(239,68,68,.3); background: rgba(239,68,68,.08); border-radius: 12px; padding: 20px; max-width: 46ch; }+ button { font: inherit; cursor: pointer; }+ .da-btn {+ background: var(--accent); color: #fff; border: none; border-radius: 8px; padding: 9px 16px;+ font-weight: 600; transition: filter .15s ease;+ }+ .da-btn:hover { filter: brightness(1.1); }+ .da-btn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }+ .da-btn:disabled { opacity: .5; cursor: not-allowed; }++ .da-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; }+ .da-header h1 { font-size: 15px; margin: 0; letter-spacing: -0.01em; }+ .da-participants { display: flex; flex-wrap: wrap; gap: 6px; }+ .da-chip { background: var(--card); border: 1px solid var(--line); border-radius: 999px; padding: 3px 10px; font-size: 12px; color: var(--muted); }++ .da-status { color: var(--muted); font-size: 12.5px; min-height: 1.4em; }++ .da-feed { flex: 1; min-height: 120px; max-height: 32vh; overflow-y: auto; border: 1px solid var(--line); border-radius: 10px; background: var(--card); padding: 10px 12px; display: flex; flex-direction: column; gap: 4px; }+ .da-feed-line { margin: 0; font-size: 12.5px; color: var(--muted); }+ .da-feed-line--agent { color: #a5b4fc; font-style: italic; }++ .da-creation { border: 1px solid var(--line); border-radius: 12px; background: var(--card); overflow: hidden; }+ .da-creation img { width: 100%; max-height: 220px; object-fit: contain; background: #000; display: block; }+ .da-creation-body { padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; }+ .da-creation-prompt { margin: 0; font-size: 13px; color: var(--muted); }+ .da-creation-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }+ .da-vote-btn {+ background: transparent; border: 1px solid var(--line-2); color: var(--text); border-radius: 8px;+ padding: 7px 12px; display: inline-flex; align-items: center; gap: 6px; transition: border-color .15s ease, color .15s ease;+ }+ .da-vote-btn:hover { border-color: var(--green); }+ .da-vote-btn[aria-pressed='true'] { border-color: var(--green); color: var(--green); }+ .da-vote-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .da-open3d { background: transparent; border: 1px solid var(--line-2); color: var(--text); border-radius: 8px; padding: 7px 12px; }+ .da-open3d:hover { border-color: var(--accent); }+ .da-open3d:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }++ .da-prompt-form { display: flex; gap: 8px; }+ .da-prompt-form input {+ flex: 1; background: var(--card); border: 1px solid var(--line-2); color: var(--text);+ border-radius: 8px; padding: 10px 12px; font: inherit;+ }+ .da-prompt-form input:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }+ </style>+ </head>+ <body>+ <div class="da-shell">+ <div id="da-boot" class="da-center">+ <div class="da-spinner" role="status" aria-label="Loading"></div>+ <p id="da-boot-msg">Connecting to Discord...</p>+ </div>++ <div id="da-error" class="da-center" hidden>+ <div class="da-error-box">+ <p id="da-error-msg">Something went wrong.</p>+ </div>+ <button id="da-retry" class="da-btn" type="button">Try again</button>+ </div>++ <div id="da-room" hidden style="display: flex; flex-direction: column; gap: 12px; flex: 1;">+ <div class="da-header">+ <h1>Forge Room</h1>+ <div id="da-participants" class="da-participants"></div>+ </div>++ <p id="da-status" class="da-status" aria-live="polite"></p>++ <div id="da-creation" class="da-creation" hidden>+ <img id="da-creation-img" alt="" />+ <div class="da-creation-body">+ <p id="da-creation-prompt" class="da-creation-prompt"></p>+ <div class="da-creation-actions">+ <button id="da-vote-up" class="da-vote-btn" type="button" aria-pressed="false">+ <span aria-hidden="true">👍</span> <span id="da-vote-count">0</span>+ </button>+ <button id="da-open-3d" class="da-open3d" type="button">Open in 3D ↗</button>+ </div>+ </div>+ </div>++ <div id="da-feed" class="da-feed" aria-live="polite" aria-label="Room activity"></div>++ <form id="da-prompt-form" class="da-prompt-form">+ <input id="da-prompt-input" type="text" maxlength="400" placeholder="Describe something to forge together..." autocomplete="off" />+ <button id="da-prompt-submit" class="da-btn" type="submit">Forge</button>+ </form>+ </div>+ </div>++ <script type="module" src="/src/discord-activity/app.js"></script>+ </body>+</html>diff --git a/src/discord-activity/app.js b/src/discord-activity/app.jsnew file mode 100644index 000000000..9c60666e4--- /dev/null+++ b/src/discord-activity/app.js@@ -0,0 +1,303 @@+// Discord Activity: a shared Forge room. Everyone in the voice channel who+// opens the Activity sees the same prompt, the same generated model, and the+// same vote tally, because all of it lives server-side in one event-sourced+// room (api/_lib/gateway/discord-activity-store.js) keyed by the Activity+// instance id. This module only does three things: authenticate the Discord+// user into a room-scoped session, submit/poll the real /api/forge pipeline,+// and render whatever the room's SSE stream says changed. No coin, wallet, or+// purchase path: this room is free, by design (see the order's scope note).++import { DiscordSDK, patchUrlMappings } from '@discord/embedded-app-sdk';++const READY_TIMEOUT_MS = 8_000;+const FORGE_POLL_MS = 3_000;+const FORGE_TIMEOUT_MS = 180_000;++const CLIENT_ID = (() => {+ const KEY = 'discordActivity:cid';+ try {+ let id = sessionStorage.getItem(KEY);+ if (!id) {+ id = crypto?.randomUUID?.() || `da-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;+ sessionStorage.setItem(KEY, id);+ }+ return id;+ } catch {+ return `da-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;+ }+})();+const FORGE_HEADERS = { 'content-type': 'application/json', 'x-forge-client': CLIENT_ID, 'x-witness': 'handled' };++const els = {+ boot: document.getElementById('da-boot'),+ bootMsg: document.getElementById('da-boot-msg'),+ error: document.getElementById('da-error'),+ errorMsg: document.getElementById('da-error-msg'),+ retry: document.getElementById('da-retry'),+ room: document.getElementById('da-room'),+ participants: document.getElementById('da-participants'),+ feed: document.getElementById('da-feed'),+ promptForm: document.getElementById('da-prompt-form'),+ promptInput: document.getElementById('da-prompt-input'),+ promptSubmit: document.getElementById('da-prompt-submit'),+ status: document.getElementById('da-status'),+ creation: document.getElementById('da-creation'),+ creationImg: document.getElementById('da-creation-img'),+ creationPrompt: document.getElementById('da-creation-prompt'),+ voteCount: document.getElementById('da-vote-count'),+ voteUp: document.getElementById('da-vote-up'),+ open3d: document.getElementById('da-open-3d'),+};++const state = {+ discordSdk: null,+ sessionToken: null,+ user: null,+ roomId: null,+ snapshot: null,+ voted: false,+ generating: false,+ seenEventIds: new Set(),+};++function show(el) {+ for (const key of ['boot', 'error', 'room']) els[key].hidden = els[key] !== el;+}++function withTimeout(promise, ms, message) {+ let timer;+ const timeout = new Promise((_, reject) => {+ timer = setTimeout(() => reject(new Error(message)), ms);+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));+}++async function fetchConfig() {+ const res = await fetch('/api/gateway/discord-activity-config');+ if (res.status === 503) return null;+ if (!res.ok) throw new Error('Could not load the Activity configuration.');+ return res.json();+}++async function exchangeCode(clientId, code) {+ const res = await fetch('/api/gateway/discord-activity-token', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ client_id: clientId, code }),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(data.error_description || 'Discord could not sign you in.');+ return data.access_token;+}++async function openSession(accessToken) {+ const res = await fetch('/api/gateway/discord-activity-session', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ access_token: accessToken,+ instance_id: state.discordSdk.instanceId,+ guild_id: state.discordSdk.guildId,+ channel_id: state.discordSdk.channelId,+ }),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(data.error_description || 'Could not open the room.');+ return data;+}++function roomUrl(sub = '') {+ return `/api/gateway/discord-activity-room/${encodeURIComponent(state.roomId)}${sub}`;+}++async function roomPost(sub, body) {+ const res = await fetch(roomUrl(sub), {+ method: 'POST',+ headers: { 'content-type': 'application/json', authorization: `Bearer ${state.sessionToken}` },+ body: JSON.stringify(body || {}),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(data.error_description || 'That did not go through.');+ return data.data;+}++async function loadSnapshot() {+ const res = await fetch(roomUrl(), { headers: { authorization: `Bearer ${state.sessionToken}` } });+ const data = await res.json().catch(() => ({}));+ if (res.ok) renderSnapshot(data.data);+}++function connectStream() {+ const es = new EventSource(roomUrl(`/stream?token=${encodeURIComponent(state.sessionToken)}&after=${state.snapshot?.lastEventId || 0}`));+ es.onmessage = (ev) => {+ let payload;+ try { payload = JSON.parse(ev.data); } catch { return; }+ if (state.seenEventIds.has(payload.id)) return;+ state.seenEventIds.add(payload.id);+ appendFeedLine(payload);+ loadSnapshot();+ };+ es.onerror = () => {+ es.close();+ setTimeout(connectStream, 4_000);+ };+}++function displayName(discordUserId) {+ const p = state.snapshot?.participants?.find((x) => x.discordUserId === discordUserId);+ return p?.globalName || p?.username || (discordUserId === state.user?.id ? 'You' : 'Someone');+}++function appendFeedLine({ kind, actor_discord_id, payload }) {+ const line = document.createElement('p');+ line.className = 'da-feed-line';+ const who = displayName(actor_discord_id);+ if (kind === 'join') line.textContent = `${who} joined the room.`;+ else if (kind === 'prompt') line.textContent = `${who} prompted: "${payload.text}"`;+ else if (kind === 'creation') line.textContent = `${who} shared a finished model.`;+ else if (kind === 'vote') line.textContent = `${who} ${payload.voted ? 'liked' : 'un-liked'} the model (${payload.vote_count} total).`;+ else if (kind === 'agent_say') { line.textContent = payload.text; line.className += ' da-feed-line--agent'; }+ else return;+ els.feed.appendChild(line);+ els.feed.scrollTop = els.feed.scrollHeight;+}++function renderSnapshot(snapshot) {+ state.snapshot = snapshot;+ els.participants.innerHTML = '';+ for (const p of snapshot.participants) {+ const chip = document.createElement('span');+ chip.className = 'da-chip';+ chip.textContent = p.globalName || p.username;+ els.participants.appendChild(chip);+ }+ els.voteCount.textContent = String(snapshot.voteCount || 0);+ if (snapshot.creation) {+ els.creation.hidden = false;+ els.creationImg.src = snapshot.creation.previewImageUrl || '';+ els.creationImg.alt = snapshot.creation.prompt || 'Generated model';+ els.creationPrompt.textContent = snapshot.creation.prompt || '';+ els.open3d.onclick = () => openExternal(`https://three.ws/forge/share/${snapshot.creation.id}`);+ } else {+ els.creation.hidden = true;+ }+}++function openExternal(url) {+ if (state.discordSdk?.commands?.openExternalLink) state.discordSdk.commands.openExternalLink({ url });+ else window.open(url, '_blank', 'noopener');+}++function setStatus(text) {+ els.status.textContent = text;+}++async function submitPrompt(text) {+ state.generating = true;+ els.promptSubmit.disabled = true;+ setStatus('Submitting to Forge...');+ try {+ await roomPost('/prompt', { text });+ const res = await fetch('/api/forge', { method: 'POST', headers: FORGE_HEADERS, body: JSON.stringify({ prompt: text, director: true }) });+ const job = await res.json().catch(() => ({}));+ if (!res.ok || job.error) throw new Error(job.message || 'The generator could not start.');++ let result = job;+ if (job.job_id && !(job.status === 'done' && job.glb_url)) {+ setStatus('Generating a 3D model for the room...');+ result = await pollForge(job.job_id);+ }+ if (!result.creation_id) throw new Error('The generator finished without a shareable model.');+ await roomPost('/creation', { creation_id: result.creation_id });+ setStatus('Done. Everyone in the room can see it now.');+ } catch (err) {+ setStatus(err.message || 'That generation failed.');+ } finally {+ state.generating = false;+ els.promptSubmit.disabled = false;+ }+}++async function pollForge(jobId) {+ const deadline = Date.now() + FORGE_TIMEOUT_MS;+ while (Date.now() < deadline) {+ await new Promise((r) => setTimeout(r, FORGE_POLL_MS));+ const res = await fetch(`/api/forge?job=${encodeURIComponent(jobId)}`, { headers: FORGE_HEADERS });+ const data = await res.json().catch(() => ({}));+ if (data.status === 'done' && data.glb_url) return data;+ if (data.status === 'failed') throw new Error(data.message || 'The generator failed on this prompt.');+ if (data.message) setStatus(data.message);+ }+ throw new Error('The generator is taking longer than expected. Try again in a bit.');+}++function wireRoomUi() {+ els.promptForm.addEventListener('submit', (e) => {+ e.preventDefault();+ const text = els.promptInput.value.trim();+ if (!text || state.generating) return;+ els.promptInput.value = '';+ submitPrompt(text);+ });+ els.voteUp.addEventListener('click', async () => {+ if (!state.snapshot?.creation) return;+ try {+ await roomPost('/vote', { vote: !state.voted });+ state.voted = !state.voted;+ els.voteUp.setAttribute('aria-pressed', String(state.voted));+ } catch (err) {+ setStatus(err.message);+ }+ });+ els.retry.addEventListener('click', () => boot());+}++async function boot() {+ show(els.boot);+ els.bootMsg.textContent = 'Connecting to Discord...';+ try {+ const config = await fetchConfig();+ if (!config) {+ els.errorMsg.textContent = 'This Activity has not been turned on yet. Ask the three.ws team to finish Discord setup.';+ show(els.error);+ return;+ }++ state.discordSdk = new DiscordSDK(config.client_id);+ await withTimeout(state.discordSdk.ready(), READY_TIMEOUT_MS, 'not_in_discord');++ if (config.cdn_host) {+ patchUrlMappings([{ prefix: 'cdn', target: config.cdn_host }], { patchFetch: true, patchXhr: true, patchSrcAttributes: true });+ }++ els.bootMsg.textContent = 'Signing you in...';+ const { code } = await state.discordSdk.commands.authorize({+ client_id: config.client_id,+ response_type: 'code',+ state: '',+ prompt: 'none',+ scope: ['identify'],+ });+ const accessToken = await exchangeCode(config.client_id, code);+ await state.discordSdk.commands.authenticate({ access_token: accessToken });++ els.bootMsg.textContent = 'Opening the room...';+ const session = await openSession(accessToken);+ state.sessionToken = session.session_token;+ state.user = session.user;+ state.roomId = state.discordSdk.instanceId;++ await loadSnapshot();+ connectStream();+ show(els.room);+ setStatus('Ready. Type a prompt and everyone in the room will see what comes out.');+ } catch (err) {+ els.errorMsg.textContent = err?.message === 'not_in_discord'+ ? 'Open this from inside a Discord voice channel. It only works embedded in the Discord client.'+ : err?.message || 'Something went wrong connecting to Discord.';+ show(els.error);+ }+}++wireRoomUi();+boot();diff --git a/tests/discord-activity-auth.test.js b/tests/discord-activity-auth.test.jsnew file mode 100644index 000000000..1e351c90e--- /dev/null+++ b/tests/discord-activity-auth.test.js@@ -0,0 +1,99 @@+// api/_lib/gateway/discord-activity-auth.js: the OAuth2 code exchange and+// user lookup against (mocked) Discord endpoints, and the real HMAC+// sign/verify roundtrip for the Activity session token, unmocked.++import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';++process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-jwt-secret';+process.env.DISCORD_CLIENT_ID = 'test-client-id';+process.env.DISCORD_CLIENT_SECRET = 'test-client-secret';++const {+ discordActivityConfigured,+ DiscordActivityAuthError,+ exchangeActivityCode,+ fetchDiscordUser,+ signActivitySession,+ verifyActivitySession,+} = await import('../api/_lib/gateway/discord-activity-auth.js');++describe('discord-activity-auth', () => {+ let fetchSpy;++ beforeEach(() => {+ fetchSpy = vi.spyOn(globalThis, 'fetch');+ });++ afterEach(() => {+ fetchSpy.mockRestore();+ });++ it('reports configured once both env vars are present', () => {+ expect(discordActivityConfigured()).toBe(true);+ });++ it('exchanges a real-shaped request and surfaces Discord\'s own error on rejection', async () => {+ fetchSpy.mockResolvedValue({ ok: false, json: async () => ({ error: 'invalid_grant', error_description: 'Invalid "code" in request.' }) });+ await expect(exchangeActivityCode('bad-code')).rejects.toMatchObject({ code: 'token_exchange_failed', status: 502 });++ const [url, init] = fetchSpy.mock.calls[0];+ expect(url).toBe('https://discord.com/api/oauth2/token');+ expect(init.method).toBe('POST');+ const body = new URLSearchParams(init.body);+ expect(body.get('client_id')).toBe('test-client-id');+ expect(body.get('client_secret')).toBe('test-client-secret');+ expect(body.get('grant_type')).toBe('authorization_code');+ expect(body.get('code')).toBe('bad-code');+ });++ it('returns the access token on a successful exchange', async () => {+ fetchSpy.mockResolvedValue({ ok: true, json: async () => ({ access_token: 'tok-123', scope: 'identify' }) });+ const result = await exchangeActivityCode('good-code');+ expect(result).toEqual({ accessToken: 'tok-123', scope: 'identify' });+ });++ it('rejects a missing code before ever calling Discord', async () => {+ await expect(exchangeActivityCode('')).rejects.toMatchObject({ code: 'bad_code' });+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it('fetchDiscordUser re-verifies the token against /users/@me', async () => {+ fetchSpy.mockResolvedValue({ ok: true, json: async () => ({ id: '123456789', username: 'alice', global_name: 'Alice', avatar: 'abc' }) });+ const user = await fetchDiscordUser('tok-123');+ expect(user).toEqual({ id: '123456789', username: 'alice', globalName: 'Alice', avatar: 'abc' });+ const [url, init] = fetchSpy.mock.calls[0];+ expect(url).toBe('https://discord.com/api/users/@me');+ expect(init.headers.Authorization).toBe('Bearer tok-123');+ });++ it('fetchDiscordUser surfaces a rejected token as a DiscordActivityAuthError', async () => {+ fetchSpy.mockResolvedValue({ ok: false, json: async () => ({ message: '401: Unauthorized' }) });+ await expect(fetchDiscordUser('expired')).rejects.toBeInstanceOf(DiscordActivityAuthError);+ });++ it('signs and verifies a session scoped to one room, and rejects a tampered one', () => {+ const token = signActivitySession({ discordUserId: 'u1', username: 'alice', globalName: 'Alice', roomId: 'room-1', guildId: 'g1', channelId: 'c1' });+ expect(token).toMatch(/^da1\./);++ const verified = verifyActivitySession(token);+ expect(verified).toMatchObject({ discordUserId: 'u1', roomId: 'room-1', guildId: 'g1', channelId: 'c1' });++ const [prefix, payload, sig] = token.split('.');+ const tampered = `${prefix}.${payload}.${sig.slice(0, -2)}xx`;+ expect(verifyActivitySession(tampered)).toBeNull();+ });++ it('rejects an expired session', () => {+ const realNow = Date.now;+ Date.now = () => realNow() - 5 * 3600 * 1000;+ const token = signActivitySession({ discordUserId: 'u1', username: 'alice', roomId: 'room-1', guildId: 'g1', channelId: 'c1' });+ Date.now = realNow;+ expect(verifyActivitySession(token)).toBeNull();+ });++ it('rejects malformed tokens without throwing', () => {+ expect(verifyActivitySession(null)).toBeNull();+ expect(verifyActivitySession('not-a-token')).toBeNull();+ expect(verifyActivitySession('da1.onlyonepart')).toBeNull();+ });+});diff --git a/tests/discord-activity-store.test.js b/tests/discord-activity-store.test.jsnew file mode 100644index 000000000..2f9816f12--- /dev/null+++ b/tests/discord-activity-store.test.js@@ -0,0 +1,116 @@+// api/_lib/gateway/discord-activity-store.js against a real in-process+// Postgres (PGlite): the room/participant/event tables plus the fold that+// produces one snapshot both a fresh GET and a reconnecting SSE client agree+// on. No mocked SQL semantics: this is the real jsonb insert, the real+// ON CONFLICT upsert, the real ORDER BY.++import { beforeAll, beforeEach, describe, it, expect, vi } from 'vitest';+import { createPgliteSql } from './_helpers/pglite-sql.js';++const holder = vi.hoisted(() => ({ db: null }));++vi.mock('../api/_lib/db.js', async (importActual) => {+ const actual = await importActual();+ return { ...actual, sql: (...args) => holder.db.sql(...args) };+});++process.env.DATABASE_URL ||= 'postgres://pglite.test/db';++const DDL = `+ create table discord_activity_rooms (+ id text primary key,+ guild_id text not null,+ channel_id text not null,+ created_at timestamptz not null default now(),+ last_active_at timestamptz not null default now()+ );+ create table discord_activity_participants (+ room_id text not null references discord_activity_rooms(id) on delete cascade,+ discord_user_id text not null,+ username text not null,+ global_name text,+ joined_at timestamptz not null default now(),+ last_seen_at timestamptz not null default now(),+ primary key (room_id, discord_user_id)+ );+ create table discord_activity_events (+ id bigserial primary key,+ room_id text not null references discord_activity_rooms(id) on delete cascade,+ kind text not null,+ actor_discord_id text,+ payload jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now()+ );+ create index discord_activity_events_room_idx on discord_activity_events (room_id, id);+`;++let store;++beforeAll(async () => {+ store = await import('../api/_lib/gateway/discord-activity-store.js');+});++beforeEach(async () => {+ holder.db = createPgliteSql();+ await holder.db.exec(DDL);+});++describe('discord-activity-store', () => {+ it('ensureRoom is idempotent and upsertParticipant tracks who is in the room', async () => {+ await store.ensureRoom({ roomId: 'inst-1', guildId: 'g1', channelId: 'c1' });+ await store.ensureRoom({ roomId: 'inst-1', guildId: 'g1', channelId: 'c1' });+ const room = await store.getRoom('inst-1');+ expect(room.id).toBe('inst-1');++ await store.upsertParticipant({ roomId: 'inst-1', discordUserId: 'u1', username: 'alice', globalName: 'Alice' });+ await store.upsertParticipant({ roomId: 'inst-1', discordUserId: 'u1', username: 'alice', globalName: 'Alice W' });+ await store.upsertParticipant({ roomId: 'inst-1', discordUserId: 'u2', username: 'bob', globalName: null });++ const participants = await store.listParticipants('inst-1');+ expect(participants).toHaveLength(2);+ expect(participants.find((p) => p.discord_user_id === 'u1').global_name).toBe('Alice W');+ });++ it('rejects an event kind outside the fixed set', async () => {+ await store.ensureRoom({ roomId: 'inst-1', guildId: 'g1', channelId: 'c1' });+ await expect(store.appendEvent({ roomId: 'inst-1', kind: 'not_a_kind', payload: {} })).rejects.toThrow(/unknown event kind/);+ });++ it('folds the event log into one snapshot that agrees with incremental SSE reads', async () => {+ await store.ensureRoom({ roomId: 'inst-1', guildId: 'g1', channelId: 'c1' });+ await store.upsertParticipant({ roomId: 'inst-1', discordUserId: 'u1', username: 'alice', globalName: 'Alice' });+ await store.appendEvent({ roomId: 'inst-1', kind: 'join', actorDiscordId: 'u1', payload: { username: 'alice' } });+ await store.appendEvent({ roomId: 'inst-1', kind: 'prompt', actorDiscordId: 'u1', payload: { text: 'a tiny dragon' } });+ await store.appendEvent({+ roomId: 'inst-1',+ kind: 'creation',+ actorDiscordId: 'u1',+ payload: { id: 'creation-1', glb_url: 'https://cdn.example/a.glb', preview_image_url: 'https://cdn.example/a.png', prompt: 'a tiny dragon' },+ });+ await store.appendEvent({ roomId: 'inst-1', kind: 'vote', actorDiscordId: 'u1', payload: { voted: true, vote_count: 1 } });+ await store.appendEvent({ roomId: 'inst-1', kind: 'agent_say', actorDiscordId: null, payload: { text: 'nice dragon' } });++ const snapshot = await store.getRoomSnapshot('inst-1');+ expect(snapshot.prompt.text).toBe('a tiny dragon');+ expect(snapshot.creation.id).toBe('creation-1');+ expect(snapshot.creation.glbUrl).toBe('https://cdn.example/a.glb');+ expect(snapshot.voteCount).toBe(1);+ expect(snapshot.agentLines).toHaveLength(1);+ expect(snapshot.participants).toEqual([{ discordUserId: 'u1', username: 'alice', globalName: 'Alice' }]);++ const tail = await store.listEvents({ roomId: 'inst-1', afterId: 0 });+ expect(tail).toHaveLength(5);+ expect(tail[tail.length - 1].kind).toBe('agent_say');+ });++ it('a new creation event clears the vote tally from the previous one', async () => {+ await store.ensureRoom({ roomId: 'inst-1', guildId: 'g1', channelId: 'c1' });+ await store.appendEvent({ roomId: 'inst-1', kind: 'creation', actorDiscordId: 'u1', payload: { id: 'c1', glb_url: 'x', preview_image_url: 'y', prompt: 'p1' } });+ await store.appendEvent({ roomId: 'inst-1', kind: 'vote', actorDiscordId: 'u1', payload: { voted: true, vote_count: 1 } });+ await store.appendEvent({ roomId: 'inst-1', kind: 'creation', actorDiscordId: 'u2', payload: { id: 'c2', glb_url: 'x2', preview_image_url: 'y2', prompt: 'p2' } });++ const snapshot = await store.getRoomSnapshot('inst-1');+ expect(snapshot.creation.id).toBe('c2');+ expect(snapshot.voteCount).toBe(0);+ });+});diff --git a/vercel.json b/vercel.jsonindex a3886abce..ec4244848 100644--- a/vercel.json+++ b/vercel.json@@ -3357,6 +3357,14 @@"src": "/companion/","dest": "/companion.html"},+ {+ "src": "/discord-activity",+ "dest": "/discord-activity.html"+ },+ {+ "src": "/discord-activity/",+ "dest": "/discord-activity.html"+ },{"src": "/knock","dest": "/knock.html"@@ -5932,6 +5940,14 @@"src": "/api/teams","dest": "/api/teams"},+ {+ "src": "/api/gateway/discord-activity-room/([^/]+)/(stream|prompt|creation|vote)",+ "dest": "/api/gateway/discord-activity-room/[id]"+ },+ {+ "src": "/api/gateway/discord-activity-room/([^/]+)",+ "dest": "/api/gateway/discord-activity-room/[id]"+ },{"src": "/api/swarms/([^/]+)/stream","dest": "/api/swarms/[id]"diff --git a/vite.config.js b/vite.config.jsindex 66f0b4f9b..af1146e99 100644--- a/vite.config.js+++ b/vite.config.js@@ -831,6 +831,7 @@ const appConfig = {// replace it.'herald-page': resolve(__dirname, 'pages/herald.html'),companion: resolve(__dirname, 'pages/companion.html'),+ 'discord-activity': resolve(__dirname, 'pages/discord-activity.html'),knock: resolve(__dirname, 'pages/knock.html'),'knock-door': resolve(__dirname, 'pages/knock-door.html'),portal: resolve(__dirname, 'pages/portal.html'),