Skip to content

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.

feat(gateway): Telegram and Discord chat gateways for agents with webhook delivery and notification preferences

nirholasfc813410b664
diff --git a/api/_lib/gateway/bots.js b/api/_lib/gateway/bots.js
new file mode 100644
index 000000000..8e0c00260
--- /dev/null
+++ b/api/_lib/gateway/bots.js
@@ -0,0 +1,79 @@
+// Direct platform REST for the chat gateways: which bots are configured, how a
+// user reaches them, and a plain send used by server code that runs outside the
+// gateway worker (notifications, "this chat was unlinked" notices).
+
+import { cacheGet, cacheSet } from '../cache.js';
+
+const TG_API = 'https://api.telegram.org';
+const DISCORD_API = 'https://discord.com/api/v10';
+// View Channel, Send Messages, Embed Links, Attach Files, Read Message History.
+export const DISCORD_BOT_PERMISSIONS = String(1024 + 2048 + 16384 + 32768 + 65536);
+
+export function telegramConfigured(env = process.env) {
+ return Boolean(env.TELEGRAM_BOT_TOKEN);
+}
+
+export function discordConfigured(env = process.env) {
+ return Boolean(env.DISCORD_BOT_TOKEN && env.DISCORD_APP_ID && env.DISCORD_PUBLIC_KEY);
+}
+
+async function telegramUsername() {
+ if (process.env.TELEGRAM_BOT_USERNAME) return process.env.TELEGRAM_BOT_USERNAME.replace(/^@/, '');
+ const cached = await cacheGet('gateway:tg:username').catch(() => null);
+ if (cached) return cached;
+ const r = await fetch(`${TG_API}/bot${process.env.TELEGRAM_BOT_TOKEN}/getMe`, { signal: AbortSignal.timeout(5000) });
+ const j = await r.json().catch(() => null);
+ const name = j?.ok ? j.result.username : null;
+ if (name) await cacheSet('gateway:tg:username', name, 3600).catch(() => {});
+ return name;
+}
+
+/** How the settings page offers each bot. Unconfigured bots say so. */
+export async function gatewayBots() {
+ const out = { telegram: { available: false }, discord: { available: false } };
+ if (telegramConfigured()) {
+ const username = await telegramUsername().catch(() => null);
+ out.telegram = username
+ ? { available: true, username, url: `https://t.me/${username}` }
+ : { available: false, reason: 'unreachable' };
+ }
+ if (discordConfigured()) {
+ out.discord = {
+ available: true,
+ invite_url: `https://discord.com/oauth2/authorize?client_id=${process.env.DISCORD_APP_ID}&scope=bot+applications.commands&permissions=${DISCORD_BOT_PERMISSIONS}`,
+ dm_url: `https://discord.com/users/${process.env.DISCORD_APP_ID}`,
+ };
+ }
+ return out;
+}
+
+/** Send one plain-text message to a paired chat. Throws on a platform refusal. */
+export async function sendPlatformText(platform, chatId, text) {
+ if (platform === 'telegram') {
+ if (!telegramConfigured()) throw new Error('telegram not configured');
+ const r = await fetch(`${TG_API}/bot${process.env.TELEGRAM_BOT_TOKEN}/sendMessage`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ chat_id: chatId, text: String(text).slice(0, 4000), disable_web_page_preview: true }),
+ signal: AbortSignal.timeout(8000),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (!j.ok) throw Object.assign(new Error(j.description || `telegram ${r.status}`), { status: r.status, code: j.error_code });
+ return j.result;
+ }
+ if (platform === 'discord') {
+ if (!process.env.DISCORD_BOT_TOKEN) throw new Error('discord not configured');
+ const r = await fetch(`${DISCORD_API}/channels/${chatId}/messages`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bot ${process.env.DISCORD_BOT_TOKEN}` },
+ body: JSON.stringify({ content: String(text).slice(0, 1900), allowed_mentions: { parse: [] } }),
+ signal: AbortSignal.timeout(8000),
+ });
+ if (!r.ok) {
+ const j = await r.json().catch(() => ({}));
+ throw Object.assign(new Error(j.message || `discord ${r.status}`), { status: r.status, code: j.code });
+ }
+ return r.json();
+ }
+ throw new Error(`unknown platform ${platform}`);
+}
diff --git a/api/_lib/gateway/notify.js b/api/_lib/gateway/notify.js
new file mode 100644
index 000000000..0e93f8414
--- /dev/null
+++ b/api/_lib/gateway/notify.js
@@ -0,0 +1,63 @@
+// Notifications delivered into paired chats: the `telegram` and `discord`
+// channels of the preference center (api/_lib/notify-prefs.js). Alerts, run
+// completions, received bids and incoming mail all land in the chat the owner
+// already talks to their agent in, so they can reply in place.
+//
+// Delivery is queued, not sent: each target chat gets a {kind:'notify'} row in
+// gateway_inbox and the gateway worker sends it, so platform credentials live
+// in one process and every adapter the worker has gets notifications for free.
+// A row older than NOTIFY_TTL_MS when the worker reaches it is dropped rather
+// than delivered stale.
+
+import { sql } from '../db.js';
+import { channelEnabled, pushPayloadFor } from '../notify-prefs.js';
+import { enqueueInbox } from './store.js';
+import { appOrigin } from './format.js';
+
+export const NOTIFY_TTL_MS = 60 * 60 * 1000;
+export const CHAT_CHANNELS = ['telegram', 'discord'];
+
+/** One notification as chat text: title, body, and an absolute link. */
+export function notificationText(type, payload, notificationId) {
+ const p = pushPayloadFor(type, payload, notificationId);
+ const url = p.url?.startsWith('/') ? `${appOrigin()}${p.url}` : p.url;
+ return [p.title, p.body, url].filter(Boolean).join('\n');
+}
+
+async function targetChats(userId, platforms, legacyTelegramChatId) {
+ const rows = await sql`
+ SELECT id, platform, chat_id FROM gateway_links
+ WHERE user_id = ${userId} AND revoked_at IS NULL AND notify = true
+ AND platform = ANY(${platforms})`;
+ const out = rows.map((r) => ({ linkId: r.id, platform: r.platform, chatId: r.chat_id }));
+ // A chat id saved in the notification settings before the gateway existed
+ // still receives Telegram notifications, unless it is also a paired chat.
+ if (legacyTelegramChatId && platforms.includes('telegram') && !out.some((t) => t.platform === 'telegram' && t.chatId === String(legacyTelegramChatId))) {
+ out.push({ linkId: null, platform: 'telegram', chatId: String(legacyTelegramChatId) });
+ }
+ return out;
+}
+
+/**
+ * Queue a notification for every chat channel the owner left on for its
+ * category. Returns how many chats it was queued for, per platform.
+ * @returns {Promise<Record<string, number>>}
+ */
+export async function queueChatNotifications({ userId, type, payload, notificationId, prefs }) {
+ const platforms = CHAT_CHANNELS.filter((ch) => channelEnabled(prefs, type, ch));
+ const queued = {};
+ if (!platforms.length) return queued;
+ const targets = await targetChats(userId, platforms, prefs?.telegram_chat_id);
+ const text = notificationText(type, payload, notificationId);
+ const ref = notificationId || `${type}:${Date.now()}:${Math.random().toString(36).slice(2, 10)}`;
+ for (const t of targets) {
+ const inserted = await enqueueInbox({
+ platform: t.platform,
+ dedupeKey: `notify:${ref}:${t.linkId || t.chatId}`,
+ chatKey: `${t.platform}:${t.chatId}`,
+ payload: { kind: 'notify', chatId: t.chatId, linkId: t.linkId, type, text, expiresAt: new Date(Date.now() + NOTIFY_TTL_MS).toISOString() },
+ });
+ if (inserted) queued[t.platform] = (queued[t.platform] || 0) + 1;
+ }
+ return queued;
+}
diff --git a/api/_lib/gateway/reply-codes.js b/api/_lib/gateway/reply-codes.js
new file mode 100644
index 000000000..413f69365
--- /dev/null
+++ b/api/_lib/gateway/reply-codes.js
@@ -0,0 +1,94 @@
+// Approve and Cancel for channels without buttons (SMS, Signal, email).
+//
+// A preview there is rendered as text ending "Reply APPROVE 482913 to execute or
+// CANCEL 482913 to discard." The six-digit code is bound to one chat (link) and
+// one preview, stored as a sha256, used once, and dead when the preview expires.
+// Only a message that is exactly that verb plus that code, from the paired
+// sender, becomes a button press; every other message, including prose that
+// merely contains the word "approve", goes to the agent as ordinary text and can
+// never set the confirm flag.
+
+import { randomInt, createHash } from 'node:crypto';
+import { sql } from '../db.js';
+import { APPROVE, CANCEL } from './conversation.js';
+
+export const REPLY_CODE_DIGITS = 6;
+const REPLY_RE = /^\s*(approve|cancel|dismiss)\s+(\d{6})\s*[.!]?\s*$/i;
+
+function hashReplyCode(linkId, code) {
+ return createHash('sha256').update(`gateway-reply:${linkId}:${code}`).digest('hex');
+}
+
+function newCode() {
+ return String(randomInt(0, 10 ** REPLY_CODE_DIGITS)).padStart(REPLY_CODE_DIGITS, '0');
+}
+
+/** Parse a whole message as a reply code answer, or null. */
+export function parseReplyCode(text) {
+ const m = REPLY_RE.exec(String(text || ''));
+ if (!m) return null;
+ const verb = m[1].toLowerCase() === 'approve' ? 'approve' : 'cancel';
+ return { verb, code: m[2] };
+}
+
+/** The preview id a choice id carries (gw:ap:<uuid> or gw:cx:<uuid>). */
+export function previewIdOfChoice(choiceId) {
+ const s = String(choiceId || '');
+ if (s.startsWith(APPROVE)) return s.slice(APPROVE.length);
+ if (s.startsWith(CANCEL)) return s.slice(CANCEL.length);
+ return null;
+}
+
+/**
+ * Issue a code for a preview in a chat. One code answers both verbs, so the
+ * owner replies APPROVE or CANCEL with the same digits. Retries a collision
+ * inside the same chat (the unique index is per link).
+ * @returns {Promise<string>} the plaintext code
+ */
+export async function issueReplyCode({ linkId, previewId, expiresAt }) {
+ for (let attempt = 0; attempt < 5; attempt++) {
+ const code = newCode();
+ try {
+ await sql`
+ INSERT INTO gateway_reply_codes (link_id, preview_id, code_hash, expires_at)
+ VALUES (${linkId}, ${previewId}, ${hashReplyCode(linkId, code)}, ${expiresAt})`;
+ return code;
+ } catch (e) {
+ if (e?.code !== '23505') throw e;
+ }
+ }
+ throw new Error('could not allocate a unique reply code');
+}
+
+/**
+ * Resolve a reply code answer in a chat to a button action, consuming the code.
+ * Returns null when the code is unknown, used or expired for this chat.
+ * @returns {Promise<{ verb:'approve'|'cancel', previewId:string } | null>}
+ */
+export async function redeemReplyCode({ linkId, verb, code }) {
+ const [row] = await sql`
+ UPDATE gateway_reply_codes SET used_at = now()
+ WHERE link_id = ${linkId} AND code_hash = ${hashReplyCode(linkId, code)}
+ AND used_at IS NULL AND expires_at > now()
+ RETURNING preview_id`;
+ return row ? { verb, previewId: row.preview_id } : null;
+}
+
+/**
+ * Render a choice list as text for a channel without buttons, issuing the code.
+ * `choices` is what conversation.js passes to sendChoice.
+ * @returns {Promise<string>} the full message text
+ */
+export async function renderTextChoices({ link, text, choices }) {
+ const previewId = choices.map((c) => previewIdOfChoice(c.id)).find(Boolean);
+ if (!previewId || !link) return text;
+ const [preview] = await sql`SELECT id, expires_at FROM gateway_previews WHERE id = ${previewId} LIMIT 1`;
+ if (!preview) return text;
+ const code = await issueReplyCode({ linkId: link.id, previewId: preview.id, expiresAt: preview.expires_at });
+ const canApprove = choices.some((c) => String(c.id).startsWith(APPROVE));
+ const body = String(text).replace(/\n*Approve to execute, Cancel to discard\.[^\n]*$/, '');
+ const tail = canApprove
+ ? `Reply APPROVE ${code} to execute or CANCEL ${code} to discard. The code works once, only from this chat, and expires with the preview.`
+ : `Reply CANCEL ${code} to dismiss.`;
+ return `${body}\n\n${tail}`;
+}
diff --git a/api/_lib/gateway/store.js b/api/_lib/gateway/store.js
index 605fd8fbc..bf1c5a114 100644
--- a/api/_lib/gateway/store.js
+++ b/api/_lib/gateway/store.js
@@ -283,3 +283,31 @@ export async function finishPreview(id, status, result) {
UPDATE gateway_previews SET status = ${status}, result = ${JSON.stringify(result || {})}::jsonb
WHERE id = ${id}`;
}
+
+/**
+ * Expire every live preview past its deadline and return what the sweeper
+ * needs to strip its buttons: the message ref and the chat's platform.
+ */
+export async function expireDuePreviews({ limit = 50 } = {}) {
+ return sql`
+ WITH due AS (
+ SELECT id FROM gateway_previews
+ WHERE status = 'pending' AND expires_at <= now()
+ ORDER BY expires_at
+ LIMIT ${limit}
+ )
+ UPDATE gateway_previews p
+ SET status = 'expired', decided_at = now()
+ FROM due, gateway_links l
+ WHERE p.id = due.id AND l.id = p.link_id AND p.status = 'pending'
+ RETURNING p.id, p.proposal, p.message_ref, l.platform`;
+}
+
+/** Queue depth for health reporting: open deliveries and the oldest one's age. */
+export async function inboxBacklog() {
+ const [row] = await sql`
+ SELECT count(*)::int AS open,
+ COALESCE(EXTRACT(EPOCH FROM (now() - min(created_at))), 0)::int AS oldest_s
+ FROM gateway_inbox WHERE status IN ('queued', 'processing')`;
+ return { open: row?.open ?? 0, oldestSeconds: row?.oldest_s ?? 0 };
+}
diff --git a/api/_lib/gateway/webhooks.js b/api/_lib/gateway/webhooks.js
new file mode 100644
index 000000000..fc8782f8d
--- /dev/null
+++ b/api/_lib/gateway/webhooks.js
@@ -0,0 +1,91 @@
+// Verification and normalisation for the chat gateway webhooks. The receivers
+// (api/gateway/telegram.js, api/gateway/discord.js) verify the platform's proof,
+// queue the delivery in gateway_inbox and answer at once; the worker does the
+// slow part. Kept free of HTTP so the tests can drive every branch.
+
+import { createHash, createPublicKey, timingSafeEqual, verify } from 'node:crypto';
+
+// ── Telegram ─────────────────────────────────────────────────────────────────
+
+/**
+ * The secret Telegram echoes in X-Telegram-Bot-Api-Secret-Token. Derived from
+ * the bot token (so there is no second credential to mint or rotate) unless
+ * TELEGRAM_WEBHOOK_SECRET pins one. Telegram allows [A-Za-z0-9_-], 1-256 chars.
+ */
+export function telegramWebhookSecret(env = process.env) {
+ if (env.TELEGRAM_WEBHOOK_SECRET) return env.TELEGRAM_WEBHOOK_SECRET;
+ if (!env.TELEGRAM_BOT_TOKEN) return null;
+ return createHash('sha256').update(`three-ws-gateway-webhook:${env.TELEGRAM_BOT_TOKEN}`).digest('hex');
+}
+
+function safeEqual(a, b) {
+ const x = Buffer.from(String(a || ''));
+ const y = Buffer.from(String(b || ''));
+ return x.length === y.length && x.length > 0 && timingSafeEqual(x, y);
+}
+
+export function verifyTelegramSecret(headerValue, env = process.env) {
+ const expected = telegramWebhookSecret(env);
+ return Boolean(expected) && safeEqual(headerValue, expected);
+}
+
+/** The chat an update belongs to, or null for updates the gateway ignores. */
+export function telegramChatId(update) {
+ const chat = (update?.message || update?.callback_query?.message)?.chat;
+ return chat?.id != null ? String(chat.id) : null;
+}
+
+/** @returns {{ dedupeKey:string, chatKey:string } | null} */
+export function telegramInboxKeys(update) {
+ if (!update || update.update_id == null) return null;
+ const chatId = telegramChatId(update);
+ if (!chatId) return null;
+ return { dedupeKey: String(update.update_id), chatKey: `telegram:${chatId}` };
+}
+
+// ── Discord ──────────────────────────────────────────────────────────────────
+
+const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
+const DISCORD_MAX_SKEW_S = 300;
+
+/**
+ * Verify Discord's Ed25519 signature over timestamp + raw body. Also refuses a
+ * timestamp more than five minutes off, so a captured request cannot be replayed.
+ */
+export function verifyDiscordSignature({ rawBody, signature, timestamp, publicKey, now = Date.now() }) {
+ if (!rawBody || !/^[0-9a-f]{128}$/i.test(String(signature || '')) || !/^\d{1,12}$/.test(String(timestamp || ''))) return false;
+ if (!/^[0-9a-f]{64}$/i.test(String(publicKey || ''))) return false;
+ if (Math.abs(now / 1000 - Number(timestamp)) > DISCORD_MAX_SKEW_S) return false;
+ try {
+ const key = createPublicKey({ key: Buffer.concat([ED25519_SPKI_PREFIX, Buffer.from(publicKey, 'hex')]), format: 'der', type: 'spki' });
+ const body = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(String(rawBody));
+ return verify(null, Buffer.concat([Buffer.from(String(timestamp)), body]), key, Buffer.from(signature, 'hex'));
+ } catch {
+ return false;
+ }
+}
+
+export const DISCORD_INTERACTION = { PING: 1, APPLICATION_COMMAND: 2, MESSAGE_COMPONENT: 3, AUTOCOMPLETE: 4 };
+export const DISCORD_RESPONSE = { PONG: 1, DEFERRED_CHANNEL_MESSAGE: 5, DEFERRED_UPDATE_MESSAGE: 6, AUTOCOMPLETE_RESULT: 8 };
+
+/**
+ * The immediate answer to an interaction, sent inside Discord's three-second
+ * window. Commands get "thinking..." and buttons a silent deferred update; the
+ * worker fills both in through the interaction webhook.
+ */
+export function discordImmediateResponse(interaction) {
+ switch (interaction?.type) {
+ case DISCORD_INTERACTION.PING: return { type: DISCORD_RESPONSE.PONG };
+ case DISCORD_INTERACTION.APPLICATION_COMMAND: return { type: DISCORD_RESPONSE.DEFERRED_CHANNEL_MESSAGE };
+ case DISCORD_INTERACTION.MESSAGE_COMPONENT: return { type: DISCORD_RESPONSE.DEFERRED_UPDATE_MESSAGE };
+ case DISCORD_INTERACTION.AUTOCOMPLETE: return { type: DISCORD_RESPONSE.AUTOCOMPLETE_RESULT, data: { choices: [] } };
+ default: return null;
+ }
+}
+
+/** @returns {{ dedupeKey:string, chatKey:string } | null} */
+export function discordInboxKeys(interaction) {
+ if (!interaction?.id || !interaction.channel_id) return null;
+ if (interaction.type !== DISCORD_INTERACTION.APPLICATION_COMMAND && interaction.type !== DISCORD_INTERACTION.MESSAGE_COMPONENT) return null;
+ return { dedupeKey: String(interaction.id), chatKey: `discord:${interaction.channel_id}` };
+}
diff --git a/api/_lib/migrations/20260922180000_chat_gateways.sql b/api/_lib/migrations/20260922180000_chat_gateways.sql
index cddb3304e..572ba4a60 100644
--- a/api/_lib/migrations/20260922180000_chat_gateways.sql
+++ b/api/_lib/migrations/20260922180000_chat_gateways.sql
@@ -25,6 +25,13 @@
-- the linked platform user, inside its ten-minute life,
-- can execute it.
+-- Paired chats also receive notifications (api/_lib/gateway/notify.js); the
+-- funnel records each delivery under its platform name, so the channel check
+-- accepts discord next to telegram.
+ALTER TABLE notification_events DROP CONSTRAINT IF EXISTS notification_events_channel_check;
+ALTER TABLE notification_events ADD CONSTRAINT notification_events_channel_check
+ CHECK (channel IN ('in_app', 'push', 'email', 'telegram', 'discord', 'avatar'));
+
ALTER TABLE agent_messages ADD COLUMN IF NOT EXISTS channel text NOT NULL DEFAULT 'api';
DO $$ BEGIN
ALTER TABLE agent_messages ADD CONSTRAINT agent_messages_channel_check CHECK (channel ~ '^[a-z0-9_-]{1,24}$');
diff --git a/api/_lib/migrations/20260922190000_more_chat_gateways.sql b/api/_lib/migrations/20260922190000_more_chat_gateways.sql
new file mode 100644
index 000000000..4be19b73a
--- /dev/null
+++ b/api/_lib/migrations/20260922190000_more_chat_gateways.sql
@@ -0,0 +1,49 @@
+-- More chat gateways: Slack, WhatsApp, Signal, SMS and email-as-chat on the same
+-- gateway tables as Telegram and Discord (20260922180000_chat_gateways.sql), plus
+-- spoken replies and a per-account notification channel (docs/chat-gateways.md).
+--
+-- platform checks widened on gateway_links, gateway_pair_codes and
+-- gateway_inbox so every channel shares one pairing,
+-- queue and approval path.
+-- voice_replies the owner turned on spoken replies for this chat: the
+-- agent's text reply is followed by the same reply as
+-- audio on channels that can play it.
+-- preferred the one chat the owner wants notifications in. When an
+-- account has a preferred chat, notifications go there
+-- only; otherwise every chat with notify on gets them.
+-- gateway_reply_codes SMS, Signal and email have no buttons. A preview there
+-- is answered by replying "APPROVE 123456" or
+-- "CANCEL 123456": a six-digit code bound to one chat and
+-- one preview, stored as a sha256, single use, and dead
+-- when the preview behind it expires. Free text never
+-- matches a code.
+
+ALTER TABLE gateway_links DROP CONSTRAINT IF EXISTS gateway_links_platform_check;
+ALTER TABLE gateway_links ADD CONSTRAINT gateway_links_platform_check
+ CHECK (platform IN ('telegram', 'discord', 'slack', 'whatsapp', 'signal', 'sms', 'email'));
+
+ALTER TABLE gateway_pair_codes DROP CONSTRAINT IF EXISTS gateway_pair_codes_platform_check;
+ALTER TABLE gateway_pair_codes ADD CONSTRAINT gateway_pair_codes_platform_check
+ CHECK (platform IN ('telegram', 'discord', 'slack', 'whatsapp', 'signal', 'sms', 'email'));
+
+ALTER TABLE gateway_inbox DROP CONSTRAINT IF EXISTS gateway_inbox_platform_check;
+ALTER TABLE gateway_inbox ADD CONSTRAINT gateway_inbox_platform_check
+ CHECK (platform IN ('telegram', 'discord', 'slack', 'whatsapp', 'signal', 'sms', 'email'));
+
+ALTER TABLE gateway_links ADD COLUMN IF NOT EXISTS voice_replies boolean NOT NULL DEFAULT false;
+ALTER TABLE gateway_links ADD COLUMN IF NOT EXISTS preferred boolean NOT NULL DEFAULT false;
+CREATE UNIQUE INDEX IF NOT EXISTS gateway_links_one_preferred_uidx
+ ON gateway_links (user_id) WHERE preferred AND revoked_at IS NULL;
+
+CREATE TABLE IF NOT EXISTS gateway_reply_codes (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ link_id uuid NOT NULL REFERENCES gateway_links(id) ON DELETE CASCADE,
+ preview_id uuid NOT NULL REFERENCES gateway_previews(id) ON DELETE CASCADE,
+ code_hash text NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ expires_at timestamptz NOT NULL,
+ used_at timestamptz
+);
+CREATE UNIQUE INDEX IF NOT EXISTS gateway_reply_codes_link_code_uidx
+ ON gateway_reply_codes (link_id, code_hash);
+CREATE INDEX IF NOT EXISTS gateway_reply_codes_preview_idx ON gateway_reply_codes (preview_id);
diff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.js
index ecdca4e01..1fc94c05a 100644
--- a/api/_lib/notify-prefs.js
+++ b/api/_lib/notify-prefs.js
@@ -57,6 +57,11 @@ export const CATEGORIES = [
label: 'Knocks at your door',
description: 'Someone paid your price to reach you through /knock. Your companion delivers it in person.',
},
+ {
+ key: 'mail',
+ label: 'Agent mail',
+ description: 'An email arrived in one of your agents\' inboxes (spam is held back and never notifies).',
+ },
{
key: 'account',
label: 'Account & security',
@@ -70,7 +75,7 @@ export const CATEGORIES = [
},
];
-export const CHANNELS = ['in_app', 'push', 'email', 'telegram', 'avatar'];
+export const CHANNELS = ['in_app', 'push', 'email', 'telegram', 'discord', 'avatar'];
/**
* Channels that always deliver for a category, regardless of preferences.
@@ -126,6 +131,8 @@ const TYPE_CATEGORY = {
knock_received: 'knock',
+ mail_received: 'mail',
+
forge_complete: 'creations',
forge_failed: 'creations',
@@ -157,7 +164,8 @@ export function typeCategoryMap() {
// no push subscription simply never receives one, so defaulting it on is not
// spammy. email defaults on only for money + security; off for the higher-
// frequency social/irl/alerts categories. telegram is always opt-in (needs a
-// linked chat id) so it defaults off.
+// linked chat id) so it defaults off. discord mirrors telegram: both deliver to
+// chats paired through the chat gateways (api/_lib/gateway/notify.js).
// avatar is the most interruptive channel there is: the corner companion walks
// on screen and says the line out loud. It defaults on only for the three
// categories worth stopping the visitor for (money in, a creation that
@@ -165,21 +173,22 @@ export function typeCategoryMap() {
// higher-frequency ones. Every category stays togglable in the preference
// center either way.
const DEFAULTS = {
- sales: { in_app: true, push: true, email: true, telegram: false, avatar: true },
- purchases: { in_app: true, push: true, email: true, telegram: false, avatar: false },
- social: { in_app: true, push: true, email: false, telegram: false, avatar: false },
- irl: { in_app: true, push: true, email: false, telegram: false, avatar: false },
- alerts: { in_app: true, push: true, email: false, telegram: true, avatar: false },
+ sales: { in_app: true, push: true, email: true, telegram: false, discord: false, avatar: true },
+ purchases: { in_app: true, push: true, email: true, telegram: false, discord: false, avatar: false },
+ social: { in_app: true, push: true, email: false, telegram: false, discord: false, avatar: false },
+ irl: { in_app: true, push: true, email: false, telegram: false, discord: false, avatar: false },
+ alerts: { in_app: true, push: true, email: false, telegram: true, discord: true, avatar: false },
// Only unattended completions notify (api/cron/forge-finalize.js), so email
// defaulting on is the feature, not spam: the user left the page and asked
// to hear back.
- creations: { in_app: true, push: true, email: true, telegram: false, avatar: true },
+ creations: { in_app: true, push: true, email: true, telegram: false, discord: false, avatar: true },
// The companion category exists to be spoken: a message the visitor's own
// companion triaged as worth hearing (api/_lib/companion/triage.js). Email
// and telegram would just relay what the user already gets in that inbox.
- companion: { in_app: true, push: true, email: false, telegram: false, avatar: true },
- knock: { in_app: true, push: true, email: true, telegram: false, avatar: true },
- account: { in_app: true, push: true, email: true, telegram: false, avatar: true },
+ companion: { in_app: true, push: true, email: false, telegram: false, discord: false, avatar: true },
+ knock: { in_app: true, push: true, email: true, telegram: false, discord: false, avatar: true },
+ mail: { in_app: true, push: true, email: false, telegram: false, discord: false, avatar: false },
+ account: { in_app: true, push: true, email: true, telegram: false, discord: false, avatar: true },
};
/** The full default matrix, used to seed the preference-center UI. */
@@ -292,6 +301,7 @@ const PUSH_COPY = {
irl_reply: (p) => ['Agent replied 💬', p.message ? `“${p.message}”` : 'An agent replied to your message'],
pump_alert: (p) => ['Market alert 📈', p.summary || 'A token alert you configured just fired'],
companion_delivery: (p) => [p.sender ? `${p.sender} 👋` : 'Your companion 👋', p.line || p.title || 'Something worth your attention just came in'],
+ mail_received: (p) => [`${p.agent_name || 'Your agent'} got an email ✉️`, `${p.from_name || p.from || 'Someone'}: ${p.subject || '(no subject)'}`],
knock_received: (p) => [p.sender ? `${p.sender} is at your door 🚪` : 'Someone is at your door 🚪', p.title || p.body || 'Someone paid to reach you'],
forge_complete: (p) => ['Your 3D model is ready ✨', p.prompt ? `"${String(p.prompt).slice(0, 80)}" finished generating` : 'Your generation finished. Tap to view it'],
forge_failed: (p) => ['Generation failed ⚠️', p.prompt ? `"${String(p.prompt).slice(0, 80)}" could not be generated. Tap to retry` : 'A generation could not be completed. Tap to retry'],
diff --git a/api/_lib/notify.js b/api/_lib/notify.js
index 6ae741d4f..e0d9c8a4f 100644
--- a/api/_lib/notify.js
+++ b/api/_lib/notify.js
@@ -8,7 +8,9 @@
* `in_app` channel is on,
* 3. records a `sent` funnel event for in_app,
* 4. fans out to Web Push for the categories the user left enabled,
- * 5. records a `sent` event per push delivery.
+ * 5. records a `sent` event per push delivery,
+ * 6. queues Telegram and Discord delivery into the chats the owner paired
+ * through the chat gateways (api/_lib/gateway/notify.js).
*
* Every channel is gated by the user's preference center (api/_lib/notify-prefs)
* so there is no notification a user can't turn off, including the bell itself:
@@ -31,6 +33,7 @@ import {
lockedChannelsFor,
} from './notify-prefs.js';
import { sendPushToUser } from './web-push.js';
+import { queueChatNotifications } from './gateway/notify.js';
export function insertNotification(userId, type, payload = {}) {
return deliver(userId, type, payload).catch((err) => {
@@ -85,6 +88,14 @@ async function deliver(userId, type, payload) {
console.error('[notify] push fan-out failed:', err.message);
}
+ // 6: paired chats. Queued for the gateway worker, gated per channel.
+ try {
+ const queued = await queueChatNotifications({ userId, type, payload, notificationId: id, prefs });
+ for (const [channel, count] of Object.entries(queued)) recordEvent(id, userId, channel, 'sent', { count });
+ } catch (err) {
+ console.error('[notify] chat fan-out failed:', err.message);
+ }
+
return { id, in_app: wantsInApp };
}
diff --git a/api/gateway/connections.js b/api/gateway/connections.js
new file mode 100644
index 000000000..98f77bcc7
--- /dev/null
+++ b/api/gateway/connections.js
@@ -0,0 +1,116 @@
+// /api/gateway/connections — the owner's side of the chat gateways, behind
+// /settings/connections.
+//
+// GET → { links, agents, bots } paired chats, the account's agents,
+// and how to reach each bot
+// POST { action:'issue' } → { code, expires_at } a code to send
+// the bot as /link <code>
+// POST { action:'redeem', code } → { link } pair the chat that printed it
+// PATCH { id, notify?, default_agent_id? } → { link }
+// DELETE ?id= → { revoked: true }
+//
+// Session or bearer auth; writes are CSRF-gated (bearer exempt) and share the
+// gatewaySiteWrite budget. docs/chat-gateways.md describes the whole flow.
+
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { getRequestUser } from '../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { limits } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+import {
+ listLinksForUser, issueSiteCode, redeemChatCode, revokeLink, setLinkNotify, setLinkDefaultAgent, GatewayError,
+} from '../_lib/gateway/store.js';
+import { normalizePairCode, formatPairCode } from '../_lib/gateway/codes.js';
+import { gatewayBots, sendPlatformText } from '../_lib/gateway/bots.js';
+
+const postBody = z.discriminatedUnion('action', [
+ z.object({ action: z.literal('issue') }),
+ z.object({ action: z.literal('redeem'), code: z.string().min(8).max(16) }),
+]);
+const patchBody = z.object({
+ id: z.string().uuid(),
+ notify: z.boolean().optional(),
+ default_agent_id: z.string().uuid().nullable().optional(),
+});
+
+function linkOut(l) {
+ return {
+ id: l.id,
+ platform: l.platform,
+ chat_title: l.chat_title,
+ chat_type: l.chat_type,
+ platform_username: l.platform_username,
+ default_agent_id: l.default_agent_id,
+ default_agent_name: l.default_agent_name ?? null,
+ notify: l.notify,
+ created_at: l.created_at,
+ last_seen_at: l.last_seen_at,
+ };
+}
+
+async function readLink(userId, id) {
+ const rows = await listLinksForUser(userId);
+ return rows.find((r) => r.id === id) || null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'PATCH', 'DELETE'])) return;
+ const user = await getRequestUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in to manage chat connections');
+
+ if (req.method === 'GET') {
+ const [links, agents, bots] = await Promise.all([
+ listLinksForUser(user.id),
+ sql`SELECT id, name FROM agent_identities WHERE user_id = ${user.id} AND deleted_at IS NULL ORDER BY created_at ASC LIMIT 50`,
+ gatewayBots(),
+ ]);
+ return json(res, 200, { links: links.map(linkOut), agents, bots }, { 'cache-control': 'no-store' });
+ }
+
+ if (!(await requireCsrf(req, res, user.id))) return;
+ const rl = await limits.gatewaySiteWrite(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ try {
+ if (req.method === 'POST') {
+ const body = parse(postBody, await readJson(req));
+ if (body.action === 'issue') {
+ const { code, expiresAt } = await issueSiteCode(user.id);
+ return json(res, 201, { code: formatPairCode(code), expires_at: expiresAt });
+ }
+ const code = normalizePairCode(body.code);
+ if (!code) return error(res, 400, 'code_invalid', 'Codes are eight characters, like ABCD-EFGH.');
+ const link = await redeemChatCode({ code, userId: user.id });
+ return json(res, 201, { link: linkOut((await readLink(user.id, link.id)) || link) });
+ }
+
+ if (req.method === 'PATCH') {
+ const body = parse(patchBody, await readJson(req));
+ const current = await readLink(user.id, body.id);
+ if (!current) return error(res, 404, 'not_found', 'that connection does not exist');
+ if (body.notify !== undefined) await setLinkNotify(body.id, user.id, body.notify);
+ if (body.default_agent_id !== undefined) {
+ if (body.default_agent_id) {
+ const [own] = await sql`SELECT id FROM agent_identities WHERE id = ${body.default_agent_id} AND user_id = ${user.id} AND deleted_at IS NULL`;
+ if (!own) return error(res, 404, 'agent_not_found', 'that agent is not yours');
+ }
+ await setLinkDefaultAgent(body.id, body.default_agent_id);
+ }
+ return json(res, 200, { link: linkOut(await readLink(user.id, body.id)) });
+ }
+
+ const id = new URL(req.url, 'http://x').searchParams.get('id') || '';
+ if (!/^[0-9a-f-]{36}$/i.test(id)) return error(res, 400, 'validation_error', 'id is required');
+ const revoked = await revokeLink(id, user.id);
+ if (!revoked) return error(res, 404, 'not_found', 'that connection does not exist');
+ // Tell the chat, so a stale session there does not look like a broken bot.
+ await sendPlatformText(revoked.platform, revoked.chat_id, 'This chat was disconnected from your three.ws account on the web. Send /start to pair it again.').catch(() => {});
+ return json(res, 200, { revoked: true });
+ } catch (e) {
+ if (e instanceof GatewayError) return error(res, e.status, e.code, e.message);
+ throw e;
+ }
+});
diff --git a/api/gateway/discord.js b/api/gateway/discord.js
new file mode 100644
index 000000000..afd4146e7
--- /dev/null
+++ b/api/gateway/discord.js
@@ -0,0 +1,49 @@
+// POST /api/gateway/discord — the Discord interactions endpoint for the agent
+// chat gateway (slash commands and the Approve / Cancel buttons).
+//
+// Discord signs every interaction with Ed25519 over timestamp + raw body; an
+// unverifiable request gets 401, which is also what Discord's endpoint check
+// expects. Verified commands and button presses are queued in gateway_inbox and
+// deferred inside Discord's three-second window; the gateway worker completes
+// them through the interaction webhook. Plain messages (DMs, mentions) arrive
+// over the worker's own Discord connection, not here.
+
+import { cors, json, method, error, readBody } from '../_lib/http.js';
+import { verifyDiscordSignature, discordImmediateResponse, discordInboxKeys, DISCORD_INTERACTION } from '../_lib/gateway/webhooks.js';
+import { enqueueInbox } from '../_lib/gateway/store.js';
+
+export default async function handler(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', payments: false })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const publicKey = process.env.DISCORD_PUBLIC_KEY;
+ if (!publicKey) return error(res, 503, 'not_configured', 'the Discord gateway is not configured');
+
+ let raw;
+ try {
+ raw = await readBody(req, 1_000_000);
+ } catch (e) {
+ return error(res, e?.status || 400, 'bad_request', e?.message || 'invalid body');
+ }
+ const ok = verifyDiscordSignature({
+ rawBody: raw,
+ signature: req.headers['x-signature-ed25519'],
+ timestamp: req.headers['x-signature-timestamp'],
+ publicKey,
+ });
+ if (!ok) return error(res, 401, 'unauthorized', 'invalid request signature');
+
+ let interaction;
+ try {
+ interaction = JSON.parse(raw.toString('utf8'));
+ } catch {
+ return error(res, 400, 'bad_request', 'invalid JSON');
+ }
+ const immediate = discordImmediateResponse(interaction);
+ if (!immediate) return error(res, 400, 'unsupported', 'unsupported interaction type');
+ if (interaction.type !== DISCORD_INTERACTION.PING) {
+ const keys = discordInboxKeys(interaction);
+ if (keys) await enqueueInbox({ platform: 'discord', ...keys, payload: interaction });
+ }
+ return json(res, 200, immediate);
+}
diff --git a/api/gateway/telegram.js b/api/gateway/telegram.js
new file mode 100644
index 000000000..9af38094b
--- /dev/null
+++ b/api/gateway/telegram.js
@@ -0,0 +1,33 @@
+// POST /api/gateway/telegram — the Telegram webhook for the agent chat gateway.
+//
+// Telegram proves each delivery with the X-Telegram-Bot-Api-Secret-Token header
+// it was given at setWebhook time (api/_lib/gateway/webhooks.js derives it). A
+// verified update is queued in gateway_inbox and answered 200 at once; the
+// gateway worker (workers/agent-gateway) runs the turn and replies. A retried
+// update_id is deduplicated by the inbox's unique key, so Telegram's redelivery
+// never produces a second reply. docs/chat-gateways.md has the full flow.
+
+import { cors, json, method, error, readJson } from '../_lib/http.js';
+import { verifyTelegramSecret, telegramInboxKeys } from '../_lib/gateway/webhooks.js';
+import { enqueueInbox } from '../_lib/gateway/store.js';
+
+export default async function handler(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', payments: false })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ if (!verifyTelegramSecret(req.headers['x-telegram-bot-api-secret-token'])) {
+ return error(res, 401, 'unauthorized', 'invalid webhook secret');
+ }
+ let update;
+ try {
+ update = await readJson(req, 2_000_000);
+ } catch (e) {
+ return error(res, e?.status || 400, 'bad_request', e?.message || 'invalid body');
+ }
+ const keys = telegramInboxKeys(update);
+ // Updates the gateway does not handle (channel posts, member changes) are
+ // acknowledged so Telegram stops redelivering them.
+ if (!keys) return json(res, 200, { ok: true, ignored: true });
+ await enqueueInbox({ platform: 'telegram', ...keys, payload: update });
+ return json(res, 200, { ok: true });
+}
diff --git a/api/notifications/preferences.js b/api/notifications/preferences.js
index 1ecb5ab6e..721ccb852 100644
--- a/api/notifications/preferences.js
+++ b/api/notifications/preferences.js
@@ -51,9 +51,17 @@ export default wrap(async (req, res) => {
if (req.method === 'GET') {
const prefs = await resolvePrefs(user.id);
- const [pushRow] = await sql`
- select count(*)::int as count from push_subscriptions where user_id = ${user.id}
- `;
+ const [[pushRow], chats] = await Promise.all([
+ sql`select count(*)::int as count from push_subscriptions where user_id = ${user.id}`,
+ // Chats paired through the chat gateways (/settings/connections). The
+ // telegram and discord channels deliver there, so the matrix enables
+ // those columns once a chat with notifications on exists.
+ sql`select platform, count(*)::int as count from gateway_links
+ where user_id = ${user.id} and revoked_at is null and notify = true
+ group by platform`.catch(() => []),
+ ]);
+ const gateways = { telegram: 0, discord: 0 };
+ for (const r of chats) gateways[r.platform] = r.count;
return json(res, 200, {
categories: CATEGORIES,
channels: CHANNELS,
@@ -63,6 +71,7 @@ export default wrap(async (req, res) => {
type_categories: typeCategoryMap(),
prefs,
push: { subscribed_devices: pushRow?.count ?? 0 },
+ gateways,
});
}
diff --git a/src/dashboard-next/pages/settings.js b/src/dashboard-next/pages/settings.js
index 07bc0bec4..09061edf2 100644
--- a/src/dashboard-next/pages/settings.js
+++ b/src/dashboard-next/pages/settings.js
@@ -2,6 +2,7 @@
//
// Consolidates everything that doesn't fit in Account or Monetize:
// • Active sessions (list + revoke)
+// • Connected apps (OAuth grants: desktop console, CLI, editors; revoke)
// • Notifications (list + mark-read)
// • Avatar storage mode (R2 vs IPFS, pin to IPFS)
// • Storage usage (avatar files, animation clips)
@@ -13,6 +14,8 @@
// GET /api/auth/sessions { sessions: [...] }
// DELETE /api/auth/sessions/:id revoke one session
// DELETE /api/auth/sessions revoke all others + rotate current
+// GET /api/oauth/grants { grants: [...] } apps holding a live refresh token
+// DELETE /api/oauth/grants?client_id= revoke one app
// GET /api/notifications { notifications: [...], unread: N }
// POST /api/notifications/read-all
// GET /api/billing/summary { usage: { total_bytes, avatar_count, ... } }
@@ -111,9 +114,10 @@ async function loadContent(host) {
const retry = () => loadContent(host);
- const [sessionsResp, notifResp, notifPrefsResp, avatarsResp, summaryResp, usageResp, prefsResp, versionResp] =
+ const [sessionsResp, grantsResp, notifResp, notifPrefsResp, avatarsResp, summaryResp, usageResp, prefsResp, versionResp] =
await Promise.all([
safeGet('/api/auth/sessions'),
+ safeGet('/api/oauth/grants'),
safeGet('/api/notifications?limit=20'),
safeGet('/api/notifications/preferences'),
safeGet('/api/avatars/mine?limit=24'),
@@ -128,6 +132,7 @@ async function loadContent(host) {
host.innerHTML = '';
host.appendChild(renderTheme());
host.appendChild(renderSessions(sessionsResp, retry));
+ host.appendChild(renderConnectedApps(grantsResp, retry));
host.appendChild(renderNotifications(notifResp, retry));
host.appendChild(renderNotificationPrefs(notifPrefsResp, retry));
host.appendChild(renderDefaultNetwork(prefs));
@@ -138,6 +143,8 @@ async function loadContent(host) {
host.appendChild(renderPrefs(prefs));
host.appendChild(renderDataExport());
host.appendChild(renderAbout(versionResp));
+ // The OAuth consent screen and three.ws Desktop link here to revoke an app.
+ if (location.hash === '#connected-apps') document.getElementById('connected-apps')?.scrollIntoView({ block: 'start' });
}
// Returns { ok, data } so callers can tell a genuine fetch failure (show an
@@ -256,6 +263,74 @@ function renderSessions(resp, onRetry) {
return panel;
}
+// ── Connected apps ─────────────────────────────────────────────────────────
+
+const SCOPE_WORDS = {
+ profile: 'profile', offline_access: 'stay signed in', 'agents:read': 'read agents', 'agents:write': 'edit agents',
+ 'avatars:read': 'read avatars', 'avatars:write': 'edit avatars', 'avatars:delete': 'delete avatars',
+ 'memory:read': 'read memory', 'memory:write': 'write memory', 'wallet:read': 'read wallets', 'wallet:write': 'spend from wallets',
+ 'services:write': 'sell services', 'home:read': 'read home', 'home:act': 'control home', 'feedback:read': 'read feedback',
+};
+
+function renderConnectedApps(resp, onRetry) {
+ const panel = document.createElement('div');
+ panel.className = 'dn-panel';
+ panel.id = 'connected-apps';
+ panel.setAttribute('aria-label', 'Connected apps');
+ panel.innerHTML = `
+ <div class="set-panel-head">
+ <div>
+ <div class="dn-panel-title">Connected apps</div>
+ <div class="dn-panel-sub" style="margin:2px 0 0">Apps you signed in with three.ws: the desktop app, the CLI, and coding clients using your MCP tools. Revoking stops an app within an hour, when its current access expires.</div>
+ </div>
+ </div>
+ <div data-slot="grants-list"></div>
+ `;
+ const listHost = panel.querySelector('[data-slot="grants-list"]');
+ if (!resp.ok) {
+ listHost.innerHTML = errorStateHTML({ title: "Couldn't load connected apps", body: 'We couldn’t reach the sign-in service. Check your connection and try again.' });
+ attachRetry(listHost, onRetry);
+ return panel;
+ }
+ const render = (grants) => {
+ if (!grants.length) {
+ listHost.innerHTML = emptyStateHTML({ icon: '', title: 'No connected apps', body: 'When you sign in to three.ws Desktop, the CLI, or an editor over MCP, it appears here.', compact: true });
+ return;
+ }
+ listHost.innerHTML = grants.map((g) => `
+ <div style="display:flex;align-items:center;gap:12px;padding:12px 0;border-bottom:1px solid var(--nxt-stroke);flex-wrap:wrap" data-client-id="${esc(g.client_id)}">
+ <div style="flex:1;min-width:200px">
+ <div style="font-size:13.5px;color:var(--nxt-ink);font-weight:500">${esc(g.name)}${g.software ? ` <span style="color:var(--nxt-ink-fade);font-weight:400;font-family:${MONO};font-size:11.5px">${esc(g.software)}</span>` : ''}</div>
+ <div style="font-size:12px;color:var(--nxt-ink-fade);margin-top:3px">
+ Can ${esc(g.scopes.map((sc) => SCOPE_WORDS[sc] || sc).join(', '))} · used ${esc(relTime(g.last_used_at))} · authorized ${esc(relTime(g.authorized_at))}
+ </div>
+ </div>
+ <button class="dn-btn danger" data-action="revoke-grant" data-id="${esc(g.client_id)}" data-name="${esc(g.name)}" style="padding:5px 10px;font-size:12px">Revoke</button>
+ </div>
+ `).join('');
+ listHost.querySelectorAll('[data-action="revoke-grant"]').forEach((btn) => {
+ btn.addEventListener('click', async () => {
+ if (!confirm(`Revoke ${btn.dataset.name}? It will need to sign in again.`)) return;
+ btn.disabled = true;
+ btn.textContent = 'Revoking…';
+ try {
+ await del(`/api/oauth/grants?client_id=${encodeURIComponent(btn.dataset.id)}`);
+ toast(`${btn.dataset.name} revoked`);
+ grants = grants.filter((g) => g.client_id !== btn.dataset.id);
+ render(grants);
+ } catch (err) {
+ toast(err?.message || 'Failed to revoke');
+ btn.disabled = false;
+ btn.textContent = 'Revoke';
+ }
+ });
+ });
+ };
+ let grants = resp.data?.grants || [];
+ render(grants);
+ return panel;
+}
+
// ── Notifications ──────────────────────────────────────────────────────────
function renderNotifications(resp, onRetry) {
@@ -341,10 +416,11 @@ function renderNotifications(resp, onRetry) {
// api/_lib/notify.js checks this before sending push/email, so a toggle here
// takes effect on the very next event, not just in the UI.
-const CHANNEL_LABEL = { in_app: 'In-app', push: 'Push', email: 'Email', telegram: 'Telegram', avatar: 'Avatar' };
+const CHANNEL_LABEL = { in_app: 'In-app', push: 'Push', email: 'Email', telegram: 'Telegram', discord: 'Discord', avatar: 'Avatar' };
// One line of help per channel, shown under the table, because "Avatar" is not
// self-explanatory the way Push and Email are.
const CHANNEL_HINT = {
+ telegram: 'Telegram and Discord: delivered to the chats you paired with your agent, where you can reply in place. Pair a chat at /settings/connections.',
avatar: 'Avatar: your companion walks on screen and says it out loud while you are on the site. Turn it off for this browser only from the "Turn off" control in its bubble.',
};
@@ -371,14 +447,14 @@ function renderNotificationPrefs(resp, onRetry) {
const body = resp.data || {};
const categories = Array.isArray(body.categories) ? body.categories : [];
- const channels = Array.isArray(body.channels) ? body.channels : ['in_app', 'push', 'email', 'telegram', 'avatar'];
+ const channels = Array.isArray(body.channels) ? body.channels : ['in_app', 'push', 'email', 'telegram', 'discord', 'avatar'];
const matrix = body.prefs?.categories || {};
const subscribedDevices = body.push?.subscribed_devices ?? 0;
panel.innerHTML = `
<div style="margin-bottom:14px">
<div class="dn-panel-title">Notification preferences</div>
- <div class="dn-panel-sub" style="margin:2px 0 0">Mute noisy categories per channel. Account and security events always stay in your bell so nothing important is silently lost, but you can still quiet their push, email, Telegram and avatar announcements.</div>
+ <div class="dn-panel-sub" style="margin:2px 0 0">Mute noisy categories per channel. Account and security events always stay in your bell so nothing important is silently lost, but you can still quiet their push, email, Telegram, Discord and avatar announcements.</div>
</div>
${!categories.length ? emptyStateHTML({
icon: '',
@@ -407,12 +483,16 @@ function renderNotificationPrefs(resp, onRetry) {
// non-interactive rather than as a toggle that does nothing.
const locked = (cat.lockedChannels || []).includes(ch);
const on = locked || (matrix?.[cat.key]?.[ch] ?? false);
- const noTelegram = ch === 'telegram' && !body.prefs?.telegram_chat_id;
+ // Chat channels need somewhere to deliver: a chat paired at
+ // /settings/connections (or, for Telegram, a legacy chat id).
+ const paired = body.gateways || {};
+ const noTelegram = (ch === 'telegram' && !body.prefs?.telegram_chat_id && !paired.telegram)
+ || (ch === 'discord' && !paired.discord);
const disabled = locked || noTelegram;
const title = locked
? 'Always on: account and security events are kept in your bell'
: noTelegram
- ? 'Link a Telegram chat id to enable'
+ ? `Pair a ${CHANNEL_LABEL[ch]} chat at /settings/connections to enable`
: '';
return `
<td style="padding:10px;text-align:center">
diff --git a/tests/notify-prefs.test.js b/tests/notify-prefs.test.js
index d4d303f88..90adf5dd8 100644
--- a/tests/notify-prefs.test.js
+++ b/tests/notify-prefs.test.js
@@ -20,9 +20,9 @@ import {
describe('category model', () => {
it('exposes the nine display categories and five channels', () => {
expect(CATEGORIES.map((c) => c.key)).toEqual([
- 'sales', 'purchases', 'social', 'irl', 'alerts', 'creations', 'companion', 'knock', 'account',
+ 'sales', 'purchases', 'social', 'irl', 'alerts', 'creations', 'companion', 'knock', 'mail', 'account',
]);
- expect(CHANNELS).toEqual(['in_app', 'push', 'email', 'telegram', 'avatar']);
+ expect(CHANNELS).toEqual(['in_app', 'push', 'email', 'telegram', 'discord', 'avatar']);
});
it('every category has a label and description for the preference center', () => {