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.

Sync workspace: forge timeline, world persistence, press-kit and mobile audits

nirholasdb9426387dbc
diff --git a/ISSUES.md b/ISSUES.md
index 6812f42e1..055e91cfc 100644
--- a/ISSUES.md
+++ b/ISSUES.md
@@ -29,13 +29,14 @@ this repo:
OpenRouter as $0). Traffic survives on the free lanes (Groq/NIM plus the
vertex-gemini credits anchor). Action: reactivate OpenAI billing and/or
fund the OpenRouter key, or accept free-lane-only service.
-2. **Neon storage over the high-water mark; write crons silently no-op**
- (found 2026-07-21). Database size exceeds the 2048MB high-water, which
- makes six write crons no-op without alerting, and `db-retention`'s plain
- `VACUUM` never returns space to the OS, so the condition cannot self-heal.
- `intel-learn` also OOMs on an unbounded 64k-row query while the cap holds.
- Action: bump the Neon plan or approve a destructive prune; until then the
- affected crons stay dark.
+2. **Neon storage pressure — RESOLVED, re-verified 2026-07-29.** The branch
+ measures 2538MB against a 3072MB high-water (`isStoragePressured()` reports
+ `pressured: false`), so no write cron is gated. The two code defects behind
+ the original report are also closed: `wrapCron`'s `requireWriteCapacity`
+ preflight logs a named warn and heartbeats a healthy skip instead of failing
+ silently, and `db-retention` now VACUUM FULLs the worst offenders under
+ pressure (section D), which does return space to the OS. Re-open only if the
+ size crosses the high-water again.
3. **Helius quota exhaustion, still live** (observed 2026-07-22: mainnet and
devnet RPC 429 "max usage reached"; balances and solana-rpc fail over to
public RPC with the designed 10min/360min cooldowns). Action: bump the
@@ -44,15 +45,29 @@ this repo:
Carried forward from the retired `prompts/x402-catalog/` tracker (campaign
closed 2026-07-28; full history in git):
-4. **No web-search key in prod** (owner action). `BRAVE_API_KEY` /
+4. **No web-search key in prod** (owner action, now non-blocking). `BRAVE_API_KEY` /
`TAVILY_API_KEY` / `EXA_API_KEY` / `SERPER_API_KEY` are all absent on
- `three-ws-api`, degrading the paid $0.10 fact-check product. Action: set
- one of the four keys on the Cloud Run service.
-5. **Fact-check accuracy is 20% (8/40) on the published benchmark** (code).
- `computeVerdict`'s support/contradict threshold and the query-generation
- prompt need a rework; flagged as the next work order when the x402-catalog
- campaign closed but never opened. Benchmark:
- `data/_generated/fact-check-benchmark.json`.
+ `three-ws-api`. This no longer leaves the fact-checker on DuckDuckGo scraps:
+ the search chain now leads with Vertex-grounded Google Search (service-account
+ auth, GCP credits, no third-party key) and the keyless Wikipedia rung returns
+ full intro extracts rather than 150-char highlight fragments. Setting one of
+ the four keys is still an upgrade, not a prerequisite.
+5. **Fact-check verdict quality — reworked in-repo 2026-07-29, benchmark
+ awaiting a clean run** (code). The chain-level defects behind the 20% score
+ are fixed: `computeVerdict` now judges direction over stance-BEARING weight
+ with a coverage gate (all-neutral evidence returns `insufficient` instead of
+ collapsing every class to `mixed`), the Wikipedia rung returns real intro
+ extracts, `searchAll` interleaves the three query angles round-robin instead
+ of letting query 1 take all five checked slots, and the stance prompt carries
+ an explicit rubric that names a differing figure/date/record-holder as a
+ contradiction rather than "neutral". The published number is NOT restated
+ here because no trustworthy run exists yet: the last one scored 7.5% with 30
+ of 40 claims errored (it measured the LLM outage in item 1, not accuracy) and
+ `data/_generated/fact-check-benchmark.json` has been removed so `/fact-check`
+ renders its honest "not yet run" state. The runner now refuses to publish any
+ run with >10% errored claims. Action: re-run
+ `node scripts/fact-check-benchmark.mjs` against production once the deploy
+ below lands (Vertex answers there, so the chain is not degraded).
6. **ASR/media backstops unconfigured** (owner action).
`NVIDIA_ASR_FUNCTION_ID` unset in prod (`/api/v1/ai/asr` returns 503
`not_configured`); the Replicate account is out of credit; Upstash Redis is
diff --git a/api/_lib/mem-cache.js b/api/_lib/mem-cache.js
index d2085c691..039176475 100644
--- a/api/_lib/mem-cache.js
+++ b/api/_lib/mem-cache.js
@@ -29,12 +29,18 @@ import { LRUCache } from 'lru-cache';
export function createCache({ max = 512, ttlMs, updateAgeOnGet = false } = {}) {
return new LRUCache({
max: Math.max(1, max),
- // `Date` rather than lru-cache's default `performance`, for parity with
- // the `Date.now()` expiry the hand-rolled Maps used, and because caches
- // are constructed at module load — a monotonic clock captured then
- // cannot be advanced by a test's fake timers, making TTL behaviour
- // untestable. TTLs here are minutes long, so clock drift is immaterial.
- perf: Date,
+ // Wall-clock TTL, for parity with the `Date.now()` expiry the hand-rolled
+ // Maps used (TTLs here are minutes long, so drift is immaterial). The
+ // indirection matters: lru-cache captures this object once, at
+ // construction, and caches are built at module load — resolving `Date`
+ // inside the call keeps TTL behaviour observable under fake timers
+ // instead of frozen against a clock captured before the test ran.
+ perf: { now: () => Date.now() },
+ // Read the clock on every TTL check. By default lru-cache memoizes "now"
+ // and clears it from a timer, which makes expiry granular and leaves a
+ // stale timestamp behind whenever that timer is discarded. One Date.now()
+ // per read is not worth the imprecision.
+ ttlResolution: 0,
...(ttlMs ? { ttl: ttlMs, updateAgeOnGet } : {}),
});
}
diff --git a/api/_lib/notify.js b/api/_lib/notify.js
index bf0c79fbc..6ae741d4f 100644
--- a/api/_lib/notify.js
+++ b/api/_lib/notify.js
@@ -23,19 +23,15 @@
* @returns {Promise<{ id: string|null, in_app?: boolean }>}
*/
import { sql } from './db.js';
-import { resolvePrefs, channelEnabled, pushPayloadFor, categoryForType } from './notify-prefs.js';
+import {
+ resolvePrefs,
+ channelEnabled,
+ pushPayloadFor,
+ categoryForType,
+ lockedChannelsFor,
+} from './notify-prefs.js';
import { sendPushToUser } from './web-push.js';
-// Categories whose in-app row is written no matter what the user muted. The
-// bell is the durable record of what happened to an account, not an
-// interruption: muting should quiet push, email and telegram, never erase the
-// user's own audit trail. 'account' is "Account & security" and carries
-// security_alert, wallet_anomaly_frozen, withdrawal_failed and the payment
-// mismatches, and it is also the fallback for any type not yet in
-// TYPE_CATEGORY, so honoring a mute here would silently hide future
-// security-relevant events too. The interruptive channels stay fully mutable.
-const IN_APP_ALWAYS = new Set(['account']);
-
export function insertNotification(userId, type, payload = {}) {
return deliver(userId, type, payload).catch((err) => {
console.error('[notify] delivery failed:', err.message);
@@ -48,8 +44,12 @@ async function deliver(userId, type, payload) {
// resolvePrefs already falls back to defaults on a DB error, so a lookup
// problem degrades to "deliver on the default channels", never to silence.
const prefs = await resolvePrefs(userId);
+ // The bell is the durable record of what happened to an account, so a few
+ // categories (Account & security) always write their row; muting there
+ // quiets push, email and telegram only. See lockedChannelsFor.
const wantsInApp =
- IN_APP_ALWAYS.has(categoryForType(type)) || channelEnabled(prefs, type, 'in_app');
+ lockedChannelsFor(categoryForType(type)).includes('in_app') ||
+ channelEnabled(prefs, type, 'in_app');
// 2: durable in-app row, only when the user left the bell on for this
// category. Muting in_app must leave no row behind: the inbox list and the
diff --git a/api/forge.js b/api/forge.js
index 96194b230..a5d18bec1 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -781,6 +781,10 @@ async function runHfImageLane({
mode = 'image_to_3d',
previewImageUrl = null,
textToImageModel = null,
+ // The art-directed rewrite that painted `previewImageUrl`, when it differed
+ // from the caller's raw prompt. Reported back verbatim so the client can show
+ // what the model was actually asked for. Null on image→3D (nothing to rewrite).
+ directedPrompt = null,
opts = null,
cacheKey = null,
}) {
@@ -999,6 +1003,7 @@ async function runHfImageLane({
tier: tier.id,
backend: backendId,
prompt: prompt || null,
+ directed_prompt: directedPrompt,
preview_image_url: preview,
reference_image_urls: isImageMode ? [imageUrls[0]] : [preview],
text_to_image_model: isImageMode ? null : textToImageModel,
@@ -2024,6 +2029,7 @@ async function startJob(req, res) {
tier: tier.id,
backend: backendId,
prompt: prompt || null,
+ directed_prompt: directedPrompt,
preview_image_url: referenceImageUrl,
reference_image_urls: views,
text_to_image_model: isImageMode ? null : textToImageModel,
@@ -2067,6 +2073,7 @@ async function startJob(req, res) {
mode: isImageMode ? 'image_to_3d' : 'text_to_3d',
previewImageUrl: referenceImageUrl,
textToImageModel,
+ directedPrompt,
opts,
cacheKey,
})
@@ -2104,6 +2111,7 @@ async function startJob(req, res) {
mode: isImageMode ? 'image_to_3d' : 'text_to_3d',
previewImageUrl: referenceImageUrl,
textToImageModel,
+ directedPrompt,
opts,
cacheKey,
})
@@ -2267,6 +2275,7 @@ async function startJob(req, res) {
mode: isImageMode ? 'image_to_3d' : 'text_to_3d',
previewImageUrl: referenceImageUrl,
textToImageModel,
+ directedPrompt,
opts,
cacheKey,
})
@@ -2341,6 +2350,7 @@ async function startJob(req, res) {
tier: tier.id,
backend: backendId,
prompt: prompt || null,
+ directed_prompt: directedPrompt,
preview_image_url: referenceImageUrl,
reference_image_urls: views,
views_requested: viewsRequested,
@@ -2737,6 +2747,12 @@ async function pollJob(req, res, jobId) {
backend: meta.backend ?? null,
tier: meta.tier ?? null,
path: meta.path ?? null,
+ // The reference view this job reconstructs from. The submit response
+ // already carries it, but a client that never saw that response —
+ // a coalesced job, a resumed job after a reload, a poll-time failover
+ // successor — otherwise has no way to learn it. Repeating it here lets
+ // the generation timeline reveal the reference the moment it exists.
+ preview_image_url: meta.preview_image_url ?? null,
}
: {};
diff --git a/character-studio/.gitignore b/character-studio/.gitignore
index d07eb1f6c..b924c2de3 100644
--- a/character-studio/.gitignore
+++ b/character-studio/.gitignore
@@ -103,11 +103,6 @@ web_modules/
# Optional eslint cache
.eslintcache
-<<<<<<< HEAD
-lerna-debug.log
-.vscode
-=======
-<<<<<<< HEAD
# Microbundle cache
.rpt2_cache/
@@ -283,7 +278,7 @@ fabric.properties
# Documentation here: https://yarnpkg.com/features/zero-installs
#!/.yarn/cache
/.pnp.*
-=======
+
lerna-debug.log
.vscode
diff --git a/data/_generated/fact-check-benchmark.json b/data/_generated/fact-check-benchmark.json
deleted file mode 100644
index fc68d31a6..000000000
--- a/data/_generated/fact-check-benchmark.json
+++ /dev/null
@@ -1,64 +0,0 @@
-{
- "generated_at": "2026-07-28T23:50:58.991Z",
- "endpoint": "in-process:api/x402/fact-check.js#_checkClaim (real chain, no HTTP/x402 payment layer)",
- "fixture_version": "1.0.0",
- "claim_count": 40,
- "total": 40,
- "correct": 3,
- "errors": 30,
- "accuracy_pct": 7.5,
- "by_class": {
- "supported": {
- "total": 10,
- "correct": 1,
- "accuracy_pct": 10
- },
- "contradicted": {
- "total": 10,
- "correct": 0,
- "accuracy_pct": 0
- },
- "mixed": {
- "total": 10,
- "correct": 0,
- "accuracy_pct": 0
- },
- "insufficient": {
- "total": 10,
- "correct": 2,
- "accuracy_pct": 20
- }
- },
- "by_difficulty": {
- "easy": {
- "total": 13,
- "correct": 1,
- "accuracy_pct": 7.7
- },
- "medium": {
- "total": 20,
- "correct": 2,
- "accuracy_pct": 10
- },
- "hard": {
- "total": 7,
- "correct": 0,
- "accuracy_pct": 0
- }
- },
- "confusion": {
- "supported": {
- "insufficient": 2,
- "supported": 1
- },
- "contradicted": {
- "insufficient": 2
- },
- "mixed": {
- "insufficient": 3
- },
- "insufficient": {
- "insufficient": 2
- }
- }
-}
diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.md
index aa6e464dc..bc44aa61d 100644
--- a/docs/x402-ring-economy.md
+++ b/docs/x402-ring-economy.md
@@ -328,6 +328,79 @@ then kept in a verified, watched, auto-fundable state:
Generates the role wallets, writes secrets to a gitignored file, prints the env
block. Never funds anything.
+## One signature, one payment
+
+A settlement is only real if it has its own on-chain transaction. Enforcing that
+turns out to be less obvious than it sounds, and getting it wrong overstated our
+own books for three weeks.
+
+**What went wrong.** Ed25519 signatures are deterministic: sign identical
+transaction bytes with the same key and you get the same signature. Two ring
+payments with the same payer, recipient, mint and amount, built against one
+shared tick blockhash with the same fee configuration, compile to *the same
+transaction*. Only one can land; the rest are rejected by the network as already
+processed. The facilitator treated that rejection as an idempotent retry of the
+payment in hand and reported success — so several distinct payments were
+credited against a single transfer.
+
+Measured on mainnet 2026-07-28, before the fix:
+
+| | |
+| --- | --- |
+| Credited settle rows | 59,271 |
+| Distinct signatures | 46,597 |
+| Rows sharing a signature | 12,674 (21.4%) |
+| USDC the log implied | 1,103.444 |
+| USDC actually moved | 1,027.424 |
+
+Two sampled transactions each carried exactly **one** SPL transfer of 1,000
+atomic units while **nine** settle rows, with nine distinct idempotency keys and
+timestamps seconds apart, were credited against them.
+
+**The fix, in three layers.**
+
+1. **Atomic credit at settle.** A successful broadcast is no longer a settled
+ payment. [`settle-credit.js`](../api/_lib/x402/settle-credit.js) claims the
+ credit for a signature, and only the winner is credited. A retry carrying the
+ *same* idempotency key is recognised as an idempotent replay and answered
+ with success without double-counting the fee; anything else is refused with
+ `signature_already_settled`, so the service is not delivered against a
+ transfer that settled a different payment. With the database unreachable the
+ claim fails **closed** (`settle_credit_unavailable`) — a refused settle is
+ retryable, whereas a wrongly-granted one is not recoverable.
+
+2. **A database constraint, not just code.** Migration
+ `20260729000000_x402_settle_sig_unique.sql` adds a partial unique index over
+ `tx_sig`. That index, not the pre-check, is what makes concurrent claims safe:
+ the credit insert runs `ON CONFLICT DO NOTHING`, so of any set of simultaneous
+ settles sharing a signature exactly one wins. The constraint is scoped by a
+ `credit_gated` marker column rather than a timestamp, because a migration
+ cannot know when its deploy will actually land — history is excluded by
+ construction and the rule takes effect precisely when the new code starts
+ serving.
+
+3. **Stop building identical transactions.** [`pay.js`](../api/_lib/x402/pay.js)
+ previously perturbed the priority fee from a 997-slot per-process counter that
+ started at the same value on every instance, so two instances paying the same
+ endpoint in one blockhash window produced identical bytes. It now draws from
+ ~4.08M slots with a CSPRNG, varying the **compute-unit limit** as well as the
+ price. The limit dimension is free: priority fee is `price × limit / 1e6`, so
+ at the baseline 5 µlamports even the top of the range floors to zero lamports,
+ and unused compute units are not billed. Sponsor mode, which sits exactly at
+ the 10,000-lamport ceiling, is restricted to the price slots that still floor
+ to zero.
+
+**Proving it stays fixed.** The `settle-signature-audit` pipeline
+([source](../api/_lib/x402/pipelines/settle-signature-audit.js)) runs hourly,
+free and read-only, and alerts if a single gated signature is ever credited
+twice. It also reports the gate's own refusals: a non-zero duplicate-refusal
+count is the gate *working*, while a sharp rise means payer-side entropy has
+regressed and buyers are eating avoidable retries.
+
+Pre-fix history is deliberately left intact. Those duplicates are real and
+published; `scripts/x402-milestone-stats.mjs` prints a warning with both figures
+so nobody quotes the row count as an on-chain transaction count.
+
## Reconciliation — proving every ring dollar on-chain
The daily [revenue reconciler](../api/_lib/x402/revenue-reconciliation.js) proves
diff --git a/marketing/x402-milestone/README.md b/marketing/x402-milestone/README.md
index b90fc7282..1ef51dcb3 100644
--- a/marketing/x402-milestone/README.md
+++ b/marketing/x402-milestone/README.md
@@ -59,9 +59,17 @@ warning with the live numbers on every run.
Two consequences. For copy: "payments settled" is a claim about the
facilitator's own settlement operations and is what the video says; a claim of
one chain transaction per payment would not survive an explorer check. For
-engineering: the settle path is returning an already-used signature for distinct
-payment requests, meaning some paid requests were served without their own
-settlement. That is a live correctness bug, tracked separately from this video.
+engineering: the settle path was returning an already-used signature for
+distinct payment requests, meaning some paid requests were served without their
+own settlement.
+
+**The engineering half is fixed** (2026-07-29). Settlement credit is now claimed
+atomically, one payment per signature, backed by a partial unique index; the
+payment builder draws from a ~4.08M-slot fee-nonce space so identical
+transactions are not built in the first place; and an hourly audit alerts on any
+recurrence. See ["One signature, one payment"](../../docs/x402-ring-economy.md)
+for the full write-up. The figures above are the pre-fix history and are left
+intact on purpose — they are what the published video reports.
## Files
diff --git a/package.json b/package.json
index 4028ba4df..35a55017b 100644
--- a/package.json
+++ b/package.json
@@ -215,6 +215,8 @@
"test:gate": "node scripts/test-gate.mjs",
"test:e2e": "playwright test",
"audit:a11y": "playwright test tests/e2e/a11y-top-pages.spec.js",
+ "perf:mobile": "node scripts/mobile-perf.mjs",
+ "audit:mobile-touch": "node scripts/mobile-touch-audit.mjs",
"test:pages": "node scripts/test-pages.mjs",
"verify:ibm": "node scripts/verify-ibm-pages.mjs",
"verify:zauth": "node scripts/verify-zauth-runtime.mjs",
diff --git a/pages/forge.html b/pages/forge.html
index 708ec10d7..ad35bf55a 100644
--- a/pages/forge.html
+++ b/pages/forge.html
@@ -1401,9 +1401,19 @@
justify-content: center;
gap: var(--space-sm);
}
+ /* Stage timeline list. Rows are rendered by src/forge-timeline.js; the
+ markers are the dots below, so the list itself carries none. */
+ .gen-stages {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-sm);
+ }
.step {
display: flex;
- align-items: center;
+ align-items: flex-start;
gap: 0.7rem;
color: var(--ink-dim);
font-size: var(--text-sm);
@@ -1414,6 +1424,127 @@
border-radius: 50%;
border: 2px solid var(--stroke-strong);
flex: none;
+ margin-top: 0.2em;
+ }
+ .step-body {
+ display: flex;
+ flex-direction: column;
+ gap: 0.15rem;
+ min-width: 0;
+ flex: 1 1 auto;
+ }
+ .step-label {
+ line-height: var(--leading-snug, 1.35);
+ }
+ .step-detail {
+ font-size: var(--text-2xs);
+ line-height: 1.45;
+ color: var(--ink-dim);
+ opacity: 0.85;
+ }
+ .step[data-state='pending'] .step-detail {
+ opacity: 0.6;
+ }
+ /* Reference view revealed inside the timeline the moment the API hands
+ one over. Anchor, so it is keyboard reachable and opens full size. */
+ .step-thumb {
+ flex: none;
+ width: 34px;
+ height: 34px;
+ border-radius: var(--radius-sm, 6px);
+ overflow: hidden;
+ border: 1px solid var(--stroke);
+ background: var(--surface-1);
+ display: block;
+ transition: border-color 0.18s ease, transform 0.18s ease;
+ }
+ .step-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ animation: paint-in 0.9s cubic-bezier(0.2, 0.7, 0.2, 1) both;
+ }
+ .step-thumb:hover {
+ border-color: var(--accent);
+ transform: scale(1.06);
+ }
+ .step-thumb:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ border-color: var(--accent);
+ }
+ .step-thumb:active {
+ transform: scale(0.98);
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .step-thumb,
+ .step-thumb img {
+ transition: none;
+ animation: none;
+ }
+ .step-thumb:hover {
+ transform: none;
+ }
+ }
+ /* Cold-start warming card: a designed, honest waiting state for a GPU
+ worker that is booting, instead of a silent stall. */
+ .gen-warming {
+ display: flex;
+ align-items: flex-start;
+ gap: 0.6rem;
+ margin-top: var(--space-sm);
+ padding: var(--space-sm) var(--space-md);
+ border: 1px solid color-mix(in srgb, var(--warning, #e0a93e) 40%, var(--stroke));
+ border-radius: var(--radius-md);
+ background: color-mix(in srgb, var(--warning, #e0a93e) 7%, var(--surface-2));
+ }
+ .gen-warming.is-hidden {
+ display: none;
+ }
+ .gen-warming-pip {
+ flex: none;
+ width: 9px;
+ height: 9px;
+ margin-top: 0.35rem;
+ border-radius: 50%;
+ background: var(--warning, #e0a93e);
+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--warning, #e0a93e) 60%, transparent);
+ animation: warm-pulse 1.9s ease-out infinite;
+ }
+ @keyframes warm-pulse {
+ to {
+ box-shadow: 0 0 0 10px transparent;
+ }
+ }
+ .gen-warming-copy {
+ min-width: 0;
+ }
+ .gen-warming-title {
+ margin: 0;
+ font-size: var(--text-sm);
+ font-weight: 600;
+ color: var(--ink);
+ }
+ .gen-warming-body {
+ margin: 0.2rem 0 0;
+ font-size: var(--text-xs);
+ line-height: 1.5;
+ color: var(--ink-dim);
+ }
+ .gen-warming-count {
+ margin: 0.3rem 0 0;
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ color: var(--warning, #e0a93e);
+ }
+ .gen-warming[data-phase='over'] .gen-warming-pip {
+ animation-duration: 3.2s;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .gen-warming-pip {
+ animation: none;
+ }
}
.step[data-state='active'] {
color: var(--ink);
@@ -1795,6 +1926,132 @@
animation: saved-pop 3s ease forwards;
}
.saved-chip.is-hidden { display: none; }
+
+ /* "What we actually asked the model" — the art-directed rewrite, shown
+ under the result bar. Collapsed by default: context, not headline. */
+ .directed {
+ border-top: 1px solid var(--stroke);
+ }
+ .directed[hidden] {
+ display: none;
+ }
+ .directed-summary {
+ display: flex;
+ align-items: center;
+ gap: var(--space-xs);
+ padding: var(--space-sm) var(--space-md);
+ cursor: pointer;
+ list-style: none;
+ font-size: var(--text-sm);
+ color: var(--ink-dim);
+ transition: color 0.18s ease, background 0.18s ease;
+ }
+ .directed-summary::-webkit-details-marker {
+ display: none;
+ }
+ .directed-summary:hover {
+ color: var(--ink);
+ background: var(--surface-1);
+ }
+ .directed-summary:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: -2px;
+ color: var(--ink);
+ }
+ .directed-summary:active {
+ background: var(--surface-2);
+ }
+ .directed-chip {
+ flex: none;
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--accent);
+ background: var(--accent-soft);
+ border: 1px solid color-mix(in srgb, var(--accent) 40%, transparent);
+ border-radius: 999px;
+ padding: 1px 8px;
+ }
+ .directed-summary-text {
+ min-width: 0;
+ }
+ .directed-caret {
+ flex: none;
+ margin-left: auto;
+ transition: transform 0.2s ease;
+ }
+ .directed[open] .directed-caret {
+ transform: rotate(180deg);
+ }
+ .directed-body {
+ padding: 0 var(--space-md) var(--space-md);
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-sm);
+ animation: directed-in 0.24s ease both;
+ }
+ @keyframes directed-in {
+ from {
+ opacity: 0;
+ transform: translateY(-4px);
+ }
+ }
+ .directed-intro {
+ margin: 0;
+ font-size: var(--text-xs);
+ line-height: 1.55;
+ color: var(--ink-dim);
+ max-width: 68ch;
+ }
+ .directed-block {
+ min-width: 0;
+ }
+ .directed-label {
+ margin: 0 0 0.25rem;
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+ }
+ .directed-model {
+ text-transform: none;
+ letter-spacing: 0;
+ opacity: 0.8;
+ }
+ .directed-text {
+ margin: 0;
+ font-size: var(--text-sm);
+ line-height: 1.6;
+ color: var(--ink);
+ overflow-wrap: anywhere;
+ }
+ .directed-text--enhanced {
+ padding: var(--space-sm) var(--space-md);
+ border: 1px solid var(--stroke);
+ border-left: 2px solid var(--accent);
+ border-radius: var(--radius-md);
+ background: var(--surface-1);
+ }
+ .directed-actions {
+ display: flex;
+ align-items: center;
+ gap: var(--space-xs);
+ flex-wrap: wrap;
+ }
+ .directed-status {
+ font-size: var(--text-xs);
+ color: var(--accent);
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .directed-body {
+ animation: none;
+ }
+ .directed-caret {
+ transition: none;
+ }
+ }
.result-bar .actions {
display: flex;
gap: var(--space-xs);
@@ -3112,17 +3369,21 @@
<div class="shimmer" aria-hidden="true"></div>
</div>
<div class="gen-steps">
- <div class="step" id="step-image" data-state="active">
- <span class="dot" aria-hidden="true"></span>
- <span data-i18n="forge.painting_photoreal_reference_image">Painting photoreal reference image</span>
- </div>
- <div class="step" id="step-mesh" data-state="pending">
- <span class="dot" aria-hidden="true"></span>
- <span data-i18n="forge.reconstructing_textured_mesh">Reconstructing textured mesh</span>
- </div>
- <div class="step" id="step-finish" data-state="pending">
- <span class="dot" aria-hidden="true"></span>
- <span data-i18n="forge.finalizing_glb">Finalizing GLB</span>
+ <!-- Named stage timeline. Every row, and every state change on it, is
+ driven by a real /api/forge signal (see src/forge-timeline.js);
+ the lane decides which stages exist, so a text→3D engine with no
+ reference-image step simply never shows one. -->
+ <ol class="gen-stages" id="gen-stages" aria-live="polite"></ol>
+ <!-- Cold-start honesty: shown only when the API reports cold_start
+ for the chosen self-hosted GPU lane, and dismissed by the first
+ real "running" poll, never by a timer. -->
+ <div class="gen-warming is-hidden" id="gen-warming" role="status" data-phase="off">
+ <span class="gen-warming-pip" aria-hidden="true"></span>
+ <div class="gen-warming-copy">
+ <p class="gen-warming-title">Waking up a GPU</p>
+ <p class="gen-warming-body"></p>
+ <p class="gen-warming-count"></p>
+ </div>
</div>
<div
class="gen-progress"
@@ -3399,6 +3660,44 @@
</div>
</div>
+ <!-- What the model was actually asked for: the art-directed rewrite
+ that painted the reference view, straight from the API's
+ directed_prompt field. Hidden unless the server reports one.
+ Wired in src/forge-directed-prompt.js. -->
+ <details class="directed" id="forge-directed" hidden>
+ <summary class="directed-summary">
+ <span class="directed-chip">art-directed</span>
+ <span class="directed-summary-text">What we actually asked the model</span>
+ <svg class="directed-caret" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <polyline points="6 9 12 15 18 9" />
+ </svg>
+ </summary>
+ <div class="directed-body">
+ <p class="directed-intro">
+ Your words set the subject. Before anything is painted, an art
+ director rewrites them into a single-subject brief with materials,
+ lighting and composition cues, and that rewrite is what conditions
+ the reference view your mesh is built from.
+ </p>
+ <div class="directed-block">
+ <p class="directed-label">You typed</p>
+ <p class="directed-text" id="forge-directed-raw"></p>
+ </div>
+ <div class="directed-block">
+ <p class="directed-label">
+ Sent to the reference painter
+ <span class="directed-model" id="forge-directed-model" hidden></span>
+ </p>
+ <p class="directed-text directed-text--enhanced" id="forge-directed-text"></p>
+ </div>
+ <div class="directed-actions">
+ <button class="btn btn-ghost" type="button" id="forge-directed-copy">Copy prompt</button>
+ <button class="btn btn-ghost" type="button" id="forge-directed-use">Use as my prompt</button>
+ <span class="directed-status" id="forge-directed-status" role="status" aria-live="polite"></span>
+ </div>
+ </div>
+ </details>
+
<!-- Category picker — label your model so the gallery and explore feed
can surface it under the right filter. Wired in forge.js via the
forge-category-picker id; hidden by default, becomes visible when
diff --git a/server/index.mjs b/server/index.mjs
index fe8f77880..5681cc3e6 100644
--- a/server/index.mjs
+++ b/server/index.mjs
@@ -35,6 +35,7 @@ import compression from 'compression';
import { existsSync, statSync, readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { pathToFileURL, fileURLToPath } from 'node:url';
+import { isSsrRoute, renderSsrPage } from './ssr-pages.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
@@ -487,6 +488,28 @@ app.use(async (req, res) => {
if (req.method === 'GET' || req.method === 'HEAD') {
const file = resolveStatic(currentPath);
if (file) {
+ // A few directory pages render their whole body from client JS, which
+ // leaves crawlers and no-JS visitors an empty shell. For those routes we
+ // inject the page's own first view before sending it. Any failure inside
+ // falls through to the untouched file, so this can never break a page.
+ if (req.method === 'GET' && isSsrRoute(currentPath) && !url.search) {
+ try {
+ const shell = readFileSync(file, 'utf8');
+ const html = await renderSsrPage(currentPath, shell, `http://127.0.0.1:${PORT}`);
+ if (html) {
+ res.set(collected);
+ if (fileStatus) res.status(fileStatus);
+ res.set('content-type', 'text/html; charset=utf-8');
+ // Same freshness the static shell gets from the CDN, but the
+ // injected block is only as fresh as its own cache TTL.
+ res.set('cache-control', 'public, max-age=60, s-maxage=300');
+ res.send(html);
+ return;
+ }
+ } catch (err) {
+ console.error(`[ssr] ${currentPath} fell back to the static shell:`, err.message);
+ }
+ }
await serveFile(req, res, file, collected, fileStatus);
return;
}
diff --git a/src/dashboard-next/pages/settings.js b/src/dashboard-next/pages/settings.js
index f169189cb..2c124fbf3 100644
--- a/src/dashboard-next/pages/settings.js
+++ b/src/dashboard-next/pages/settings.js
@@ -373,7 +373,7 @@ function renderNotificationPrefs(resp, onRetry) {
panel.innerHTML = `
<div style="margin-bottom:14px">
<div class="dn-panel-title">Notification preferences</div>
- <div class="dn-panel-sub" style="margin:2px 0 0">Mute noisy categories per channel — the bell (in-app) always stays available so nothing is ever silently lost.</div>
+ <div class="dn-panel-sub" style="margin:2px 0 0">Mute noisy categories per channel. Account and security events always stay in your bell so nothing important is silently lost, but you can still quiet their push, email and Telegram.</div>
</div>
${!categories.length ? emptyStateHTML({
icon: '',
@@ -397,15 +397,25 @@ function renderNotificationPrefs(resp, onRetry) {
${cat.description ? `<div style="font-size:12px;color:var(--nxt-ink-dim);margin-top:2px">${esc(cat.description)}</div>` : ''}
</td>
${channels.map((ch) => {
- const on = matrix?.[cat.key]?.[ch] ?? false;
- const disabled = ch === 'telegram' && !body.prefs?.telegram_chat_id;
+ // A locked channel always delivers for this category (see
+ // notify-prefs lockedChannelsFor), so it renders on and
+ // non-interactive rather than as a toggle that does nothing.
+ const locked = (cat.lockedChannels || []).includes(ch);
+ const on = locked || (matrix?.[cat.key]?.[ch] ?? false);
+ const noTelegram = ch === 'telegram' && !body.prefs?.telegram_chat_id;
+ const disabled = locked || noTelegram;
+ const title = locked
+ ? 'Always on: account and security events are kept in your bell'
+ : noTelegram
+ ? 'Link a Telegram chat id to enable'
+ : '';
return `
<td style="padding:10px;text-align:center">
<button type="button" role="switch" class="set-switch" data-notif-cat="${esc(cat.key)}" data-notif-ch="${esc(ch)}"
aria-checked="${on ? 'true' : 'false'}"
- ${disabled ? 'disabled title="Link a Telegram chat id to enable"' : ''}
- aria-label="${esc(cat.label || cat.key)} via ${esc(CHANNEL_LABEL[ch] || ch)}"
- style="${disabled ? 'opacity:.35;cursor:not-allowed' : ''}"></button>
+ ${disabled ? 'disabled' : ''}${title ? ` title="${esc(title)}"` : ''}
+ aria-label="${esc(cat.label || cat.key)} via ${esc(CHANNEL_LABEL[ch] || ch)}${locked ? ', always on' : ''}"
+ style="${noTelegram ? 'opacity:.35;cursor:not-allowed' : locked ? 'cursor:not-allowed' : ''}"></button>
</td>
`;
}).join('')}
diff --git a/src/game/community-net.js b/src/game/community-net.js
index 723b329a9..f663ae096 100644
--- a/src/game/community-net.js
+++ b/src/game/community-net.js
@@ -169,6 +169,12 @@ export class CommunityNet {
objectChange: new Set(), // (obj, id) — its transform/owner changed
objectRemove: new Set(), // (id) — an object left the world
objectReject: new Set(), // ({reason}) — server refused a spawn (world/player full)
+ // Fired once per connection, the moment the FIRST authoritative state
+ // snapshot has been decoded — i.e. every objectAdd/blockAdd the room had at
+ // join has already been emitted. `/play` uses it to retire the build it
+ // restored locally from the durable world store (P3.1), because from this
+ // point the room's own copies are in the scene and ours are duplicates.
+ synced: new Set(), // () — first full state patch applied
reaction: new Set(), // ({id, emoji}) — a player sent a floating reaction
tag: new Set(), // ({event, itId, leaderboard}) — tag mini-game state (R08)
floorBeat: new Set(), // ({clip}) — disco-pad beat tick (R06): pulses the floor + aligns standing dancers
@@ -452,6 +458,11 @@ export class CommunityNet {
this.worldTime = Number(this.room.state.worldTime) || 0;
$state?.listen?.('worldTime', (v) => { this.worldTime = Number(v) || 0; this._emit('worldtime', this.worldTime); });
+ // The first decoded state snapshot: everything the room already held
+ // (blocks, objects, vehicles) has now been emitted through the callbacks
+ // registered above. Registered AFTER them so their handlers run first.
+ this.room.onStateChange.once(() => { if (!this._destroyed && gen === this._connectGen) this._emit('synced'); });
+
this.room.onLeave((code, reason) => {
this._setStatus('offline');
// A play-pass eviction (the server dropped us because our pass expired
@@ -653,6 +664,10 @@ export class CommunityNet {
const msg = { kind: String(kind || ''), x, y, z };
if (typeof opts.type === 'string') msg.type = opts.type;
if (typeof opts.id === 'string') msg.id = opts.id;
+ // P3.3: a player-uploaded model url. The server re-validates it against the
+ // storage allow-list and refuses the spawn outright if it doesn't pass, so
+ // this is a request like any other, never a trusted value.
+ if (typeof opts.url === 'string' && opts.url) msg.url = opts.url;
if (Number.isFinite(opts.yaw)) msg.yaw = opts.yaw;
if (Number.isFinite(opts.scale)) msg.scale = opts.scale;
if (Number.isFinite(opts.vx)) msg.vx = opts.vx;
diff --git a/src/receipts-lib.js b/src/receipts-lib.js
index ce308f9a7..5832e5b43 100644
--- a/src/receipts-lib.js
+++ b/src/receipts-lib.js
@@ -124,30 +124,30 @@ export function resourceDisplay(resourceUrl) {
}
}
-// Every x402 asset we settle in is a 6-decimal stablecoin (USDC on Solana and
-// on each EVM chain). Anything else stays unformatted rather than being
-// rendered at the wrong scale.
-const SIX_DECIMAL_ASSETS = new Set([
- 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC, Solana mainnet
- '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', // USDC, Base
- '0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d', // USDC, BNB Chain
- '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // USDC, Ethereum
-]);
-
/**
* Human amount for a settled receipt, or null when we can't render it safely.
+ *
+ * The scale comes from the API's `assetDecimals` field, which the server
+ * resolves from the same env config that builds the 402 accepts. The client
+ * deliberately keeps NO copy of our asset addresses: a local registry would
+ * silently drift the day an asset is repointed, and rendering an amount at the
+ * wrong scale is worse than not rendering it. An unrecognised asset arrives
+ * with `assetDecimals: null` and stays unformatted.
+ *
* @param {string|number|null|undefined} amountAtomics
- * @param {string|null|undefined} asset
+ * @param {number|null|undefined} assetDecimals
* @returns {{ value: number, label: string }|null}
*/
-export function formatReceiptAmount(amountAtomics, asset) {
+export function formatReceiptAmount(amountAtomics, assetDecimals) {
if (amountAtomics == null || amountAtomics === '') return null;
const atomic = Number(amountAtomics);
if (!Number.isFinite(atomic)) return null;
- const key = String(asset || '').toLowerCase();
- const known = SIX_DECIMAL_ASSETS.has(String(asset || '')) || SIX_DECIMAL_ASSETS.has(key);
- if (!known) return null;
- const value = atomic / 1e6;
+ // Guard the null/undefined case BEFORE coercing: Number(null) is 0, which
+ // would pass an integer check and render a $0.01 payment as $10000.00.
+ if (assetDecimals == null) return null;
+ const decimals = Number(assetDecimals);
+ if (!Number.isInteger(decimals) || decimals < 0 || decimals > 18) return null;
+ const value = atomic / 10 ** decimals;
// Sub-cent micropayments are the norm on this rail, so show enough
// precision that a $0.001 call doesn't render as $0.00.
const label =
@@ -160,14 +160,14 @@ export function formatReceiptAmount(amountAtomics, asset) {
/**
* Total spend across rows whose amount we can render, plus how many rows had
* no recorded amount (receipts issued before settlement capture landed).
- * @param {Array<{amountAtomics?: string|null, asset?: string|null}>} rows
+ * @param {Array<{amountAtomics?: string|null, assetDecimals?: number|null}>} rows
*/
export function totalSpend(rows) {
let total = 0;
let priced = 0;
let unpriced = 0;
for (const r of rows || []) {
- const amt = formatReceiptAmount(r.amountAtomics, r.asset);
+ const amt = formatReceiptAmount(r.amountAtomics, r.assetDecimals);
if (amt) {
total += amt.value;
priced++;
diff --git a/src/receipts.js b/src/receipts.js
index 99f24d19b..cc2e15439 100644
--- a/src/receipts.js
+++ b/src/receipts.js
@@ -294,7 +294,7 @@ function renderVault() {
const when = r.issuedAt
? `<time datetime="${esc(r.issuedAt)}" title="${esc(new Date(r.issuedAt).toLocaleString())}">${esc(timeAgo(r.issuedAt))}</time>`
: '·';
- const amount = formatReceiptAmount(r.amountAtomics, r.asset);
+ const amount = formatReceiptAmount(r.amountAtomics, r.assetDecimals);
const amountCell = amount
? `<span class="rc-amount" title="${esc(r.amountAtomics)} atomic units">${esc(amount.label)}</span>`
: '';
diff --git a/tests/api/notify-in-app-gate.test.js b/tests/api/notify-in-app-gate.test.js
index 86a8f4854..d326d9e17 100644
--- a/tests/api/notify-in-app-gate.test.js
+++ b/tests/api/notify-in-app-gate.test.js
@@ -130,13 +130,29 @@ describe('insertNotification: a muted in_app category', () => {
expect(funnelEvents()).toEqual([]);
});
- it('applies to unmapped types through the account fallback category', async () => {
+ it('keeps the bell row for Account & security even when in_app is muted', async () => {
+ // 'account' is a locked in_app category (notify-prefs lockedChannelsFor):
+ // the bell is the durable record of what happened to the account, so
+ // muting it quiets push, email and telegram only. Without this, a user
+ // could hide their own security_alert and wallet_anomaly_frozen rows.
+ prefsState.stored = {
+ categories: { account: { in_app: false, push: false, email: false, telegram: false } },
+ };
+
+ const out = await insertNotification(USER, 'security_alert', {});
+
+ expect(out.in_app).toBe(true);
+ expect(inboxInserts()).toHaveLength(1);
+ expect(sendPushToUser).not.toHaveBeenCalled(); // the mutable channels still obey
+ });
+
+ it('routes unmapped types through the account fallback, so they are never silently hidden', async () => {
prefsState.stored = { categories: { account: { in_app: false } } };
const out = await insertNotification(USER, 'some_brand_new_type', {});
- expect(out.in_app).toBe(false);
- expect(inboxInserts()).toHaveLength(0);
+ expect(out.in_app).toBe(true);
+ expect(inboxInserts()).toHaveLength(1);
});
});
diff --git a/tests/check-merge-conflicts.test.js b/tests/check-merge-conflicts.test.js
new file mode 100644
index 000000000..6e1ae04ce
--- /dev/null
+++ b/tests/check-merge-conflicts.test.js
@@ -0,0 +1,122 @@
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+// Guards the guard. On 2026-07-29 a `git stash pop` conflict was committed
+// wholesale: `<<<<<<< Updated upstream` reached HEAD in production source
+// (api/chat/config.js, src/walk.js, src/avatar-garment.js) and in
+// character-studio/.gitignore. Nothing caught it, because a conflict marker is
+// a SYNTAX error rather than a lint violation, and neither eslint nor vitest
+// runs on commit.
+//
+// The subtle half is character-studio/.gitignore: that conflict had TWO nested
+// opening markers, two `=======` separators, and no closing marker at all. A
+// check that requires the OPEN/CLOSE pair calls that file clean — exactly
+// backwards, since an unterminated conflict means the merge stopped partway.
+// The "unterminated" case below is the regression test for that.
+
+const script = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ '..',
+ 'scripts',
+ 'check-merge-conflicts.mjs',
+);
+
+const OPEN = '<'.repeat(7);
+const MID = '='.repeat(7);
+const CLOSE = '>'.repeat(7);
+
+let repo;
+
+/** Run the checker inside a throwaway git repo; returns { code, stdout }. */
+function runIn(dir) {
+ try {
+ const stdout = execFileSync('node', [script], { cwd: dir, encoding: 'utf8' });
+ return { code: 0, stdout };
+ } catch (err) {
+ return { code: err.status, stdout: `${err.stdout || ''}${err.stderr || ''}` };
+ }
+}
+
+function commitAll(dir) {
+ execFileSync('git', ['add', '-A'], { cwd: dir });
+ execFileSync('git', ['-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-m', 'x', '--no-verify'], {
+ cwd: dir,
+ });
+}
+
+beforeAll(() => {
+ repo = mkdtempSync(join(tmpdir(), 'conflict-guard-'));
+ execFileSync('git', ['init', '-q'], { cwd: repo });
+ mkdirSync(join(repo, 'src'), { recursive: true });
+ writeFileSync(join(repo, 'src', 'clean.js'), 'export const ok = 1;\n');
+ commitAll(repo);
+});
+
+afterAll(() => {
+ rmSync(repo, { recursive: true, force: true });
+});
+
+describe('check-merge-conflicts', () => {
+ it('passes on a tree with no markers', () => {
+ const { code, stdout } = runIn(repo);
+ expect(code).toBe(0);
+ expect(stdout).toContain('no unresolved merge-conflict markers');
+ });
+
+ it('fails on a fully-formed conflict and names the file and line', () => {
+ writeFileSync(
+ join(repo, 'src', 'paired.js'),
+ ['const a = 1;', `${OPEN} Updated upstream`, 'const b = 2;', MID, 'const b = 3;', `${CLOSE} Stashed changes`, ''].join('\n'),
+ );
+ commitAll(repo);
+ const { code, stdout } = runIn(repo);
+ expect(code).toBe(1);
+ expect(stdout).toContain('src/paired.js');
+ expect(stdout).toContain('line 2');
+ rmSync(join(repo, 'src', 'paired.js'));
+ commitAll(repo);
+ });
+
+ it('fails on an UNTERMINATED conflict (opening marker, no closing one)', () => {
+ // The character-studio/.gitignore shape: nested opens, no close.
+ writeFileSync(
+ join(repo, 'src', 'unterminated.js'),
+ ['const a = 1;', `${OPEN} HEAD`, 'const b = 2;', MID, `${OPEN} HEAD`, 'const c = 3;', MID, ''].join('\n'),
+ );
+ commitAll(repo);
+ const { code, stdout } = runIn(repo);
+ expect(code).toBe(1);
+ expect(stdout).toContain('src/unterminated.js');
+ expect(stdout).toContain('no closing marker');
+ rmSync(join(repo, 'src', 'unterminated.js'));
+ commitAll(repo);
+ });
+
+ it('ignores a bare separator line, which is ordinary markdown', () => {
+ writeFileSync(join(repo, 'HEADING.md'), ['Title', MID, '', 'Body text.', ''].join('\n'));
+ commitAll(repo);
+ const { code } = runIn(repo);
+ expect(code).toBe(0);
+ rmSync(join(repo, 'HEADING.md'));
+ commitAll(repo);
+ });
+
+ it('ignores untracked files, so a scratch file cannot block a build', () => {
+ writeFileSync(
+ join(repo, 'scratch.js'),
+ [`${OPEN} HEAD`, 'x', MID, 'y', `${CLOSE} other`, ''].join('\n'),
+ );
+ const { code } = runIn(repo);
+ expect(code).toBe(0);
+ rmSync(join(repo, 'scratch.js'));
+ });
+
+ it('this repository is clean', () => {
+ const { code } = runIn(resolve(dirname(fileURLToPath(import.meta.url)), '..'));
+ expect(code).toBe(0);
+ });
+});
diff --git a/tests/receipts-lib.test.js b/tests/receipts-lib.test.js
index 6fbf03fac..6d7491c46 100644
--- a/tests/receipts-lib.test.js
+++ b/tests/receipts-lib.test.js
@@ -17,8 +17,9 @@ import {
totalSpend,
} from '../src/receipts-lib.js';
-const USDC_SOL = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
-const USDC_BASE = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';
+// The API supplies the scale (server-resolved from the same env config that
+// builds the 402 accepts), so these tests exercise decimals, not addresses.
+const USDC_DECIMALS = 6;
const SOL_ADDR = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
const EVM_ADDR = '0xAbCdEf0123456789aBcDeF0123456789ABCDEF01';
@@ -106,34 +107,37 @@ describe('display helpers', () => {
describe('formatReceiptAmount', () => {
it('renders 6-decimal stablecoin amounts', () => {
- expect(formatReceiptAmount('10000', USDC_SOL).label).toBe('$0.01');
- expect(formatReceiptAmount('1000000', USDC_SOL).label).toBe('$1.00');
- expect(formatReceiptAmount('2500000', USDC_BASE).label).toBe('$2.50');
+ expect(formatReceiptAmount('10000', USDC_DECIMALS).label).toBe('$0.01');
+ expect(formatReceiptAmount('1000000', USDC_DECIMALS).label).toBe('$1.00');
+ expect(formatReceiptAmount('2500000', USDC_DECIMALS).label).toBe('$2.50');
});
it('keeps precision on sub-cent micropayments instead of showing $0.00', () => {
- expect(formatReceiptAmount('1000', USDC_SOL).label).toBe('$0.001');
- expect(formatReceiptAmount('100', USDC_SOL).label).toBe('$0.0001');
+ expect(formatReceiptAmount('1000', USDC_DECIMALS).label).toBe('$0.001');
+ expect(formatReceiptAmount('100', USDC_DECIMALS).label).toBe('$0.0001');
});
- it('refuses to guess the scale of an unknown asset', () => {
- expect(formatReceiptAmount('10000', 'SomeUnknownMint1111')).toBe(null);
+ it('refuses to guess the scale when the server did not supply one', () => {
+ // An asset this deployment does not settle in arrives with a null scale.
expect(formatReceiptAmount('10000', null)).toBe(null);
+ expect(formatReceiptAmount('10000', undefined)).toBe(null);
+ expect(formatReceiptAmount('10000', 'six')).toBe(null);
+ expect(formatReceiptAmount('10000', 99)).toBe(null);
});
it('handles missing or malformed amounts', () => {
- expect(formatReceiptAmount(null, USDC_SOL)).toBe(null);
- expect(formatReceiptAmount('', USDC_SOL)).toBe(null);
- expect(formatReceiptAmount('not-a-number', USDC_SOL)).toBe(null);
+ expect(formatReceiptAmount(null, USDC_DECIMALS)).toBe(null);
+ expect(formatReceiptAmount('', USDC_DECIMALS)).toBe(null);
+ expect(formatReceiptAmount('not-a-number', USDC_DECIMALS)).toBe(null);
});
});
describe('totalSpend', () => {
it('sums priced rows and counts the unpriced ones', () => {
const s = totalSpend([
- { amountAtomics: '10000', asset: USDC_SOL },
- { amountAtomics: '1000000', asset: USDC_SOL },
- { amountAtomics: null, asset: null },
+ { amountAtomics: '10000', assetDecimals: USDC_DECIMALS },
+ { amountAtomics: '1000000', assetDecimals: USDC_DECIMALS },
+ { amountAtomics: null, assetDecimals: null },
]);
expect(s.label).toBe('$1.01');
expect(s.priced).toBe(2);
@@ -156,7 +160,7 @@ describe('receiptsToCsv', () => {
network: 'solana',
resourceUrl: 'https://three.ws/api/x402/d/prices?a="x",b',
amountAtomics: '10000',
- asset: USDC_SOL,
+ asset: 'the-settlement-asset',
transaction: 'sig1',
format: 'jws',
payer: SOL_ADDR,
diff --git a/tests/ssr-pages.test.js b/tests/ssr-pages.test.js
new file mode 100644
index 000000000..e9ab0e3c4
--- /dev/null
+++ b/tests/ssr-pages.test.js
@@ -0,0 +1,124 @@
+// Guards the server-side render that gives JS-only directory pages real content
+// before hydration (server/ssr-pages.mjs).
+//
+// The failure this protects against is silent: if the shell's markers drift, or
+// the upstream payload changes shape, /discover quietly goes back to shipping an
+// empty grid to crawlers and no-JS visitors, and nothing in CI notices.
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { __test, isSsrRoute, renderSsrPage } from '../server/ssr-pages.mjs';
+
+const root = resolve(__dirname, '..');
+const { renderDiscover, renderDiscoverCard, escapeHtml, PAGES } = __test;
+
+const sampleData = {
+ items: [
+ {
+ kind: 'onchain',
+ chainId: 8453,
+ chainShortName: 'Base',
+ agentId: '60087',
+ name: 'Weather Oracle',
+ description: 'Answers forecast questions and settles per call.',
+ has3d: true,
+ x402Support: true,
+ },
+ {
+ kind: 'onchain',
+ chainId: 1,
+ chainShortName: 'Ethereum',
+ agentId: '42',
+ name: 'Agent #42',
+ description: '',
+ has3d: false,
+ x402Support: false,
+ },
+ ],
+ totals: { all: 150065, threeD: 17936, onchain: 130559, solana: 1571 },
+};
+
+describe('ssr-pages: the /discover shell markers still match', () => {
+ it('every registered page markup marker appears exactly once in its shell', () => {
+ for (const page of PAGES) {
+ const shell = readFileSync(resolve(root, 'public', page.file), 'utf8');
+ const rendered = page.build(sampleData);
+ expect(rendered, `${page.route} produced no render`).toBeTruthy();
+ const out = page.apply(shell, rendered);
+ // apply() is a no-op when a marker has drifted; that is the exact
+ // regression this test exists to catch.
+ expect(out, `${page.route}: shell markers no longer match`).not.toBe(shell);
+ }
+ });
+
+ it('the client clears the container it renders into, so SSR content cannot duplicate', () => {
+ // public/discover/discover.js must reset the grid before rendering; without
+ // that, the injected cards would sit above the hydrated ones.
+ const client = readFileSync(resolve(root, 'public/discover/discover.js'), 'utf8');
+ expect(client).toMatch(/els\.grid\.innerHTML\s*=\s*''/);
+ });
+});
+
+describe('ssr-pages: rendering', () => {
+ it('renders a link to the on-chain detail page for on-chain agents', () => {
+ const html = renderDiscoverCard(sampleData.items[0]);
+ expect(html).toContain('href="/discover/a/8453/60087"');
+ expect(html).toContain('Weather Oracle');
+ });
+
+ it('renders badges only for the capabilities an agent actually has', () => {
+ const rich = renderDiscoverCard(sampleData.items[0]);
+ expect(rich).toContain('>3D<');
+ expect(rich).toContain('>x402<');
+ const plain = renderDiscoverCard(sampleData.items[1]);
+ expect(plain).not.toContain('>3D<');
+ expect(plain).not.toContain('>x402<');
+ });
+
+ it('formats the directory totals the same way the client does', () => {
+ const rendered = renderDiscover(sampleData);
+ expect(rendered.stats).toBe(
+ '150,065 agents · 17,936 with 3D avatars · 130,559 on EVM chains · 1,571 on Solana',
+ );
+ });
+
+ it('escapes agent-supplied text', () => {
+ // Agent names and descriptions are user/on-chain data: untrusted by default.
+ const html = renderDiscoverCard({
+ kind: 'onchain',
+ chainId: 1,
+ agentId: '1',
+ name: '<img src=x onerror=alert(1)>',
+ description: '"><script>alert(2)</script>',
+ });
+ expect(html).not.toContain('<img src=x');
+ expect(html).not.toContain('<script>');
+ expect(html).toContain('&lt;img');
+ });
+
+ it('escapes every HTML-significant character', () => {
+ expect(escapeHtml(`<>&"'`)).toBe('&lt;&gt;&amp;&quot;&#39;');
+ });
+
+ it('renders nothing when the payload carries no items, leaving the shell alone', () => {
+ expect(renderDiscover({ items: [], totals: {} })).toBeNull();
+ expect(renderDiscover({})).toBeNull();
+ expect(renderDiscover(null)).toBeNull();
+ });
+});
+
+describe('ssr-pages: failure modes never take the page down', () => {
+ it('only claims routes it is registered for', () => {
+ expect(isSsrRoute('/discover')).toBe(true);
+ expect(isSsrRoute('/discover/')).toBe(false);
+ expect(isSsrRoute('/gallery')).toBe(false);
+ });
+
+ it('falls back to the static shell when the upstream is unreachable', async () => {
+ // Port 1 refuses instantly: stands in for a dead/hanging internal API.
+ const shell = '<div class="explore-grid" data-role="grid"></div>';
+ const out = await renderSsrPage('/discover', shell, 'http://127.0.0.1:1');
+ expect(out).toBeNull();
+ });
+});