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(ops): admin ops-alert dashboard — alerts persist to DB, not Telegram-only

fudjia91f552a8b332
diff --git a/api/_lib/alerts.js b/api/_lib/alerts.js
index a2dab142f..050b4cd1f 100644
--- a/api/_lib/alerts.js
+++ b/api/_lib/alerts.js
@@ -1,25 +1,30 @@
// @ts-check
-// Real-time ops alerts → Telegram. Errors should find the operator, not wait
-// to be hunted: serverError()/wrap() report 5xx server faults here and
-// api/client-errors.js reports browser errors, so production failures surface
-// in an ops channel seconds after they happen.
+// Ops alerts. Errors should find the operator, not wait to be hunted:
+// serverError()/wrap() report 5xx server faults here and api/client-errors.js
+// reports browser errors, so production failures surface seconds after they
+// happen.
//
-// Env (both required, else every call is a silent no-op — dev and tests need
-// no config):
-// TELEGRAM_BOT_TOKEN — same bot the changelog pusher uses
-// TELEGRAM_ALERTS_CHAT_ID — PRIVATE ops chat/channel id. Never the public
-// holders' channel: alerts carry stack traces,
-// URLs, and IPs.
+// Two independent sinks, and the DB one is always on:
+// 1. The admin dashboard (PRIMARY). Every alert is upserted into `ops_alerts`
+// keyed by its stable signature — a recurring condition is ONE row with a
+// growing count, not a flood. This happens regardless of any Telegram
+// config, so the ops surface at /admin/ops always has the record. Read via
+// GET /api/admin/ops-alerts.
+// 2. Telegram (OPTIONAL push). Only when BOTH vars are set:
+// TELEGRAM_BOT_TOKEN — the platform bot
+// TELEGRAM_ALERTS_CHAT_ID — a PRIVATE ops chat/DM. Never the public
+// holders' channel: alerts carry stack traces,
+// URLs, and IPs. Absent → dashboard-only, which
+// is the intended default.
//
-// Noise control, because an alert channel that floods gets muted and then it
-// protects nothing:
-// - per-signature dedup: one alert per unique error signature per hour
-// - global ceiling: max 20 alerts per hour, then one "throttled" notice
-// Both windows live in the shared cache (Upstash Redis when configured, so
-// dedup holds across serverless instances; in-memory otherwise).
+// Noise control on the Telegram push (the dashboard keeps the full count):
+// - per-signature dedup: one push per unique signature per hour
+// - global ceiling: max 20 pushes per hour, then one "throttled" notice
+// Both windows live in the shared cache (Redis when configured, else in-memory).
//
-// Fire-and-forget like sentry.js: a hard 2.5s abort, every failure swallowed.
-// An alerting pipeline must never delay or break the request it's reporting on.
+// Fire-and-forget like sentry.js: every failure swallowed, the DB write is a
+// single-row upsert, the Telegram send has a hard 2.5s abort. An alerting
+// pipeline must never delay or break the request it's reporting on.
import { createHash } from 'node:crypto';
import { cacheGet, cacheSet } from './cache.js';
@@ -34,10 +39,10 @@ function config() {
}
/**
- * Whether a real alert channel is wired. When false, every sendOpsAlert() is a
- * silent no-op — intended for dev/tests, but dangerous to leave unnoticed in
- * production, so /api/healthz reports this instead of letting the silence pass
- * for health.
+ * Whether the Telegram PUSH channel is wired. The dashboard sink is always on,
+ * so this is not "are alerts working" — it is "do alerts also get pushed to
+ * Telegram". /api/healthz reports it so a deliberately dashboard-only setup
+ * reads as intentional rather than broken.
* @returns {boolean}
*/
export function alertsConfigured() {
@@ -48,6 +53,54 @@ function signatureOf(text) {
return createHash('sha256').update(text).digest('hex').slice(0, 16);
}
+/**
+ * Classify an alert by its title. Callers encode urgency with a leading emoji
+ * (🚨 for compromise/leak/CRITICAL, ⚠️/💸/⛽/💵 for degradations); map that to a
+ * stable severity the dashboard can sort and colour by. Overridable via
+ * opts.severity.
+ * @param {string} title
+ * @returns {'critical'|'warn'|'info'}
+ */
+export function severityOf(title) {
+ const t = String(title || '');
+ if (/🚨/.test(t) || /\b(CRITICAL|LEAK|COMPROMISED|halted)\b/i.test(t)) return 'critical';
+ if (/ℹ️|\binfo\b/i.test(t)) return 'info';
+ return 'warn';
+}
+
+/**
+ * Upsert the alert into `ops_alerts`. Best-effort and fail-soft: a missing DB,
+ * an absent table (pre-migration), or any query error is swallowed so the
+ * caller's error path is never affected. Keyed by signature so repeats
+ * increment a count and refresh last_seen instead of piling up rows; a repeat
+ * also clears a prior acknowledgement (the condition is happening again).
+ * @param {{ sig: string, title: string, detail: string, severity: string, environment: string }} a
+ */
+async function persistAlert({ sig, title, detail, severity, environment }) {
+ try {
+ const [{ sql }, { databaseConfigured }] = await Promise.all([
+ import('./db.js'),
+ import('./env.js'),
+ ]);
+ if (typeof databaseConfigured === 'function' && !databaseConfigured()) return;
+ await sql`
+ insert into ops_alerts (signature, title, detail, severity, environment, count, first_seen, last_seen)
+ values (${sig}, ${title}, ${detail || null}, ${severity}, ${environment}, 1, now(), now())
+ on conflict (signature) do update set
+ title = excluded.title,
+ detail = excluded.detail,
+ severity = excluded.severity,
+ environment = excluded.environment,
+ count = ops_alerts.count + 1,
+ last_seen = now(),
+ acknowledged_at = null,
+ acknowledged_by = null
+ `;
+ } catch {
+ /* dashboard sink is best-effort — never throws into the caller */
+ }
+}
+
function post(cfg, text) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 2500);
@@ -67,18 +120,28 @@ function post(cfg, text) {
}
/**
- * Send an ops alert. Deduped and throttled; safe to call on every error path.
+ * Send an ops alert. Always recorded to the dashboard (`ops_alerts`); also
+ * pushed to Telegram when that channel is configured (deduped + throttled).
+ * Safe to call on every error path — fail-soft, never throws.
* @param {string} title one-line summary, e.g. "5xx in /api/chat"
* @param {string} [detail] body lines (message, ref, page, stack head)
- * @param {{ signature?: string }} [opts] override the dedup signature when
- * the title/detail contain per-event noise (ids, refs) that would
- * defeat dedup.
+ * @param {{ signature?: string, severity?: 'critical'|'warn'|'info' }} [opts]
+ * signature overrides the dedup/identity key when the title/detail carry
+ * per-event noise (ids, refs) that would otherwise defeat coalescing;
+ * severity overrides the title-derived classification.
*/
export async function sendOpsAlert(title, detail = '', opts = {}) {
+ const environment = process.env.VERCEL_ENV || 'development';
+ const sig = signatureOf(opts.signature || `${title}\n${detail}`);
+ const severity = opts.severity || severityOf(title);
+
+ // 1. Dashboard sink — always on, independent of Telegram.
+ await persistAlert({ sig, title, detail, severity, environment });
+
+ // 2. Telegram push — optional, only when a private ops chat is wired.
const cfg = config();
if (!cfg) return;
try {
- const sig = signatureOf(opts.signature || `${title}\n${detail}`);
if (await cacheGet(`alert:dedup:${sig}`)) return;
await cacheSet(`alert:dedup:${sig}`, 1, DEDUP_TTL_S);
@@ -87,15 +150,14 @@ export async function sendOpsAlert(title, detail = '', opts = {}) {
if (sent >= GLOBAL_LIMIT_PER_HOUR) {
if (sent === GLOBAL_LIMIT_PER_HOUR) {
await cacheSet(hourBucket, sent + 1, DEDUP_TTL_S);
- post(cfg, `⚠️ three.ws alerts throttled — over ${GLOBAL_LIMIT_PER_HOUR}/h. Check the logs directly.`);
+ post(cfg, `⚠️ three.ws alerts throttled — over ${GLOBAL_LIMIT_PER_HOUR}/h. Check /admin/ops.`);
}
return;
}
await cacheSet(hourBucket, sent + 1, DEDUP_TTL_S);
- const env = process.env.VERCEL_ENV || 'development';
- post(cfg, `🔴 three.ws [${env}] ${title}${detail ? `\n${detail}` : ''}`);
+ post(cfg, `🔴 three.ws [${environment}] ${title}${detail ? `\n${detail}` : ''}`);
} catch {
- /* alerting is best-effort, never throws into the caller */
+ /* push is best-effort, never throws into the caller */
}
}
diff --git a/api/_lib/migrations/20260712000000_ops_alerts.sql b/api/_lib/migrations/20260712000000_ops_alerts.sql
new file mode 100644
index 000000000..4fbe06567
--- /dev/null
+++ b/api/_lib/migrations/20260712000000_ops_alerts.sql
@@ -0,0 +1,29 @@
+-- Ops alerts store — the durable record behind the admin ops dashboard.
+--
+-- Every sendOpsAlert() (api/_lib/alerts.js) upserts one row here, keyed by the
+-- alert's stable signature, so a recurring condition is ONE row with a growing
+-- count rather than a flood. This is independent of the Telegram channel: alerts
+-- persist here even when no chat is configured, which is what lets the admin
+-- surface at /admin/ops show them. Acknowledging a row silences it in the active
+-- feed until the same signature fires again (which re-activates it).
+
+CREATE TABLE IF NOT EXISTS ops_alerts (
+ signature text PRIMARY KEY,
+ title text NOT NULL,
+ detail text,
+ severity text NOT NULL DEFAULT 'warn', -- 'critical' | 'warn' | 'info'
+ count integer NOT NULL DEFAULT 1,
+ environment text,
+ first_seen timestamptz NOT NULL DEFAULT now(),
+ last_seen timestamptz NOT NULL DEFAULT now(),
+ acknowledged_at timestamptz,
+ acknowledged_by text
+);
+
+-- Active feed: unacknowledged, newest breach first.
+CREATE INDEX IF NOT EXISTS ops_alerts_active_idx
+ ON ops_alerts (acknowledged_at, last_seen DESC);
+
+-- Full history browse.
+CREATE INDEX IF NOT EXISTS ops_alerts_last_seen_idx
+ ON ops_alerts (last_seen DESC);
diff --git a/api/admin/ops-alerts.js b/api/admin/ops-alerts.js
new file mode 100644
index 000000000..d2711cad0
--- /dev/null
+++ b/api/admin/ops-alerts.js
@@ -0,0 +1,116 @@
+// GET /api/admin/ops-alerts — the ops-alert feed for /admin/ops.
+// POST /api/admin/ops-alerts — { signature, action: 'ack'|'unack' }.
+//
+// Auth mirrors /api/ops/health exactly: an `x-ops-secret` (or Bearer) header
+// equal to OPS_SECRET, falling back to CRON_SECRET so the same credential the
+// ops page already uses works here too. No extra setup for the admin.
+//
+// The rows come from `ops_alerts`, upserted by every sendOpsAlert()
+// (api/_lib/alerts.js). This surface is what replaced the Telegram-only channel:
+// alerts persist here whether or not a chat is configured, so the dashboard is
+// the source of truth. Acknowledging a row drops it from the active feed until
+// the same signature fires again (which re-activates it).
+
+import { wrap, cors, json, error, readJson, rateLimited } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+
+function authorized(req) {
+ const secret = env.OPS_SECRET || env.CRON_SECRET;
+ if (!secret) return true; // no secret configured (dev) → open, same as /api/ops/health
+ const provided =
+ req.headers['x-ops-secret'] || req.headers['authorization']?.replace(/^Bearer\s+/i, '');
+ return !!provided && constantTimeEquals(provided, secret);
+}
+
+const ACTIVE_LIMIT = 200;
+const RESOLVED_LIMIT = 50;
+
+async function listAlerts() {
+ // Active (unacknowledged) first — critical before warn before info, then most
+ // recent. Resolved (acknowledged) shown separately, capped, for context.
+ const active = await sql`
+ select signature, title, detail, severity, count, environment,
+ first_seen, last_seen
+ from ops_alerts
+ where acknowledged_at is null
+ order by
+ case severity when 'critical' then 0 when 'warn' then 1 else 2 end,
+ last_seen desc
+ limit ${ACTIVE_LIMIT}
+ `;
+ const resolved = await sql`
+ select signature, title, detail, severity, count, environment,
+ first_seen, last_seen, acknowledged_at, acknowledged_by
+ from ops_alerts
+ where acknowledged_at is not null
+ order by acknowledged_at desc
+ limit ${RESOLVED_LIMIT}
+ `;
+ const counts = {
+ active: active.length,
+ critical: active.filter((a) => a.severity === 'critical').length,
+ warn: active.filter((a) => a.severity === 'warn').length,
+ info: active.filter((a) => a.severity === 'info').length,
+ };
+ return { counts, active, resolved };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: 'same' })) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (!authorized(req)) return error(res, 401, 'unauthorized', 'x-ops-secret required');
+
+ const m = req.method?.toUpperCase();
+
+ if (m === 'GET') {
+ try {
+ return json(res, 200, await listAlerts());
+ } catch (err) {
+ // Table absent (pre-migration) or DB down — report an empty, honest feed
+ // rather than 500 the dashboard.
+ return json(res, 200, {
+ counts: { active: 0, critical: 0, warn: 0, info: 0 },
+ active: [],
+ resolved: [],
+ note: `alerts_unavailable: ${err?.message || 'db error'}`,
+ });
+ }
+ }
+
+ if (m === 'POST') {
+ const body = await readJson(req).catch(() => null);
+ const signature = String(body?.signature || '').trim();
+ const action = String(body?.action || 'ack').trim();
+ if (!signature) return error(res, 400, 'bad_request', 'signature required');
+ if (action !== 'ack' && action !== 'unack') {
+ return error(res, 400, 'bad_request', "action must be 'ack' or 'unack'");
+ }
+ const by = String(body?.by || 'admin').slice(0, 120);
+ try {
+ const rows =
+ action === 'ack'
+ ? await sql`
+ update ops_alerts
+ set acknowledged_at = now(), acknowledged_by = ${by}
+ where signature = ${signature}
+ returning signature`
+ : await sql`
+ update ops_alerts
+ set acknowledged_at = null, acknowledged_by = null
+ where signature = ${signature}
+ returning signature`;
+ if (rows.length === 0) return error(res, 404, 'not_found', 'no alert with that signature');
+ return json(res, 200, { ok: true, signature, action });
+ } catch (err) {
+ return error(res, 500, 'server_error', err?.message || 'update failed');
+ }
+ }
+
+ return error(res, 405, 'method_not_allowed', 'GET or POST');
+});
diff --git a/api/healthz.js b/api/healthz.js
index 91a66a85e..a9ad4df28 100644
--- a/api/healthz.js
+++ b/api/healthz.js
@@ -361,19 +361,15 @@ export default wrap(async (req, res) => {
requires: ['NVIDIA_API_KEY', 'NVIDIA_ASR_FUNCTION_ID'],
},
},
- // The real-time ops alert channel (api/_lib/alerts.js). It is a deliberate
- // silent no-op when unconfigured, so dev and tests need no secrets — but
- // that same silence in production means every 5xx report, browser-error
- // report, ring-leak CRITICAL, and low-balance warning goes nowhere with no
- // indication anything is wrong. Surface the gate here so a missing channel
- // is visible on the dashboard instead of only discoverable by reading code.
+ // Ops alerts (api/_lib/alerts.js). Every sendOpsAlert() ALWAYS persists to
+ // the ops_alerts table and surfaces on the admin dashboard (/admin/ops), so
+ // alerts are never silently dropped. Telegram is an OPTIONAL extra push for
+ // real-time notification; its absence is expected, not a fault.
alerts: {
- configured: alertsConfigured(),
- channel: 'telegram',
- requires: ['TELEGRAM_BOT_TOKEN', 'TELEGRAM_ALERTS_CHAT_ID'],
- ...(alertsConfigured() ? {} : {
- warning: 'ops alerts are a silent no-op — sendOpsAlert() calls (5xx faults, client errors, ring leaks, low-balance) are dropped',
- }),
+ primary: 'dashboard',
+ dashboard: '/admin/ops',
+ telegram_push: alertsConfigured() ? 'enabled' : 'disabled',
+ telegram_requires: ['TELEGRAM_BOT_TOKEN', 'TELEGRAM_ALERTS_CHAT_ID'],
},
}, { 'cache-control': 'public, max-age=2, s-maxage=2' });
});
diff --git a/docs/ops/gcp-production.md b/docs/ops/gcp-production.md
index 7da422987..de2e1e1a4 100644
--- a/docs/ops/gcp-production.md
+++ b/docs/ops/gcp-production.md
@@ -297,28 +297,34 @@ pattern-matching an RPC error string, whose wording varies by provider.
To resume autonomous spend, fund the payer's USDC float. The loop self-recovers
on the next tick — no redeploy, no flag flip.
-### Resolved: ops alert channel wired (2026-07-11)
-
-`/api/healthz` reported `alerts.configured: false` and **every** `sendOpsAlert()`
-was a silent no-op — 5xx faults, `api/client-errors.js` browser reports,
-ring-leak CRITICALs, and low-balance warnings all dropped (`api/_lib/alerts.js`
-returns early when either Telegram var is missing). Production had no real-time
-alerting, which is why the x402 payment storm below ran for a day unnoticed.
-
-Fix: bot `@threewsbot` (owner-created via `@BotFather`). Token stored in Secret
-Manager (`telegram-bot-token`, granted to the `three-ws@` runtime SA) and
-referenced by `TELEGRAM_BOT_TOKEN`; `TELEGRAM_ALERTS_CHAT_ID` set inline to the
-owner's private DM chat id (a bot cannot DM a user until that user has messaged
-it first — the owner sent `/start` to seed the chat, then the id was read off
-`getUpdates`). Verified end to end: a direct `sendMessage` delivered, `healthz`
-now reports `alerts.configured: true`, and the app's own empty-float alert
-fired from revision `three-ws-api-00059-vbg`. Alerts are deduped per signature
-for 1h and capped at 20/h (`alerts.js`), so a recurring condition notifies once,
-not every tick.
-
-To point alerts at a shared private group instead of the owner's DM: add
-`@threewsbot` to the group (admin if it's a channel), post any message, read the
-new negative chat id from `getUpdates`, and update `TELEGRAM_ALERTS_CHAT_ID`.
+### Ops alerts: dashboard-primary (2026-07-12)
+
+Ops alerting used to be Telegram-only, and Telegram-only meant that with no chat
+configured **every** `sendOpsAlert()` was a silent no-op — 5xx faults,
+`api/client-errors.js` browser reports, ring-leak CRITICALs, and low-balance
+warnings all dropped. That is why the x402 payment storm below ran for a day
+unnoticed.
+
+Now every `sendOpsAlert()` **always** persists to the `ops_alerts` table
+(`api/_lib/alerts.js`, migration `20260712000000_ops_alerts.sql`), keyed by the
+alert's stable signature so a recurring condition is one row with a growing
+`count`, not a flood. The admin surface at **`/admin/ops`** ("Platform Health")
+renders the active feed — severity-sorted, with acknowledge / reopen — from
+`GET/POST /api/admin/ops-alerts`. Auth is the same `x-ops-secret`
+(`OPS_SECRET`, falling back to `CRON_SECRET`) the ops page already uses. This is
+the primary sink and needs no third-party service.
+
+Telegram is now an **optional extra push**, off by default. When both
+`TELEGRAM_BOT_TOKEN` and `TELEGRAM_ALERTS_CHAT_ID` are set, alerts also push to
+that private chat (deduped per signature for 1h, capped at 20/h). It is
+deliberately unset in production — the dashboard is the channel. `/api/healthz`
+reports `alerts.primary: "dashboard"` and `alerts.telegram_push:
+"disabled"|"enabled"`; a disabled push is expected, not a fault. The
+`@threewsbot` token remains in Secret Manager (`telegram-bot-token`) for
+user-facing bot use (e.g. changelog push to holders); it is **not** wired to ops
+alerts. To turn the extra push on, add `@threewsbot` to a private ops chat, read
+its id from `getUpdates`, and set `TELEGRAM_ALERTS_CHAT_ID` (+ point
+`TELEGRAM_BOT_TOKEN` at the secret).
### Resolved: x402 sponsor co-signing key (2026-07-09)
diff --git a/pages/admin/ops.html b/pages/admin/ops.html
index 2ea4b0256..3b134c63d 100644
--- a/pages/admin/ops.html
+++ b/pages/admin/ops.html
@@ -43,6 +43,42 @@
.banner-text { font-size: 14.5px; font-weight: 600; }
.banner-sub { font-size: 12.5px; color: rgba(255,255,255,0.45); margin-left: auto; }
+ /* Ops alerts feed */
+ .alerts-section { margin-bottom: 2.5rem; }
+ .alerts-hd { display: flex; align-items: center; gap: 0.75rem; margin-bottom: 0.85rem; }
+ .alerts-hd-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 700; color: rgba(255,255,255,0.3); }
+ .alerts-hd-counts { display: flex; gap: 0.4rem; }
+ .alert-count-pill { font-size: 11px; font-weight: 700; padding: 2px 9px; border-radius: 99px; border: 1px solid; }
+ .alert-count-pill.critical { color: #f87171; background: rgba(248,113,113,0.1); border-color: rgba(248,113,113,0.25); }
+ .alert-count-pill.warn { color: #f0a93b; background: rgba(240,169,59,0.1); border-color: rgba(240,169,59,0.25); }
+ .alert-count-pill.info { color: #60a5fa; background: rgba(96,165,250,0.1); border-color: rgba(96,165,250,0.25); }
+ .alerts-empty { display: flex; align-items: center; gap: 0.6rem; padding: 1.1rem 1.4rem; border-radius: 12px; background: rgba(47,191,113,0.06); border: 1px solid rgba(47,191,113,0.16); color: #2fbf71; font-size: 13.5px; font-weight: 600; }
+ .alert-card { display: grid; grid-template-columns: 4px 1fr auto; gap: 0 1rem; align-items: start; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.07); border-radius: 12px; padding: 0.9rem 1.1rem 0.9rem 0; margin-bottom: 0.65rem; overflow: hidden; }
+ .alert-card .rail { grid-row: 1 / -1; align-self: stretch; border-radius: 4px 0 0 4px; }
+ .alert-card.critical .rail { background: #f87171; }
+ .alert-card.warn .rail { background: #f0a93b; }
+ .alert-card.info .rail { background: #60a5fa; }
+ .alert-body { min-width: 0; }
+ .alert-title { font-size: 13.5px; font-weight: 700; color: #f1f5f9; margin: 0 0 0.3rem; line-height: 1.4; word-break: break-word; }
+ .alert-detail { font-size: 12px; color: rgba(255,255,255,0.5); line-height: 1.55; white-space: pre-wrap; word-break: break-word; margin: 0.15rem 0 0; max-height: 3.4em; overflow: hidden; position: relative; cursor: pointer; }
+ .alert-detail.expanded { max-height: none; }
+ .alert-detail.clamped::after { content: '… more'; position: absolute; right: 0; bottom: 0; padding-left: 1.5rem; background: linear-gradient(90deg, transparent, #131318 40%); color: rgba(255,255,255,0.4); font-weight: 600; }
+ .alert-meta { display: flex; flex-wrap: wrap; gap: 0.5rem 0.9rem; margin-top: 0.5rem; font-size: 11px; color: rgba(255,255,255,0.32); }
+ .alert-meta .sev { font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; }
+ .alert-card.critical .sev { color: #f87171; }
+ .alert-card.warn .sev { color: #f0a93b; }
+ .alert-card.info .sev { color: #60a5fa; }
+ .alert-count-badge { font-variant-numeric: tabular-nums; }
+ .alert-actions { align-self: center; }
+ .alert-ack { font: inherit; font-size: 11.5px; font-weight: 600; padding: 6px 13px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.14); background: rgba(255,255,255,0.05); color: rgba(255,255,255,0.7); cursor: pointer; transition: all .15s; white-space: nowrap; }
+ .alert-ack:hover { background: rgba(47,191,113,0.14); border-color: rgba(47,191,113,0.4); color: #2fbf71; }
+ .alert-ack:disabled { opacity: 0.5; cursor: default; }
+ .alerts-resolved-toggle { font: inherit; font-size: 11.5px; font-weight: 600; color: rgba(255,255,255,0.4); background: none; border: none; cursor: pointer; padding: 0.4rem 0; margin-top: 0.3rem; }
+ .alerts-resolved-toggle:hover { color: rgba(255,255,255,0.7); }
+ .alert-card.resolved { opacity: 0.55; }
+ .alert-unack { font: inherit; font-size: 11.5px; font-weight: 600; padding: 6px 13px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.1); background: transparent; color: rgba(255,255,255,0.45); cursor: pointer; white-space: nowrap; }
+ .alert-unack:hover { color: #f0a93b; border-color: rgba(240,169,59,0.4); }
+
/* Summary cards */
.ops-summary { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 1rem; margin-bottom: 2rem; }
.sum-card { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.07); border-radius: 12px; padding: 1rem 1.1rem; }
@@ -139,6 +175,19 @@ import '/nav.js';
<div class="banner-sub" id="bannerSub"></div>
</div>
+ <!-- Ops alerts (from ops_alerts — every sendOpsAlert persists here) -->
+ <div class="alerts-section" id="alertsSection">
+ <div class="alerts-hd">
+ <span class="alerts-hd-title">Alerts</span>
+ <span class="alerts-hd-counts" id="alertCounts"></span>
+ </div>
+ <div id="alertsBody">
+ <div class="skeleton" style="height:56px"></div>
+ </div>
+ <button class="alerts-resolved-toggle" id="resolvedToggle" style="display:none" onclick="toggleResolved()"></button>
+ <div id="resolvedBody" style="display:none"></div>
+ </div>
+
<div class="ops-summary" id="summaryCards"></div>
<!-- Failing spotlight -->
@@ -225,6 +274,99 @@ async function load() {
$('refreshBtn').textContent = 'Refresh now';
$('refreshBtn').disabled = false;
}
+ loadAlerts();
+}
+
+let _showResolved = false;
+
+async function loadAlerts() {
+ if (!_secret) return;
+ try {
+ const r = await fetch('/api/admin/ops-alerts', { headers: { 'x-ops-secret': _secret } });
+ if (!r.ok) throw new Error('HTTP ' + r.status);
+ renderAlerts(await r.json());
+ } catch (e) {
+ $('alertsBody').innerHTML = `<div class="alerts-empty" style="background:rgba(248,113,113,0.06);border-color:rgba(248,113,113,0.16);color:#f87171">Couldn't load alerts: ${esc(e.message)}</div>`;
+ }
+}
+
+function alertCard(a, resolved) {
+ const sev = a.severity || 'warn';
+ const last = a.last_seen ? fmtAgo(Date.now() - new Date(a.last_seen).getTime()) : '—';
+ const first = a.first_seen ? new Date(a.first_seen).toLocaleString() : '';
+ const countTxt = a.count > 1 ? `×${a.count}` : '';
+ const detail = a.detail
+ ? `<p class="alert-detail clamped" onclick="this.classList.toggle('expanded');this.classList.toggle('clamped')">${esc(a.detail)}</p>`
+ : '';
+ const action = resolved
+ ? `<button class="alert-unack" onclick="ackAlert('${esc(a.signature)}','unack',this)">Reopen</button>`
+ : `<button class="alert-ack" onclick="ackAlert('${esc(a.signature)}','ack',this)">Acknowledge</button>`;
+ return `<div class="alert-card ${sev}${resolved ? ' resolved' : ''}">
+ <div class="rail"></div>
+ <div class="alert-body">
+ <p class="alert-title">${esc(a.title)}</p>
+ ${detail}
+ <div class="alert-meta">
+ <span class="sev">${sev}</span>
+ ${countTxt ? `<span class="alert-count-badge">${countTxt}</span>` : ''}
+ <span>last ${last}</span>
+ ${first ? `<span title="first seen">since ${esc(first)}</span>` : ''}
+ ${a.environment ? `<span>${esc(a.environment)}</span>` : ''}
+ ${resolved && a.acknowledged_by ? `<span>ack’d by ${esc(a.acknowledged_by)}</span>` : ''}
+ </div>
+ </div>
+ <div class="alert-actions">${action}</div>
+ </div>`;
+}
+
+function renderAlerts(d) {
+ const c = d.counts || { active: 0, critical: 0, warn: 0, info: 0 };
+ const pills = [];
+ if (c.critical) pills.push(`<span class="alert-count-pill critical">${c.critical} critical</span>`);
+ if (c.warn) pills.push(`<span class="alert-count-pill warn">${c.warn} warning</span>`);
+ if (c.info) pills.push(`<span class="alert-count-pill info">${c.info} info</span>`);
+ $('alertCounts').innerHTML = pills.join('');
+
+ const active = d.active || [];
+ if (!active.length) {
+ $('alertsBody').innerHTML = `<div class="alerts-empty">✓ No active alerts — all clear${d.note ? ' (' + esc(d.note) + ')' : ''}</div>`;
+ } else {
+ $('alertsBody').innerHTML = active.map(a => alertCard(a, false)).join('');
+ }
+
+ const resolved = d.resolved || [];
+ const tog = $('resolvedToggle');
+ if (resolved.length) {
+ tog.style.display = 'block';
+ tog.textContent = (_showResolved ? '▾ Hide' : '▸ Show') + ` ${resolved.length} acknowledged`;
+ $('resolvedBody').style.display = _showResolved ? 'block' : 'none';
+ $('resolvedBody').innerHTML = _showResolved ? resolved.map(a => alertCard(a, true)).join('') : '';
+ } else {
+ tog.style.display = 'none';
+ $('resolvedBody').style.display = 'none';
+ }
+}
+
+function toggleResolved() { _showResolved = !_showResolved; loadAlerts(); }
+
+async function ackAlert(signature, action, btn) {
+ if (btn) { btn.disabled = true; btn.textContent = action === 'ack' ? 'Acknowledging…' : 'Reopening…'; }
+ try {
+ const r = await fetch('/api/admin/ops-alerts', {
+ method: 'POST',
+ headers: { 'x-ops-secret': _secret, 'content-type': 'application/json' },
+ body: JSON.stringify({ signature, action }),
+ });
+ if (!r.ok) throw new Error('HTTP ' + r.status);
+ await loadAlerts();
+ } catch (e) {
+ if (btn) { btn.disabled = false; btn.textContent = action === 'ack' ? 'Acknowledge' : 'Reopen'; }
+ alert('Failed: ' + e.message);
+ }
+}
+
+function esc(s) {
+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c]));
}
function render(d) {
@@ -313,6 +455,7 @@ async function tryAuth() {
render(data);
$('authGate').style.display = 'none';
$('dashboard').style.display = 'block';
+ loadAlerts();
startAutoRefresh();
}
diff --git a/tests/api/healthz.test.js b/tests/api/healthz.test.js
index abb1258bc..400875b20 100644
--- a/tests/api/healthz.test.js
+++ b/tests/api/healthz.test.js
@@ -63,10 +63,10 @@ describe('GET /api/healthz', () => {
expect(body.monitor.running).toBe(true);
});
- // api/_lib/alerts.js is a deliberate silent no-op without both env vars. That
- // is right for dev/tests and wrong to leave unnoticed in production, where it
- // means every 5xx report, ring-leak CRITICAL, and low-balance warning is
- // dropped with nothing to show for it. healthz must report the gate honestly.
+ // Ops alerts always persist to the dashboard (ops_alerts / /admin/ops); the
+ // dashboard is the primary sink and is never a no-op. Telegram is an optional
+ // extra push. healthz reports the dashboard as primary and telegram_push as
+ // enabled/disabled — a disabled push is expected, not a fault.
describe('ops alert channel', () => {
const SAVED = [process.env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_ALERTS_CHAT_ID];
afterEach(() => {
@@ -76,28 +76,31 @@ describe('GET /api/healthz', () => {
}
});
- it('reports configured=false AND a warning when the channel is unwired', async () => {
+ it('always reports the dashboard as the primary sink', async () => {
delete process.env.TELEGRAM_BOT_TOKEN;
delete process.env.TELEGRAM_ALERTS_CHAT_ID;
const { body } = await callHealthz();
- expect(body.alerts.configured).toBe(false);
- expect(body.alerts.warning).toMatch(/silent no-op/i);
- expect(body.alerts.requires).toEqual(['TELEGRAM_BOT_TOKEN', 'TELEGRAM_ALERTS_CHAT_ID']);
+ expect(body.alerts.primary).toBe('dashboard');
+ expect(body.alerts.dashboard).toBe('/admin/ops');
+ // No "silent no-op" framing — alerts persist regardless of Telegram.
+ expect(body.alerts.warning).toBeUndefined();
});
- it('reports configured=false when only one of the two vars is set', async () => {
+ it('reports telegram_push disabled when the channel is unwired or half-set', async () => {
+ delete process.env.TELEGRAM_BOT_TOKEN;
+ delete process.env.TELEGRAM_ALERTS_CHAT_ID;
+ expect((await callHealthz()).body.alerts.telegram_push).toBe('disabled');
+
process.env.TELEGRAM_BOT_TOKEN = 'bot-token';
delete process.env.TELEGRAM_ALERTS_CHAT_ID;
- const { body } = await callHealthz();
- expect(body.alerts.configured).toBe(false);
+ expect((await callHealthz()).body.alerts.telegram_push).toBe('disabled');
});
- it('reports configured=true with no warning once both vars are set', async () => {
+ it('reports telegram_push enabled once both vars are set', async () => {
process.env.TELEGRAM_BOT_TOKEN = 'bot-token';
process.env.TELEGRAM_ALERTS_CHAT_ID = '-1001234567890';
const { body } = await callHealthz();
- expect(body.alerts.configured).toBe(true);
- expect(body.alerts.warning).toBeUndefined();
+ expect(body.alerts.telegram_push).toBe('enabled');
});
});
diff --git a/tests/ops-alerts-persist.test.js b/tests/ops-alerts-persist.test.js
new file mode 100644
index 000000000..a5dc5d3e6
--- /dev/null
+++ b/tests/ops-alerts-persist.test.js
@@ -0,0 +1,86 @@
+// Ops alerts persist to the dashboard sink (ops_alerts) on every sendOpsAlert(),
+// independent of Telegram, and fail soft. Covers the change that moved ops
+// alerting from a Telegram-only channel to a durable, admin-dashboard-backed one.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const sqlMock = vi.fn(async () => []);
+
+vi.mock('../api/_lib/cache.js', () => ({
+ cacheGet: vi.fn(async () => null),
+ cacheSet: vi.fn(async () => {}),
+}));
+vi.mock('../api/_lib/db.js', () => ({ sql: sqlMock }));
+vi.mock('../api/_lib/env.js', () => ({ databaseConfigured: () => true }));
+
+let sendOpsAlert, severityOf, alertsConfigured;
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ delete process.env.TELEGRAM_BOT_TOKEN;
+ delete process.env.TELEGRAM_ALERTS_CHAT_ID;
+ sqlMock.mockImplementation(async () => []);
+ ({ sendOpsAlert, severityOf, alertsConfigured } = await import('../api/_lib/alerts.js'));
+});
+
+describe('severityOf', () => {
+ it('classifies 🚨 and halt/leak/critical words as critical', () => {
+ expect(severityOf('🚨 x402 ring LEAK — funds left the set')).toBe('critical');
+ expect(severityOf('x402 autonomous loop halted — payer USDC float is empty')).toBe('critical');
+ expect(severityOf('CRITICAL: signer compromised')).toBe('critical');
+ });
+ it('defaults to warn for degradations', () => {
+ expect(severityOf('⛽ x402 ring sponsor low on SOL')).toBe('warn');
+ expect(severityOf('5xx in /api/chat')).toBe('warn');
+ });
+ it('honours an explicit info marker', () => {
+ expect(severityOf('ℹ️ nightly rollup complete')).toBe('info');
+ });
+});
+
+describe('sendOpsAlert — dashboard sink', () => {
+ it('persists to ops_alerts even when Telegram is not configured', async () => {
+ expect(alertsConfigured()).toBe(false); // no telegram env
+ await sendOpsAlert('⛽ sponsor low on SOL', 'wallet X below floor', { signature: 'sig-1' });
+ expect(sqlMock).toHaveBeenCalledTimes(1);
+ // The tagged-template call receives the SQL fragments as its first arg.
+ const fragments = sqlMock.mock.calls[0][0];
+ expect(fragments.join('?')).toMatch(/insert into ops_alerts/i);
+ expect(fragments.join('?')).toMatch(/on conflict \(signature\) do update/i);
+ });
+
+ it('passes the derived severity and interpolated values as bound params', async () => {
+ await sendOpsAlert('🚨 ring leak', 'detail body', { signature: 'sig-crit' });
+ const params = sqlMock.mock.calls[0].slice(1);
+ // signature is stored as its stable 16-hex hash (round-tripped to the ack API)
+ expect(params.some((p) => typeof p === 'string' && /^[0-9a-f]{16}$/.test(p))).toBe(true);
+ expect(params).toContain('🚨 ring leak'); // title
+ expect(params).toContain('detail body'); // detail
+ expect(params).toContain('critical'); // severity (derived from 🚨)
+ });
+
+ it('coalesces repeats under one stable signature (same key for same input)', async () => {
+ await sendOpsAlert('⚠️ repeat', 'body', { signature: 'k' });
+ await sendOpsAlert('⚠️ repeat', 'body', { signature: 'k' });
+ const sig1 = sqlMock.mock.calls[0].slice(1).find((p) => /^[0-9a-f]{16}$/.test(String(p)));
+ const sig2 = sqlMock.mock.calls[1].slice(1).find((p) => /^[0-9a-f]{16}$/.test(String(p)));
+ expect(sig1).toBe(sig2); // same signature → the upsert increments count, not a new row
+ });
+
+ it('never throws when the DB write fails (fail-soft)', async () => {
+ sqlMock.mockImplementation(async () => { throw new Error('db down'); });
+ await expect(
+ sendOpsAlert('warn thing', 'x', { signature: 'sig-2' }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('still persists when a Telegram push IS configured', async () => {
+ process.env.TELEGRAM_BOT_TOKEN = 't';
+ process.env.TELEGRAM_ALERTS_CHAT_ID = '123';
+ // stub fetch so the telegram post is a no-op
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true });
+ await sendOpsAlert('⚠️ both sinks', 'body', { signature: 'sig-3' });
+ expect(sqlMock).toHaveBeenCalledTimes(1); // dashboard sink ran
+ fetchSpy.mockRestore();
+ });
+});