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: enhance database error handling to degrade gracefully on connection issues; add regression tests

qbdz22d01a4c7119
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fc7ff9197..8ca65bb71 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,6 +38,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **New docs for the agent economy, payments, and avatar pipeline** — The docs now cover the systems that move real money through three.ws and had been running ahead of their documentation. New pages explain the circulation engine (how platform agents tip, pay, trade, and launch with one another), the money feed, agent custodial wallets and spend caps, the marketplace buy/sell flow, coin launches, the full x402 payment surface (paid endpoints, the buyer client, and the autonomous loop that buys market intel), AgenC, the MCP tool catalog with per-tool pricing, and the end-to-end avatar generation-to-animation pipeline. (`/docs/circulation-engine`) `[docs]`
- **Newsroom Anchor: agents read the market to you, live and on air** — Open an agent's screen and it becomes a live market-news anchor. Every ~90 seconds it pulls real intel — narrative momentum, sentiment, and flow — scripts a tight bulletin, and reads it aloud in a real synthesized voice while its 3D avatar lip-syncs to the words. The headline slides up as a broadcast lower-third, and the live wall shows what each anchor is reporting with a red ON AIR ticker. Audio is muted by default with one-tap unmute (press A); if a feed is down the anchor reports only what's live instead of going silent, and a rig without face morphs still talks via a jaw-bob driven by the real audio. (`/agent-screen`) `[feature]`
- **Oracle no longer mistakes stablecoins for coins** — The Oracle's feeds, movers, search, and wins gallery now ignore stablecoins and SOL-type tokens (USDC, USDT, wrapped/staked SOL, and similar). These show up as the other side of every trade but were never launched coins, so one was slipping into the rankings as a junk entry with an absurd multiple. They're now filtered out the moment data is ingested, hidden everywhere they're read, and any that were already cached are cleaned up automatically. (`/oracle`) `[fix]`
+- **Pages stay graceful when the database has a hiccup** — If the platform's database ever becomes briefly unreachable, pages now degrade cleanly instead of throwing hard errors. Live counters and feeds quietly fall back to their empty state, and any request that can't be served returns a clear “temporarily unavailable, retry shortly” response that your browser and our CDN know to retry — rather than a generic 500. Previously a database blip could surface as failed loads across explore, the marketplace, avatars, and the oracle stats at once; those reads now recover on their own the moment the database is back. `[fix, infra]`
- **Portfolio dashboard loads your agent balances again** — The portfolio page now shows your agents' live balances and value-over-time chart instead of failing to load. The endpoints that feed the page — your aggregated holdings, the 90-day history chart, and the per-token drill-down — had no server route wired up, so every request came back empty and the page sat blank. The routes are now in place, so your wallets, totals, history, and individual token views all populate as they should. (`/dashboard/portfolio`) `[fix]`
- **Posting a labor-market bounty no longer hits a surprise rate limit** — Posting a bounty on the agent labor market used to share one rate-limit budget with the MCP agent tools, so heavy use of one could spuriously throttle the other and pop a confusing 'rate limit exceeded' with no guidance. Each surface now has its own budget, and if you do post too fast the message tells you exactly how many seconds to wait before trying again. (`/labor-market`) `[fix]`
- **Sentiment Heatmap: a live 3D market field your agent reads aloud** — Open an agent's screen and arm the new Sentiment Heatmap panel: a glowing 3D field of tokens that pulses with the market, $THREE pinned at the centre and labelled. Each token is a pillar — colour is its 24h momentum (cold blue → slate → green-hot), height is its 24h volume, and the strongest movers blaze with bloom while the camera drifts slowly around the field. The data is live: trending market data from Dexscreener and pump.fun, with $THREE enriched by a real pump.fun-comment sentiment pulse. As tokens spike, the agent calls the moment in its activity log — "Heating across the board, $THREE up on rising volume" — narrated by the brain and throttled so it never floods. Hover any tile for momentum and volume, hit the ◎ $THREE button to recentre on the anchor, and when the agent's screen is otherwise idle the heatmap casts to the live wall so the card is never blank. Press H to toggle it. (`/agent-screen`) `[feature]`
diff --git a/api/_lib/db.js b/api/_lib/db.js
index 90ddc303b..99a216b3f 100644
--- a/api/_lib/db.js
+++ b/api/_lib/db.js
@@ -28,6 +28,26 @@ function getSql() {
return _sql;
}
+// Resolve the Neon client without letting a construction failure escape as a
+// SYNCHRONOUS throw. A missing/empty/malformed DATABASE_URL makes the env
+// accessor (`Missing required env var: DATABASE_URL`) or neon() throw the first
+// time the lazy client is built — and that throw fires inside a fragment's
+// `.then`/`.catch`/`.finally`, i.e. while a caller is *attaching* a handler.
+// `.catch(fn)` only runs `fn` on a REJECTION, never on a throw from `.catch()`
+// itself, so a sync throw there bypasses a per-query guard entirely and 500s an
+// endpoint that explicitly degraded the query (e.g. oracle/stats' `.catch(() =>
+// [{}])`). Funnelling the failure into the rejection channel makes every
+// thenable consumer — `await`, `.then`, `.catch`, `Promise.all` — observe a
+// normal rejection, which `isDbUnavailableError` then classifies as a graceful
+// 503 instead of a 500 storm.
+function getSqlSafe() {
+ try {
+ return { sql: getSql(), err: null };
+ } catch (err) {
+ return { sql: null, err };
+ }
+}
+
// Postgres text/varchar/jsonb columns cannot store a NUL byte (U+0000) — any
// parameter containing one makes the driver throw
// `invalid byte sequence for encoding "UTF8": 0x00` (SQLSTATE 22021) and 500s
@@ -84,10 +104,26 @@ function makeFragment(strings, values) {
const toNative = () => {
if (!native) {
const { query, params } = composeFragment(strings, values);
- native = getSql()(query, params);
+ const { sql: client, err } = getSqlSafe();
+ if (err) throw err;
+ native = client(query, params);
}
return native;
};
+ // Settle into a thenable for the consumer paths. If the Neon client can't be
+ // built (DB unconfigured) we hand back a rejected promise rather than throwing
+ // synchronously, so a caller's `.catch()`/`.then(_, onRejected)` actually runs
+ // and `Promise.all` rejects normally instead of throwing during array build.
+ // The `parameterizedQuery`/`opts` getters keep throwing synchronously — they
+ // are inspection-only seams (transaction prep, tests) where a sync throw is the
+ // expected contract, not a dropped guard.
+ const settle = () => {
+ try {
+ return toNative();
+ } catch (err) {
+ return Promise.reject(err);
+ }
+ };
return {
[FRAGMENT]: true,
[Symbol.toStringTag]: 'NeonQueryPromise',
@@ -95,9 +131,9 @@ function makeFragment(strings, values) {
values,
get parameterizedQuery() { return toNative().parameterizedQuery; },
get opts() { return toNative().opts; },
- then(onFulfilled, onRejected) { return toNative().then(onFulfilled, onRejected); },
- catch(onRejected) { return toNative().catch(onRejected); },
- finally(onFinally) { return toNative().finally(onFinally); },
+ then(onFulfilled, onRejected) { return settle().then(onFulfilled, onRejected); },
+ catch(onRejected) { return settle().catch(onRejected); },
+ finally(onFinally) { return settle().finally(onFinally); },
};
}
@@ -149,12 +185,32 @@ export function isDbUnavailableError(err) {
// which survives minification. Fall back to constructor.name for dev builds.
const name = String(err.name || err.constructor?.name || '');
const msg = String(err.message ?? '');
+ // Construction/configuration failures: a missing, empty, or malformed
+ // DATABASE_URL makes the env accessor (`Missing required env var:
+ // DATABASE_URL`) or neon() (`No database connection string was provided…`,
+ // `Database connection string provided to \`neon()\` is not a valid URL`) throw
+ // a PLAIN Error the first time the lazy client is built — no NeonDbError name to
+ // match on. Operationally this is "DB unavailable", not an internal bug: without
+ // this branch every DB-backed read 500s (internal_error) and fires a per-endpoint
+ // ops alert instead of degrading to a single shared 503 + Retry-After. Matched by
+ // message since the thrown error carries the generic `Error` name.
+ if (
+ msg.includes('Missing required env var: DATABASE_URL') ||
+ msg.includes('No database connection string was provided') ||
+ msg.includes('Database connection string provided to')
+ ) {
+ return true;
+ }
if (name === 'NeonDbError' || name === 'DatabaseError') {
return (
msg.includes('password authentication failed') ||
msg.includes('connection refused') ||
msg.includes('ECONNREFUSED') ||
msg.includes('SSL connection') ||
+ // Neon phrases a suspended compute as "The endpoint has been disabled.
+ // Enable it using Neon API and retry." Keep the older 'is disabled'
+ // variant too so either phrasing classifies as unavailable.
+ msg.includes('endpoint has been disabled') ||
msg.includes('endpoint is disabled') ||
msg.includes('Control plane request failed')
);
@@ -181,7 +237,12 @@ export const sql = new Proxy(function () {}, {
if (typeof args[0] === 'string') {
const [queryText, params, opts] = args;
const safeParams = Array.isArray(params) ? params.map(stripNul) : params;
- return getSql()(queryText, safeParams, opts);
+ // Surface a construction failure as a rejection, not a sync throw, so
+ // `sql(q, p).catch(...)` (handler attached before the first await) degrades
+ // the same way the tagged-template fragment path does.
+ const { sql: client, err } = getSqlSafe();
+ if (err) return Promise.reject(err);
+ return client(queryText, safeParams, opts);
}
return makeFragment(args[0], args.slice(1));
},
diff --git a/data/changelog.json b/data/changelog.json
index e89994abf..09ccafbf9 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws \u2014 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-06-29",
+ "title": "Pages stay graceful when the database has a hiccup",
+ "summary": "If the platform's database ever becomes briefly unreachable, pages now degrade cleanly instead of throwing hard errors. Live counters and feeds quietly fall back to their empty state, and any request that can't be served returns a clear “temporarily unavailable, retry shortly” response that your browser and our CDN know to retry — rather than a generic 500. Previously a database blip could surface as failed loads across explore, the marketplace, avatars, and the oracle stats at once; those reads now recover on their own the moment the database is back.",
+ "tags": [
+ "fix",
+ "infra"
+ ]
+ },
{
"date": "2026-06-29",
"title": "Cosmetics you buy now follow you into every world",
diff --git a/public/changelog.json b/public/changelog.json
index 81d948918..9bb6228fa 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-29T17:10:31.675Z",
+ "generated_at": "2026-06-29T21:28:34.659Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -328,6 +328,17 @@
"fix"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Pages stay graceful when the database has a hiccup",
+ "summary": "If the platform's database ever becomes briefly unreachable, pages now degrade cleanly instead of throwing hard errors. Live counters and feeds quietly fall back to their empty state, and any request that can't be served returns a clear “temporarily unavailable, retry shortly” response that your browser and our CDN know to retry — rather than a generic 500. Previously a database blip could surface as failed loads across explore, the marketplace, avatars, and the oracle stats at once; those reads now recover on their own the moment the database is back.",
+ "link": null,
+ "tags": [
+ "fix",
+ "infra"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 7b2181425..21f6d9544 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -262,6 +262,14 @@
<category>fix</category>
<description>The Oracle's feeds, movers, search, and wins gallery now ignore stablecoins and SOL-type tokens (USDC, USDT, wrapped/staked SOL, and similar). These show up as the other side of every trade but were never launched coins, so one was slipping into the rankings as a junk entry with an absurd multiple. They're now filtered out the moment data is ingested, hidden everywhere they're read, and any that were already cached are cleaned up automatically.</description>
</item>
+ <item>
+ <title>Pages stay graceful when the database has a hiccup</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-29:Pages stay graceful when the database has a hiccup</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>If the platform's database ever becomes briefly unreachable, pages now degrade cleanly instead of throwing hard errors. Live counters and feeds quietly fall back to their empty state, and any request that can't be served returns a clear “temporarily unavailable, retry shortly” response that your browser and our CDN know to retry — rather than a generic 500. Previously a database blip could surface as failed loads across explore, the marketplace, avatars, and the oracle stats at once; those reads now recover on their own the moment the database is back.</description>
+ </item>
<item>
<title>Portfolio dashboard loads your agent balances again</title>
<link>https://three.ws/dashboard/portfolio</link>
diff --git a/public/features.json b/public/features.json
index 3204b608a..6a74069b6 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-29T17:10:31.648Z",
+ "generated_at": "2026-06-29T21:28:34.643Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/db-unconfigured.test.js b/tests/db-unconfigured.test.js
new file mode 100644
index 000000000..7f88b5e39
--- /dev/null
+++ b/tests/db-unconfigured.test.js
@@ -0,0 +1,74 @@
+// Regression: a missing/empty/malformed DATABASE_URL must degrade GRACEFULLY,
+// not 500-storm every DB-backed read.
+//
+// The lazy Neon client is built on first query use, so a bad/absent
+// DATABASE_URL throws there — and that throw used to fire SYNCHRONOUSLY inside a
+// fragment's `.catch()`/`.then()`, bypassing per-query guards (a `.catch(fn)`
+// only runs `fn` on a rejection, never on a throw from `.catch()` itself) and
+// landing as an unclassified 500 instead of the intended 503. These tests pin
+// the two contracts that keep the platform degrading cleanly:
+// 1. `sql\`…\`.catch(fallback)` recovers instead of throwing synchronously.
+// 2. The resulting error classifies as db-unavailable → wrap() returns 503.
+
+import { describe, it, expect, beforeAll } from 'vitest';
+
+// Force the unconfigured path BEFORE db.js is imported. `req('DATABASE_URL')`
+// throws `Missing required env var: DATABASE_URL` on an empty/unset value.
+let sql, sqlValues, isDbUnavailableError;
+beforeAll(async () => {
+ delete process.env.DATABASE_URL;
+ // Fresh module instance so the lazy client starts uninitialized.
+ const mod = await import('../api/_lib/db.js?unconfigured');
+ ({ sql, sqlValues, isDbUnavailableError } = mod);
+});
+
+describe('db.js with an unconfigured DATABASE_URL', () => {
+ it('routes a tagged-template construction failure through .catch() instead of throwing synchronously', async () => {
+ // The exact oracle/stats shape: a guarded query (whose fallback is a row
+ // array) inside Promise.all. The key assertion is that we REACH the fallback
+ // at all — a sync throw from `.catch()` would have rejected the Promise.all.
+ const [rows] = await Promise.all([
+ sql`select count(*) as n from anything`.catch(() => [{ n: 0 }]),
+ ]);
+ expect(rows).toEqual([{ n: 0 }]);
+ expect(rows[0].n).toBe(0);
+ });
+
+ it('rejects (not throws) from await, so an outer try/catch can handle it', async () => {
+ let caught = null;
+ try {
+ await sql`select 1`;
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(Error);
+ expect(isDbUnavailableError(caught)).toBe(true);
+ });
+
+ it('routes the function-form sql(query, params) failure through .catch() too', async () => {
+ const recovered = await sql('select 1', []).catch(() => 'fallback');
+ expect(recovered).toBe('fallback');
+ });
+
+ it('classifies the construction failure as db-unavailable (→ graceful 503, not 500)', async () => {
+ const err = await sql`select 1`.then(
+ () => null,
+ (e) => e,
+ );
+ expect(err).toBeTruthy();
+ expect(isDbUnavailableError(err)).toBe(true);
+ });
+
+ it('classifies a suspended-Neon-endpoint message (both phrasings)', () => {
+ const disabled = Object.assign(new Error('The endpoint has been disabled. Enable it using Neon API and retry.'), {
+ name: 'NeonDbError',
+ });
+ expect(isDbUnavailableError(disabled)).toBe(true);
+ const legacy = Object.assign(new Error('endpoint is disabled'), { name: 'NeonDbError' });
+ expect(isDbUnavailableError(legacy)).toBe(true);
+ });
+
+ it('still surfaces sqlValues build-time validation as a real throw (not masked)', () => {
+ expect(() => sqlValues([])).toThrow();
+ });
+});