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.

fix(developer): report real x402 revenue and stop 500ing on a mistyped id

nirholas71ab8a677573
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2f6516d61..100940a5a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Run your own inference node: the open inference network operator client is here**: Phase 4 of the roadmap (decouple agent inference from any single provider) takes its first concrete step: anyone can now run a node. The new node-operator client is a self-contained daemon that registers with the platform, claims inference jobs, executes them with a real open model (distilgpt2 via ONNX, CPU by default with a one-flag GPU image), and returns every result signed with the node's own Solana key so anyone can verify it. The proof runs end to end locally: register, claim a job, and return a cryptographically verified result, with a built-in selftest that proves the whole loop on a fresh checkout. Operators bring their own hardware; the network supplies the jobs and the on-chain receipts. This is the first piece of the bet that agent inference settles permissionlessly, closer to how blockchains settle blocks than to how today's AI APIs settle bills. (`/docs/inference-node-operator`) `[feature, infra]`
- **Seed your agent's memory from your X account, with your explicit consent**: Your agent can now learn how you write from your own X account, and only after you say yes. Connect X in Settings, and the consent screen tells you exactly what is read (your profile and up to 100 of your recent original public posts), what is stored (a handful of short distilled facts about what you talk about and how you talk, never your posts themselves and never links), and what is never touched (messages, likes, bookmarks, your follower list, your credentials). Agree and the agent's next replies already speak from those facts; change your mind and revoking, or disconnecting X, deletes every memory the seed created. (`/docs/x-memory-seeding`) `[feature]`
- **The DeFi market pages stop hammering their data source when they get busy**: The /defi, /chains, /yields, /stablecoins, /fees, /dex-volumes and /hacks pages, plus the protocol, chain and stablecoin detail pages, all read live data from DeFiLlama and hold it in memory for a few minutes. The moment that held copy expired, every request that arrived at once went and fetched its own fresh copy instead of sharing one. Ten simultaneous visitors to the DEX volume board meant ten downloads of the same two megabytes, and the protocol leaderboard's feed is closer to eight. That burst lands precisely when the page is busiest, and when the source pushed back, the page showed an error even though the data behind it was perfectly good. Now the first request through fetches, and everyone else waiting shares that one result. A chain profile also reuses a single copy of the protocol list rather than pulling it again for every chain. If a fetch does fail, the failure is no longer held on to, so the next visitor gets a real retry instead of the same error for the rest of the window. One cosmetic fix rode along: a pool whose name is missing on /yields now reads "Unknown" instead of a bare dash. (`/defi`) `[fix, improvement]`
+- **The developer dashboard's x402 earnings finally show your real revenue**: The Usage tab on /dashboard/developers has an x402 Payments figure. It read zero for everyone, always, no matter how many paid calls your checkout products had settled: the query behind it looked for columns that do not exist on the receipts table, and the failure was swallowed so the panel reported a confident 0 instead of an error. It now counts settled checkout calls against the products you own and reports both the payment count and the gross in USDC. The rest of the panel got the same treatment: if one of its numbers cannot be read, the response says so by name instead of quietly showing zero. Two more fixes rode along on the developer endpoints: a mistyped webhook or API-key id now comes back as a clean not-found rather than a server error, and registering a webhook for an event type that does not exist is rejected with the list of valid ones instead of silently creating a webhook subscribed to nothing. (`/dashboard/developers`) `[fix, improvement]`
- **The Forge can now federate GPU work to the Livepeer decentralized compute network**: Text-to-3D jobs start by painting a reference image, and that GPU step can now run on the Livepeer network instead of our own lanes, behind a flag, with the same request shape and the same verification our own workers get (safety screening plus byte-level image checks before anything is stored). It ships dark: our measured probe found Livepeer's free public gateway dead at the DNS edge, so the lane goes live only after a funded Studio key lands and clears a 20-job latency, cost, and success comparison run by the new bench script. The full record and the expansion criteria are in the operator docs. `[feature, infra]`
- **The free trending and whale feeds stop going blank under their own traffic**: Ask the trending feed for the 5-minute, 1-hour and 24-hour view back to back and the last two used to come back empty, blaming an upstream outage that was not happening. The cause was our own request volume: each call pulled the trade history of twenty pump.fun coins, and three calls in a row hit pump.fun's rate limiter, which then refused everything for a while. Both feeds now read pump.fun through one shared, short-lived cache, so every window and every caller reuses a single set of pulls instead of re-fetching the same coins, and a repeat call answers in milliseconds. When the limiter does bite, the whale feed serves the last successful pull and marks it stale instead of pretending the market is empty. A token nobody is trading now also reports an honest empty result rather than a false feed-down warning. (`/docs/crypto-api`) `[fix, improvement]`
- **The photo-to-avatar lane is now sized for the 10,000 avatars per day launch target**: The service that turns your selfies into a rigged 3D avatar was measured under real load and one number mattered: it was configured so the autoscaler could never see how busy it was. The service answers each request in milliseconds and does the real work in the background, so the scaling signal looked idle while its processors ground away, and no amount of extra quota would ever have added capacity. The configuration is fixed, and the lane then proved the roadmap's launch target for real: a sustained ten-minute run at the full 10,000-avatars-per-day rate finished every job, with the typical avatar ready in about six seconds and the slowest in under nine. The capacity is there when launch day brings the crowd. `[improvement, infra]`
diff --git a/api/_lib/webhook-dispatch.js b/api/_lib/webhook-dispatch.js
index b6f34440a..afe949d10 100644
--- a/api/_lib/webhook-dispatch.js
+++ b/api/_lib/webhook-dispatch.js
@@ -28,6 +28,35 @@ const EVENT_TYPES = [
export { EVENT_TYPES };
+/**
+ * Resolve a caller-supplied event subscription into the list to store.
+ *
+ * Two failure modes this closes, both of which produced a webhook that looked
+ * healthy in the dashboard and never fired:
+ *
+ * - An unknown name (a typo like "avatar.create") was silently filtered out.
+ * It is an error now, and the caller gets the offending names back plus the
+ * full menu of valid ones.
+ * - An omitted or empty list became `[]`, i.e. subscribed to nothing, even
+ * though docs/developer-platform.md has always documented it as "all
+ * events". The documented contract wins.
+ *
+ * @param {unknown} raw - the request's `events` value.
+ * @returns {{ events: string[] } | { error: string }}
+ */
+export function selectEventTypes(raw) {
+ if (raw === undefined || raw === null) return { events: [...EVENT_TYPES] };
+ if (!Array.isArray(raw)) return { error: 'events must be an array of event types' };
+ const unknown = raw.filter((e) => !EVENT_TYPES.includes(e));
+ if (unknown.length) {
+ return {
+ error: `unknown event type(s): ${unknown.join(', ')}. Valid types: ${EVENT_TYPES.join(', ')}`,
+ };
+ }
+ const events = [...new Set(raw)];
+ return { events: events.length ? events : [...EVENT_TYPES] };
+}
+
export async function dispatchWebhooks({ userId, eventType, data }) {
if (!EVENT_TYPES.includes(eventType)) return;
diff --git a/api/developer/mcp-test.js b/api/developer/mcp-test.js
index 0fe087821..ebd307cf4 100644
--- a/api/developer/mcp-test.js
+++ b/api/developer/mcp-test.js
@@ -17,6 +17,7 @@ import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { isUuid } from '../_lib/validate.js';
import { limits } from '../_lib/rate-limit.js';
import { dispatch } from '../_mcp/dispatch.js';
@@ -43,6 +44,10 @@ export default wrap(async (req, res) => {
const { keyId } = await readJson(req, 4_000).catch(() => ({}));
if (!keyId || typeof keyId !== 'string')
return error(res, 400, 'bad_request', 'keyId is required');
+ // api_keys.id is a uuid column: a non-uuid keyId makes Postgres reject the
+ // comparison ("invalid input syntax for type uuid") and 500s what is really
+ // just a key the caller doesn't own. Same answer as an unknown id.
+ if (!isUuid(keyId)) return error(res, 404, 'not_found', 'API key not found');
const [key] = await sql`
select id, scope, revoked_at, expires_at
diff --git a/api/developer/usage.js b/api/developer/usage.js
index 77f320552..d16eccda2 100644
--- a/api/developer/usage.js
+++ b/api/developer/usage.js
@@ -1,7 +1,8 @@
// GET /api/developer/usage — API usage metrics for the developer dashboard.
//
// Returns request counts, error rates, top endpoints, and usage over time
-// aggregated from audit_log + webhook_deliveries + x402 transactions.
+// aggregated from audit_log + webhook_deliveries + settled x402 checkout calls
+// against the caller's own SKUs.
//
// Query parameters:
// days — lookback window: 7 | 30 | 90 (default: 30)
@@ -9,9 +10,24 @@
import { cors, error, json, method, wrap } from '../_lib/http.js';
import { getSessionUser } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
+import { atomicsToUsdc } from '../_lib/agent-economy.js';
const ALLOWED_DAYS = [7, 30, 90];
+// One panel failing must not blank the whole dashboard, but a panel that fails
+// every time must not read as a real zero either: the x402 block did exactly
+// that, querying payee_user_id/amount_usdc/created_at columns x402_receipts has
+// never had, so a silent catch reported 0 payments to every developer. Degraded
+// sections are logged and named in the response so the UI (and the next reader)
+// can tell "no activity" from "this number is unavailable".
+function section(name, query, fallback, degraded) {
+ return query.catch((err) => {
+ console.warn(`[developer/usage] ${name} query failed: ${err?.message || err}`);
+ degraded.push(name);
+ return fallback;
+ });
+}
+
export default wrap(async function handler(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
@@ -26,16 +42,18 @@ export default wrap(async function handler(req, res) {
const since = new Date(Date.now() - days * 86400_000).toISOString();
+ const degraded = [];
+
const [apiKeyStats, auditStats, auditTimeseries, topActions, webhookStats, x402Stats] =
await Promise.all([
- sql`
+ section('api_keys', sql`
select count(*)::int as total_keys,
count(*) filter (where revoked_at is null)::int as active_keys
from api_keys
where user_id = ${user.id}
- `.catch(() => [{ total_keys: 0, active_keys: 0 }]),
+ `, [{ total_keys: 0, active_keys: 0 }], degraded),
- sql`
+ section('requests', sql`
select count(*)::int as total_requests,
count(distinct action)::int as unique_actions,
count(*) filter (where action like '%.error%' or action like '%fail%')::int as error_count,
@@ -43,47 +61,55 @@ export default wrap(async function handler(req, res) {
max(created_at) as last_request_at
from audit_log
where user_id = ${user.id} and created_at >= ${since}::timestamptz
- `.catch(() => [{ total_requests: 0, unique_actions: 0, error_count: 0, first_request_at: null, last_request_at: null }]),
+ `, [{ total_requests: 0, unique_actions: 0, error_count: 0, first_request_at: null, last_request_at: null }], degraded),
- sql`
+ section('timeseries', sql`
select date_trunc('day', created_at)::date as day,
count(*)::int as requests
from audit_log
where user_id = ${user.id} and created_at >= ${since}::timestamptz
group by 1
order by 1
- `.catch(() => []),
+ `, [], degraded),
- sql`
+ section('top_actions', sql`
select action, count(*)::int as count
from audit_log
where user_id = ${user.id} and created_at >= ${since}::timestamptz
group by action
order by count desc
limit 10
- `.catch(() => []),
+ `, [], degraded),
- sql`
+ section('webhooks', sql`
select count(*)::int as total_deliveries,
count(*) filter (where status_code between 200 and 299)::int as succeeded,
count(*) filter (where status_code is null or status_code >= 400)::int as failed
from webhook_deliveries wd
join developer_webhooks dw on dw.id = wd.webhook_id
where dw.user_id = ${user.id} and wd.created_at >= ${since}::timestamptz
- `.catch(() => [{ total_deliveries: 0, succeeded: 0, failed: 0 }]),
+ `, [{ total_deliveries: 0, succeeded: 0, failed: 0 }], degraded),
- sql`
+ // Paid calls against the SKUs this developer owns, the only place the
+ // schema links x402 revenue to a user account (x402_receipts is keyed by
+ // payer wallet and carries no owner column). Mirrors api/x402-skus.js:
+ // response_status < 400 is a settled call, amounts are USDC atomics held
+ // as text.
+ section('x402', sql`
select count(*)::int as total_payments,
- coalesce(sum(amount_usdc), 0)::bigint as total_usdc
- from x402_receipts
- where payee_user_id = ${user.id} and created_at >= ${since}::timestamptz
- `.catch(() => [{ total_payments: 0, total_usdc: 0 }]),
+ coalesce(sum(case when c.amount_atomics ~ '^[0-9]+$' then c.amount_atomics::numeric else 0 end), 0)::text as total_atomics
+ from x402_checkout_calls c
+ join x402_skus s on s.id = c.sku_id
+ where s.owner_user_id = ${user.id}
+ and c.paid_at >= ${since}::timestamptz
+ and c.response_status < 400
+ `, [{ total_payments: 0, total_atomics: '0' }], degraded),
]);
const audit = auditStats[0] || { total_requests: 0, unique_actions: 0, error_count: 0 };
const keys = apiKeyStats[0] || { total_keys: 0, active_keys: 0 };
const wh = webhookStats[0] || { total_deliveries: 0, succeeded: 0, failed: 0 };
- const x402 = x402Stats[0] || { total_payments: 0, total_usdc: 0 };
+ const x402 = x402Stats[0] || { total_payments: 0, total_atomics: '0' };
const errorRate = audit.total_requests > 0
? Number(((audit.error_count / audit.total_requests) * 100).toFixed(2))
: 0;
@@ -104,7 +130,9 @@ export default wrap(async function handler(req, res) {
webhooks: wh,
x402: {
payments: x402.total_payments,
- volume_usdc: Number(x402.total_usdc),
+ volume_usdc: atomicsToUsdc(x402.total_atomics),
+ volume_atomics: String(x402.total_atomics ?? '0'),
},
+ degraded,
});
});
diff --git a/api/developer/webhooks.js b/api/developer/webhooks.js
index 12ae54ebd..a0fc3b0bd 100644
--- a/api/developer/webhooks.js
+++ b/api/developer/webhooks.js
@@ -6,7 +6,7 @@ import { getSessionUser } from '../_lib/auth.js';
import { requireCsrf } from '../_lib/csrf.js';
import { sql } from '../_lib/db.js';
import { randomToken } from '../_lib/crypto.js';
-import { EVENT_TYPES } from '../_lib/webhook-dispatch.js';
+import { EVENT_TYPES, selectEventTypes } from '../_lib/webhook-dispatch.js';
import { assertPublicHttpsUrl } from '../_lib/ssrf.js';
const MAX_WEBHOOKS_PER_USER = 10;
@@ -19,29 +19,31 @@ export default wrap(async function handler(req, res) {
if (!user) return error(res, 401, 'unauthorized', 'Sign in required');
if (req.method === 'GET') {
- const webhooks = await sql`
- select id, url, events, active, description, created_at, updated_at
- from developer_webhooks
- where user_id = ${user.id}
- order by created_at desc
- `;
-
- const withStats = await Promise.all(
- webhooks.map(async (wh) => {
- const [stats] = await sql`
+ // One round trip for the list AND its 7-day delivery stats: the lateral
+ // join keeps a 10-webhook dashboard at a single query instead of 1 + N.
+ const rows = await sql`
+ select w.id, w.url, w.events, w.active, w.description, w.created_at, w.updated_at,
+ s.total, s.succeeded, s.failed, s.last_delivery_at
+ from developer_webhooks w
+ left join lateral (
select
count(*)::int as total,
count(*) filter (where status_code between 200 and 299)::int as succeeded,
count(*) filter (where status_code is null or status_code >= 400)::int as failed,
max(created_at) as last_delivery_at
- from webhook_deliveries
- where webhook_id = ${wh.id} and created_at > now() - interval '7 days'
- `;
- return { ...wh, stats_7d: stats };
- }),
- );
+ from webhook_deliveries d
+ where d.webhook_id = w.id and d.created_at > now() - interval '7 days'
+ ) s on true
+ where w.user_id = ${user.id}
+ order by w.created_at desc
+ `;
+
+ const webhooks = rows.map(({ total, succeeded, failed, last_delivery_at, ...wh }) => ({
+ ...wh,
+ stats_7d: { total, succeeded, failed, last_delivery_at },
+ }));
- return json(res, 200, { webhooks: withStats, event_types: EVENT_TYPES });
+ return json(res, 200, { webhooks, event_types: EVENT_TYPES });
}
if (!method(req, res, ['POST'])) return;
@@ -76,9 +78,9 @@ export default wrap(async function handler(req, res) {
return error(res, 400, 'bad_request', 'Webhook URL must resolve to a public address');
}
- const events = Array.isArray(body.events)
- ? body.events.filter((e) => EVENT_TYPES.includes(e))
- : [];
+ const selection = selectEventTypes(body.events);
+ if (selection.error) return error(res, 400, 'bad_request', selection.error);
+ const events = selection.events;
const description =
typeof body.description === 'string' ? body.description.trim().slice(0, 200) : null;
diff --git a/api/developer/webhooks/[id].js b/api/developer/webhooks/[id].js
index 6926cf9ee..d42f271c1 100644
--- a/api/developer/webhooks/[id].js
+++ b/api/developer/webhooks/[id].js
@@ -6,8 +6,9 @@ import { cors, error, json, method, readJson, wrap } from '../../_lib/http.js';
import { getSessionUser } from '../../_lib/auth.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { sql } from '../../_lib/db.js';
-import { EVENT_TYPES } from '../../_lib/webhook-dispatch.js';
+import { selectEventTypes } from '../../_lib/webhook-dispatch.js';
import { assertPublicHttpsUrl } from '../../_lib/ssrf.js';
+import { isUuid } from '../../_lib/validate.js';
const URL_MAX_LENGTH = 2048;
@@ -20,6 +21,11 @@ export default wrap(async function handler(req, res) {
const url = new URL(req.url, 'http://x');
const id = url.searchParams.get('id') || extractId(url.pathname);
if (!id) return error(res, 400, 'bad_request', 'Webhook ID required');
+ // developer_webhooks.id is a uuid column, so a non-uuid path segment makes
+ // Postgres reject the comparison outright ("invalid input syntax for type
+ // uuid") and turns a plain wrong-id request into a 500. It is a webhook this
+ // caller does not have, which is exactly what the lookup below reports.
+ if (!isUuid(id)) return error(res, 404, 'not_found', 'Webhook not found');
const [webhook] = await sql`
select id, url, events, active, description, created_at, updated_at
@@ -75,8 +81,10 @@ export default wrap(async function handler(req, res) {
}
updates.url = trimmed;
}
- if (Array.isArray(body.events)) {
- updates.events = body.events.filter((e) => EVENT_TYPES.includes(e));
+ if (body.events !== undefined) {
+ const selection = selectEventTypes(body.events);
+ if (selection.error) return error(res, 400, 'bad_request', selection.error);
+ updates.events = selection.events;
}
if (typeof body.active === 'boolean') {
updates.active = body.active;
diff --git a/data/changelog.json b/data/changelog.json
index ba445fd92..14bddabf7 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$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. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-08-12",
+ "title": "The developer dashboard's x402 earnings finally show your real revenue",
+ "summary": "The Usage tab on /dashboard/developers has an x402 Payments figure. It read zero for everyone, always, no matter how many paid calls your checkout products had settled: the query behind it looked for columns that do not exist on the receipts table, and the failure was swallowed so the panel reported a confident 0 instead of an error. It now counts settled checkout calls against the products you own and reports both the payment count and the gross in USDC. The rest of the panel got the same treatment: if one of its numbers cannot be read, the response says so by name instead of quietly showing zero. Two more fixes rode along on the developer endpoints: a mistyped webhook or API-key id now comes back as a clean not-found rather than a server error, and registering a webhook for an event type that does not exist is rejected with the list of valid ones instead of silently creating a webhook subscribed to nothing.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/dashboard/developers"
+ },
{
"date": "2026-08-12",
"title": "Token holder and safety checks stop failing when the free data lanes are busy",
diff --git a/docs/developer-platform.md b/docs/developer-platform.md
index 20faec626..7d0d10484 100644
--- a/docs/developer-platform.md
+++ b/docs/developer-platform.md
@@ -171,7 +171,8 @@ or is already revoked.
### GET /api/developer/usage
Aggregated activity for your account over a lookback window, built from the
-audit log, webhook deliveries, and x402 receipts. Session required.
+audit log, webhook deliveries, and settled x402 checkout calls against the SKUs
+you own. Session required.
Query parameters:
@@ -200,7 +201,8 @@ Response, `200`:
"timeseries": [ { "day": "2026-07-23", "requests": 61 } ],
"top_actions": [ { "action": "avatar.render", "count": 118 } ],
"webhooks": { "total_deliveries": 24, "succeeded": 23, "failed": 1 },
- "x402": { "payments": 5, "volume_usdc": 5000 }
+ "x402": { "payments": 5, "volume_usdc": 1.25, "volume_atomics": "1250000" },
+ "degraded": []
}
```
@@ -214,10 +216,15 @@ Field notes, exactly as computed:
- `top_actions` is the top 10 actions by count.
- `webhooks.succeeded` counts deliveries with a 2xx status; `failed` counts
null status (network failure) or status >= 400.
-- `x402.payments` and `volume_usdc` cover receipts where you were the payee;
- `volume_usdc` is in USDC base units.
+- `x402.payments` counts settled checkout calls (`response_status < 400`)
+ against the SKUs you own, over the same window. `volume_atomics` is their
+ gross in USDC atomic units as a string; `volume_usdc` is the same figure in
+ whole USDC.
- Each aggregate degrades independently to zeros or an empty array if its
- source query fails, so the endpoint never 500s over one missing table.
+ source query fails, so the endpoint never 500s over one missing table. When
+ that happens the section names itself in `degraded` (`["x402"]`,
+ `["timeseries"]`, …) so you can tell "no activity" from "unavailable".
+ `degraded` is `[]` on a healthy response.
Errors: `401 unauthorized`.
@@ -276,7 +283,7 @@ Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
| `url` | string | yes | HTTPS only, max 2048 characters, must resolve to a public address |
-| `events` | string[] | no | filtered to the known event types; empty or omitted = **all events** |
+| `events` | string[] | no | empty or omitted = **all events**; an unknown event type is rejected, it is never silently dropped |
| `description` | string | no | trimmed, truncated to 200 characters |
The URL is checked against SSRF at registration time: a hostname that resolves
@@ -315,8 +322,8 @@ Response, `201`:
Store it; you need it to verify signatures.
Errors: `400 bad_request` (missing/invalid/too-long/non-HTTPS/non-public URL,
-malformed JSON, or a non-JSON content type), `409 limit_reached` at 10
-webhooks, `401`, `403` (CSRF).
+an unknown or non-array `events` value, malformed JSON, or a non-JSON content
+type), `409 limit_reached` at 10 webhooks, `401`, `403` (CSRF).
### GET /api/developer/webhooks/:id
@@ -335,7 +342,8 @@ delivery is
Partial update. Session + CSRF required. Any subset of:
- `url` (same HTTPS, length, and SSRF validation as create)
-- `events` (replaces the array, filtered to known types)
+- `events` (replaces the array; same validation as create, so an unknown type is
+ a `400` and an empty array resets the webhook to all events)
- `active` (boolean; pause or resume delivery)
- `description`
@@ -347,8 +355,9 @@ Response, `200`: `{ "webhook": { … } }` with `updated_at` refreshed.
Delete the webhook and stop all delivery. Session + CSRF required.
Response, `200`: `{ "deleted": true }`.
-Errors for all three `:id` routes: `404 not_found` when the ID does not exist
-or is not yours, `400 bad_request` when the ID is missing.
+Errors for all three `:id` routes: `404 not_found` when the ID does not exist,
+is not yours, or is not a well-formed UUID; `400 bad_request` when the ID is
+missing.
### Delivery format and signature verification
@@ -448,8 +457,8 @@ If either JSON-RPC step returns an error, the HTTP status is still `200` and
the body is `{ "ok": false, "error": { …JSON-RPC error… } }`.
Errors: `400 bad_request` (`keyId` missing or not a string),
-`404 not_found` (key does not exist or is not yours), `400 revoked`,
-`400 expired`, `401`, `403` (CSRF), `429`.
+`404 not_found` (key does not exist, is not yours, or is not a well-formed
+UUID), `400 revoked`, `400 expired`, `401`, `403` (CSRF), `429`.
See [MCP integration](./mcp.md) for configuring a real client against
`/api/mcp`.
diff --git a/public/changelog.json b/public/changelog.json
index 771bb4a10..348a6e763 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-12T20:49:10.329Z",
+ "generated_at": "2026-08-12T21:00:49.102Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -90,6 +90,17 @@
"improvement"
]
},
+ {
+ "date": "2026-08-12",
+ "type": "update",
+ "title": "The developer dashboard's x402 earnings finally show your real revenue",
+ "summary": "The Usage tab on /dashboard/developers has an x402 Payments figure. It read zero for everyone, always, no matter how many paid calls your checkout products had settled: the query behind it looked for columns that do not exist on the receipts table, and the failure was swallowed so the panel reported a confident 0 instead of an error. It now counts settled checkout calls against the products you own and reports both the payment count and the gross in USDC. The rest of the panel got the same treatment: if one of its numbers cannot be read, the response says so by name instead of quietly showing zero. Two more fixes rode along on the developer endpoints: a mistyped webhook or API-key id now comes back as a clean not-found rather than a server error, and registering a webhook for an event type that does not exist is rejected with the list of valid ones instead of silently creating a webhook subscribed to nothing.",
+ "link": "/dashboard/developers",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-08-12",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index f3b318218..95bd5f174 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -70,6 +70,14 @@
<category>fix</category>
<description>The /defi, /chains, /yields, /stablecoins, /fees, /dex-volumes and /hacks pages, plus the protocol, chain and stablecoin detail pages, all read live data from DeFiLlama and hold it in memory for a few minutes. The moment that held copy expired, every request that arrived at once went and fetched its own fresh copy instead of sharing one. Ten simultaneous visitors to the DEX volume board meant ten downloads of the same two megabytes, and the protocol leaderboard's feed is closer to eight. That burst lands precisely when the page is busiest, and when the source pushed back, the page showed an error even though the data behind it was perfectly good. Now the first request through fetches, and everyone else waiting shares that one result. A chain profile also reuses a single copy of the protocol list rather than pulling it again for every chain. If a fetch does fail, the failure is no longer held on to, so the next visitor gets a real retry instead of the same error for the rest of the window. One cosmetic fix rode along: a pool whose name is missing on /yields now reads &quot;Unknown&quot; instead of a bare dash.</description>
</item>
+ <item>
+ <title>The developer dashboard's x402 earnings finally show your real revenue</title>
+ <link>https://three.ws/dashboard/developers</link>
+ <guid isPermaLink="false">2026-08-12:The developer dashboard's x402 earnings finally show your real revenue</guid>
+ <pubDate>Wed, 12 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The Usage tab on /dashboard/developers has an x402 Payments figure. It read zero for everyone, always, no matter how many paid calls your checkout products had settled: the query behind it looked for columns that do not exist on the receipts table, and the failure was swallowed so the panel reported a confident 0 instead of an error. It now counts settled checkout calls against the products you own and reports both the payment count and the gross in USDC. The rest of the panel got the same treatment: if one of its numbers cannot be read, the response says so by name instead of quietly showing zero. Two more fixes rode along on the developer endpoints: a mistyped webhook or API-key id now comes back as a clean not-found rather than a server error, and registering a webhook for an event type that does not exist is rejected with the list of valid ones instead of silently creating a webhook subscribed to nothing.</description>
+ </item>
<item>
<title>The Forge can now federate GPU work to the Livepeer decentralized compute network</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index f1b482b23..2cedb68ce 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-12T20:41:12.166Z",
+ "generated_at": "2026-08-12T21:00:49.093Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/dashboard-next/pages/developers.js b/src/dashboard-next/pages/developers.js
index 16c39c6df..6c9919269 100644
--- a/src/dashboard-next/pages/developers.js
+++ b/src/dashboard-next/pages/developers.js
@@ -765,6 +765,14 @@ function wireWebhookForm(el) {
if (!url) { urlInput.focus(); return; }
const desc = el.querySelector('#wh-desc').value.trim();
const events = [...el.querySelectorAll('input[name="wh-events"]:checked')].map(c => c.value);
+ // An empty list means "all events" to the API. From this form, where every
+ // box starts checked, clearing them all reads as "none", so ask rather
+ // than silently subscribing to everything.
+ if (!events.length) {
+ showToast('Select at least one event to subscribe to', 'danger');
+ el.querySelector('input[name="wh-events"]')?.focus();
+ return;
+ }
saveBtn.disabled = true;
saveBtn.textContent = 'Creating...';
diff --git a/tests/api-developer-mcp-test.test.js b/tests/api-developer-mcp-test.test.js
index 6cec49a5c..5ededcb4a 100644
--- a/tests/api-developer-mcp-test.test.js
+++ b/tests/api-developer-mcp-test.test.js
@@ -72,7 +72,12 @@ beforeEach(() => {
dispatchMock.mockReset();
});
-const okKey = { id: 'key-1', scope: 'avatars:read profile', revoked_at: null, expires_at: null };
+// api_keys.id is a uuid column and the handler guards on that before querying,
+// so the fixtures have to be real uuids.
+const KEY_ID = '33333333-3333-4333-8333-333333333333';
+const UNKNOWN_KEY_ID = '44444444-4444-4444-8444-444444444444';
+
+const okKey = { id: KEY_ID, scope: 'avatars:read profile', revoked_at: null, expires_at: null };
function dispatchHappyPath() {
dispatchMock.mockImplementation((msg) => {
@@ -96,14 +101,14 @@ describe('mcp-test auth & method', () => {
it('returns 401 without a session', async () => {
getSessionUserMock.mockResolvedValue(null);
const res = mkRes();
- await handler(mkReq({ body: { keyId: 'key-1' } }), res);
+ await handler(mkReq({ body: { keyId: KEY_ID } }), res);
expect(res.statusCode).toBe(401);
});
it('returns 429 when the user is rate limited', async () => {
mcpUserMock.mockResolvedValue({ success: false, limit: 1200, remaining: 0, reset: Date.now() + 60_000 });
const res = mkRes();
- await handler(mkReq({ body: { keyId: 'key-1' } }), res);
+ await handler(mkReq({ body: { keyId: KEY_ID } }), res);
expect(res.statusCode).toBe(429);
});
});
@@ -118,10 +123,21 @@ describe('mcp-test key validation', () => {
expect(parseBody(res).error).toBe('bad_request');
});
+ it('returns 404 for a malformed keyId without querying Postgres', async () => {
+ const res = mkRes();
+ await handler(mkReq({ body: { keyId: 'not-a-uuid' } }), res);
+ // api_keys.id is a uuid column: handing it a non-uuid used to surface
+ // Postgres error 22P02 to the dashboard as a 500.
+ expect(res.statusCode).toBe(404);
+ expect(parseBody(res).error).toBe('not_found');
+ expect(sqlMock).not.toHaveBeenCalled();
+ expect(dispatchMock).not.toHaveBeenCalled();
+ });
+
it('returns 404 when the key is not owned by the caller', async () => {
sqlMock.mockResolvedValue([]); // no row
const res = mkRes();
- await handler(mkReq({ body: { keyId: 'nope' } }), res);
+ await handler(mkReq({ body: { keyId: UNKNOWN_KEY_ID } }), res);
expect(res.statusCode).toBe(404);
expect(dispatchMock).not.toHaveBeenCalled();
});
@@ -129,7 +145,7 @@ describe('mcp-test key validation', () => {
it('returns 400 for a revoked key', async () => {
sqlMock.mockResolvedValue([{ ...okKey, revoked_at: new Date().toISOString() }]);
const res = mkRes();
- await handler(mkReq({ body: { keyId: 'key-1' } }), res);
+ await handler(mkReq({ body: { keyId: KEY_ID } }), res);
expect(res.statusCode).toBe(400);
expect(parseBody(res).error).toBe('revoked');
expect(dispatchMock).not.toHaveBeenCalled();
@@ -138,7 +154,7 @@ describe('mcp-test key validation', () => {
it('returns 400 for an expired key', async () => {
sqlMock.mockResolvedValue([{ ...okKey, expires_at: new Date(Date.now() - 1000).toISOString() }]);
const res = mkRes();
- await handler(mkReq({ body: { keyId: 'key-1' } }), res);
+ await handler(mkReq({ body: { keyId: KEY_ID } }), res);
expect(res.statusCode).toBe(400);
expect(parseBody(res).error).toBe('expired');
expect(dispatchMock).not.toHaveBeenCalled();
@@ -152,7 +168,7 @@ describe('mcp-test handshake', () => {
sqlMock.mockResolvedValue([okKey]);
dispatchHappyPath();
const res = mkRes();
- await handler(mkReq({ body: { keyId: 'key-1' } }), res);
+ await handler(mkReq({ body: { keyId: KEY_ID } }), res);
expect(res.statusCode).toBe(200);
const body = parseBody(res);
@@ -177,7 +193,7 @@ describe('mcp-test handshake', () => {
),
);
const res = mkRes();
- await handler(mkReq({ body: { keyId: 'key-1' } }), res);
+ await handler(mkReq({ body: { keyId: KEY_ID } }), res);
expect(res.statusCode).toBe(200);
const body = parseBody(res);
@@ -191,7 +207,7 @@ describe('mcp-test handshake', () => {
sqlMock.mockResolvedValue([{ ...okKey, scope: '' }]);
dispatchHappyPath();
const res = mkRes();
- await handler(mkReq({ body: { keyId: 'key-1' } }), res);
+ await handler(mkReq({ body: { keyId: KEY_ID } }), res);
expect(parseBody(res).scopes).toEqual([]);
});
});
diff --git a/tests/api/developer-usage.test.js b/tests/api/developer-usage.test.js
new file mode 100644
index 000000000..89c53feef
--- /dev/null
+++ b/tests/api/developer-usage.test.js
@@ -0,0 +1,119 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { invoke } from '../_helpers/monetization.js';
+
+// The developer dashboard's usage panel. Two behaviors pinned here:
+//
+// 1. x402 revenue is read from settled checkout calls against the caller's own
+// SKUs. The original query hit x402_receipts on payee_user_id/amount_usdc/
+// created_at, columns that table has never had, so every request threw and
+// a blanket .catch() reported a clean 0 to every developer.
+// 2. A query that does fail still degrades gracefully, but now names itself in
+// `degraded` instead of masquerading as real zeros.
+
+const authState = { session: null };
+const sqlState = { calls: [], handler: null };
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+}));
+
+vi.mock('../../api/_lib/db.js', () => {
+ const sql = vi.fn((strings, ...values) => {
+ const query = Array.isArray(strings) ? strings.join('?') : String(strings);
+ sqlState.calls.push({ query, values });
+ return sqlState.handler(query, values);
+ });
+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
+});
+
+const { default: handler } = await import('../../api/developer/usage.js');
+
+const OWNER = { id: '11111111-1111-4111-8111-111111111111' };
+
+function defaultRows(query) {
+ if (query.includes('from api_keys')) return [{ total_keys: 2, active_keys: 1 }];
+ if (query.includes('date_trunc')) return [{ day: '2026-08-01', requests: 4 }];
+ if (query.includes('group by action')) return [{ action: 'login', count: 4 }];
+ if (query.includes('from audit_log')) {
+ return [{
+ total_requests: 10,
+ unique_actions: 3,
+ error_count: 2,
+ first_request_at: '2026-08-01T00:00:00.000Z',
+ last_request_at: '2026-08-02T00:00:00.000Z',
+ }];
+ }
+ if (query.includes('webhook_deliveries')) return [{ total_deliveries: 5, succeeded: 4, failed: 1 }];
+ if (query.includes('x402_checkout_calls')) return [{ total_payments: 3, total_atomics: '750000' }];
+ return [];
+}
+
+beforeEach(() => {
+ authState.session = OWNER;
+ sqlState.calls = [];
+ sqlState.handler = async (query) => defaultRows(query);
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+});
+
+describe('GET /api/developer/usage', () => {
+ it('reports x402 revenue from settled checkout calls on the caller\'s SKUs', async () => {
+ const { status, body } = await invoke(handler, { method: 'GET', url: '/api/developer/usage' });
+
+ expect(status).toBe(200);
+ expect(body.x402).toEqual({ payments: 3, volume_usdc: 0.75, volume_atomics: '750000' });
+ expect(body.degraded).toEqual([]);
+
+ const x402Query = sqlState.calls.find((c) => c.query.includes('x402_checkout_calls'));
+ expect(x402Query.query).toContain('x402_skus');
+ expect(x402Query.query).toContain('owner_user_id');
+ expect(x402Query.query).toContain('response_status < 400');
+ // The old, permanently-broken source must not come back.
+ expect(sqlState.calls.some((c) => c.query.includes('x402_receipts'))).toBe(false);
+ });
+
+ it('clamps the lookback window to the allowed set', async () => {
+ const { body: outOfRange } = await invoke(handler, { method: 'GET', url: '/api/developer/usage?days=999' });
+ expect(outOfRange.period.days).toBe(30);
+
+ const { body: garbage } = await invoke(handler, { method: 'GET', url: '/api/developer/usage?days=abc' });
+ expect(garbage.period.days).toBe(30);
+
+ const { body: allowed } = await invoke(handler, { method: 'GET', url: '/api/developer/usage?days=7' });
+ expect(allowed.period.days).toBe(7);
+ });
+
+ it('computes the error rate from the audit counts', async () => {
+ const { body } = await invoke(handler, { method: 'GET', url: '/api/developer/usage' });
+ expect(body.requests.total).toBe(10);
+ expect(body.requests.errors).toBe(2);
+ expect(body.error_rate ?? body.requests.error_rate).toBe(20);
+ });
+
+ it('names a failed section in `degraded` rather than reporting it as zero', async () => {
+ sqlState.handler = async (query) => {
+ if (query.includes('x402_checkout_calls')) throw new Error('relation "x402_skus" does not exist');
+ return defaultRows(query);
+ };
+
+ const { status, body } = await invoke(handler, { method: 'GET', url: '/api/developer/usage' });
+
+ expect(status).toBe(200);
+ expect(body.degraded).toEqual(['x402']);
+ expect(body.x402.payments).toBe(0);
+ // The rest of the dashboard still renders real numbers.
+ expect(body.webhooks.total_deliveries).toBe(5);
+ expect(console.warn).toHaveBeenCalled();
+ });
+
+ it('returns 401 without a session', async () => {
+ authState.session = null;
+ const { status } = await invoke(handler, { method: 'GET', url: '/api/developer/usage' });
+ expect(status).toBe(401);
+ expect(sqlState.calls).toHaveLength(0);
+ });
+
+ it('rejects a non-GET method', async () => {
+ const { status } = await invoke(handler, { method: 'POST', url: '/api/developer/usage', body: {} });
+ expect(status).toBe(405);
+ });
+});
diff --git a/tests/api/developer-webhooks.test.js b/tests/api/developer-webhooks.test.js
new file mode 100644
index 000000000..72e0ccd76
--- /dev/null
+++ b/tests/api/developer-webhooks.test.js
@@ -0,0 +1,222 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { invoke } from '../_helpers/monetization.js';
+
+// Coverage for the developer webhook surface (list/create and the per-webhook
+// detail route). Three behaviors this pins, each a bug the endpoints shipped
+// with:
+// 1. developer_webhooks.id is uuid, so a malformed path segment reached
+// Postgres as `where id = 'not-a-uuid'` and 22P02 surfaced as a 500.
+// 2. An unknown or empty `events` list was silently reduced to [], producing a
+// webhook that looked healthy in the dashboard and never fired.
+// 3. The list route's 7-day delivery stats now come back on the same row as
+// the webhook (one query instead of 1 + N), and must still be nested under
+// stats_7d on the wire.
+
+const authState = { session: null };
+const sqlState = { calls: [], responses: [] };
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+}));
+
+vi.mock('../../api/_lib/db.js', () => {
+ const sql = vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: Array.isArray(strings) ? strings.join('?') : String(strings), values });
+ return sqlState.responses.shift() ?? [];
+ });
+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
+});
+
+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
+
+// assertPublicHttpsUrl does real DNS resolution; the SSRF module has its own
+// suite, so here it only needs to accept the example URLs under test.
+vi.mock('../../api/_lib/ssrf.js', () => ({ assertPublicHttpsUrl: vi.fn(async () => true) }));
+
+const { EVENT_TYPES } = await import('../../api/_lib/webhook-dispatch.js');
+const { default: listHandler } = await import('../../api/developer/webhooks.js');
+const { default: detailHandler } = await import('../../api/developer/webhooks/[id].js');
+
+const OWNER = { id: '11111111-1111-4111-8111-111111111111' };
+const WEBHOOK_ID = '22222222-2222-4222-8222-222222222222';
+const BAD_ID = 'not-a-uuid';
+
+const webhookRow = {
+ id: WEBHOOK_ID,
+ url: 'https://example.com/hook',
+ events: ['agent.created'],
+ active: true,
+ description: null,
+ created_at: '2026-08-01T00:00:00.000Z',
+ updated_at: '2026-08-01T00:00:00.000Z',
+};
+
+beforeEach(() => {
+ authState.session = OWNER;
+ sqlState.calls = [];
+ sqlState.responses = [];
+});
+
+describe('GET /api/developer/webhooks', () => {
+ it('nests the joined delivery stats under stats_7d and issues one query', async () => {
+ sqlState.responses = [[
+ { ...webhookRow, total: 3, succeeded: 2, failed: 1, last_delivery_at: '2026-08-02T00:00:00.000Z' },
+ ]];
+
+ const { status, body } = await invoke(listHandler, { method: 'GET', url: '/api/developer/webhooks' });
+
+ expect(status).toBe(200);
+ expect(sqlState.calls).toHaveLength(1);
+ expect(body.webhooks).toHaveLength(1);
+ expect(body.webhooks[0].stats_7d).toEqual({
+ total: 3,
+ succeeded: 2,
+ failed: 1,
+ last_delivery_at: '2026-08-02T00:00:00.000Z',
+ });
+ // The flattened join columns must not leak alongside the nested object.
+ expect(body.webhooks[0].total).toBeUndefined();
+ expect(body.event_types).toContain('agent.created');
+ });
+
+ it('returns 401 without a session', async () => {
+ authState.session = null;
+ const { status } = await invoke(listHandler, { method: 'GET', url: '/api/developer/webhooks' });
+ expect(status).toBe(401);
+ expect(sqlState.calls).toHaveLength(0);
+ });
+});
+
+describe('POST /api/developer/webhooks event validation', () => {
+ it('rejects an unknown event type instead of silently dropping it', async () => {
+ const { status, body } = await invoke(listHandler, {
+ method: 'POST',
+ url: '/api/developer/webhooks',
+ body: { url: 'https://example.com/hook', events: ['avatar.create'] },
+ });
+
+ expect(status).toBe(400);
+ expect(body.error).toBe('bad_request');
+ expect(body.error_description).toContain('avatar.create');
+ expect(sqlState.calls).toHaveLength(0);
+ });
+
+ it('treats an omitted list as every event type, per the documented contract', async () => {
+ sqlState.responses = [[{ count: 0 }], [webhookRow]];
+
+ const { status } = await invoke(listHandler, {
+ method: 'POST',
+ url: '/api/developer/webhooks',
+ body: { url: 'https://example.com/hook' },
+ });
+
+ expect(status).toBe(201);
+ const insert = sqlState.calls.at(-1);
+ expect(insert.values).toContainEqual([...EVENT_TYPES]);
+ });
+
+ it('treats an explicitly empty list the same way, never storing a webhook subscribed to nothing', async () => {
+ sqlState.responses = [[{ count: 0 }], [webhookRow]];
+
+ const { status } = await invoke(listHandler, {
+ method: 'POST',
+ url: '/api/developer/webhooks',
+ body: { url: 'https://example.com/hook', events: [] },
+ });
+
+ expect(status).toBe(201);
+ const insert = sqlState.calls.at(-1);
+ expect(insert.values).toContainEqual([...EVENT_TYPES]);
+ });
+
+ it('rejects a non-array events value', async () => {
+ const { status, body } = await invoke(listHandler, {
+ method: 'POST',
+ url: '/api/developer/webhooks',
+ body: { url: 'https://example.com/hook', events: 'agent.created' },
+ });
+
+ expect(status).toBe(400);
+ expect(body.error_description).toContain('must be an array');
+ expect(sqlState.calls).toHaveLength(0);
+ });
+
+ it('creates the webhook with deduped events and returns the secret once', async () => {
+ sqlState.responses = [
+ [{ count: 0 }],
+ [{ ...webhookRow, events: ['agent.created', 'agent.updated'] }],
+ ];
+
+ const { status, body } = await invoke(listHandler, {
+ method: 'POST',
+ url: '/api/developer/webhooks',
+ body: {
+ url: 'https://example.com/hook',
+ events: ['agent.created', 'agent.updated', 'agent.created'],
+ },
+ });
+
+ expect(status).toBe(201);
+ expect(body.webhook.secret).toMatch(/^whsec_/);
+ const insert = sqlState.calls.at(-1);
+ expect(insert.query).toContain('insert into developer_webhooks');
+ expect(insert.values).toContainEqual(['agent.created', 'agent.updated']);
+ });
+
+ it('enforces the per-user webhook cap', async () => {
+ sqlState.responses = [[{ count: 10 }]];
+
+ const { status, body } = await invoke(listHandler, {
+ method: 'POST',
+ url: '/api/developer/webhooks',
+ body: { url: 'https://example.com/hook', events: ['agent.created'] },
+ });
+
+ expect(status).toBe(409);
+ expect(body.error).toBe('limit_reached');
+ });
+});
+
+describe('/api/developer/webhooks/:id uuid guard', () => {
+ it('answers 404 for a malformed id without querying Postgres', async () => {
+ const { status, body } = await invoke(detailHandler, {
+ method: 'GET',
+ url: `/api/developer/webhooks/${BAD_ID}?id=${BAD_ID}`,
+ query: { id: BAD_ID },
+ });
+
+ expect(status).toBe(404);
+ expect(body.error).toBe('not_found');
+ expect(sqlState.calls).toHaveLength(0);
+ });
+
+ it('returns the webhook and its recent deliveries for a valid id', async () => {
+ sqlState.responses = [[webhookRow], [{ id: 'd1', event_type: 'agent.created', status_code: 200 }]];
+
+ const { status, body } = await invoke(detailHandler, {
+ method: 'GET',
+ url: `/api/developer/webhooks/${WEBHOOK_ID}?id=${WEBHOOK_ID}`,
+ query: { id: WEBHOOK_ID },
+ });
+
+ expect(status).toBe(200);
+ expect(body.webhook.id).toBe(WEBHOOK_ID);
+ expect(body.deliveries).toHaveLength(1);
+ });
+
+ it('rejects an unknown event type on PATCH', async () => {
+ sqlState.responses = [[webhookRow]];
+
+ const { status, body } = await invoke(detailHandler, {
+ method: 'PATCH',
+ url: `/api/developer/webhooks/${WEBHOOK_ID}?id=${WEBHOOK_ID}`,
+ query: { id: WEBHOOK_ID },
+ body: { events: ['agent.created', 'nope'] },
+ });
+
+ expect(status).toBe(400);
+ expect(body.error_description).toContain('nope');
+ // Only the ownership lookup ran; no update was attempted.
+ expect(sqlState.calls).toHaveLength(1);
+ });
+});