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: add watch page for 3D model generation progress

nirholas55d44fa34d68
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7a9a3f271..e4943f2f7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,11 @@
Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).
+## 2026-07-29
+
+- **Generation Watch** (`/watch`) — Live progress page for a running text-to-3D generation: real countdown, the painted concept art, and an automatic hand-off into the interactive viewer the moment the model is ready.
+- **Watch your 3D model being made, live** — Free text-to-3D generations now come with a live progress page. When a generation is still running, the API (and the three.ws 3D Studio GPT in ChatGPT) hands you a three.ws/watch link showing a real countdown, the painted concept art the generator sculpts from, and an automatic jump into the interactive 3D viewer with download and AR links the moment your model is ready. No more staring at a chat window wondering how long is left. (`/watch`) `[feature]`
+
## 2026-07-28
- **Agent Symphony** (`/symphony`) — The agent economy, played live as generative music. Every real payment, trade, launch and level-up on three.ws becomes a synthesized note in real time; record a clip and share the sound of machines doing business.
diff --git a/CLAUDE.md b/CLAUDE.md
index 2b2363684..3ad6e13d2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -32,9 +32,9 @@ Agents stopping mid-task to ask a question is a failure mode the owner explicitl
| Blocker | Resolution (do this, don't ask) |
|---|---|
| Missing env var / credential | Look in `.env` and `.env.local`, then the Cloud Run service (`gcloud run services describe three-ws-api --region us-central1 --project aerial-vehicle-466722-p5 --format=yaml`), then Secret Manager (`gcloud secrets list`). Never trust `vercel env pull` (returns empty for secrets). Update single vars with `--update-env-vars` (merges); `--set-env-vars` REPLACES the whole set, so never use it for one key. If a credential truly exists nowhere, build the feature fully wired behind the env var, prove it with a mock-free dry run, and list the single missing var in your report. |
-| A QA login for authed page testing | QA account credentials are in `.env`; the authed console sweep is `npm run audit:web`. |
+| A QA login for authed page testing | `AUDIT_EMAIL` / `AUDIT_PASSWORD` in `.env` are a real production QA account. Unauthenticated sweep: `npm run audit:web`. Authed sweep: `npm run audit:web:login`. |
| GCP access / project facts | Already authenticated in this workspace. Project `aerial-vehicle-466722-p5`, region `us-central1`. Fleet + quota + pre-approved scaling: `docs/ops/gcp-credits-plan.md`. Full production runbook (LB/DNS/TLS/env/rollback): `docs/ops/gcp-production.md`. Logs: `gcloud logging read 'resource.type="cloud_run_revision" resource.labels.service_name="three-ws-api" textPayload:"<term>"' --freshness=24h`. |
-| The database | `DATABASE_URL` in `.env` (Neon); production's authoritative copy is on the Cloud Run service env. Migrations: `npm run db:migrate` (dry-run) / `-- --apply`. `forge_creations` carries per-generation backend/status/error/prompt: the fastest ground truth for generation issues. |
+| The database | `DATABASE_URL` in `.env` (Neon); production's authoritative copy is on the Cloud Run service env. Migrations: `npm run db:status` previews pending ones, `npm run db:check` is the deploy gate (exit 4 if pending), and **`npm run db:migrate` APPLIES immediately, with no dry run** (the npm script hardcodes `--apply`). Read `db:status` before you ever run `db:migrate`; it applies every pending migration in `api/_lib/migrations/`, not just yours. `forge_creations` carries per-generation backend/status/error/prompt: the fastest ground truth for generation issues. |
| GCP quota hit | File the increase request immediately (`gcloud` or console link in your report), then route around it: lower minScale on an idle service, use another region, or queue behind existing capacity. Never park the task on the quota. |
| Third-party API down / throttled | Every lane has a failover chain (forge lanes, LLM chain, RPC providers). Use it. If a chain is missing a rung, adding one is part of the task. |
| Ambiguous product decision | Pick the option that is most reversible and closest to existing platform patterns, implement it, and record the decision + alternative in your report. A shipped reasonable default beats a stalled question. |
@@ -193,7 +193,7 @@ $THREE holders follow the public changelog (three.ws/changelog, RSS, JSON, Teleg
- **New page?** Nothing extra: the `added` date in `data/pages.json` feeds the changelog automatically.
- **Everything else users would notice** (feature, improvement, fix, SDK release, security work): append an entry to `data/changelog.json` with date, holder-readable title + summary (plain language, no commit jargon), and tags from: feature, improvement, fix, sdk, infra, docs, security. Optional `link` must be a live page path.
- `npm run build:pages` regenerates CHANGELOG.md, public/changelog.json, and public/changelog.xml. It also validates your entry and fails the build on a malformed one.
-- **Delivery to holders is automatic.** `/api/cron/changelog-push` (Cloud Scheduler, every 20 min) reads the feed baked into the running image, diffs it against DB state (`app_settings`), and posts anything new to the holders' Telegram channel (@three_ws) and the @trythreews X release thread. An entry goes out on its own shortly after the deploy that ships it; there is no manual push step. Credentials live on the Cloud Run service. Do NOT run `npm run changelog:push` / `changelog:push:x` for routine releases anymore: their file-based state (`data/changelog-*-state.json`) is separate from the cron's DB state, so a manual push double-posts. The scripts remain for `--dry-run` previews and owner-directed backfills only.
+- **Delivery to holders is automatic.** `/api/cron/changelog-push` (Cloud Scheduler, every 20 min) reads the feed baked into the running image, diffs it against DB state (`app_settings`), and posts anything new to the holders' Telegram channel (`TELEGRAM_CHANGELOG_CHAT_ID`, @three_ws). **X.com delivery is retired** (owner directive 2026-07-18): `pushXLane` and `scripts/changelog-x.mjs` stay in the tree but the cron never calls them, so do not describe X as an automatic lane. An entry goes out on its own shortly after the deploy that ships it; there is no manual push step. Credentials live on the Cloud Run service. Do NOT run `npm run changelog:push` / `changelog:push:x` for routine releases anymore: their file-based state (`data/changelog-*-state.json`) is separate from the cron's DB state, so a manual push double-posts. The scripts remain for `--dry-run` previews and owner-directed backfills only.
- Internal-only chores (CI, lockfiles, refactors with no visible effect) do NOT get entries.
## Documentation: every feature ships with its docs
@@ -266,7 +266,7 @@ The whole build + submit + purge in one command: `npm run deploy:gcp:full`.
- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).
- 3D: Three.js with glTF/GLB.
- Backend touchpoints: serverless-style handlers in `api/`, workers in `workers/`.
-- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (89 as of 2026-07-18, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file consumed by the server (routes + crons): never delete it as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.
+- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (100 as of 2026-07-29, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file consumed by the server (routes + crons): never delete it as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.
- **Env-var trap:** `vercel env pull` returns EMPTY for secret-type vars. Never trust a Vercel env export as complete. Production env lives on the Cloud Run service (`gcloud run services describe/update three-ws-api --region us-central1`).
- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.
- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.
diff --git a/README.md b/README.md
index 9592ba4a3..7e7a52f49 100644
--- a/README.md
+++ b/README.md
@@ -8871,7 +8871,7 @@ three.ws is available on major cloud marketplaces and open to infrastructure par
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **AWS** | **AWS Partner** (APN Software Path). AWS Marketplace SaaS listing in review — see [docs/aws-marketplace.md](docs/aws-marketplace.md) and the public partner page at [three.ws/aws](https://three.ws/aws). Part of the stack runs on AWS `us-east-1` — the Forge sculptor Lambda (`three-ws-forge`) and the S3 avatar bucket — registered in AWS MyApplications under account `155407237916` (the main app runs on Google Cloud Run). |
| **Alibaba Cloud** | Live: [product listing →](https://marketplace.alibabacloud.com/products/56724001/sgcmfw00036800.html) · [storefront →](https://marketplace.alibabacloud.com/store/3247293.html) |
-| **Google Cloud** | Production runs on **Google Cloud Run** (`three-ws-api`, `us-central1`) fronted by a global HTTPS load balancer + Cloud CDN, with the ~80 scheduled jobs on Cloud Scheduler and GPU inference workers on Cloud Run — a natural fit for GCP's AI infrastructure and Vertex AI. Open to co-listing, credits, and joint GTM. |
+| **Google Cloud** | Production runs on **Google Cloud Run** (`three-ws-api`, `us-central1`) fronted by a global HTTPS load balancer + Cloud CDN, with all 100 scheduled jobs on Cloud Scheduler and GPU inference workers on Cloud Run — a natural fit for GCP's AI infrastructure and Vertex AI. Open to co-listing, credits, and joint GTM. |
## Ecosystem Directories
@@ -10942,7 +10942,7 @@ npm run build # frontend build to dist/ (only when frontend changed)
npm run deploy:gcp # check:dist + db:check, gcloud builds submit, purge CDN
```
-`npm run deploy:gcp` runs `gcloud builds submit --config server/cloudbuild.yaml`. Routing, cache headers, and cron schedules are defined in `vercel.json`, which the server reads at runtime. The ~80 scheduled jobs run on **Cloud Scheduler** (provisioned by [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs)); the GPU inference workers run as their own Cloud Run services. Full ops runbook (load balancer, DNS/TLS, env, rollback, recovery): **[docs/ops/gcp-production.md](docs/ops/gcp-production.md)**.
+`npm run deploy:gcp` runs `gcloud builds submit --config server/cloudbuild.yaml`. Routing, cache headers, and cron schedules are defined in `vercel.json`, which the server reads at runtime. The scheduled jobs (100 at time of writing, one per entry in the `crons` array of `vercel.json`) run on **Cloud Scheduler** (provisioned by [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs)); the GPU inference workers run as their own Cloud Run services. Full ops runbook (load balancer, DNS/TLS, env, rollback, recovery): **[docs/ops/gcp-production.md](docs/ops/gcp-production.md)**.
**Environment variables** live on the Cloud Run service, not in `.env` files — inspect or update them with `gcloud run services describe/update three-ws-api --region us-central1`. See [Environment Variables](#environment-variables) for the full list.
diff --git a/agents/fact-checker/src/search-sources.js b/agents/fact-checker/src/search-sources.js
index 0c2ebbd4b..1838ee8bc 100644
--- a/agents/fact-checker/src/search-sources.js
+++ b/agents/fact-checker/src/search-sources.js
@@ -350,19 +350,32 @@ export async function searchWeb(query) {
}
/**
- * Run the same query across all three search queries in parallel (max 2 sources each).
- * Returns a flat deduplicated result list.
+ * Run every query in parallel and interleave the per-query result lists
+ * round-robin (query1[0], query2[0], query3[0], query1[1], …) before
+ * deduplicating.
+ *
+ * Order matters downstream: the consumer only stance-checks the first 5
+ * results, so a plain concatenation handed all five slots to query 1 and threw
+ * away the other two search angles the query generator was asked to produce.
+ * Round-robin guarantees each angle is represented in the checked set, which is
+ * what makes a contradicting source reachable when the first angle's phrasing
+ * only surfaces confirmations.
*
* @param {string[]} queries Up to 3 queries.
* @returns {Promise<Array<{url: string, title: string, snippet: string}>>}
*/
export async function searchAll(queries) {
const settled = await Promise.allSettled(queries.map((q) => searchWeb(q)));
- const combined = [];
- for (const outcome of settled) {
- if (outcome.status === 'fulfilled') {
- combined.push(...outcome.value);
+ const lists = settled
+ .filter((o) => o.status === 'fulfilled' && Array.isArray(o.value))
+ .map((o) => o.value);
+
+ const interleaved = [];
+ const depth = Math.max(0, ...lists.map((l) => l.length));
+ for (let i = 0; i < depth; i++) {
+ for (const list of lists) {
+ if (i < list.length) interleaved.push(list[i]);
}
}
- return deduplicate(combined);
+ return deduplicate(interleaved);
}
diff --git a/api/3d/studio.js b/api/3d/studio.js
index b984e7ce2..ced500cb6 100644
--- a/api/3d/studio.js
+++ b/api/3d/studio.js
@@ -17,14 +17,19 @@
//
// POST { prompt, tier? } (tier: draft | standard (default) | high)
// → 200 { status:'done', glbUrl, viewerUrl, arUrl, format, previewImageUrl?, tier? }
-// → 200 { status:'pending', job, poll, format, previewImageUrl?, tier?, etaSeconds? }
+// → 200 { status:'pending', job, poll, watchUrl, format, previewImageUrl?, tier?, etaSeconds? }
// → 400 { error:'prompt_rejected', message } (safety gate refusal)
//
// GET ?job=<id>&title=<prompt> (title optional — labels the AR/viewer pages)
-// → 200 { status:'pending', job, poll, previewImageUrl?, tier? }
+// → 200 { status:'pending', job, poll, watchUrl, previewImageUrl?, tier? }
// → 200 { status:'done', glbUrl, viewerUrl, arUrl, format, previewImageUrl?, tier? }
// → 200 { status:'error', error } (upstream failed — retry is free)
//
+// watchUrl is the live progress page (public/watch.html): a three.ws link the
+// GPT hands the user on pending states so they can watch the countdown and the
+// concept image in a real browser tab instead of waiting inside the chat. When
+// the job finishes, that page forwards itself into the /viewer funnel.
+//
// previewImageUrl is the forge's painted concept view — the image-generation
// first step of the text path — surfaced on pending states so the GPT can show
// the user what is being sculpted while the mesh is still generating.
@@ -96,6 +101,7 @@ export function shapeSubmit(job, base, prompt) {
status: 'pending',
job: handle,
poll: handle ? `/api/3d/studio?job=${encodeURIComponent(handle)}${t}` : null,
+ ...(handle ? { watchUrl: `${base}/watch?job=${encodeURIComponent(handle)}${t}` } : {}),
format: 'glb',
...(preview ? { previewImageUrl: preview } : {}),
...(tier ? { tier } : {}),
@@ -141,6 +147,7 @@ export function shapePoll(data, base, jobId, title) {
status: 'pending',
job: jobId,
poll: `/api/3d/studio?job=${encodeURIComponent(jobId)}${t}`,
+ watchUrl: `${base}/watch?job=${encodeURIComponent(jobId)}${t}`,
...(preview ? { previewImageUrl: preview } : {}),
...(tier ? { tier } : {}),
...(Number.isFinite(etaRemaining) && etaRemaining > 0 ? { etaSeconds: Math.round(etaRemaining) } : {}),
diff --git a/api/_lib/llm-pricing.js b/api/_lib/llm-pricing.js
index f31e741df..bd2890e89 100644
--- a/api/_lib/llm-pricing.js
+++ b/api/_lib/llm-pricing.js
@@ -75,10 +75,25 @@ function priceForModel(model) {
return best ? PRICE_PER_MTOK[best] : null;
}
+// Anthropic prompt-cache multipliers against the model's base INPUT price.
+// A cache write costs more than a plain input token; a cache read costs a
+// tenth. These are ratios, not prices, so they stay correct as list prices
+// move. We only ever send the default 5-minute TTL (`{type:'ephemeral'}` with
+// no `ttl`), whose write multiplier is 1.25 — the 1h TTL's 2x does not apply.
+const CACHE_WRITE_MULTIPLIER = 1.25;
+const CACHE_READ_MULTIPLIER = 0.1;
+
// Compute the cost of one completion in micro-USD. Returns an integer (rounded)
// or 0 when the provider is free or the model is unpriced — never null, so the
// caller can always record a numeric cost.
-export function costMicroUsd({ provider, model, input = 0, output = 0 } = {}) {
+//
+// `cacheWrite`/`cacheRead` are the Anthropic prompt-caching token counts
+// (`usage.cache_creation_input_tokens` / `usage.cache_read_input_tokens`).
+// They are DISJOINT from `input`: on a cached request the API reports
+// `input_tokens` as the uncached remainder only, so the three must be summed
+// (at their own rates) to price the full prompt. Omitting them would silently
+// under-report spend on every cached call.
+export function costMicroUsd({ provider, model, input = 0, output = 0, cacheWrite = 0, cacheRead = 0 } = {}) {
// A paid/BYOK model draws real spend even when its transport provider is an
// otherwise-free tier (e.g. OpenRouter Granite), so it is metered by its list
// price below rather than zeroed. Genuinely-free models still short-circuit.
@@ -91,7 +106,11 @@ export function costMicroUsd({ provider, model, input = 0, output = 0 } = {}) {
if (!price) return 0;
const [inPerM, outPerM] = price;
// tokens / 1e6 * usdPerM * 1e6 micro-usd == tokens * usdPerM
- const usdMicros = input * inPerM + output * outPerM;
+ const usdMicros =
+ input * inPerM +
+ output * outPerM +
+ cacheWrite * inPerM * CACHE_WRITE_MULTIPLIER +
+ cacheRead * inPerM * CACHE_READ_MULTIPLIER;
return Math.round(usdMicros);
}
diff --git a/api/_lib/llm.js b/api/_lib/llm.js
index 5c49c37dc..9dc7c9057 100644
--- a/api/_lib/llm.js
+++ b/api/_lib/llm.js
@@ -198,6 +198,18 @@ function anthropicSystemField(system) {
return system;
}
+// Anthropic reports `input_tokens` as the UNCACHED remainder once caching is in
+// play, with cache hits/writes on their own counters. Surfacing all three keeps
+// spend metering honest (see recordLlmSpend / costMicroUsd).
+function anthropicUsage(r) {
+ return {
+ input: r.usage?.input_tokens ?? 0,
+ output: r.usage?.output_tokens ?? 0,
+ cacheWrite: r.usage?.cache_creation_input_tokens ?? 0,
+ cacheRead: r.usage?.cache_read_input_tokens ?? 0,
+ };
+}
+
function anthropicProvider(key, model) {
const m = model || ANTHROPIC_MODEL;
return {
@@ -216,7 +228,7 @@ function anthropicProvider(key, model) {
messages: [{ role: 'user', content: user }],
}),
extractText: anthropicText,
- extractUsage: (r) => ({ input: r.usage?.input_tokens ?? 0, output: r.usage?.output_tokens ?? 0 }),
+ extractUsage: anthropicUsage,
};
}
@@ -240,7 +252,7 @@ function vertexAnthropicProvider(model) {
messages: [{ role: 'user', content: user }],
}),
extractText: anthropicText,
- extractUsage: (r) => ({ input: r.usage?.input_tokens ?? 0, output: r.usage?.output_tokens ?? 0 }),
+ extractUsage: anthropicUsage,
};
}
@@ -626,13 +638,18 @@ export async function llmComplete({ system, user, maxTokens = 1024, anthropicKey
function recordLlmSpend(provider, usage, latencyMs, track) {
const input = usage?.input ?? 0;
const output = usage?.output ?? 0;
+ // Prompt-cache tokens are reported separately from `input` (which is the
+ // uncached remainder), so they are added to inputTokens for the "how big was
+ // the prompt" view and priced at their own rates by costMicroUsd.
+ const cacheWrite = usage?.cacheWrite ?? 0;
+ const cacheRead = usage?.cacheRead ?? 0;
recordEvent({
kind: 'llm',
provider: provider.name,
model: provider.model,
- inputTokens: input,
+ inputTokens: input + cacheWrite + cacheRead,
outputTokens: output,
- costMicroUsd: costMicroUsd({ provider: provider.name, model: provider.model, input, output }),
+ costMicroUsd: costMicroUsd({ provider: provider.name, model: provider.model, input, output, cacheWrite, cacheRead }),
latencyMs,
userId: track?.userId ?? null,
agentId: track?.agentId ?? null,
diff --git a/api/_lib/migrations/2026-07-28-x402-receipt-settlement.sql b/api/_lib/migrations/2026-07-28-x402-receipt-settlement.sql
new file mode 100644
index 000000000..20151f026
--- /dev/null
+++ b/api/_lib/migrations/2026-07-28-x402-receipt-settlement.sql
@@ -0,0 +1,22 @@
+-- Migration: record the settlement amount + asset alongside each x402 receipt.
+-- Apply: npm run db:migrate -- --apply --file 2026-07-28-x402-receipt-settlement.sql
+-- Idempotent.
+--
+-- The signed receipt artifact follows spec §5.1 and carries no amount, and it
+-- omits the transaction hash entirely when the endpoint declares
+-- includeTxHash=false (spec §5.2 privacy default). That is correct for the
+-- wire, but it left our own durable log unable to answer the buyer's first
+-- question: "what did I actually pay for this?"
+--
+-- These columns hold the settlement facts we already had in hand at issue time
+-- (from the verified payment requirement and the facilitator's settle
+-- response). They are OUR audit trail, not part of the signed artifact, so the
+-- wire format and its privacy properties are unchanged. /api/x402/my-receipts
+-- only ever returns them to the wallet that signed for its own receipts.
+
+begin;
+
+alter table x402_receipts add column if not exists amount_atomics text;
+alter table x402_receipts add column if not exists asset text;
+
+commit;
diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.js
index 85ff4294d..dfe450bab 100644
--- a/api/_lib/solana/connection.js
+++ b/api/_lib/solana/connection.js
@@ -28,6 +28,8 @@
import { Connection } from '@solana/web3.js';
+import { cacheGet, cacheSet } from '../cache.js';
+
function deriveWsUrl(httpUrl) {
return String(httpUrl)
.replace(/^https:/, 'wss:')
@@ -183,11 +185,75 @@ const PUBLIC_MAINNET = 'https://api.mainnet-beta.solana.com';
const PUBLIC_DEVNET = 'https://api.devnet.solana.com';
// Process-wide endpoint cooldown, keyed by full URL. Shared across every
-// Connection built in this lambda instance — both solanaConnection() and
-// RpcFallback — so once one provider reports quota-exhausted, ALL callers skip
-// it until it recovers. Per-instance state is correct on Vercel: it self-heals
-// on cooldown expiry and a cold start simply re-probes.
+// Connection built in this instance (both solanaConnection() and RpcFallback),
+// so once one provider reports quota-exhausted, ALL callers skip it until it
+// recovers.
+//
+// The breaker is also FLEET-WIDE, mirrored through the shared cache. A
+// per-instance map alone was correct on Vercel's short-lived lambdas but is a
+// real cost on Cloud Run: the map dies with every cold start, so each fresh
+// instance re-discovers an exhausted quota the hard way, burning one more
+// doomed request against a provider that is already over its cap. On a DAILY
+// cap (QuickNode's -32003) that is actively harmful, since the wasted probes
+// are themselves what keeps the account pinned at its ceiling. Publishing the
+// verdict to L2 and inheriting it on the first call collapses fleet-wide waste
+// to roughly one probe per window. Same pattern, same reasoning as the
+// market-data breaker in api/_lib/market/token-market.js.
const _endpointCooldown = new Map();
+const COOLDOWN_CACHE_KEY = 'rpccool:v1';
+// Re-read the shared verdict at most this often per instance; the first call on
+// a cold instance always awaits one read (that is the case worth paying for).
+const COOLDOWN_HYDRATE_MS = 60_000;
+let _cooldownHydratedAt = 0;
+let _cooldownHydrateInFlight = null;
+
+// Merge still-active shared cooldowns into the in-process map. Best-effort: a
+// cache miss or error leaves the local map as-is and the request proceeds.
+async function readSharedCooldowns() {
+ try {
+ const shared = await cacheGet(COOLDOWN_CACHE_KEY);
+ if (!shared || typeof shared !== 'object') return;
+ const now = Date.now();
+ for (const [url, until] of Object.entries(shared)) {
+ const ms = Number(until);
+ if (ms > now && ms > (_endpointCooldown.get(url) || 0)) _endpointCooldown.set(url, ms);
+ }
+ } catch {
+ /* local breaker still applies */
+ }
+}
+
+/**
+ * Inherit the fleet's view of dead endpoints. Awaited once per cold instance so
+ * the very first request already skips a quota-exhausted provider; refreshed in
+ * the background afterwards so steady-state RPC calls pay no cache round trip.
+ */
+export async function hydrateEndpointCooldowns(now = Date.now()) {
+ if (now - _cooldownHydratedAt < COOLDOWN_HYDRATE_MS) return;
+ if (_cooldownHydrateInFlight) return _cooldownHydrateInFlight;
+ _cooldownHydrateInFlight = readSharedCooldowns().finally(() => {
+ _cooldownHydratedAt = Date.now();
+ _cooldownHydrateInFlight = null;
+ });
+ return _cooldownHydrateInFlight;
+}
+
+// Publish the in-process cooldowns (only those still active) so siblings inherit
+// them. TTL tracks the longest remaining window; once it lapses the key vanishes
+// and endpoints are retried. Fire-and-forget by design: parking an endpoint must
+// never wait on, or fail because of, the cache.
+function publishCooldowns(now) {
+ const active = {};
+ let maxRemainingMs = 0;
+ for (const [url, until] of _endpointCooldown) {
+ if (until > now) {
+ active[url] = until;
+ maxRemainingMs = Math.max(maxRemainingMs, until - now);
+ }
+ }
+ if (maxRemainingMs <= 0) return;
+ cacheSet(COOLDOWN_CACHE_KEY, active, Math.ceil(maxRemainingMs / 1000)).catch(() => {});
+}
function cooldownMsFor(status, bodyText) {
if (status === 429) {
@@ -222,7 +288,12 @@ export function isEndpointCooling(url) {
*/
export function markEndpointCooldown(url, status, bodyText) {
const ms = cooldownMsFor(status, bodyText);
- _endpointCooldown.set(url, Date.now() + ms);
+ const now = Date.now();
+ _endpointCooldown.set(url, now + ms);
+ // Only quota/auth-class parks are worth telling the fleet about. A 30s network
+ // blip would churn the shared key for no benefit, and a sibling re-probing a
+ // briefly-flaky node is exactly the behaviour we want to keep.
+ if (ms >= RATE_LIMIT_COOLDOWN_MS) publishCooldowns(now);
return ms;
}
@@ -269,6 +340,20 @@ function lastResortUrls() {
.filter(Boolean);
}
+// The caller's explicit `url` is pinned at priority 1 — but ~35 call sites spell
+// their default as `process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com'`,
+// so whenever SOLANA_RPC_URL is unset they would pin the single most-throttled
+// endpoint in the chain AHEAD of Helius and every paid lane, silently inverting
+// the whole priority order. A bare public-cluster URL is that default leaking
+// through, never a deliberate choice, so it does not earn the pin. The endpoint
+// is NOT dropped: it still serves at its natural position near the end of the
+// free set, so behaviour degrades to the designed order instead of to nothing.
+function pinnedUrl(url) {
+ const v = normalizeRpcUrl(url);
+ if (!v) return '';
+ return v === PUBLIC_MAINNET || v === PUBLIC_DEVNET ? '' : v;
+}
+
/**
* Priority-ordered endpoint list for a network. An explicit `url` (the value a
* call site already resolved) is pinned first; keyed providers, then any
@@ -289,7 +374,7 @@ export function solanaRpcEndpoints(network = 'mainnet', url = null) {
// .filter(isHttpUrl) is the hard guarantee: only a value `new Connection`
// accepts survives, so a malformed env entry can never reach the constructor.
return dedupe([
- normalizeRpcUrl(url),
+ pinnedUrl(url),
normalizeRpcUrl(process.env.SOLANA_RPC_URL_DEVNET),
// QuickNode — a full dedicated endpoint URL (key embedded in the path), so
// it takes a URL var rather than an api-key. Premium/reliable, placed high.
@@ -301,7 +386,7 @@ export function solanaRpcEndpoints(network = 'mainnet', url = null) {
]).filter(isHttpUrl);
}
return dedupe([
- normalizeRpcUrl(url),
+ pinnedUrl(url),
normalizeRpcUrl(process.env.SOLANA_RPC_URL),
// QuickNode — a full dedicated endpoint URL (key embedded in the path), so it
// takes a URL var rather than an api-key. A premium paid lane: placed right
@@ -596,6 +681,13 @@ export function makeRotatingFetch(endpoints) {
}
};
+ // Inherit the fleet's verdict before choosing an endpoint, so a cold
+ // instance's very first call already skips a quota-dead provider instead of
+ // re-burning it. Awaited only on the first call of this instance; later
+ // refreshes run in the background (see hydrateEndpointCooldowns).
+ if (_cooldownHydratedAt === 0) await hydrateEndpointCooldowns();
+ else hydrateEndpointCooldowns();
+
let lastErr = null;
// Pass 1 skips endpoints currently in cooldown. Pass 2 runs ONLY when pass 1
// tried nothing (every endpoint was already cooling) — it ignores cooldowns so
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index cfadbdd8d..2341e6096 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -871,7 +871,10 @@ async function classifyAvatarImage({ thumbUrl, prompt, env }) {
});
if (!r.ok) throw Object.assign(new Error(`anthropic vision ${r.status}`), { code: 'vision_api_error' });
const d = await r.json();
- return d.content?.[0]?.text || '';
+ // Pick the first TEXT block rather than content[0]: on a thinking-capable
+ // model the leading block is a (possibly empty) thinking block, which
+ // would silently classify every avatar as untagged.
+ return (d.content || []).find((b) => b?.type === 'text')?.text || '';
});
}
if (!attempts.length) {
diff --git a/api/chat.js b/api/chat.js
index 490665914..0beee3fea 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -984,8 +984,18 @@ export default wrap(async (req, res) => {
// from the first-party 'anthropic' provider so spend/usage reporting can
// attribute GCP-credit traffic; falls back to the provider name otherwise.
provider: route.via || route.name,
- input_tokens: result.inputTokens,
+ // Full prompt size: on a cached Anthropic turn `input_tokens` is only
+ // the uncached remainder, so the cache counters are folded back in
+ // (and reported separately for cache-hit-rate visibility).
+ input_tokens:
+ result.inputTokens + (result.cacheWriteTokens ?? 0) + (result.cacheReadTokens ?? 0),
output_tokens: result.outputTokens,
+ ...(result.cacheReadTokens || result.cacheWriteTokens
+ ? {
+ cache_read_tokens: result.cacheReadTokens ?? 0,
+ cache_write_tokens: result.cacheWriteTokens ?? 0,
+ }
+ : {}),
actions: governedActions.map((a) => a.type),
governance: governance?.decision ?? null,
has_context: Boolean(body.context?.modelName),
@@ -1433,6 +1443,12 @@ async function streamAnthropic(upstream, sendSSE) {
const blocks = {};
let inputTokens = 0;
let outputTokens = 0;
+ // Prompt-cache counters. Anthropic reports input_tokens as the UNCACHED
+ // remainder once a cache breakpoint is in play, so these must be added back
+ // to get the true prompt size (and are reported separately so the dashboard
+ // can see how well the persona-prefix cache is working).
+ let cacheWriteTokens = 0;
+ let cacheReadTokens = 0;
try {
while (true) {
@@ -1453,6 +1469,8 @@ async function streamAnthropic(upstream, sendSSE) {
}
if (evt.type === 'message_start') {
inputTokens = evt.message?.usage?.input_tokens ?? 0;
+ cacheWriteTokens = evt.message?.usage?.cache_creation_input_tokens ?? 0;
+ cacheReadTokens = evt.message?.usage?.cache_read_input_tokens ?? 0;
} else if (evt.type === 'content_block_start') {
const cb = evt.content_block;
blocks[evt.index] = { type: cb.type, name: cb.name, partialJson: '' };
@@ -1477,10 +1495,10 @@ async function streamAnthropic(upstream, sendSSE) {
}
}
} catch (err) {
- return { error: err, reply, actions, inputTokens, outputTokens };
+ return { error: err, reply, actions, inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens };
}
- return { reply, actions, inputTokens, outputTokens };
+ return { reply, actions, inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens };
}
async function streamOpenAI(upstream, sendSSE) {
diff --git a/api/llm/anthropic.js b/api/llm/anthropic.js
index 1c8482ace..a24838e94 100644
--- a/api/llm/anthropic.js
+++ b/api/llm/anthropic.js
@@ -726,6 +726,12 @@ export default wrap(async (req, res) => {
let inputTokens = 0;
let outputTokens = 0;
+ // Prompt-cache counters ride alongside input_tokens on message_start and
+ // are DISJOINT from it (input_tokens is the uncached remainder once a
+ // cache breakpoint is in play). Tracked separately so the quota counts
+ // the true prompt size and costMicroUsd can price each at its own rate.
+ let cacheWriteTokens = 0;
+ let cacheReadTokens = 0;
if (route.kind === 'anthropic') {
// Pass upstream Anthropic SSE through verbatim; sniff usage events
@@ -745,8 +751,11 @@ export default wrap(async (req, res) => {
if (!line.startsWith('data: ')) continue;
try {
const ev = JSON.parse(line.slice(6));
- if (ev.type === 'message_start')
+ if (ev.type === 'message_start') {
inputTokens = ev.message?.usage?.input_tokens ?? 0;
+ cacheWriteTokens = ev.message?.usage?.cache_creation_input_tokens ?? 0;
+ cacheReadTokens = ev.message?.usage?.cache_read_input_tokens ?? 0;
+ }
if (ev.type === 'message_delta')
outputTokens = ev.usage?.output_tokens ?? 0;
} catch {
@@ -765,9 +774,12 @@ export default wrap(async (req, res) => {
}
const latencyMs = Date.now() - t0;
- if (inputTokens || outputTokens) {
+ // Cache tokens are part of the prompt the agent actually sent, so they
+ // count against the monthly token budget even though they bill cheaper.
+ const promptTokens = inputTokens + cacheWriteTokens + cacheReadTokens;
+ if (promptTokens || outputTokens) {
try {
- await addMonthlyTokens(agentId, inputTokens + outputTokens);
+ await addMonthlyTokens(agentId, promptTokens + outputTokens);
} catch (err) {
log.warn('token_counter_write_failed', { agentId, msg: err?.message });
}
@@ -781,19 +793,23 @@ export default wrap(async (req, res) => {
status: 'ok',
provider: via,
model: usedModel,
- inputTokens,
+ inputTokens: promptTokens,
outputTokens,
costMicroUsd: costMicroUsd({
provider: via,
model: usedModel,
input: inputTokens,
output: outputTokens,
+ cacheWrite: cacheWriteTokens,
+ cacheRead: cacheReadTokens,
}),
meta: {
model: usedModel,
requested_model: requestedModel,
- input_tokens: inputTokens,
+ input_tokens: promptTokens,
output_tokens: outputTokens,
+ cache_write_tokens: cacheWriteTokens,
+ cache_read_tokens: cacheReadTokens,
upstream_status: upstream.status,
},
});
@@ -813,12 +829,18 @@ export default wrap(async (req, res) => {
let inputTokens = 0;
let outputTokens = 0;
+ // Disjoint from inputTokens once a cache breakpoint is in play — see the
+ // streaming path above.
+ let cacheWriteTokens = 0;
+ let cacheReadTokens = 0;
let outBody = upstreamText;
let outContentType = upstream.headers.get('content-type') || 'application/json';
if (route.kind === 'anthropic') {
inputTokens = upstreamJson?.usage?.input_tokens ?? 0;
outputTokens = upstreamJson?.usage?.output_tokens ?? 0;
+ cacheWriteTokens = upstreamJson?.usage?.cache_creation_input_tokens ?? 0;
+ cacheReadTokens = upstreamJson?.usage?.cache_read_input_tokens ?? 0;
} else if (upstreamJson) {
inputTokens = upstreamJson?.usage?.prompt_tokens ?? 0;
outputTokens = upstreamJson?.usage?.completion_tokens ?? 0;
@@ -827,9 +849,10 @@ export default wrap(async (req, res) => {
outContentType = 'application/json';
}
- if (inputTokens || outputTokens) {
+ const promptTokens = inputTokens + cacheWriteTokens + cacheReadTokens;
+ if (promptTokens || outputTokens) {
try {
- await addMonthlyTokens(agentId, inputTokens + outputTokens);
+ await addMonthlyTokens(agentId, promptTokens + outputTokens);
} catch (err) {
log.warn('token_counter_write_failed', { agentId, msg: err?.message });
}
@@ -844,19 +867,23 @@ export default wrap(async (req, res) => {
status: 'ok',
provider: via,
model: usedModel,
- inputTokens,
+ inputTokens: promptTokens,
outputTokens,
costMicroUsd: costMicroUsd({
provider: via,
model: usedModel,
input: inputTokens,
output: outputTokens,
+ cacheWrite: cacheWriteTokens,
+ cacheRead: cacheReadTokens,
}),
meta: {
model: usedModel,
requested_model: requestedModel,
- input_tokens: inputTokens,
+ input_tokens: promptTokens,
output_tokens: outputTokens,
+ cache_write_tokens: cacheWriteTokens,
+ cache_read_tokens: cacheReadTokens,
upstream_status: upstream.status,
},
});
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index a3ceb6a38..2e913356f 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -30,6 +30,7 @@ import {
vertexGeminiChatUrl,
vertexGeminiHeaders,
} from '../_lib/vertex-gemini.js';
+import { modelThinksByDefault } from '../_lib/chat-models.js';
import { getSkillPrices, skillPriceMap } from '../_lib/skill-price-cache.js';
import { viewerNftGatedSkills } from '../_lib/nft-gate.js';
import { z } from 'zod';
@@ -1100,7 +1101,11 @@ export function buildPreviewRoutes() {
},
buildPayload: ({ systemPrompt, history }) => ({
model,
- max_tokens: 512,
+ // A preview reply is short, but on a thinking-by-default model
+ // max_tokens covers thinking AND the visible text — a 512 cap
+ // there returns an empty preview. Floor it for those ids only,
+ // so the default (Haiku) keeps its tight, cheap budget.
+ max_tokens: modelThinksByDefault(model) ? 4096 : 512,
system: systemPrompt,
messages: history,
stream: true,
diff --git a/data/_generated/fact-check-benchmark.json b/data/_generated/fact-check-benchmark.json
index c264bb7d0..fc68d31a6 100644
--- a/data/_generated/fact-check-benchmark.json
+++ b/data/_generated/fact-check-benchmark.json
@@ -1,17 +1,17 @@
{
- "generated_at": "2026-07-08T01:46:16.570Z",
- "endpoint": "in-process:api/x402/fact-check.js#_checkClaim (real chain, no HTTP/x402 payment layer — see prompts/x402-catalog/PROGRESS.md for why)",
+ "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": 8,
- "errors": 3,
- "accuracy_pct": 20,
+ "correct": 3,
+ "errors": 30,
+ "accuracy_pct": 7.5,
"by_class": {
"supported": {
"total": 10,
- "correct": 0,
- "accuracy_pct": 0
+ "correct": 1,
+ "accuracy_pct": 10
},
"contradicted": {
"total": 10,
@@ -20,45 +20,45 @@
},
"mixed": {
"total": 10,
- "correct": 8,
- "accuracy_pct": 80
+ "correct": 0,
+ "accuracy_pct": 0
},
"insufficient": {
"total": 10,
- "correct": 0,
- "accuracy_pct": 0
+ "correct": 2,
+ "accuracy_pct": 20
}
},
"by_difficulty": {
"easy": {
"total": 13,
- "correct": 0,
- "accuracy_pct": 0
+ "correct": 1,
+ "accuracy_pct": 7.7
},
"medium": {
"total": 20,
- "correct": 5,
- "accuracy_pct": 25
+ "correct": 2,
+ "accuracy_pct": 10
},
"hard": {
"total": 7,
- "correct": 3,
- "accuracy_pct": 42.9
+ "correct": 0,
+ "accuracy_pct": 0
}
},
"confusion": {
"supported": {
- "mixed": 10
+ "insufficient": 2,
+ "supported": 1
},
"contradicted": {
- "mixed": 9
+ "insufficient": 2
},
"mixed": {
- "mixed": 8,
- "contradicted": 1
+ "insufficient": 3
},
"insufficient": {
- "mixed": 9
+ "insufficient": 2
}
}
}
diff --git a/data/changelog.json b/data/changelog.json
index 8194dc40b..ada95d080 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -16446,6 +16446,15 @@
"tags": [
"fix"
]
+ },
+ {
+ "date": "2026-07-29",
+ "title": "Watch your 3D model being made, live",
+ "summary": "Free text-to-3D generations now come with a live progress page. When a generation is still running, the API (and the three.ws 3D Studio GPT in ChatGPT) hands you a three.ws/watch link showing a real countdown, the painted concept art the generator sculpts from, and an automatic jump into the interactive 3D viewer with download and AR links the moment your model is ready. No more staring at a chat window wondering how long is left.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/watch"
}
]
}
diff --git a/data/pages.json b/data/pages.json
index 509702720..77a7c3be2 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -850,6 +850,14 @@
"changefreq": "monthly",
"added": "2026-07-08"
},
+ {
+ "path": "/watch",
+ "title": "Generation Watch",
+ "description": "Live progress page for a running text-to-3D generation: real countdown, the painted concept art, and an automatic hand-off into the interactive viewer the moment the model is ready.",
+ "priority": 0.4,
+ "changefreq": "monthly",
+ "added": "2026-07-29"
+ },
{
"path": "/ar",
"title": "AR Forge",
diff --git a/docs/animations.md b/docs/animations.md
index 8b0e2ec74..43655caf8 100644
--- a/docs/animations.md
+++ b/docs/animations.md
@@ -27,7 +27,7 @@ There are 5 animation collections across the codebase. They are separate and use
## Adding a new animation to the runtime
-1. Drop the FBX into `public/animations/`
+1. Drop the FBX into `animation-sources/` (the build's first-choice source directory, gitignored so raw sources never ship). Dropping it into `public/animations/` also resolves, but that directory is served publicly, so the multi-megabyte FBX would be deployed to production alongside the built clip.
2. Add an entry to `scripts/animations.config.json`
3. Run `node scripts/build-animations.mjs` (or `npm run build:animations`) — retargets to the Avaturn rig, writes a JSON clip to `public/animations/clips/`, and updates `manifest.json`
4. Update `public/animations/registry.json` so the new clip is catalogued under the `clips` collection
@@ -49,7 +49,7 @@ Hip units are detected from the clip data, not the file extension. Raw Mixamo FB
### If a source file is missing
-Some retarget sources are deliberately never committed (`animation-sources/mx-*.fbx` is gitignored), so a clean checkout will not have them. When a configured clip's source is absent but its built JSON is already in `clips/`, the build republishes the built clip and logs `PREBUILT`. Only an entry with neither a source nor a built clip fails. Retiring a clip is therefore done by removing its config entry, not by deleting its source.
+Retarget sources are deliberately never committed: the whole `animation-sources/` directory is gitignored, so a clean checkout has none of them and the built clips in `clips/` are the shipped artifact. When a configured clip's source is absent but its built JSON is already in `clips/`, the build republishes the built clip and logs `PREBUILT`. That is the normal path on a fresh clone, not an edge case. Only an entry with neither a source nor a built clip fails, and the failure message points at `npm run extract:animations` to regenerate extracted sources. Retiring a clip is therefore done by removing its config entry, not by deleting its source.
## Agent slots
diff --git a/docs/chatgpt-3d-studio-gpt.md b/docs/chatgpt-3d-studio-gpt.md
new file mode 100644
index 000000000..8cc956a3e
--- /dev/null
+++ b/docs/chatgpt-3d-studio-gpt.md
@@ -0,0 +1,159 @@
+# The "three.ws 3D Studio" custom GPT: builder configuration
+
+This is the canonical configuration for the **three.ws 3D Studio** custom GPT in the ChatGPT GPT Store. The action contract it calls is served from [public/.well-known/3d-studio-openapi.yaml](../public/.well-known/3d-studio-openapi.yaml) (live at `https://three.ws/.well-known/3d-studio-openapi.yaml`) and documented in [AR in ChatGPT](./chatgpt-ar.md). The GPT itself is configured by hand in the ChatGPT builder UI, so this file is the source of truth to paste from. If you change the GPT in the builder, mirror the change here in the same commit.
+
+## Why this file exists
+
+QA on 2026-07-29 found the GPT failing in two of the four suggested-prompt flows:
+
+- "Make me a low-poly fox for my game" produced a DALL-E image, never called the action, and returned no model at all.
+- "Create a dragon miniature" produced a DALL-E image plus two fabricated links (`three.ws/models/<id>.glb` and `three.ws/preview/<id>`). Neither route exists; both returned 404 when checked. Real responses carry an R2 `glbUrl` and a `three.ws/viewer?src=...` URL, never `/models/` or `/preview/` paths.
+- "Create a 3D mascot" stalled on clarifying questions instead of generating.
+- "Surprise me" worked end to end (action call, poll, real links, viewer loads).
+
+Three root causes, all in builder configuration:
+
+1. **Image Generation capability enabled.** With DALL-E available, the model sometimes satisfies "make me a fox" by painting a picture instead of calling the action. Style-section rules like "do not return .png" do not reliably stop it; only unchecking the capability does.
+2. **The instruction "Always return GLB files links from https://three.ws".** Real GLB downloads live on `pub-*.r2.dev` CDN URLs, so this rule pushed the model to fabricate plausible three.ws-hosted links (`/models/...`, `/preview/...`) when it had skipped the action. The corrected instructions say the opposite: present URLs exactly as returned, and the R2 host is correct.
+3. **Stale action schema.** The builder held an inline paste of an old spec revision without `arUrl`, `previewImageUrl`, `tier`, `etaSeconds`, or the title-carrying poll path, so the GPT could not offer AR links or show concept images while waiting.
+
+## Builder settings
+
+| Setting | Value |
+|---|---|
+| Name | three.ws 3D Studio |
+| Description | Turn any idea into a real, downloadable 3D model. Describe it ("a low-poly fox", "a ceramic robot") and get a GLB you can open, spin, and download. Free. |
+| Capabilities: Web Search | Off |
+| Capabilities: Apps (Beta) | Off |
+| Capabilities: Image Generation | **Off (load-bearing: with it on, the GPT paints images instead of calling the action)** |
+| Capabilities: Code Interpreter & Data Analysis | Off |
+| Recommended Model | None |
+| Action | Import from URL: `https://three.ws/.well-known/3d-studio-openapi.yaml` (re-import after any spec change; never hand-edit the schema inline) |
+| Action auth | None |
+| Action privacy policy | `https://three.ws/legal/privacy.html` |
+| Conversation starters | Make me a low-poly fox for my game / Sculpt a detailed dragon miniature for my tabletop campaign / Make a cute robot buddy I can put on my desk in AR / Surprise me with something cool in 3D |
+
+Starter design rule: every starter must name ONE concrete subject so the GPT can generate immediately without clarifying questions ("Create a 3D mascot for my community" was dropped for stalling on questions), and at least one starter should surface the AR placement link. Alternates to rotate in: "Turn my initials into a chrome 3D logo", "Make a ceramic mug shaped like a sleepy cat", "Create a treasure chest prop for my indie game", "Make a crystal jellyfish I can spin in my browser".
+
+## Instructions (paste verbatim into the builder)
+
+```
+You are three.ws 3D Studio. You turn a user's text description into a real,
+downloadable 3D model (GLB) by calling the three.ws generation Actions. You
+are a friendly, practical 3D-modeling assistant for hobbyists, students, game
+makers, and designers.
+
+THE ONE IRON RULE
+- The ONLY way you produce a model is the generate3DModel action. Never use
+ image generation, never present a picture as the result, and never show a
+ URL that an action did not return in this conversation. The only image you
+ may ever show is the previewImageUrl field from an action response. If you
+ have no URL from an action, you have no model.
+
+WHAT YOU DO
+- When the user describes an object, character, mascot, prop, or creature,
+ call generate3DModel immediately. For a single subject, do not ask
+ clarifying questions first: pick tasteful defaults (style, colors, pose),
+ state in one line what you chose, and generate. "Surprise me" means invent
+ one concrete, fun subject and generate it right away.
+- Rewrite vague requests into ONE concrete subject before calling. A good
+ prompt names the subject, its style, and key colors: "a low-poly orange fox
+ sitting down", "a small ceramic robot figurine with round eyes". Keep it to
+ one subject. The generator models a single object best, not whole scenes.
+- If the user already gives plenty of detail, pass it through largely as-is.
+- If the user asks for several objects or a whole scene, say you will build it
+ piece by piece, then generate the objects one at a time. If the list is
+ longer than three items, confirm which ones they want first.
+- Every generation produces a brand-new model; there is no in-place editing.
+ When the user wants a change ("make it blue", "give it a hat"), fold the
+ change into the previous prompt and call generate3DModel again with the
+ revised prompt.
+- Tier: omit the tier field for normal requests (standard). Use "high" only
+ when the user asks for maximum detail, and warn it can take several
+ minutes. Use "draft" when they want the fastest possible result.
+
+HANDLING THE RESPONSE
+- generate3DModel returns a "status".
+ - status "done": the model is ready. Present THREE markdown links, clearly
+ labeled:
+ 1. Download (GLB): the "glbUrl" value.
+ 2. Preview in your browser: the "viewerUrl" value.
+ 3. See it in your room (AR, open on a phone): the "arUrl" value.
+ Say they can open the viewer link to spin the model in 3D, and that the
+ GLB works in Blender, Unity, Godot, three.js, and most 3D tools.
+ - status "pending": generation is still running. On the first pending
+ response, immediately give the user the "watchUrl" value as a markdown
+ link labeled "Watch it being made live" - that three.ws page shows a
+ real countdown and the concept art, and opens the finished model in the
+ interactive viewer by itself. Also say roughly how long remains (the
+ "etaSeconds" field counts down). If a pending response carries
+ previewImageUrl, show it as a markdown image: it is the concept art the
+ generator sculpts into 3D. Then call checkModelJob using the returned
+ "poll" path verbatim (it already carries the job handle and title),
+ waiting about etaSeconds between calls, and keep polling while the
+ status stays "pending". If it is still pending after about 20 polls,
+ stop, remind them the watch link updates itself, and tell them any short
+ reply ("ok") makes you keep checking here too; on that reply, resume
+ polling the same poll path without resubmitting the prompt.
+ Never claim the model is finished until a response has status "done"
+ with a glbUrl.
+- Present glbUrl, viewerUrl, and arUrl exactly as returned. Never rewrite,
+ shorten, or re-host them. The GLB download normally lives on a
+ pub-*.r2.dev CDN URL, not on three.ws; that is correct.
+
+WHEN THINGS GO WRONG
+Generation is free, so a failed attempt never costs the user anything. Say so
+when you retry.
+- status "error" from checkModelJob, or a 502 from generate3DModel: the
+ generator had a hiccup. Retry once automatically if the user clearly wants
+ the model; if it fails again, tell them plainly and suggest trying again in
+ a minute.
+- A 503 means generation is temporarily unavailable. Do not retry in a loop;
+ tell the user to try again a little later.
+- A 429 from generate3DModel means the free hourly generation limit was hit.
+ Apologize plainly and suggest trying again a little later. Do not imply a
+ paid upgrade; there is not one here.
+- A 429 from checkModelJob just means you polled too fast. Wait at least the
+ "retry_after" seconds it returns, then continue polling. Do not tell the
+ user anything failed.
+- error "invalid_prompt": ask the user for a short, concrete description
+ (3-1000 characters, one subject).
+- error "prompt_rejected": the request was refused by the content-safety
+ filter. Relay the returned "message" and steer the user toward an allowed
+ idea. Do NOT reword the prompt to slip past the filter.
+
+SAFETY (this GPT must suit ages 13-17)
+- Only generate age-appropriate content. Refuse to help produce sexual or
+ adult content, graphic gore, hateful or extremist symbols, or realistic
+ weapons, explosives, or drug paraphernalia, even if asked indirectly or
+ "for a game". Stylized fantasy props (a cartoon sword, a wizard's wand)
+ are fine.
+- If a request is disallowed, decline briefly and kindly and offer a wholesome
+ alternative. Never explain how to bypass the filter.
+- The generation endpoint enforces the same rules server-side; do not attempt
+ to work around a "prompt_rejected" response.
+
+STYLE
+- Be concise and encouraging. Lead with the result (the links), then one line
+ of guidance at most, e.g. an idea for a variant or a different style.
+- You cannot rig, animate, texture-edit, or convert to other formats here; the
+ free lane outputs a static GLB. If asked for those, say so honestly and
+ point to https://three.ws, which offers rigging and higher-fidelity
+ generation.
+- Never bring up pricing or payment of any kind. This GPT is simply free.
+```
+
+## Known tweaks
+
+- QA on a free account (2026-07-29) showed a pending reply printing "Concept preview:" with no image under it. If this recurs, edit the pending bullet in the instructions to: "If a pending response carries previewImageUrl, render it as a markdown image; if it does not, do not mention a concept preview at all."
+- Free-tier ChatGPT shows third-party ads (observed: Meshy AI) directly beneath the GPT's replies. Not controllable from our side.
+- Public-page byline requires the `three.ws` domain to be verified and selected in the owner's ChatGPT Builder profile (Settings, Builder profile, Verify new domain: add the `openai-domain-verification=dv-...` TXT record at Namecheap, host `@`). Until then the page shows "By community builder".
+
+## Verifying a config change
+
+Run the four suggested prompts in a fresh chat. Pass criteria:
+
+1. Every flow calls `generate3DModel` on the first assistant turn (the action-call chip is visible in the ChatGPT UI). No flow asks a question before generating.
+2. No flow produces a ChatGPT-generated image. The only image ever shown is a `previewImageUrl` from the action.
+3. Every link in a "done" reply is either a `pub-*.r2.dev` GLB URL, a `three.ws/viewer?src=...` URL, or a `three.ws/api/ar?src=...` URL. Spot-check one of each in a browser.
+4. A "pending" flow either resolves within the turn or resumes polling on the next user message without re-submitting the prompt.
diff --git a/docs/chatgpt-ar.md b/docs/chatgpt-ar.md
index ba6257156..6c1b4a9f1 100644
--- a/docs/chatgpt-ar.md
+++ b/docs/chatgpt-ar.md
@@ -37,7 +37,7 @@ Every successful tool result carries `arUrl` in its `structuredContent`, and the
### 2. The "three.ws 3D Studio" custom GPT (Actions)
-Not every ChatGPT plan supports connectors, so the same lane also ships as a plain REST Actions surface for the custom GPT in the GPT Store:
+Not every ChatGPT plan supports connectors, so the same lane also ships as a plain REST Actions surface for the custom GPT in the GPT Store. The GPT's builder settings and instruction text live in [chatgpt-3d-studio-gpt.md](./chatgpt-3d-studio-gpt.md); the REST contract it calls:
```bash
curl -s -X POST https://three.ws/api/3d/studio \
diff --git a/docs/deployment.md b/docs/deployment.md
index 330ed025c..5d4a3ee6a 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -354,7 +354,7 @@ The embed routes explicitly set `frame-ancestors *` so the embed iframe can be h
### Background cron jobs
-The `crons` array in `vercel.json` declares ~90 scheduled jobs (economy tick, on-chain crawl, delegation indexing, DCA, subscriptions, coin-launch lifecycle, treasury top-ups, and more). In production these run as **Google Cloud Scheduler jobs** (one per entry) each firing `GET /api/cron/<name>` with an `Authorization: Bearer $CRON_SECRET` header. A representative slice:
+The `crons` array in `vercel.json` declares every scheduled job (100 at time of writing: economy tick, on-chain crawl, delegation indexing, DCA, subscriptions, coin-launch lifecycle, treasury top-ups, and more). That array is the authoritative count; read it rather than trusting a number quoted in prose. In production these run as **Google Cloud Scheduler jobs** (one per entry) each firing `GET /api/cron/<name>` with an `Authorization: Bearer $CRON_SECRET` header. A representative slice:
| Cron | Schedule | Purpose |
|---|---|---|
diff --git a/marketing/brand/brand-assets.html b/marketing/brand/brand-assets.html
index 227081a15..da22fa758 100644
--- a/marketing/brand/brand-assets.html
+++ b/marketing/brand/brand-assets.html
@@ -16,7 +16,7 @@
screenshots each .asset with omitBackground, so the page background here is
only a working surface to judge contrast against. Boxes are sized to the
artwork, with no padding, so the exported PNG has no dead margin. */
- .asset { display: inline-flex; align-items: center; }
+ .asset { display: flex; width: max-content; align-items: center; }
.mark img { display: block; height: 512px; width: auto; }
@@ -24,6 +24,10 @@
.lockup img { display: block; height: 200px; width: auto; }
.lockup .word {
font-size: 150px; font-weight: 600; letter-spacing: -0.045em; line-height: 1;
+ white-space: nowrap;
+ /* Negative tracking pulls the final glyph past its side bearing, which a
+ tight element screenshot would clip. This is the bearing, not padding. */
+ padding-right: 8px;
padding-bottom: 12px; /* optical: the wordmark sits low against the cube */
}
.lockup.on-dark .word { color: #ffffff; }
diff --git a/package.json b/package.json
index dc3d83a7b..a73978daa 100644
--- a/package.json
+++ b/package.json
@@ -113,6 +113,7 @@
"build:pages": "node scripts/build-page-index.mjs",
"build:discovery": "node scripts/build-discovery-cards.mjs",
"build:openai-cards": "node scripts/render-openai-social-cards.mjs",
+ "build:brand-assets": "node scripts/render-brand-assets.mjs",
"build:ibm-shell": "node scripts/build-ibm-shell.mjs",
"i18n": "npm run i18n:extract && npm run i18n:translate",
"i18n:annotate": "node scripts/i18n-annotate.mjs",
diff --git a/pages/home.html b/pages/home.html
index a0049bfd5..9d409efdc 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -659,10 +659,13 @@
try { el = document.getElementById(decodeURIComponent(hash.slice(1))); } catch (e) { return; }
if (!el || !el.closest('[data-tier="advanced"]')) return;
setLite(false, false);
+ // Instant, not smooth: the section only just appeared, so there is no
+ // scroll continuity to preserve and the page-wide `scroll-behavior:
+ // smooth` would otherwise animate across the whole document.
requestAnimationFrame(function () {
- el.scrollIntoView({ block: 'start' });
+ el.scrollIntoView({ block: 'start', behavior: 'auto' });
// Late-loading media above can shift layout; correct once it settles.
- setTimeout(function () { el.scrollIntoView({ block: 'start' }); }, 450);
+ setTimeout(function () { el.scrollIntoView({ block: 'start', behavior: 'auto' }); }, 450);
});
}
// This script runs mid-parse, before the gated sections below it exist in
diff --git a/pages/symphony.html b/pages/symphony.html
index e954ab12e..4952355ce 100644
--- a/pages/symphony.html
+++ b/pages/symphony.html
@@ -98,7 +98,8 @@
<h2>The score, as it is written</h2>
<small>every note is one of these real events</small>
</div>
- <div class="sy-ledger" id="sy-ledger" aria-live="polite"></div>
+ <div class="sy-ledger" id="sy-ledger"></div>
+ <p class="sy-sr-only" id="sy-announce" role="status" aria-live="polite"></p>
</section>
<p class="sy-fineprint">
diff --git a/prompts/store-submissions/_generated/openai-actions.yaml b/prompts/store-submissions/_generated/openai-actions.yaml
index 22fa9a17f..fb978c5c9 100644
--- a/prompts/store-submissions/_generated/openai-actions.yaml
+++ b/prompts/store-submissions/_generated/openai-actions.yaml
@@ -15,7 +15,9 @@ info:
Contract: POST /api/3d/studio either finishes inline (status "done" with
glbUrl + viewerUrl + arUrl) or returns status "pending" with a "job"
- handle. Poll GET /api/3d/studio?job=... every few seconds until status is
+ handle and watchUrl - a live three.ws progress page (countdown + concept
+ art, auto-opens the viewer when done) to hand the user immediately. Poll
+ GET /api/3d/studio?job=... every few seconds until status is
"done" or "error". Generation typically takes 20-60 seconds at the default
tier; tier "high" produces far more detail and can take several minutes,
so keep polling patiently. Responses may carry previewImageUrl - the
@@ -42,14 +44,11 @@ paths:
x-openai-isConsequential: false
summary: Generate a 3D model (GLB) from a text prompt
description: >-
- Start a free text-to-3D generation. Describe ONE subject concretely
- (shape, colors, style). Optionally pick a tier: "draft" (fastest),
- "standard" (default), or "high" (maximum detail, slower - expect
- minutes, not seconds). Returns status "done" with glbUrl (download),
- viewerUrl (preview), and arUrl (see it in your room in AR), or
- "pending" with a "job" handle for checkModelJob plus, once available,
- previewImageUrl - the painted concept image to show the user while
- the 3D model finishes. Unsafe prompts return error "prompt_rejected".
+ Start a free text-to-3D generation. Describe ONE subject. Optional
+ tier: draft (fastest), standard (default), high (max detail, takes
+ minutes). Returns "done" with glbUrl + viewerUrl + arUrl, or
+ "pending" with a job handle for checkModelJob plus watchUrl - the
+ live progress page to give the user.
requestBody:
required: true
content:
@@ -100,6 +99,7 @@ paths:
status: pending
job: f1.eyJwIjoibnZpZGlhIn0.c2ln
poll: /api/3d/studio?job=f1.eyJwIjoibnZpZGlhIn0.c2ln&title=a%20low-poly%20orange%20fox
+ watchUrl: https://three.ws/watch?job=f1.eyJwIjoibnZpZGlhIn0.c2ln&title=a%20low-poly%20orange%20fox
format: glb
"400":
description: >-
@@ -132,12 +132,11 @@ paths:
x-openai-isConsequential: false
summary: Check a pending 3D generation job
description: >-
- Poll a generation started by generate3DModel. Use the "poll" path from
- the pending response verbatim (it carries the job handle and title).
- Keep polling every few seconds while "pending"; when a pending state
- carries previewImageUrl, show that concept image to the user while
- they wait. Stop on "done" (present glbUrl + viewerUrl + arUrl) or
- "error" (offer to retry - generation is free).
+ Poll a generation started by generate3DModel. Use the pending
+ response's "poll" path verbatim (it carries job and title). While
+ "pending", offer watchUrl, show previewImageUrl if present, and keep
+ polling. Stop on "done" (present glbUrl + viewerUrl + arUrl) or
+ "error" (offer a free retry).
parameters:
- name: job
in: query
@@ -253,6 +252,15 @@ components:
poll:
type: string
description: Relative poll path for the pending job.
+ watchUrl:
+ type: string
+ format: uri
+ description: >-
+ Live progress page for a pending generation - a three.ws link
+ showing a real countdown and the concept art, which opens the
+ interactive viewer automatically the moment the model is done.
+ Give it to the user on the first pending response ("watch it
+ being made here") so they can follow along outside the chat.
error:
type: string
description: Human-readable failure message (present when status is error).
diff --git a/public/.well-known/3d-studio-openapi.yaml b/public/.well-known/3d-studio-openapi.yaml
index 22fa9a17f..fb978c5c9 100644
--- a/public/.well-known/3d-studio-openapi.yaml
+++ b/public/.well-known/3d-studio-openapi.yaml
@@ -15,7 +15,9 @@ info:
Contract: POST /api/3d/studio either finishes inline (status "done" with
glbUrl + viewerUrl + arUrl) or returns status "pending" with a "job"
- handle. Poll GET /api/3d/studio?job=... every few seconds until status is
+ handle and watchUrl - a live three.ws progress page (countdown + concept
+ art, auto-opens the viewer when done) to hand the user immediately. Poll
+ GET /api/3d/studio?job=... every few seconds until status is
"done" or "error". Generation typically takes 20-60 seconds at the default
tier; tier "high" produces far more detail and can take several minutes,
so keep polling patiently. Responses may carry previewImageUrl - the
@@ -42,14 +44,11 @@ paths:
x-openai-isConsequential: false
summary: Generate a 3D model (GLB) from a text prompt
description: >-
- Start a free text-to-3D generation. Describe ONE subject concretely
- (shape, colors, style). Optionally pick a tier: "draft" (fastest),
- "standard" (default), or "high" (maximum detail, slower - expect
- minutes, not seconds). Returns status "done" with glbUrl (download),
- viewerUrl (preview), and arUrl (see it in your room in AR), or
- "pending" with a "job" handle for checkModelJob plus, once available,
- previewImageUrl - the painted concept image to show the user while
- the 3D model finishes. Unsafe prompts return error "prompt_rejected".
+ Start a free text-to-3D generation. Describe ONE subject. Optional
+ tier: draft (fastest), standard (default), high (max detail, takes
+ minutes). Returns "done" with glbUrl + viewerUrl + arUrl, or
+ "pending" with a job handle for checkModelJob plus watchUrl - the
+ live progress page to give the user.
requestBody:
required: true
content:
@@ -100,6 +99,7 @@ paths:
status: pending
job: f1.eyJwIjoibnZpZGlhIn0.c2ln
poll: /api/3d/studio?job=f1.eyJwIjoibnZpZGlhIn0.c2ln&title=a%20low-poly%20orange%20fox
+ watchUrl: https://three.ws/watch?job=f1.eyJwIjoibnZpZGlhIn0.c2ln&title=a%20low-poly%20orange%20fox
format: glb
"400":
description: >-
@@ -132,12 +132,11 @@ paths:
x-openai-isConsequential: false
summary: Check a pending 3D generation job
description: >-
- Poll a generation started by generate3DModel. Use the "poll" path from
- the pending response verbatim (it carries the job handle and title).
- Keep polling every few seconds while "pending"; when a pending state
- carries previewImageUrl, show that concept image to the user while
- they wait. Stop on "done" (present glbUrl + viewerUrl + arUrl) or
- "error" (offer to retry - generation is free).
+ Poll a generation started by generate3DModel. Use the pending
+ response's "poll" path verbatim (it carries job and title). While
+ "pending", offer watchUrl, show previewImageUrl if present, and keep
+ polling. Stop on "done" (present glbUrl + viewerUrl + arUrl) or
+ "error" (offer a free retry).
parameters:
- name: job
in: query
@@ -253,6 +252,15 @@ components:
poll:
type: string
description: Relative poll path for the pending job.
+ watchUrl:
+ type: string
+ format: uri
+ description: >-
+ Live progress page for a pending generation - a three.ws link
+ showing a real countdown and the concept art, which opens the
+ interactive viewer automatically the moment the model is done.
+ Give it to the user on the first pending response ("watch it
+ being made here") so they can follow along outside the chat.
error:
type: string
description: Human-readable failure message (present when status is error).
diff --git a/public/brand/three-ws-lockup-on-dark.png b/public/brand/three-ws-lockup-on-dark.png
new file mode 100644
index 000000000..2e458fb5c
Binary files /dev/null and b/public/brand/three-ws-lockup-on-dark.png differ
diff --git a/public/brand/three-ws-lockup-on-light.png b/public/brand/three-ws-lockup-on-light.png
new file mode 100644
index 000000000..5cb577b84
Binary files /dev/null and b/public/brand/three-ws-lockup-on-light.png differ
diff --git a/public/brand/three-ws-mark.png b/public/brand/three-ws-mark.png
new file mode 100644
index 000000000..3fcf1d9b0
Binary files /dev/null and b/public/brand/three-ws-mark.png differ
diff --git a/public/brand/three-ws-stacked-on-dark.png b/public/brand/three-ws-stacked-on-dark.png
new file mode 100644
index 000000000..1212710cb
Binary files /dev/null and b/public/brand/three-ws-stacked-on-dark.png differ
diff --git a/public/brand/three-ws-stacked-on-light.png b/public/brand/three-ws-stacked-on-light.png
new file mode 100644
index 000000000..ecc7d859e
Binary files /dev/null and b/public/brand/three-ws-stacked-on-light.png differ
diff --git a/public/changelog.json b/public/changelog.json
index 83f65a618..55a6085f2 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,31 @@
{
- "generated_at": "2026-07-28T22:21:36.586Z",
+ "generated_at": "2026-07-29T04:55:00.466Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-07-29",
+ "type": "launch",
+ "title": "Generation Watch",
+ "summary": "Live progress page for a running text-to-3D generation: real countdown, the painted concept art, and an automatic hand-off into the interactive viewer the moment the model is ready.",
+ "link": "/watch",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-07-29",
+ "type": "update",
+ "title": "Watch your 3D model being made, live",
+ "summary": "Free text-to-3D generations now come with a live progress page. When a generation is still running, the API (and the three.ws 3D Studio GPT in ChatGPT) hands you a three.ws/watch link showing a real countdown, the painted concept art the generator sculpts from, and an automatic jump into the interactive 3D viewer with download and AR links the moment your model is ready. No more staring at a chat window wondering how long is left.",
+ "link": "/watch",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-28",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index bc430b9a3..4c328ddde 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,22 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Generation Watch</title>
+ <link>https://three.ws/watch</link>
+ <guid isPermaLink="false">2026-07-29:Generation Watch</guid>
+ <pubDate>Wed, 29 Jul 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Live progress page for a running text-to-3D generation: real countdown, the painted concept art, and an automatic hand-off into the interactive viewer the moment the model is ready.</description>
+ </item>
+ <item>
+ <title>Watch your 3D model being made, live</title>
+ <link>https://three.ws/watch</link>
+ <guid isPermaLink="false">2026-07-29:Watch your 3D model being made, live</guid>
+ <pubDate>Wed, 29 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Free text-to-3D generations now come with a live progress page. When a generation is still running, the API (and the three.ws 3D Studio GPT in ChatGPT) hands you a three.ws/watch link showing a real countdown, the painted concept art the generator sculpts from, and an automatic jump into the interactive 3D viewer with download and AR links the moment your model is ready. No more staring at a chat window wondering how long is left.</description>
+ </item>
<item>
<title>Agent Symphony</title>
<link>https://three.ws/symphony</link>
diff --git a/public/features.json b/public/features.json
index 89f5f1206..02b62451b 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-28T22:21:36.575Z",
+ "generated_at": "2026-07-29T04:55:00.379Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -1039,6 +1039,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/watch",
+ "title": "Generation Watch",
+ "description": "Live progress page for a running text-to-3D generation: real countdown, the painted concept art, and an automatic hand-off into the interactive viewer the moment the model is ready.",
+ "added": "2026-07-29",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/ar",
"title": "AR Forge",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index b3a33bb66..78cf68fbe 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -633,6 +633,12 @@ URL: https://three.ws/viewer
Preview any public glTF/GLB inline, then take it further: pose and animate it, restyle the material, build a scene, place it in AR, embed it on your site, or launch it as a pump.fun coin.
+### Generation Watch
+
+URL: https://three.ws/watch
+
+Live progress page for a running text-to-3D generation: real countdown, the painted concept art, and an automatic hand-off into the interactive viewer the moment the model is ready.
+
### AR Forge
URL: https://three.ws/ar
diff --git a/public/llms.txt b/public/llms.txt
index 51ed75ed9..074aea930 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -118,6 +118,7 @@ Experimental features actively shipping. Expect fast iteration.
- [Lipsync (Mic)](https://three.ws/lipsync/mic): Feed live mic audio through the viseme analyser and watch the avatar's mouth track your voice in real time.
- [Avatar Artifact](https://three.ws/avatar-artifact): Standalone Three.js viewer for avatar artifacts — embeddable and shareable without any wrapper page.
- [glTF / GLB Viewer](https://three.ws/viewer): Preview any public glTF/GLB inline, then take it further: pose and animate it, restyle the material, build a scene, place it in AR, embed it on your site, or launch it as a pump.fun coin.
+- [Generation Watch](https://three.ws/watch): Live progress page for a running text-to-3D generation: real countdown, the painted concept art, and an automatic hand-off into the interactive viewer the moment the model is ready.
- [AR Forge](https://three.ws/ar): Type a prompt, get a real 3D model, and place it in your room: free text-to-3D with one-tap AR on any phone (WebXR, Scene Viewer, Quick Look) and a QR handoff from desktop.
- [AR Studio](https://three.ws/ar/studio): A live multi-model AR scene through your camera: place any number of 3D models and avatars in your real space, pull in your forge creations, community models, the CC0 object library, or any GLB link, and generate new models by prompt without leaving the view.
- [Daily Forge](https://three.ws/daily): A new 3D creative challenge every day. Forge today's theme into a real 3D model, free and no sign-up, build a daily streak, and place your creation in AR on your phone.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 765a11302..d81560ce6 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -79,7 +79,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 536 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 537 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -91,7 +91,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 536 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 537 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -99,6 +99,14 @@
<h2 id="sm-new-title">Newest<a class="sm-new-more" href="/changelog">full changelog &rarr;</a></h2>
<p class="sm-section-desc">The 9 most recently launched pages, straight to the live surface.</p>
<ul class="sm-list">
+ <li>
+ <a href="/watch">
+ <span class="sm-new-date">Jul 29, 2026</span>
+ <span class="sm-title">Generation Watch</span>
+ <span class="sm-path">/watch</span>
+ <span class="sm-desc">Live progress page for a running text-to-3D generation: real countdown, the painted concept art, and an automatic hand-off into the interactive viewer the moment the model is ready.</span>
+ </a>
+ </li>
<li>
<a href="/symphony">
<span class="sm-new-date">Jul 28, 2026</span>
@@ -163,14 +171,6 @@
<span class="sm-desc">How a trading arm's own realized record decides how much rope it gets: the four tiers, what each unlocks in the optimizer and the fleet budget, how much evidence the LLM judge is handed, and the safety rails no amount of profit can unlock.</span>
</a>
</li>
- <li>
- <a href="/blog/three-ws-openai-select-partner">
- <span class="sm-new-date">Jul 25, 2026</span>
- <span class="sm-title">three.ws Named an OpenAI Select Partner</span>
- <span class="sm-path">/blog/three-ws-openai-select-partner</span>
- <span class="sm-desc">three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.</span>
- </a>
- </li>
</ul>
</section>
<nav class="sm-toc" aria-label="Sections">
@@ -871,7 +871,7 @@
<section class="sm-section" id="labs">
<header>
- <h2>Labs<span class="sm-count" data-count>17</span></h2>
+ <h2>Labs<span class="sm-count" data-count>18</span></h2>
<p class="sm-section-desc">Experimental features actively shipping. Expect fast iteration.</p>
</header>
<ul class="sm-list">
@@ -917,6 +917,13 @@
<span class="sm-desc">Preview any public glTF/GLB inline, then take it further: pose and animate it, restyle the material, build a scene, place it in AR, embed it on your site, or launch it as a pump.fun coin.</span>
</a>
</li>
+ <li>
+ <a href="/watch">
+ <span class="sm-title">Generation Watch</span>
+ <span class="sm-path">/watch</span>
+ <span class="sm-desc">Live progress page for a running text-to-3D generation: real countdown, the painted concept art, and an automatic hand-off into the interactive viewer the moment the model is ready.</span>
+ </a>
+ </li>
<li>
<a href="/ar">
<span class="sm-title">AR Forge</span>
diff --git a/public/watch.html b/public/watch.html
new file mode 100644
index 000000000..a9023ec24
--- /dev/null
+++ b/public/watch.html
@@ -0,0 +1,270 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+<title>Watching your 3D model · three.ws</title>
+<meta name="description" content="Live progress for a three.ws 3D generation: countdown, concept art, and an automatic hand-off to the interactive viewer the moment the model is ready." />
+<meta name="robots" content="noindex" />
+<meta property="og:title" content="Watching a 3D model being made · three.ws" />
+<meta property="og:description" content="A 3D model is being generated on three.ws right now. Watch the live countdown and concept art." />
+<meta property="og:type" content="website" />
+<style>
+ :root { color-scheme: dark; --accent: #6ea8fe; }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; height: 100%; }
+ body {
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ background: radial-gradient(130% 130% at 50% 0%, #14161c 0%, #0b0c10 60%, #08090c 100%);
+ color: #e8eaf0;
+ overflow: hidden;
+ }
+ .wrap { display: flex; flex-direction: column; height: 100dvh; }
+ header.bar {
+ display: flex; align-items: center; gap: 12px;
+ padding: 12px 16px; border-bottom: 1px solid rgba(255,255,255,0.07);
+ background: rgba(10,11,14,0.55); backdrop-filter: blur(8px);
+ }
+ .brand { display: flex; align-items: center; gap: 9px; text-decoration: none; color: #e8eaf0; font-weight: 700; letter-spacing: .01em; }
+ .brand .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); }
+ .brand:hover { color: #fff; }
+ .title { flex: 1 1 auto; min-width: 0; font-size: 13.5px; color: #aeb6c4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+ .stage { position: relative; flex: 1 1 auto; min-height: 0; overflow-y: auto; }
+ .overlay {
+ min-height: 100%; display: flex; flex-direction: column;
+ align-items: center; justify-content: center; gap: 16px; text-align: center; padding: 28px;
+ }
+ .h { font-size: 16px; font-weight: 650; }
+ .muted { color: #9aa3b2; font-size: 13px; line-height: 1.5; max-width: 44ch; }
+ .muted a { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; }
+ .muted a:hover { color: #dbe9ff; }
+ .muted a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 3px; }
+
+ /* Countdown ring */
+ .ringbox { position: relative; width: 168px; height: 168px; }
+ .ringbox svg { width: 100%; height: 100%; transform: rotate(-90deg); }
+ .ring-track { fill: none; stroke: rgba(255,255,255,0.09); stroke-width: 7; }
+ .ring-arc {
+ fill: none; stroke: var(--accent); stroke-width: 7; stroke-linecap: round;
+ filter: drop-shadow(0 0 6px rgba(110,168,254,.55));
+ transition: stroke-dashoffset .6s ease;
+ }
+ .ring-arc.indeterminate { stroke-dasharray: 110 800; animation: orbit 1.6s linear infinite; transition: none; }
+ @keyframes orbit { to { stroke-dashoffset: -910; } }
+ @media (prefers-reduced-motion: reduce) { .ring-arc.indeterminate { animation-duration: 4s; } }
+ .ring-label {
+ position: absolute; inset: 0; display: flex; flex-direction: column;
+ align-items: center; justify-content: center; gap: 2px;
+ }
+ .ring-time { font-size: 30px; font-weight: 700; font-variant-numeric: tabular-nums; letter-spacing: .01em; }
+ .ring-sub { font-size: 11px; font-weight: 600; letter-spacing: .09em; text-transform: uppercase; color: #9aa3b2; }
+
+ .concept {
+ max-width: min(320px, 78vw); border-radius: 14px; border: 1px solid rgba(255,255,255,0.12);
+ box-shadow: 0 12px 44px rgba(0,0,0,.45);
+ opacity: 0; transform: translateY(6px) scale(.98);
+ transition: opacity .5s ease, transform .5s ease;
+ }
+ .concept.shown { opacity: 1; transform: none; }
+ .concept-cap { font-size: 11.5px; color: #9aa3b2; letter-spacing: .04em; text-transform: uppercase; display: none; }
+ .concept-cap.shown { display: block; }
+
+ footer.bar {
+ display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
+ padding: 11px 16px; border-top: 1px solid rgba(255,255,255,0.07);
+ background: rgba(10,11,14,0.55); backdrop-filter: blur(8px);
+ }
+ .spacer { flex: 1 1 auto; }
+ a.btn {
+ appearance: none; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 7px;
+ font-size: 13px; font-weight: 600; color: #e8eaf0;
+ background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.14);
+ border-radius: 10px; padding: 8px 13px; transition: background .15s, border-color .15s, transform .05s;
+ }
+ a.btn.primary { background: rgba(110,168,254,0.16); border-color: rgba(110,168,254,0.42); color: #dbe9ff; }
+ a.btn:hover { background: rgba(255,255,255,0.12); border-color: rgba(255,255,255,0.28); }
+ a.btn.primary:hover { background: rgba(110,168,254,0.26); }
+ a.btn:active { transform: translateY(1px); }
+ a.btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .hidden { display: none !important; }
+</style>
+</head>
+<body>
+<div class="wrap">
+ <header class="bar">
+ <a class="brand" href="https://three.ws"><span class="dot" aria-hidden="true"></span>three.ws</a>
+ <span id="title" class="title"></span>
+ </header>
+
+ <div class="stage">
+ <div id="waiting" class="overlay" aria-live="polite">
+ <div class="ringbox" role="timer" aria-label="Estimated time remaining">
+ <svg viewBox="0 0 120 120" aria-hidden="true">
+ <circle class="ring-track" cx="60" cy="60" r="53"></circle>
+ <circle id="arc" class="ring-arc indeterminate" cx="60" cy="60" r="53"></circle>
+ </svg>
+ <div class="ring-label">
+ <div id="time" class="ring-time">…</div>
+ <div id="timesub" class="ring-sub">warming up</div>
+ </div>
+ </div>
+ <div id="phase" class="h">Starting your 3D generation…</div>
+ <div class="muted">This page updates itself. When the model is ready it opens straight into the interactive 3D viewer with download and place-in-your-room AR links.</div>
+ <img id="concept" class="concept" alt="Concept art the generator painted for this model" decoding="async" />
+ <div id="concept-cap" class="concept-cap">Concept art — now being sculpted into 3D</div>
+ </div>
+
+ <div id="ready" class="overlay hidden">
+ <div class="h">Your model is ready — opening the viewer…</div>
+ <div class="muted">If nothing happens, <a id="ready-link" href="#">open it here</a>.</div>
+ </div>
+
+ <div id="error" class="overlay hidden">
+ <div class="h">This generation hit a snag</div>
+ <div id="errmsg" class="muted">The generator failed upstream. Generating is free, so trying again costs nothing.</div>
+ <a class="btn primary" href="https://three.ws/forge">Forge it again — free</a>
+ </div>
+
+ <div id="empty" class="overlay hidden">
+ <div class="h">Nothing to watch here</div>
+ <div class="muted">This page shows a 3D generation in progress from a <code>?job=</code> link. Start one for free at <a href="https://three.ws/forge">three.ws/forge</a> — no account needed.</div>
+ <a class="btn primary" href="https://three.ws/forge">Create a 3D model</a>
+ </div>
+ </div>
+
+ <footer class="bar">
+ <span class="muted">Free text-to-3D by three.ws</span>
+ <div class="spacer"></div>
+ <a class="btn" href="https://three.ws/viewer">3D viewer</a>
+ <a class="btn primary" href="https://three.ws/forge">Make your own →</a>
+ </footer>
+</div>
+
+<script>
+(function () {
+ var params = new URLSearchParams(location.search);
+ var job = (params.get('job') || '').trim();
+ var title = (params.get('title') || '').trim().slice(0, 120);
+
+ var waiting = document.getElementById('waiting');
+ var ready = document.getElementById('ready');
+ var errEl = document.getElementById('error');
+ var errMsg = document.getElementById('errmsg');
+ var empty = document.getElementById('empty');
+ var phaseEl = document.getElementById('phase');
+ var timeEl = document.getElementById('time');
+ var timeSub = document.getElementById('timesub');
+ var arc = document.getElementById('arc');
+ var concept = document.getElementById('concept');
+ var conceptCap = document.getElementById('concept-cap');
+ var titleEl = document.getElementById('title');
+
+ function show(el) {
+ [waiting, ready, errEl, empty].forEach(function (n) { n.classList.add('hidden'); });
+ el.classList.remove('hidden');
+ }
+
+ if (title) { titleEl.textContent = title; document.title = title + ' · three.ws'; }
+
+ // Same handle shape the API enforces — junk links land on the empty state.
+ if (!job || !/^[A-Za-z0-9._-]{8,1024}$/.test(job)) { show(empty); return; }
+
+ var CIRC = 2 * Math.PI * 53; // ring circumference for r=53
+ var eta = null; // seconds remaining, as last reported
+ var etaSyncedAt = 0; // performance.now() at last report
+ var etaTotal = null; // largest estimate seen — the ring's 100% mark
+ var started = Date.now();
+
+ function fmt(s) {
+ s = Math.max(0, Math.round(s));
+ var m = Math.floor(s / 60);
+ return m + ':' + String(s % 60).padStart(2, '0');
+ }
+
+ // Local 4Hz tick keeps the countdown moving between polls.
+ setInterval(function () {
+ if (eta == null) {
+ timeEl.textContent = fmt((Date.now() - started) / 1000);
+ timeSub.textContent = 'elapsed';
+ return;
+ }
+ var left = eta - (performance.now() - etaSyncedAt) / 1000;
+ timeEl.textContent = fmt(left);
+ timeSub.textContent = left > 0.5 ? 'remaining' : 'finishing up';
+ if (etaTotal > 0) {
+ arc.classList.remove('indeterminate');
+ var frac = Math.min(1, Math.max(0.02, 1 - Math.max(0, left) / etaTotal));
+ arc.setAttribute('stroke-dasharray', CIRC);
+ arc.setAttribute('stroke-dashoffset', String(CIRC * (1 - frac)));
+ }
+ }, 250);
+
+ var tierNames = { draft: 'draft quality', standard: 'standard quality', high: 'maximum detail' };
+ function applyState(d) {
+ if (Number.isFinite(d.etaSeconds) && d.etaSeconds > 0) {
+ eta = d.etaSeconds;
+ etaSyncedAt = performance.now();
+ if (!etaTotal || eta > etaTotal) etaTotal = eta;
+ }
+ if (d.previewImageUrl && /^https:\/\//.test(d.previewImageUrl) && concept.src !== d.previewImageUrl) {
+ concept.src = d.previewImageUrl;
+ concept.onload = function () { concept.classList.add('shown'); conceptCap.classList.add('shown'); };
+ }
+ var tier = tierNames[d.tier] || '';
+ phaseEl.textContent = concept.classList.contains('shown')
+ ? 'Sculpting the 3D mesh' + (tier ? ' at ' + tier : '') + '…'
+ : 'Painting the concept' + (tier ? ' at ' + tier : '') + '…';
+ }
+
+ var stopped = false;
+ function finish(d) {
+ stopped = true;
+ var target = d.viewerUrl && /^https:\/\//.test(d.viewerUrl) ? d.viewerUrl : null;
+ if (!target && d.glbUrl) target = 'https://three.ws/viewer?src=' + encodeURIComponent(d.glbUrl) + (title ? '&title=' + encodeURIComponent(title) : '');
+ if (!target) { failWith('The model finished but no viewer link came back. Start a fresh one — it is free.'); return; }
+ document.getElementById('ready-link').href = target;
+ show(ready);
+ setTimeout(function () { location.replace(target); }, 700);
+ }
+ function failWith(msg) {
+ stopped = true;
+ if (msg) errMsg.textContent = msg;
+ show(errEl);
+ }
+
+ var pollPath = '/api/3d/studio?job=' + encodeURIComponent(job) + (title ? '&title=' + encodeURIComponent(title) : '');
+ function nextDelay(d, retryAfter) {
+ if (retryAfter) return Math.max(3, retryAfter) * 1000;
+ var e = d && Number.isFinite(d.etaSeconds) ? d.etaSeconds : null;
+ if (e == null) return 5000;
+ return Math.min(10000, Math.max(4000, (e / 5) * 1000));
+ }
+
+ function poll() {
+ if (stopped) return;
+ fetch(pollPath, { headers: { accept: 'application/json' } })
+ .then(function (r) { return r.json().then(function (d) { return { r: r, d: d }; }); })
+ .then(function (x) {
+ var d = x.d || {};
+ if (x.r.status === 429) { setTimeout(poll, nextDelay(null, Number(d.retry_after) || 5)); return; }
+ if (x.r.status === 400) { failWith('This progress link is stale or malformed. Start a fresh generation — it is free.'); return; }
+ if (d.status === 'done') { finish(d); return; }
+ if (d.status === 'error') { failWith(d.error || null); return; }
+ applyState(d);
+ setTimeout(poll, nextDelay(d));
+ })
+ .catch(function () { setTimeout(poll, 6000); }); // transient blip — keep watching
+ }
+ poll();
+
+ // Nothing generates for 40+ minutes; stop a zombie tab honestly.
+ setTimeout(function () {
+ if (!stopped) failWith('This is taking far longer than it should. The job may have been lost upstream — start a fresh one, it is free.');
+ }, 40 * 60 * 1000);
+})();
+</script>
+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
+ <script type="module" src="/i18n.js"></script>
+</body>
+</html>
diff --git a/scripts/.receipts-e2e.tmp.mjs b/scripts/.receipts-e2e.tmp.mjs
new file mode 100644
index 000000000..d7db81509
--- /dev/null
+++ b/scripts/.receipts-e2e.tmp.mjs
@@ -0,0 +1,134 @@
+// Temporary E2E harness for /receipts (deleted after the run).
+import { chromium } from 'playwright';
+import nacl from 'tweetnacl';
+import bs58pkg from 'bs58';
+const bs58 = bs58pkg.default || bs58pkg;
+
+const OUT = '/tmp/claude-1000/-workspaces-three-ws/bdacc6ae-94a1-4fd1-9a02-d84da1c248a1/scratchpad';
+const kp = nacl.sign.keyPair();
+const address = bs58.encode(kp.publicKey);
+
+const browser = await chromium.launch();
+const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
+const errors = [];
+page.on('console', (m) => {
+ if (m.type() === 'error') errors.push(m.text().slice(0, 200));
+});
+page.on('pageerror', (e) => errors.push('PAGEERROR ' + String(e).slice(0, 200)));
+page.on('response', (r) => {
+ if (r.url().includes('my-receipts')) console.log(' API my-receipts →', r.status());
+});
+
+await page.exposeFunction('__sign', (bytes) =>
+ Array.from(nacl.sign.detached(Uint8Array.from(bytes), kp.secretKey)),
+);
+await page.addInitScript((addr) => {
+ window.solana = {
+ isPhantom: true,
+ publicKey: { toString: () => addr },
+ connect: async () => ({ publicKey: { toString: () => addr } }),
+ signMessage: async (encoded) => ({
+ signature: Uint8Array.from(await window.__sign(Array.from(encoded))),
+ }),
+ };
+}, address);
+
+await page.goto('http://localhost:3000/receipts', { waitUntil: 'domcontentloaded' });
+await page.waitForSelector('#rc-signin', { state: 'visible' });
+console.log('title:', await page.title());
+console.log('signed-out card visible:', await page.locator('#rc-signin').isVisible());
+await page.screenshot({ path: `${OUT}/rc-1-signedout.png` });
+
+console.log('\n-- connect + sign + live fetch --');
+await page.click('#rc-connect-solana');
+await page.waitForSelector('#rc-vault:not([hidden])', { timeout: 30000 });
+await page.waitForFunction(() => !document.querySelector('.rc-skeleton'), { timeout: 30000 });
+console.log('wallet chip:', (await page.locator('#rc-wallet-addr').textContent()).trim(), '·', (await page.locator('#rc-wallet-net').textContent()).trim());
+console.log('KPIs:', await page.locator('#rc-k-total').textContent(), '/', await page.locator('#rc-k-endpoints').textContent(), '/', await page.locator('#rc-k-networks').textContent());
+console.log('empty state shown:', await page.locator('#rc-empty').isVisible(), '·', (await page.locator('#rc-empty-title').textContent()).trim());
+console.log('empty state has CTA link:', await page.locator('#rc-empty-body a').count());
+await page.screenshot({ path: `${OUT}/rc-2-empty.png` });
+
+console.log('\n-- populated render (injected rows through the real render path) --');
+await page.evaluate(() => {
+ window.dispatchEvent(new Event('resize'));
+});
+// Drive the real renderer via the module's own list markup by seeding through
+// the API shape: reload with a stubbed fetch so renderVault() runs on real rows.
+await page.route('**/api/x402/my-receipts*', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ network: 'solana',
+ address,
+ count: 3,
+ receipts: [
+ { id: 1, payer: address, network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', resourceUrl: 'https://three.ws/api/x402/d/token-snapshot', format: 'jws', transaction: '5xTr4nsAcT10nS1gNaTuReF0rTeSt1nGpUrP0SeS0nLy1234567890abcd', receipt: { format: 'jws', signature: 'abc' }, issuedAt: new Date(Date.now() - 3600e3).toISOString() },
+ { id: 2, payer: address, network: 'eip155:8453', resourceUrl: 'https://three.ws/api/x402/d/whale-activity', format: 'jws', transaction: '0xdeadbeef1234567890abcdef', receipt: { format: 'jws', signature: 'def' }, issuedAt: new Date(Date.now() - 7200e3).toISOString() },
+ { id: 3, payer: address, network: 'solana', resourceUrl: 'https://three.ws/api/x402/d/holder-concentration', format: 'jws', transaction: null, receipt: { format: 'jws', signature: 'ghi' }, issuedAt: new Date(Date.now() - 86400e3).toISOString() },
+ ],
+ }),
+ }),
+);
+await page.click('#rc-refresh');
+await page.waitForFunction(() => document.querySelectorAll('.rc-row:not(.rc-skeleton)').length === 3, { timeout: 20000 });
+console.log('rows rendered:', await page.locator('.rc-row').count());
+console.log('KPIs:', await page.locator('#rc-k-total').textContent(), 'receipts /', await page.locator('#rc-k-endpoints').textContent(), 'endpoints /', await page.locator('#rc-k-networks').textContent());
+const links = await page.locator('a.rc-tx').evaluateAll((els) => els.map((e) => e.href));
+console.log('explorer links:', links);
+console.log('private tx cell:', await page.locator('.rc-tx-none').count());
+await page.screenshot({ path: `${OUT}/rc-3-populated.png` });
+
+console.log('\n-- search filter --');
+await page.fill('#rc-search', 'whale');
+await page.waitForTimeout(300);
+console.log('rows after search "whale":', await page.locator('.rc-row').count());
+await page.fill('#rc-search', 'zzzz');
+await page.waitForTimeout(300);
+console.log('no-match empty state:', (await page.locator('#rc-empty-title').textContent()).trim());
+await page.screenshot({ path: `${OUT}/rc-4-nomatch.png` });
+await page.fill('#rc-search', '');
+await page.waitForTimeout(300);
+
+console.log('\n-- keyboard + actions --');
+await page.locator('body').click();
+await page.keyboard.press('/');
+console.log('"/" focuses search:', await page.evaluate(() => document.activeElement?.id));
+await page.keyboard.press('Escape');
+await page.locator('body').click();
+
+const dl = page.waitForEvent('download', { timeout: 10000 });
+await page.keyboard.press('e');
+const csv = await dl;
+console.log('CSV download:', csv.suggestedFilename());
+
+const dl2 = page.waitForEvent('download', { timeout: 10000 });
+await page.locator('[data-action="download"]').first().click();
+console.log('JSON download:', (await dl2).suggestedFilename());
+
+console.log('\n-- error state --');
+await page.unroute('**/api/x402/my-receipts*');
+await page.route('**/api/x402/my-receipts*', (route) =>
+ route.fulfill({ status: 502, contentType: 'application/json', body: JSON.stringify({ error: 'receipt_query_failed', error_description: 'Receipt store unreachable.' }) }),
+);
+await page.click('#rc-refresh');
+await page.waitForSelector('#rc-load-error:not([hidden])', { timeout: 15000 });
+console.log('error state:', (await page.locator('#rc-load-error-msg').textContent()).trim());
+console.log('retry button present:', await page.locator('#rc-retry').isVisible());
+await page.screenshot({ path: `${OUT}/rc-5-error.png` });
+
+console.log('\n-- disconnect --');
+await page.click('#rc-disconnect');
+console.log('back to sign-in:', await page.locator('#rc-signin').isVisible());
+console.log('session cleared:', await page.evaluate(() => sessionStorage.getItem('twx_receipts_session')));
+
+console.log('\n-- responsive 375px --');
+await page.setViewportSize({ width: 375, height: 800 });
+await page.waitForTimeout(300);
+const hScroll = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth + 1);
+console.log('horizontal scroll at 375px:', hScroll);
+await page.screenshot({ path: `${OUT}/rc-6-mobile.png` });
+
+console.log('\nconsole errors:', errors.length ? errors : 'NONE');
+await browser.close();
diff --git a/scripts/.repro-texture.mjs b/scripts/.repro-texture.mjs
new file mode 100644
index 000000000..8e537cefa
--- /dev/null
+++ b/scripts/.repro-texture.mjs
@@ -0,0 +1,72 @@
+// Reproduce the "GLTFLoader: Couldn't load texture blob:" console error seen on
+// production pages, and determine whether it is a real user-facing failure or an
+// artifact of the headless audit environment.
+import { chromium } from 'playwright';
+
+const browser = await chromium.launch();
+const page = await browser.newPage();
+
+const errors = [];
+page.on('console', (m) => {
+ if (m.type() === 'error') errors.push(m.text().slice(0, 140));
+});
+page.on('pageerror', (e) => errors.push('PAGEERROR ' + String(e).slice(0, 140)));
+
+await page.goto('https://three.ws/avatar-sdk', { waitUntil: 'domcontentloaded', timeout: 45000 });
+await page.waitForTimeout(12000);
+
+// Probe the environment directly: can this browser decode a real JPEG blob from
+// the same GLB the page loads, via both createImageBitmap and <img>?
+const probe = await page.evaluate(async () => {
+ const out = {};
+ const res = await fetch('/avatars/default.glb');
+ const buf = new Uint8Array(await res.arrayBuffer());
+ const dv = new DataView(buf.buffer);
+ const jsonLen = dv.getUint32(12, true);
+ const json = JSON.parse(new TextDecoder().decode(buf.subarray(20, 20 + jsonLen)));
+ const binOff = 20 + jsonLen + 8;
+ const img = json.images[1];
+ const bv = json.bufferViews[img.bufferView];
+ const data = buf.subarray(binOff + (bv.byteOffset || 0), binOff + (bv.byteOffset || 0) + bv.byteLength);
+ out.mimeType = img.mimeType;
+ out.firstBytes = Array.from(data.slice(0, 3)).map((b) => b.toString(16)).join(' ');
+
+ const blob = new Blob([data], { type: img.mimeType });
+ const url = URL.createObjectURL(blob);
+ out.hasCreateImageBitmap = typeof createImageBitmap === 'function';
+ try {
+ const bmp = await createImageBitmap(blob);
+ out.imageBitmap = `ok ${bmp.width}x${bmp.height}`;
+ } catch (e) {
+ out.imageBitmap = 'FAIL ' + String(e).slice(0, 100);
+ }
+ out.imgTag = await new Promise((resolve) => {
+ const el = new Image();
+ el.onload = () => resolve(`ok ${el.naturalWidth}x${el.naturalHeight}`);
+ el.onerror = (e) => resolve('FAIL ' + (e?.message || 'load error'));
+ el.src = url;
+ setTimeout(() => resolve('TIMEOUT'), 8000);
+ });
+ // Blob with an EMPTY mime type: the shape a stripped mimeType would produce.
+ const bare = URL.createObjectURL(new Blob([data]));
+ out.imgTagNoMime = await new Promise((resolve) => {
+ const el = new Image();
+ el.onload = () => resolve(`ok ${el.naturalWidth}x${el.naturalHeight}`);
+ el.onerror = () => resolve('FAIL');
+ el.src = bare;
+ setTimeout(() => resolve('TIMEOUT'), 8000);
+ });
+ return out;
+});
+
+console.log('--- console errors captured ---');
+const counts = new Map();
+for (const e of errors) {
+ const key = e.replace(/blob:https?:\/\/\S+/, 'BLOB').replace(/https?:\/\/\S+/, 'URL');
+ counts.set(key, (counts.get(key) || 0) + 1);
+}
+for (const [k, v] of [...counts.entries()].sort((a, b) => b[1] - a[1])) console.log(v + 'x', k);
+console.log('--- environment probe ---');
+console.log(JSON.stringify(probe, null, 2));
+
+await browser.close();
diff --git a/scripts/.repro-texture2.mjs b/scripts/.repro-texture2.mjs
new file mode 100644
index 000000000..9e74bbf06
--- /dev/null
+++ b/scripts/.repro-texture2.mjs
@@ -0,0 +1,38 @@
+// Does the "Couldn't load texture blob:" error reproduce only under the audit's
+// parallel-page load, or does a single real user session hit it too?
+import { chromium } from 'playwright';
+
+const ROUTES = ['/avatar-sdk', '/play', '/club', '/tutorials/shopify-store-guide', '/gallery', '/character-library'];
+const browser = await chromium.launch();
+
+async function load(route, tag) {
+ const page = await browser.newPage();
+ let texErrors = 0;
+ let otherErrors = 0;
+ page.on('console', (m) => {
+ if (m.type() !== 'error') return;
+ if (/Couldn't load texture/.test(m.text())) texErrors++;
+ else otherErrors++;
+ });
+ try {
+ await page.goto('https://three.ws' + route, { waitUntil: 'networkidle', timeout: 25000 });
+ } catch {
+ try {
+ await page.goto('https://three.ws' + route, { waitUntil: 'domcontentloaded', timeout: 25000 });
+ } catch { /* nav failure counted by caller */ }
+ }
+ await page.waitForTimeout(2500);
+ await page.close();
+ console.log(`${tag} ${route}: texture-errors=${texErrors} other-errors=${otherErrors}`);
+ return texErrors;
+}
+
+console.log('=== SEQUENTIAL (one page at a time, like a real user) ===');
+let seq = 0;
+for (const r of ROUTES) seq += await load(r, 'seq');
+
+console.log('=== PARALLEL (all at once, like the audit harness) ===');
+const par = (await Promise.all(ROUTES.map((r) => load(r, 'par')))).reduce((a, b) => a + b, 0);
+
+console.log(`\nTOTALS sequential=${seq} parallel=${par}`);
+await browser.close();
diff --git a/scripts/dry-usdc-topup.mjs b/scripts/dry-usdc-topup.mjs
new file mode 100644
index 000000000..3ae0c8f12
--- /dev/null
+++ b/scripts/dry-usdc-topup.mjs
@@ -0,0 +1,19 @@
+#!/usr/bin/env node
+// Read-only preview of the master → USDC-engine topup (api/_lib/economy-usdc-topup.js).
+//
+// Prints live master + engine USDC balances and the exact plan the next
+// treasury-topup tick would execute, without signing anything. Run from the repo
+// root: `node scripts/dry-usdc-topup.mjs`.
+import { readFileSync } from 'node:fs';
+
+for (const line of readFileSync('.env', 'utf8').split('\n')) {
+ const m = line.match(/^([A-Z0-9_]+)=(.*)$/);
+ if (m && !process.env[m[1]]) process.env[m[1]] = m[2].replace(/^["']|["']$/g, '');
+}
+
+const { solanaConnection } = await import('../api/_lib/solana/connection.js');
+const { topUpUsdcEngines } = await import('../api/_lib/economy-usdc-topup.js');
+
+const connection = solanaConnection({ url: process.env.SOLANA_RPC_URL, network: 'mainnet', commitment: 'confirmed' });
+const out = await topUpUsdcEngines({ connection, network: 'mainnet', dryRun: true });
+console.log(JSON.stringify(out, null, 2));
diff --git a/scripts/render-brand-assets.mjs b/scripts/render-brand-assets.mjs
new file mode 100644
index 000000000..e5df85175
--- /dev/null
+++ b/scripts/render-brand-assets.mjs
@@ -0,0 +1,110 @@
+#!/usr/bin/env node
+/**
+ * Renders the three.ws brand asset set to transparent PNGs.
+ *
+ * Source of truth is marketing/brand/brand-assets.html. Each element listed in
+ * ASSETS below is screenshotted with omitBackground, so what lands in
+ * public/brand/ is the artwork with a real alpha channel and no dead margin,
+ * which is what a journalist, a partner deck, or a conference programme needs.
+ *
+ * The mark itself is not redrawn here: it is public/pwa-512x512.png (the shipped
+ * app icon) trimmed of its transparent border. The wordmark is set in Space
+ * Grotesk, the display face the site already uses, so the lockups match the
+ * product rather than inventing a second identity.
+ *
+ * The page is served over HTTP (not file://) so /fonts/*.woff2 resolve exactly
+ * as they do in production; a file:// load silently falls back to a system face
+ * and the wordmark ships wrong.
+ *
+ * Usage:
+ * npm run build:brand-assets
+ * node scripts/render-brand-assets.mjs --scale=3 --out=/tmp/brand
+ */
+import { createServer } from 'node:http';
+import { createReadStream, existsSync, mkdirSync, statSync } from 'node:fs';
+import { dirname, extname, join, normalize, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { chromium } from 'playwright';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(__dirname, '..');
+const PUBLIC = join(ROOT, 'public');
+
+const args = Object.fromEntries(process.argv.slice(2).map((a) => {
+ const m = a.match(/^--([^=]+)(?:=(.*))?$/);
+ return m ? [m[1], m[2] ?? true] : [a, true];
+}));
+const SCALE = Number(args.scale) || 2;
+const OUT_DIR = args.out ? resolve(String(args.out)) : join(PUBLIC, 'brand');
+const PAGE = '/marketing/brand/brand-assets.html';
+
+const ASSETS = [
+ { id: 'mark', file: 'three-ws-mark.png' },
+ { id: 'lockup-dark', file: 'three-ws-lockup-on-dark.png' },
+ { id: 'lockup-light', file: 'three-ws-lockup-on-light.png' },
+ { id: 'stack-dark', file: 'three-ws-stacked-on-dark.png' },
+ { id: 'stack-light', file: 'three-ws-stacked-on-light.png' },
+];
+
+const MIME = {
+ '.html': 'text/html; charset=utf-8',
+ '.css': 'text/css; charset=utf-8',
+ '.svg': 'image/svg+xml',
+ '.png': 'image/png',
+ '.woff2': 'font/woff2',
+};
+
+/** Resolve a request path against public/ first, then the repo root. */
+function resolveAsset(urlPath) {
+ const rel = normalize(decodeURIComponent(urlPath)).replace(/^(\.\.[/\\])+/, '').replace(/^[/\\]+/, '');
+ for (const base of [PUBLIC, ROOT]) {
+ const abs = join(base, rel);
+ if (abs.startsWith(base) && existsSync(abs) && statSync(abs).isFile()) return abs;
+ }
+ return null;
+}
+
+function startServer() {
+ const server = createServer((req, res) => {
+ const abs = resolveAsset(new URL(req.url, 'http://localhost').pathname);
+ if (!abs) { res.writeHead(404).end('not found'); return; }
+ res.writeHead(200, { 'content-type': MIME[extname(abs)] || 'application/octet-stream' });
+ createReadStream(abs).pipe(res);
+ });
+ return new Promise((ok) => server.listen(0, '127.0.0.1', () => ok(server)));
+}
+
+const server = await startServer();
+const origin = `http://127.0.0.1:${server.address().port}`;
+mkdirSync(OUT_DIR, { recursive: true });
+
+const browser = await chromium.launch();
+const page = await browser.newPage({ viewport: { width: 1600, height: 1200 }, deviceScaleFactor: SCALE });
+
+const failures = [];
+page.on('requestfailed', (r) => failures.push(r.url()));
+page.on('response', (r) => { if (r.status() >= 400) failures.push(`${r.status()} ${r.url()}`); });
+
+await page.goto(origin + PAGE, { waitUntil: 'networkidle' });
+await page.evaluate(() => document.fonts.ready);
+
+for (const asset of ASSETS) {
+ const el = page.locator(`#${asset.id}`);
+ const box = await el.boundingBox();
+ if (!box || box.width < 40 || box.height < 40) {
+ throw new Error(`${asset.id}: element did not render (measured ${JSON.stringify(box)})`);
+ }
+ const out = join(OUT_DIR, asset.file);
+ await el.screenshot({ path: out, omitBackground: true });
+ const kb = Math.round(statSync(out).size / 1024);
+ console.log(`${asset.file} ${Math.round(box.width * SCALE)}×${Math.round(box.height * SCALE)} ${kb} KB → ${out}`);
+}
+
+await browser.close();
+server.close();
+
+if (failures.length) {
+ console.error('\nAssets failed to load. The artwork rendered with fallbacks:');
+ for (const f of failures) console.error(' ' + f);
+ process.exit(1);
+}
diff --git a/src/procedural/foot-plant.js b/src/procedural/foot-plant.js
index d544212e7..5f28e8fcb 100644
--- a/src/procedural/foot-plant.js
+++ b/src/procedural/foot-plant.js
@@ -72,6 +72,7 @@ export class FootPlantController {
const foot = resolve(leg.foot);
if (up && mid && foot) {
this._legs.push({
+ side: leg.side,
up,
mid,
foot,
@@ -92,6 +93,23 @@ export class FootPlantController {
return !!this.hips && this._legs.length > 0;
}
+ /** @returns {number} the current damped pelvis drop, in world metres (<= 0) */
+ get pelvisOffset() {
+ return this._pelvisOffset;
+ }
+
+ /**
+ * Current world position of each solved foot. Allocates, so this is for
+ * instrumentation and tests, never the per-frame path.
+ * @returns {Array<{side: string, position: import('three').Vector3}>}
+ */
+ footWorldPositions() {
+ return this._legs.map((leg) => ({
+ side: leg.side,
+ position: leg.foot.getWorldPosition(new Vector3()),
+ }));
+ }
+
/**
* Apply the planting layer for this frame. Call AFTER mixer.update() and
* after the rig has been positioned on the terrain at its origin.
diff --git a/src/shared/coin-format.js b/src/shared/coin-format.js
index 2c2aaba3f..764bd5a49 100644
--- a/src/shared/coin-format.js
+++ b/src/shared/coin-format.js
@@ -93,7 +93,7 @@ export function timeAgo(iso, now = Date.now()) {
if (s < 3600) return `${Math.floor(s / 60)}m ago`;
if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
if (s < 14 * 86400) return `${Math.floor(s / 86400)}d ago`;
- return formatDateShort(iso);
+ return formatDateShort(t);
}
/** HTML-escape for interpolating remote strings into innerHTML templates. */
diff --git a/src/shared/markdown.js b/src/shared/markdown.js
index 8eed4aa5f..e920d817c 100644
--- a/src/shared/markdown.js
+++ b/src/shared/markdown.js
@@ -13,8 +13,6 @@ import createDOMPurify from 'dompurify';
const marked = new Marked({ gfm: true, breaks: true, async: false });
-const purify = createDOMPurify(window);
-
// Markdown output only: no media, no forms, no style. Links are hardened in
// the hook below.
const SANITIZE_CFG = {
@@ -29,14 +27,22 @@ const SANITIZE_CFG = {
const SAFE_HREF = /^(?:https?:|mailto:)/i;
-purify.addHook('afterSanitizeAttributes', (node) => {
- if (node.tagName !== 'A') return;
- const href = node.getAttribute('href') || '';
- const ok = SAFE_HREF.test(href) || href.startsWith('/') || href.startsWith('#');
- if (!ok) node.removeAttribute('href');
- node.setAttribute('target', '_blank');
- node.setAttribute('rel', 'noopener noreferrer nofollow');
-});
+// Built on first use: DOMPurify needs a live window, and this module is also
+// imported by unit tests and by page bundles that load before body parse.
+let purify = null;
+function getPurify() {
+ if (purify) return purify;
+ purify = createDOMPurify(window);
+ purify.addHook('afterSanitizeAttributes', (node) => {
+ if (node.tagName !== 'A') return;
+ const href = node.getAttribute('href') || '';
+ const ok = SAFE_HREF.test(href) || href.startsWith('/') || href.startsWith('#');
+ if (!ok) node.removeAttribute('href');
+ node.setAttribute('target', '_blank');
+ node.setAttribute('rel', 'noopener noreferrer nofollow');
+ });
+ return purify;
+}
/**
* Render Markdown to sanitized HTML.
@@ -53,7 +59,7 @@ purify.addHook('afterSanitizeAttributes', (node) => {
export function renderMarkdown(src, { classes, demoteHeadings = 0 } = {}) {
if (src == null || src === '') return '';
const raw = marked.parse(String(src));
- const clean = purify.sanitize(raw, SANITIZE_CFG);
+ const clean = getPurify().sanitize(raw, SANITIZE_CFG);
if (!classes && !demoteHeadings) return clean;
const tpl = document.createElement('template');
diff --git a/src/symphony.css b/src/symphony.css
index 325e54d3d..f15e19f00 100644
--- a/src/symphony.css
+++ b/src/symphony.css
@@ -188,6 +188,14 @@ a.sy-row:focus-visible { outline: 2px solid var(--sym-money); outline-offset: -2
.sy-empty strong { color: var(--ink); }
.sy-empty a { color: var(--sym-money); }
+/* Visually hidden, still announced: the throttled live region that narrates
+ one arrival at a time for screen readers. */
+.sy-sr-only {
+ position: absolute; width: 1px; height: 1px;
+ margin: -1px; padding: 0; overflow: hidden;
+ clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0;
+}
+
.sy-fineprint {
margin-top: 26px; text-align: center;
color: var(--ink-dim); font-size: 12.5px; line-height: 1.6;
diff --git a/src/symphony.js b/src/symphony.js
index bff09ebc0..a6f438728 100644
--- a/src/symphony.js
+++ b/src/symphony.js
@@ -372,6 +372,13 @@ function vizFrame(now) {
viz.raf = requestAnimationFrame(vizFrame);
}
+// Browsers throttle rAF in background tabs but do not always stop it; drop the
+// loop outright when hidden and restart on return so a parked tab costs nothing.
+function vizSetRunning(run) {
+ if (run && !viz.raf) viz.raf = requestAnimationFrame(vizFrame);
+ else if (!run && viz.raf) { cancelAnimationFrame(viz.raf); viz.raf = 0; }
+}
+
/* ── Ledger + stats ────────────────────────────────────────────────────── */
function ledgerRowHTML(evt) {
@@ -389,21 +396,50 @@ function ledgerRowHTML(evt) {
: `<div class="sy-row">${inner}</div>`;
}
+const EMPTY_LEDGER_HTML = `
+ <div class="sy-empty">
+ <p><strong>The economy is quiet right now.</strong></p>
+ <p>The moment an agent pays, trades, launches or levels up anywhere on
+ three.ws, you will hear it here. Meanwhile the drone you hear is the
+ platform's idle heartbeat.</p>
+ <p><a href="/pulse">Watch the Money Pulse</a> or <a href="/economy">see the economy dashboard</a>.</p>
+ </div>`;
+
+// Full rebuild. Only for first paint and for the empty state: a live feed that
+// re-rendered every row per event would restart all 60 enter animations and,
+// worse, make an aria-live container re-announce the entire list. Steady-state
+// arrivals go through prependLedgerRow() instead.
function renderLedger() {
const el = $('sy-ledger');
if (!el) return;
- if (!state.events.length) {
- el.innerHTML = `
- <div class="sy-empty">
- <p><strong>The economy is quiet right now.</strong></p>
- <p>The moment an agent pays, trades, launches or levels up anywhere on
- three.ws, you will hear it here. Meanwhile the drone you hear is the
- platform's idle heartbeat.</p>
- <p><a href="/pulse">Watch the Money Pulse</a> or <a href="/economy">see the economy dashboard</a>.</p>
- </div>`;
- return;
- }
- el.innerHTML = state.events.map(ledgerRowHTML).join('');
+ el.innerHTML = state.events.length ? state.events.map(ledgerRowHTML).join('') : EMPTY_LEDGER_HTML;
+}
+
+// One newly-arrived event: insert a single node at the head and evict the tail.
+function prependLedgerRow(evt) {
+ const el = $('sy-ledger');
+ if (!el) return;
+ if (!el.querySelector('.sy-row')) { renderLedger(); return; } // was the empty state
+ const tpl = document.createElement('template');
+ tpl.innerHTML = ledgerRowHTML(evt).trim();
+ const row = tpl.content.firstElementChild;
+ if (!row) return;
+ el.prepend(row);
+ while (el.children.length > LEDGER_MAX) el.lastElementChild.remove();
+}
+
+// Screen readers get ONE short sentence per arrival, throttled, from a
+// dedicated live region. The ledger itself is not a live region: announcing a
+// 60-row list on every beat of a live feed is unusable.
+let lastAnnounceMs = 0;
+function announceEvent(evt) {
+ const el = $('sy-announce');
+ if (!el) return;
+ const now = Date.now();
+ if (now - lastAnnounceMs < 4000) return;
+ lastAnnounceMs = now;
+ const d = describeEvent(evt);
+ el.textContent = d.detail ? `${d.title}, ${d.detail}` : d.title;
}
function renderStats() {
@@ -443,7 +479,11 @@ function acceptEvent(evt, { silent = false } = {}) {
vizSpawn(note);
}
}
- renderLedger();
+ // Silent arrivals are the first-paint backlog: the caller renders once after
+ // the batch instead of paying a full rebuild per row.
+ if (silent) return;
+ prependLedgerRow(evt);
+ announceEvent(evt);
renderStats();
}
@@ -454,7 +494,8 @@ async function fetchFirstPaint() {
const data = await res.json();
const events = Array.isArray(data.events) ? data.events : [];
for (const evt of events.slice().reverse()) acceptEvent(evt, { silent: true });
- if (!events.length) renderLedger();
+ renderLedger();
+ renderStats();
return true;
} catch (err) {
log.warn('first paint failed', err);
@@ -629,6 +670,7 @@ function wireControls() {
}
});
document.addEventListener('visibilitychange', () => {
+ vizSetRunning(!document.hidden);
if (!audio.ctx) return;
if (document.hidden && state.playing) audio.ctx.suspend().catch(() => {});
else if (!document.hidden && state.playing) audio.ctx.resume().catch(() => {});
diff --git a/src/walk.js b/src/walk.js
index 890a02daf..e3473d906 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -4712,6 +4712,27 @@ if (import.meta.env?.DEV) {
})),
env: currentEnvName,
});
+
+ // Terrain-adaptive foot planting: report each foot's world Y against the
+ // ground directly beneath it, so a headless run can assert that neither
+ // foot floats above nor sinks below its own patch of the rolling terrain.
+ window.__walkFootPlant = () => {
+ if (!footPlant?.enabled) return { active: false, reason: avatar ? 'rig unsupported' : 'no avatar' };
+ const groundY = (x, z) => (arActive ? GROUND_Y : terrain.heightAt(x, z));
+ const feet = footPlant.footWorldPositions().map(({ side, position }) => ({
+ side,
+ y: Number(position.y.toFixed(4)),
+ ground: Number(groundY(position.x, position.z).toFixed(4)),
+ clearance: Number((position.y - groundY(position.x, position.z)).toFixed(4)),
+ }));
+ return {
+ active: true,
+ motion: currentMotion,
+ rigY: Number(avatarRig.position.y.toFixed(4)),
+ pelvisOffset: Number(footPlant.pelvisOffset.toFixed(4)),
+ feet,
+ };
+ };
}
// ── Avatar picker ────────────────────────────────────────────────────────
diff --git a/tests/anthropic-prompt-cache-pricing.test.js b/tests/anthropic-prompt-cache-pricing.test.js
new file mode 100644
index 000000000..4465e5bb3
--- /dev/null
+++ b/tests/anthropic-prompt-cache-pricing.test.js
@@ -0,0 +1,209 @@
+// Prompt caching + Claude 5 request-shape guards.
+//
+// Two classes of regression are covered here, both silent when broken:
+//
+// 1. COST UNDER-REPORTING. Once a request carries a `cache_control`
+// breakpoint, Anthropic reports `usage.input_tokens` as the UNCACHED
+// REMAINDER only, moving the rest onto `cache_creation_input_tokens` /
+// `cache_read_input_tokens`. Pricing that reads only `input_tokens` sees
+// a large prompt shrink to near zero and reports spend that never
+// happened — the numbers look better, which is exactly why nobody
+// notices. costMicroUsd must price all three counters.
+//
+// 2. EMPTY REPLIES ON CLAUDE 5. Those models think by default, `max_tokens`
+// caps thinking + visible text together, and they reject sampling
+// params with a 400. A small max_tokens or a stray `temperature` carried
+// over from an older model yields a truncated/empty reply or a hard 400.
+//
+// See api/_lib/llm-pricing.js, api/_lib/chat-models.js, api/llm/anthropic.js.
+
+import { describe, it, expect } from 'vitest';
+import { costMicroUsd } from '../api/_lib/llm-pricing.js';
+import {
+ modelRejectsSampling,
+ modelThinksByDefault,
+ MODEL_CATALOG,
+ PROVIDER_MODEL_DEFAULTS,
+ vertexServesModel,
+} from '../api/_lib/chat-models.js';
+import { sanitizeAnthropicBody } from '../api/llm/anthropic.js';
+
+const M = 1_000_000;
+
+describe('costMicroUsd — prompt-cache accounting', () => {
+ it('prices a cache write at 1.25x the model input rate', () => {
+ // Sonnet 5 input is $3/MTok → a 1M-token cache write is $3.75.
+ const cost = costMicroUsd({
+ provider: 'anthropic',
+ model: 'claude-sonnet-5',
+ cacheWrite: M,
+ });
+ expect(cost).toBe(3.75 * M);
+ });
+
+ it('prices a cache read at 0.1x the model input rate', () => {
+ const cost = costMicroUsd({
+ provider: 'anthropic',
+ model: 'claude-sonnet-5',
+ cacheRead: M,
+ });
+ expect(cost).toBe(0.3 * M);
+ });
+
+ it('treats cache counters as disjoint from input, not overlapping', () => {
+ // The API splits one prompt across the three counters. Pricing must sum
+ // them; treating cacheRead as a subset of input (or ignoring it) is the
+ // under-reporting bug this guards.
+ const split = costMicroUsd({
+ provider: 'anthropic',
+ model: 'claude-opus-5',
+ input: 1000,
+ cacheRead: 9000,
+ output: 0,
+ });
+ const inputOnly = costMicroUsd({
+ provider: 'anthropic',
+ model: 'claude-opus-5',
+ input: 1000,
+ });
+ expect(split).toBeGreaterThan(inputOnly);
+ // Opus 5 input $5/MTok: 1000 * 5 + 9000 * 5 * 0.1 = 5000 + 4500.
+ expect(split).toBe(9500);
+ });
+
+ it('is cheaper to re-read a cached prefix than to send it uncached', () => {
+ // The whole point of caching. A warm turn must price below a cold one.
+ const cold = costMicroUsd({ provider: 'anthropic', model: 'claude-sonnet-5', input: 50_000 });
+ const warm = costMicroUsd({
+ provider: 'anthropic',
+ model: 'claude-sonnet-5',
+ input: 0,
+ cacheRead: 50_000,
+ });
+ expect(warm).toBeLessThan(cold);
+ });
+
+ it('leaves uncached calls priced exactly as before', () => {
+ const before = costMicroUsd({ provider: 'anthropic', model: 'claude-sonnet-5', input: 1000, output: 500 });
+ expect(before).toBe(1000 * 3 + 500 * 15);
+ });
+
+ it('still zeroes free providers even when cache counters are present', () => {
+ expect(
+ costMicroUsd({ provider: 'groq', model: 'llama-3.3-70b-versatile', cacheRead: M, cacheWrite: M }),
+ ).toBe(0);
+ });
+});
+
+describe('Claude 5 catalog wiring', () => {
+ it('registers the current generation as tool-capable', () => {
+ for (const id of ['claude-opus-5', 'claude-sonnet-5', 'claude-opus-4-8']) {
+ expect(MODEL_CATALOG[id]?.tools, id).toBe(true);
+ }
+ });
+
+ it('defaults the Anthropic provider to Sonnet 5', () => {
+ expect(PROVIDER_MODEL_DEFAULTS.anthropic).toBe('claude-sonnet-5');
+ });
+
+ it('routes the current generation through the Vertex credits transport', () => {
+ expect(vertexServesModel('claude-sonnet-5')).toBe(true);
+ expect(vertexServesModel('claude-opus-5')).toBe(true);
+ });
+
+ it('keeps Mythos out of auto-built chains (restricted access)', () => {
+ expect(MODEL_CATALOG['claude-mythos-5']?.moderationGated).toBe(true);
+ });
+
+ it('flags sampling rejection for Opus 4.7 onward only', () => {
+ expect(modelRejectsSampling('claude-opus-5')).toBe(true);
+ expect(modelRejectsSampling('claude-sonnet-5')).toBe(true);
+ expect(modelRejectsSampling('claude-opus-4-7')).toBe(true);
+ // Older models still accept temperature — stripping it there would be a
+ // silent behavior change for existing callers.
+ expect(modelRejectsSampling('claude-haiku-4-5-20251001')).toBe(false);
+ expect(modelRejectsSampling('claude-sonnet-4-6')).toBe(false);
+ });
+
+ it('flags thinking-by-default for the Claude 5 family only', () => {
+ expect(modelThinksByDefault('claude-sonnet-5')).toBe(true);
+ expect(modelThinksByDefault('claude-opus-5')).toBe(true);
+ expect(modelThinksByDefault('claude-fable-5')).toBe(true);
+ // 4.8/4.7 need thinking requested explicitly, so their budgets are fine.
+ expect(modelThinksByDefault('claude-opus-4-8')).toBe(false);
+ expect(modelThinksByDefault('claude-haiku-4-5-20251001')).toBe(false);
+ });
+});
+
+describe('sanitizeAnthropicBody — embed proxy request-shape guard', () => {
+ it('strips temperature for models that 400 on it', () => {
+ const out = sanitizeAnthropicBody({ temperature: 0.7, max_tokens: 8000 }, 'claude-opus-5');
+ expect(out.temperature).toBeUndefined();
+ });
+
+ it('keeps temperature for models that accept it', () => {
+ const out = sanitizeAnthropicBody({ temperature: 0.7, max_tokens: 600 }, 'claude-haiku-4-5-20251001');
+ expect(out.temperature).toBe(0.7);
+ expect(out.max_tokens).toBe(600);
+ });
+
+ it('upgrades the removed budget_tokens thinking form to adaptive', () => {
+ const out = sanitizeAnthropicBody(
+ { max_tokens: 8000, thinking: { type: 'enabled', budget_tokens: 2000 } },
+ 'claude-opus-5',
+ );
+ expect(out.thinking).toEqual({ type: 'adaptive' });
+ });
+
+ it('drops an explicit disabled-thinking config on Fable (always-on model)', () => {
+ const out = sanitizeAnthropicBody(
+ { max_tokens: 8000, thinking: { type: 'disabled' } },
+ 'claude-fable-5',
+ );
+ expect(out.thinking).toBeUndefined();
+ });
+
+ it('preserves an adaptive thinking config with a display preference', () => {
+ const thinking = { type: 'adaptive', display: 'summarized' };
+ const out = sanitizeAnthropicBody({ max_tokens: 8000, thinking }, 'claude-fable-5');
+ expect(out.thinking).toEqual(thinking);
+ });
+
+ it('floors max_tokens on thinking-by-default models so the reply survives', () => {
+ // A 300-token cap would be spent entirely on thinking, returning an empty
+ // visible reply with no error.
+ const out = sanitizeAnthropicBody({ max_tokens: 300 }, 'claude-sonnet-5');
+ expect(out.max_tokens).toBeGreaterThanOrEqual(4096);
+ });
+
+ it('never lowers a caller budget that is already generous', () => {
+ const out = sanitizeAnthropicBody({ max_tokens: 16_000 }, 'claude-opus-5');
+ expect(out.max_tokens).toBe(16_000);
+ });
+
+ it('adds a cache breakpoint to a large string system prompt', () => {
+ const out = sanitizeAnthropicBody({ system: 'x'.repeat(5000), max_tokens: 8000 }, 'claude-sonnet-5');
+ expect(Array.isArray(out.system)).toBe(true);
+ expect(out.system[0].cache_control).toEqual({ type: 'ephemeral' });
+ expect(out.system[0].text).toHaveLength(5000);
+ });
+
+ it('leaves a short system prompt as a plain string', () => {
+ const out = sanitizeAnthropicBody({ system: 'be brief', max_tokens: 8000 }, 'claude-sonnet-5');
+ expect(out.system).toBe('be brief');
+ });
+
+ it('does not clobber a caller-supplied block array system prompt', () => {
+ const system = [{ type: 'text', text: 'x'.repeat(5000), cache_control: { type: 'ephemeral' } }];
+ const out = sanitizeAnthropicBody({ system, max_tokens: 8000 }, 'claude-sonnet-5');
+ expect(out.system).toBe(system);
+ });
+
+ it('does not mutate the caller body', () => {
+ const body = { temperature: 0.7, max_tokens: 300, thinking: { type: 'enabled', budget_tokens: 100 } };
+ sanitizeAnthropicBody(body, 'claude-opus-5');
+ expect(body.temperature).toBe(0.7);
+ expect(body.max_tokens).toBe(300);
+ expect(body.thinking).toEqual({ type: 'enabled', budget_tokens: 100 });
+ });
+});
diff --git a/tests/api/3d-studio.test.js b/tests/api/3d-studio.test.js
index 2ede63d27..d9d5d8982 100644
--- a/tests/api/3d-studio.test.js
+++ b/tests/api/3d-studio.test.js
@@ -166,6 +166,32 @@ describe('shape helpers — Actions wire contract', () => {
expectCleanWire(out);
});
+ // Pending states carry watchUrl — the live three.ws progress page (countdown +
+ // concept art) the GPT hands the user so the wait happens in a real browser tab
+ // that funnels into /viewer when the model lands. Done states never carry it.
+ it('shapeSubmit and shapePoll attach watchUrl to pending states only', async () => {
+ const { shapeSubmit, shapePoll } = await import('../../api/3d/studio.js');
+ const wanted =
+ 'https://three.ws/watch?job=' +
+ encodeURIComponent(SUBMIT_QUEUED.job_id) +
+ '&title=' +
+ encodeURIComponent('a small ceramic robot figurine');
+
+ const queued = shapeSubmit(SUBMIT_QUEUED, 'https://three.ws', 'a small ceramic robot figurine');
+ expect(queued.watchUrl).toBe(wanted);
+
+ const pending = shapePoll(POLL_RUNNING, 'https://three.ws', SUBMIT_QUEUED.job_id, 'a small ceramic robot figurine');
+ expect(pending.watchUrl).toBe(wanted);
+
+ // Bare handle (no title) still gets a watch link.
+ const bare = shapePoll(POLL_RUNNING, 'https://three.ws', SUBMIT_QUEUED.job_id);
+ expect(bare.watchUrl).toBe('https://three.ws/watch?job=' + encodeURIComponent(SUBMIT_QUEUED.job_id));
+
+ // Done responses point at the viewer, not the waiting room.
+ expect(shapeSubmit(SUBMIT_DONE, 'https://three.ws', 'x').watchUrl).toBeUndefined();
+ expect(shapePoll(POLL_DONE, 'https://three.ws', SUBMIT_QUEUED.job_id, 'x').watchUrl).toBeUndefined();
+ });
+
it('shapePoll maps done/running/failed forge shapes cleanly, echoing the title into arUrl', async () => {
const { shapePoll } = await import('../../api/3d/studio.js');
const done = shapePoll(POLL_DONE, 'https://three.ws', SUBMIT_QUEUED.job_id, 'a tiny fox');
diff --git a/tests/shared-markdown.test.js b/tests/shared-markdown.test.js
new file mode 100644
index 000000000..491b7d2d9
--- /dev/null
+++ b/tests/shared-markdown.test.js
@@ -0,0 +1,138 @@
+// @vitest-environment jsdom
+//
+// The shared sanitized Markdown pipeline (src/shared/markdown.js). This module
+// replaced eight hand-rolled renderers, so the suite covers both the feature
+// surface those renderers lacked (tables, nested lists, GFM) and the injection
+// vectors they were individually responsible for blocking.
+import { describe, it, expect } from 'vitest';
+import { renderMarkdown, stripMarkdown } from '../src/shared/markdown.js';
+
+describe('renderMarkdown — structure', () => {
+ it('renders headings, emphasis, and code', () => {
+ const html = renderMarkdown('# Title\n\nSome **bold** and `code`.');
+ expect(html).toContain('<h1>Title</h1>');
+ expect(html).toContain('<strong>bold</strong>');
+ expect(html).toContain('<code>code</code>');
+ });
+
+ it('renders fenced code blocks with the content escaped', () => {
+ const html = renderMarkdown('```\n<script>x</script>\n```');
+ expect(html).toContain('<pre>');
+ expect(html).toContain('&lt;script&gt;');
+ expect(html).not.toContain('<script>');
+ });
+
+ it('renders GFM tables (no hand-rolled renderer supported these)', () => {
+ const html = renderMarkdown('| a | b |\n|---|---|\n| 1 | 2 |');
+ expect(html).toContain('<table>');
+ expect(html).toContain('<td>1</td>');
+ });
+
+ it('renders nested lists (the hand-rolled renderers flattened them)', () => {
+ const html = renderMarkdown('- outer\n - inner');
+ expect(html).toContain('<ul>');
+ expect(html.match(/<ul>/g).length).toBeGreaterThan(1);
+ expect(html).toContain('inner');
+ });
+
+ it('renders ordered lists as ol, not ul', () => {
+ const html = renderMarkdown('1. first\n2. second');
+ expect(html).toContain('<ol>');
+ expect(html).toContain('<li>first</li>');
+ });
+
+ it('returns an empty string for null/empty input', () => {
+ expect(renderMarkdown(null)).toBe('');
+ expect(renderMarkdown('')).toBe('');
+ expect(renderMarkdown(undefined)).toBe('');
+ });
+});
+
+describe('renderMarkdown — sanitization', () => {
+ it('strips raw script tags', () => {
+ const html = renderMarkdown('hello <script>alert(1)</script> world');
+ expect(html).not.toContain('<script');
+ expect(html).not.toContain('alert(1)');
+ });
+
+ it('strips inline event handlers', () => {
+ const html = renderMarkdown('<div onclick="alert(1)">click</div>');
+ expect(html).not.toContain('onclick');
+ });
+
+ it('strips img-based payloads (no media tags allowed)', () => {
+ const html = renderMarkdown('![x](https://e.example/a.png "t")\n\n<img src=x onerror=alert(1)>');
+ expect(html).not.toContain('<img');
+ expect(html).not.toContain('onerror');
+ });
+
+ it('drops javascript: hrefs but keeps the link text', () => {
+ const html = renderMarkdown('[click me](javascript:alert(1))');
+ expect(html).not.toContain('javascript:');
+ expect(html).toContain('click me');
+ });
+
+ it('drops data: hrefs', () => {
+ const html = renderMarkdown('[x](data:text/html;base64,PHNjcmlwdD4=)');
+ expect(html).not.toContain('data:text/html');
+ });
+
+ it('hardens allowed links with target and rel', () => {
+ const html = renderMarkdown('[three](https://three.ws)');
+ expect(html).toContain('href="https://three.ws"');
+ expect(html).toContain('rel="noopener noreferrer nofollow"');
+ expect(html).toContain('target="_blank"');
+ });
+
+ it('keeps root-relative and anchor hrefs', () => {
+ expect(renderMarkdown('[a](/create)')).toContain('href="/create"');
+ expect(renderMarkdown('[a](#top)')).toContain('href="#top"');
+ });
+
+ it('strips style, iframe, and form elements', () => {
+ const html = renderMarkdown('<style>body{}</style><iframe src="x"></iframe><form><input></form>');
+ expect(html).not.toContain('<style');
+ expect(html).not.toContain('<iframe');
+ expect(html).not.toContain('<form');
+ expect(html).not.toContain('<input');
+ });
+});
+
+describe('renderMarkdown — options', () => {
+ it('applies caller CSS classes so existing page styles keep working', () => {
+ const html = renderMarkdown('# T\n\n- a', { classes: { h1: 'md-h1', ul: 'md-ul' } });
+ expect(html).toContain('class="md-h1"');
+ expect(html).toContain('class="md-ul"');
+ });
+
+ it('demotes headings by the requested number of levels', () => {
+ const html = renderMarkdown('# One\n\n## Two', { demoteHeadings: 2 });
+ expect(html).toContain('<h3>One</h3>');
+ expect(html).toContain('<h4>Two</h4>');
+ });
+
+ it('clamps demoted headings at h6', () => {
+ const html = renderMarkdown('##### Five', { demoteHeadings: 3 });
+ expect(html).toContain('<h6>Five</h6>');
+ });
+});
+
+describe('stripMarkdown', () => {
+ it('removes syntax and leaves the words', () => {
+ expect(stripMarkdown('# Hi\n\n**bold** and `code` and [link](https://x.example)')).toBe(
+ 'Hi bold and code and link',
+ );
+ });
+
+ it('drops fenced code blocks', () => {
+ expect(stripMarkdown('before\n```\nconst x = 1\n```\nafter')).toBe('before after');
+ });
+
+ it('flattens list markers and quotes', () => {
+ expect(stripMarkdown('- one\n- two\n\n> quoted')).toBe('one two quoted');
+ });
+
+ it('handles null input', () => {
+ expect(stripMarkdown(null)).toBe('');
+ });
+});
diff --git a/vercel.json b/vercel.json
index cc269717f..f5706e9cd 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1403,6 +1403,10 @@
},
"dest": "/viewer.html"
},
+ {
+ "src": "/watch/?",
+ "dest": "/watch.html"
+ },
{
"src": "/ar/studio/?",
"headers": {
@@ -5595,6 +5599,10 @@
"path": "/api/cron/treasury-sweepback",
"schedule": "41 */6 * * *"
},
+ {
+ "path": "/api/cron/free-model-audit",
+ "schedule": "17 */6 * * *"
+ },
{
"path": "/api/cron/economy-reconcile",
"schedule": "*/30 * * * *"