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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(3d-studio): document /api/ar in the Actions schema and pin the two copies together
nirholas8fb3559e504f
diff --git a/api/3d/studio.js b/api/3d/studio.jsindex ced500cb6..1ed066939 100644--- a/api/3d/studio.js+++ b/api/3d/studio.js@@ -45,7 +45,7 @@// returns 'pending' + a poll handle before the Action deadline instead of dying// on the socket.-import { cors, wrap, method, json, error, readJson, rateLimited } from '../_lib/http.js';+import { cors, wrap, method, json, readJson, setRateLimitHeaders } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { startForge, originFromReq, viewerUrl, arLaunchUrl } from '../_mcp-studio/gpt-forge-client.js';import { checkPromptSafety } from '../_mcp-studio/safety.js';@@ -155,6 +155,17 @@ export function shapePoll(data, base, jobId, title) {};}+// Every error body on this route is an ErrorResponse from the published Actions+// schema: { error, message, retry_after? }. The generic http.js helpers emit+// `error_description` instead of `message`, which the custom GPT has no field+// for, so the two limiter paths shape their own body while still setting the+// RateLimit-* / Retry-After headers a polling client backs off on.+function limitReached(res, result, message) {+ const retryAfter = Math.max(1, setRateLimitHeaders(res, result));+ res.setHeader('retry-after', String(retryAfter));+ return json(res, 429, { error: 'rate_limited', message, retry_after: retryAfter });+}+// Map a startForge lane failure to an honest boundary response. A well-formed// prompt must NEVER 500: every code has a designed status + actionable message.function failFromLane(res, err) {@@ -236,7 +247,7 @@ async function generate(req, res) {// /api/gpt-forge draw from, so this surface adds no new unmetered capacity.const rl = await limits.mcp3dGenerateFree(ip);if (!rl.success) {- return rateLimited(res, rl, 'Free 3D generation limit reached — try again in a little while.');+ return limitReached(res, rl, 'Free 3D generation limit reached. Try again in a little while.');}const base = originFromReq(req);@@ -277,7 +288,7 @@ async function poll(req, res, jobId, title) {// Cheap, high-frequency poll — reuse the forge status limiter (per-instance,// flood-guard only) so a polling loop can't be turned into a hammer.const rl = await limits.mcp3dStatus(clientIp(req));- if (!rl.success) return rateLimited(res, rl, 'Polling too fast — slow down and retry.');+ if (!rl.success) return limitReached(res, rl, 'Polling too fast. Slow down and retry.');const base = originFromReq(req);let upstream;@@ -318,7 +329,10 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://localhost');const jobId = (url.searchParams.get('job') || '').trim();if (!jobId) {- return error(res, 400, 'missing_job', 'Pass ?job=<id> to poll a generation, or POST { prompt } to start one.');+ return json(res, 400, {+ error: 'missing_job',+ message: 'Pass ?job=<id> to poll a generation, or POST { prompt } to start one.',+ });}const title = (url.searchParams.get('title') || '').trim().slice(0, 120);return poll(req, res, jobId, title);diff --git a/api/ar.js b/api/ar.jsindex 14274cf5e..d6c39b9bc 100644--- a/api/ar.js+++ b/api/ar.js@@ -24,6 +24,7 @@import { cors, wrap } from './_lib/http.js';import { planArLaunch } from './_lib/ar-launch.js';+import { MODEL_VIEWER_SRC } from './_lib/model-viewer-cdn.js';function esc(s) {return String(s || '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));@@ -69,7 +70,7 @@ function launchPage({ target, asset, viewerUrl, title, irlUrl, origin, pageUrl }<meta name="twitter:description" content="${esc(ogDesc)}"/><meta name="twitter:image" content="${esc(ogImage)}"/><script src="/model-viewer-meshopt.js"></script>-<script type="module" src="https://cdn.jsdelivr.net/npm/@google/[email protected]/dist/model-viewer.min.js"></script>+<script type="module" src="${MODEL_VIEWER_SRC}"></script><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,#08090c);color:#e8eaf0;overflow:hidden}.wrap{display:flex;flex-direction:column;height:100dvh}.stage{position:relative;flex:1 1 auto;min-height:0}diff --git a/data/guards.json b/data/guards.jsonindex a891f482c..4ca337c89 100644--- a/data/guards.json+++ b/data/guards.json@@ -78,6 +78,30 @@"expect": "guard-proof-nonexistent"}},+ {+ "id": "sync-studio-openapi",+ "script": "scripts/sync-studio-openapi.mjs",+ "npm": "check:studio-openapi",+ "npmAliases": [+ "sync:studio-openapi"+ ],+ "title": "3D Studio OpenAPI sync",+ "protects": "The custom-GPT Actions file in the OpenAI submission kit is byte-identical to the OpenAPI schema three.ws actually serves.",+ "why": "The served schema at public/.well-known/3d-studio-openapi.yaml is what https://three.ws/.well-known/3d-studio-openapi.yaml returns and what the GPT builder imports by URL, while prompts/store-submissions/_generated/openai-actions.yaml is the copy an OpenAI reviewer reads. Two hand-maintained copies of one contract drift, and the drift shows up as a reviewer reading a document the runtime does not serve. The served file is the source of truth and the copy is regenerated from it.",+ "stages": [+ "gate"+ ],+ "needs": "none",+ "proof": {+ "summary": "The submission kit shipping an Actions contract that no longer matches the schema the site serves.",+ "violation": {+ "append": {+ "public/.well-known/3d-studio-openapi.yaml": "\n# drift fixture: served schema edited without regenerating the submission copy\n"+ }+ },+ "expect": "drift"+ }+ },{"id": "check-rules","script": "scripts/check-rules.mjs",diff --git a/package.json b/package.jsonindex acb9a1b40..dc9de1a5c 100644--- a/package.json+++ b/package.json@@ -156,7 +156,7 @@"audit:route-shadowing": "node scripts/audit-route-shadowing.mjs","audit:handlers": "node scripts/audit-empty-handlers.mjs","audit:x402-catalog": "node scripts/audit-x402-catalog.mjs",- "gate": "npm run check:conflicts && npm run check:claude && npm run check:cron-syntax && npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:mcp-safety && npm run audit:mcp-catalog && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:docs && npm run check:tutorials && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens && npm run audit:guards && npm run audit:tour-atlas",+ "gate": "npm run check:conflicts && npm run check:claude && npm run check:cron-syntax && npm run check:studio-openapi && npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:mcp-safety && npm run audit:mcp-catalog && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:docs && npm run check:tutorials && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens && npm run audit:guards && npm run audit:tour-atlas","test:gate-3d": "vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js","audit:mcp-golden": "node scripts/audit-mcp-golden.mjs","audit:mcp-safety": "node scripts/audit-mcp-safety.mjs",@@ -319,7 +319,9 @@"capture:docs-world": "node scripts/capture-docs-media.mjs","check:runnable-docs": "node scripts/check-runnable-docs.mjs","capture:doc-media": "node scripts/capture-doc-media.mjs",- "check:doc-media": "node scripts/check-doc-media.mjs"+ "check:doc-media": "node scripts/check-doc-media.mjs",+ "sync:studio-openapi": "node scripts/sync-studio-openapi.mjs",+ "check:studio-openapi": "node scripts/sync-studio-openapi.mjs --check"},"dependencies": {"@0xsplits/splits-sdk": "^6.5.0",diff --git a/prompts/store-submissions/_generated/openai-actions.yaml b/prompts/store-submissions/_generated/openai-actions.yamlindex fb978c5c9..012b14208 100644--- a/prompts/store-submissions/_generated/openai-actions.yaml+++ b/prompts/store-submissions/_generated/openai-actions.yaml@@ -25,7 +25,9 @@ info:it to the user while the model is still generating. arUrl is theaugmented-reality launch link: opened on a phone it places the model inthe user's real room (Quick Look on iPhone, Scene Viewer on Android);- always offer it alongside the viewer link.+ always offer it alongside the viewer link. GET /api/ar is the endpoint+ behind that link and is described below, so the whole free surface of+ the studio is documented here.contact:name: three.wsurl: https://three.ws@@ -192,6 +194,76 @@ paths:application/json:schema:$ref: "#/components/schemas/ErrorResponse"+ /api/ar:+ get:+ operationId: openModelInAR+ x-openai-isConsequential: false+ summary: Augmented-reality launch for a finished model+ description: >-+ The endpoint every arUrl points at. Given a public https .glb, it+ serves a device-aware way to place that model in the user's real room:+ an Android phone is redirected into Google Scene Viewer, an iPhone gets+ a launch page whose "View in AR" button enters Apple Quick Look, and a+ desktop browser falls back to the interactive viewer. The response is a+ web page meant for a person to open, so the way to use this in a+ conversation is to hand the user the arUrl from generate3DModel or+ checkModelJob. Free and keyless like the rest of this API.+ parameters:+ - name: src+ in: query+ required: true+ schema:+ type: string+ format: uri+ maxLength: 2048+ description: >-+ Public https URL of the model to place, ending in .glb or .gltf.+ This is the glbUrl of a finished generation.+ - name: title+ in: query+ required: false+ schema:+ type: string+ maxLength: 120+ description: >-+ Short label for the model (usually the prompt). It names the AR+ launch page and its share card.+ - name: kind+ in: query+ required: false+ schema:+ type: string+ enum: [avatar]+ description: >-+ Set to "avatar" when the model is a rigged humanoid. It keeps+ Android on the launch page and adds the handoff that brings the+ character to life in the room instead of placing it as a static+ object.+ responses:+ "200":+ description: >-+ The AR launch page (iPhone and desktop, and any rigged avatar).+ content:+ text/html:+ schema:+ type: string+ "302":+ description: >-+ Redirect straight into Google Scene Viewer, for a static model on+ Android. The Location header carries the AR launch URL.+ headers:+ Location:+ description: The Scene Viewer launch URL.+ schema:+ type: string+ "400":+ description: >-+ The src value is missing, is not https, or does not point at a .glb+ or .gltf file. A designed error page explains what to fix.+ content:+ text/html:+ schema:+ type: stringcomponents:schemas:GenerationState:diff --git a/public/.well-known/3d-studio-openapi.yaml b/public/.well-known/3d-studio-openapi.yamlindex fb978c5c9..012b14208 100644--- a/public/.well-known/3d-studio-openapi.yaml+++ b/public/.well-known/3d-studio-openapi.yaml@@ -25,7 +25,9 @@ info:it to the user while the model is still generating. arUrl is theaugmented-reality launch link: opened on a phone it places the model inthe user's real room (Quick Look on iPhone, Scene Viewer on Android);- always offer it alongside the viewer link.+ always offer it alongside the viewer link. GET /api/ar is the endpoint+ behind that link and is described below, so the whole free surface of+ the studio is documented here.contact:name: three.wsurl: https://three.ws@@ -192,6 +194,76 @@ paths:application/json:schema:$ref: "#/components/schemas/ErrorResponse"+ /api/ar:+ get:+ operationId: openModelInAR+ x-openai-isConsequential: false+ summary: Augmented-reality launch for a finished model+ description: >-+ The endpoint every arUrl points at. Given a public https .glb, it+ serves a device-aware way to place that model in the user's real room:+ an Android phone is redirected into Google Scene Viewer, an iPhone gets+ a launch page whose "View in AR" button enters Apple Quick Look, and a+ desktop browser falls back to the interactive viewer. The response is a+ web page meant for a person to open, so the way to use this in a+ conversation is to hand the user the arUrl from generate3DModel or+ checkModelJob. Free and keyless like the rest of this API.+ parameters:+ - name: src+ in: query+ required: true+ schema:+ type: string+ format: uri+ maxLength: 2048+ description: >-+ Public https URL of the model to place, ending in .glb or .gltf.+ This is the glbUrl of a finished generation.+ - name: title+ in: query+ required: false+ schema:+ type: string+ maxLength: 120+ description: >-+ Short label for the model (usually the prompt). It names the AR+ launch page and its share card.+ - name: kind+ in: query+ required: false+ schema:+ type: string+ enum: [avatar]+ description: >-+ Set to "avatar" when the model is a rigged humanoid. It keeps+ Android on the launch page and adds the handoff that brings the+ character to life in the room instead of placing it as a static+ object.+ responses:+ "200":+ description: >-+ The AR launch page (iPhone and desktop, and any rigged avatar).+ content:+ text/html:+ schema:+ type: string+ "302":+ description: >-+ Redirect straight into Google Scene Viewer, for a static model on+ Android. The Location header carries the AR launch URL.+ headers:+ Location:+ description: The Scene Viewer launch URL.+ schema:+ type: string+ "400":+ description: >-+ The src value is missing, is not https, or does not point at a .glb+ or .gltf file. A designed error page explains what to fix.+ content:+ text/html:+ schema:+ type: stringcomponents:schemas:GenerationState:diff --git a/public/guards.json b/public/guards.jsonindex a891f482c..4ca337c89 100644--- a/public/guards.json+++ b/public/guards.json@@ -78,6 +78,30 @@"expect": "guard-proof-nonexistent"}},+ {+ "id": "sync-studio-openapi",+ "script": "scripts/sync-studio-openapi.mjs",+ "npm": "check:studio-openapi",+ "npmAliases": [+ "sync:studio-openapi"+ ],+ "title": "3D Studio OpenAPI sync",+ "protects": "The custom-GPT Actions file in the OpenAI submission kit is byte-identical to the OpenAPI schema three.ws actually serves.",+ "why": "The served schema at public/.well-known/3d-studio-openapi.yaml is what https://three.ws/.well-known/3d-studio-openapi.yaml returns and what the GPT builder imports by URL, while prompts/store-submissions/_generated/openai-actions.yaml is the copy an OpenAI reviewer reads. Two hand-maintained copies of one contract drift, and the drift shows up as a reviewer reading a document the runtime does not serve. The served file is the source of truth and the copy is regenerated from it.",+ "stages": [+ "gate"+ ],+ "needs": "none",+ "proof": {+ "summary": "The submission kit shipping an Actions contract that no longer matches the schema the site serves.",+ "violation": {+ "append": {+ "public/.well-known/3d-studio-openapi.yaml": "\n# drift fixture: served schema edited without regenerating the submission copy\n"+ }+ },+ "expect": "drift"+ }+ },{"id": "check-rules","script": "scripts/check-rules.mjs",diff --git a/scripts/sync-studio-openapi.mjs b/scripts/sync-studio-openapi.mjsnew file mode 100644index 000000000..b3a5ecea2--- /dev/null+++ b/scripts/sync-studio-openapi.mjs@@ -0,0 +1,57 @@+#!/usr/bin/env node+// Keeps the custom-GPT Actions file in step with the served 3D Studio schema.+//+// public/.well-known/3d-studio-openapi.yaml is the source of truth: it is what+// https://three.ws/.well-known/3d-studio-openapi.yaml returns and what the GPT+// builder imports by URL (see docs/chatgpt-3d-studio-gpt.md). The submission kit+// carries a byte copy at prompts/store-submissions/_generated/openai-actions.yaml+// so the package an OpenAI reviewer reads is the same document the site serves.+// Neither copy is hand-maintained: edit the served one, then run this.+//+// node scripts/sync-studio-openapi.mjs regenerate the copy+// node scripts/sync-studio-openapi.mjs --check exit 1 if the copy drifted+//+// The same invariant is asserted from the test side in+// tests/api/3d-studio-openapi.test.js, which also guards the schema's contents.++import { readFileSync, writeFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, relative, resolve } from 'node:path';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const SERVED = resolve(ROOT, 'public/.well-known/3d-studio-openapi.yaml');+const COPY = resolve(ROOT, 'prompts/store-submissions/_generated/openai-actions.yaml');++const rel = (p) => relative(ROOT, p);+const check = process.argv.includes('--check');++let served;+try {+ served = readFileSync(SERVED, 'utf8');+} catch {+ console.error(`Missing the served 3D Studio schema at ${rel(SERVED)}.`);+ console.error('It is the source of truth for the custom-GPT Actions contract and must exist.');+ process.exit(1);+}++let copy = null;+try {+ copy = readFileSync(COPY, 'utf8');+} catch {+ copy = null;+}++if (copy === served) {+ console.log(`3D Studio OpenAPI in sync: ${rel(COPY)} matches ${rel(SERVED)}.`);+ process.exit(0);+}++if (check) {+ console.error(`3D Studio OpenAPI drift: ${rel(COPY)} does not match ${rel(SERVED)}.`);+ console.error(copy === null ? 'The submission copy is missing.' : 'The two copies differ.');+ console.error('Fix: edit the served schema, then run `npm run sync:studio-openapi`.');+ process.exit(1);+}++writeFileSync(COPY, served);+console.log(`Wrote ${rel(COPY)} from ${rel(SERVED)}.`);diff --git a/tests/api/3d-studio-actions-contract.test.js b/tests/api/3d-studio-actions-contract.test.jsnew file mode 100644index 000000000..29a6b9df2--- /dev/null+++ b/tests/api/3d-studio-actions-contract.test.js@@ -0,0 +1,318 @@+// Contract test: every body POST/GET /api/3d/studio can put on the wire must+// validate against the OpenAPI schema three.ws serves to the custom GPT builder+// (public/.well-known/3d-studio-openapi.yaml, byte-identical to+// prompts/store-submissions/_generated/openai-actions.yaml).+//+// tests/api/3d-studio.test.js pins the handler's behaviour and+// tests/api/3d-studio-openapi.test.js pins the schema document itself. Neither+// binds one to the other: a response key could change type, a required field+// could go missing, or an error body could use a field name the GPT has no slot+// for, and both suites would stay green while the Action broke in ChatGPT.+//+// The schemas are OpenAPI 3.1, which is JSON Schema 2020-12, so ajv (already a+// dependency) validates them directly with no conversion layer.+//+// The lane itself is stubbed at the network boundary (global fetch, standing in+// for the self-call to /api/gpt-forge) using the real captured forge payloads.+// Everything downstream of that seam is the real handler, the real shapers, and+// the real schema.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';+import { Readable } from 'node:stream';+import { parse } from 'yaml';+import Ajv from 'ajv/dist/2020.js';+import addFormats from 'ajv-formats';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../..');+const spec = parse(readFileSync(resolve(ROOT, 'public/.well-known/3d-studio-openapi.yaml'), 'utf8'));++const ajv = new Ajv({ strict: false, allErrors: true });+addFormats(ajv);+// `const: glb` and `format: uri` come straight from the served document; nothing+// is relaxed for the test, so a response that ChatGPT would reject fails here.+const validateState = ajv.compile(spec.components.schemas.GenerationState);+const validateError = ajv.compile(spec.components.schemas.ErrorResponse);+const validateGenerateBody = ajv.compile(spec.paths['/api/3d/studio'].post.requestBody.content['application/json'].schema);++function why(validate) {+ return (validate.errors || []).map((e) => `${e.instancePath || '/'} ${e.message}`).join('; ');+}++function expectValidState(body, label) {+ expect(validateState(body), `${label}: ${why(validateState)}\n${JSON.stringify(body)}`).toBe(true);+}++function expectValidError(body, label) {+ expect(validateError(body), `${label}: ${why(validateError)}\n${JSON.stringify(body)}`).toBe(true);+}++// ── the handler under a stubbed lane ─────────────────────────────────────────++let freeOk = true;+let statusOk = true;+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ mcp3dGenerateFree: async () =>+ freeOk+ ? { success: true, limit: 60, remaining: 59, reset: Date.now() + 3_600_000 }+ : { success: false, limit: 60, remaining: 0, reset: Date.now() + 3_600_000 },+ mcp3dStatus: async () =>+ statusOk+ ? { success: true, limit: 240, remaining: 239, reset: Date.now() + 60_000 }+ : { success: false, limit: 240, remaining: 0, reset: Date.now() + 60_000 },+ },+ clientIp: () => '203.0.113.9',+}));++const ORIGINAL_FETCH = globalThis.fetch;++beforeEach(() => {+ freeOk = true;+ statusOk = true;+});+afterEach(() => {+ globalThis.fetch = ORIGINAL_FETCH;+ vi.restoreAllMocks();+});++function makeReq({ method = 'POST', url = '/api/3d/studio', body = null } = {}) {+ const raw = body == null ? '' : JSON.stringify(body);+ const stream = Readable.from(raw ? [Buffer.from(raw)] : []);+ stream.method = method;+ stream.url = url;+ stream.headers = { 'content-type': 'application/json', host: 'three.ws' };+ return stream;+}++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(b) { this._body = b; this.writableEnded = true; },+ };+}++async function dispatch(req) {+ const res = makeRes();+ const mod = await import('../../api/3d/studio.js');+ await mod.default(req, res);+ return { status: res.statusCode, body: res._body ? JSON.parse(res._body) : null };+}++// The network seam: one canned /api/gpt-forge reply per test.+function stubForge(payload, { status = 200 } = {}) {+ globalThis.fetch = vi.fn(async () => ({+ ok: status >= 200 && status < 300,+ status,+ headers: { get: () => 'application/json' },+ json: async () => payload,+ text: async () => JSON.stringify(payload),+ }));+}++// Real captured /api/forge draft-lane shapes (NVIDIA NIM TRELLIS), the same+// fixtures tests/api/3d-studio.test.js drives the handler with.+const FORGE_DONE = {+ job_id: null,+ creation_id: 'a1b2c3d4-0000-4000-8000-000000000001',+ status: 'done',+ glb_url: 'https://three.ws/cdn/forge/anon/a1b2c3d4.glb',+ durable: true,+ backend: 'nvidia',+ tier: 'draft',+ path: 'image',+};+const FORGE_QUEUED = {+ job_id: 'f1.eyJwIjoibnZpZGlhIiwiayI6InRleHQiLCJ0IjoibmltLXRhc2stMTIzIn0.c2lnbmF0dXJl',+ creation_id: 'a1b2c3d4-0000-4000-8000-000000000002',+ status: 'queued',+ tier: 'high',+ eta_seconds: 240,+ preview_image_url: 'https://three.ws/cdn/forge/anon/ref-view.png',+};+const FORGE_RUNNING = { job_id: FORGE_QUEUED.job_id, status: 'running', eta_remaining_seconds: 90, elapsed_seconds: 30 };+const FORGE_FAILED = { job_id: FORGE_QUEUED.job_id, status: 'failed', error: 'the generator hit a snag' };++const POLL_URL = `/api/3d/studio?job=${encodeURIComponent(FORGE_QUEUED.job_id)}&title=a%20low-poly%20fox`;++describe('POST /api/3d/studio bodies validate against the served GenerationState', () => {+ it('an inline-done generation', async () => {+ stubForge(FORGE_DONE);+ const { status, body } = await dispatch(makeReq({ body: { prompt: 'a low-poly fox' } }));+ expect(status).toBe(200);+ expectValidState(body, 'submit done');+ expect(body.status).toBe('done');+ expect(body.format).toBe('glb');+ });++ it('a queued generation carrying the poll handle, watch page, concept art and ETA', async () => {+ stubForge(FORGE_QUEUED);+ const { status, body } = await dispatch(makeReq({ body: { prompt: 'a low-poly fox', tier: 'high' } }));+ expect(status).toBe(200);+ expectValidState(body, 'submit pending');+ expect(body.status).toBe('pending');+ expect(typeof body.job).toBe('string');+ expect(typeof body.poll).toBe('string');+ expect(body.etaSeconds).toBe(240);+ });+});++describe('GET /api/3d/studio?job= bodies validate against the served GenerationState', () => {+ it('a still-running poll', async () => {+ stubForge(FORGE_RUNNING);+ const { status, body } = await dispatch(makeReq({ method: 'GET', url: POLL_URL, body: null }));+ expect(status).toBe(200);+ expectValidState(body, 'poll pending');+ expect(body).toMatchObject({ status: 'pending', etaSeconds: 90, elapsedSeconds: 30 });+ });++ it('a finished poll', async () => {+ stubForge({ job_id: FORGE_QUEUED.job_id, status: 'done', glb_url: 'https://three.ws/cdn/forge/anon/done.glb', durable: true });+ const { status, body } = await dispatch(makeReq({ method: 'GET', url: POLL_URL, body: null }));+ expect(status).toBe(200);+ expectValidState(body, 'poll done');+ expect(body.arUrl.startsWith('https://three.ws/api/ar?src=')).toBe(true);+ });++ it('a failed poll, which the schema calls status "error"', async () => {+ stubForge(FORGE_FAILED);+ const { status, body } = await dispatch(makeReq({ method: 'GET', url: POLL_URL, body: null }));+ expect(status).toBe(200);+ expectValidState(body, 'poll failed');+ expect(body.status).toBe('error');+ expect(typeof body.error).toBe('string');+ });++ it('a transient upstream hiccup stays a valid pending state rather than an error', async () => {+ stubForge({ message: 'bad gateway' }, { status: 502 });+ const { status, body } = await dispatch(makeReq({ method: 'GET', url: POLL_URL, body: null }));+ expect(status).toBe(200);+ expectValidState(body, 'poll upstream 5xx');+ expect(body.status).toBe('pending');+ });+});++describe('error bodies validate against the served ErrorResponse', () => {+ // Each documented failure code in the schema, driven through the real handler.+ it('400 invalid_prompt (too short)', async () => {+ const { status, body } = await dispatch(makeReq({ body: { prompt: 'a' } }));+ expect(status).toBe(400);+ expectValidError(body, 'invalid_prompt');+ });++ it('400 invalid_tier', async () => {+ const { status, body } = await dispatch(makeReq({ body: { prompt: 'a low-poly fox', tier: 'ultra' } }));+ expect(status).toBe(400);+ expectValidError(body, 'invalid_tier');+ });++ it('400 prompt_rejected from the age-13+ safety gate', async () => {+ const { status, body } = await dispatch(makeReq({ body: { prompt: 'a nude woman posing explicitly' } }));+ expect(status).toBe(400);+ expect(body.error).toBe('prompt_rejected');+ expectValidError(body, 'prompt_rejected');+ });++ it('400 bad_request on a non-JSON body', async () => {+ const stream = Readable.from([Buffer.from('not json at all')]);+ stream.method = 'POST';+ stream.url = '/api/3d/studio';+ stream.headers = { 'content-type': 'application/json', host: 'three.ws' };+ const { status, body } = await dispatch(stream);+ expect(status).toBe(400);+ expectValidError(body, 'bad_request');+ });++ it('400 missing_job on a bare GET', async () => {+ const { status, body } = await dispatch(makeReq({ method: 'GET', url: '/api/3d/studio', body: null }));+ expect(status).toBe(400);+ expectValidError(body, 'missing_job');+ });++ it('400 invalid_job on a malformed handle', async () => {+ const { status, body } = await dispatch(makeReq({ method: 'GET', url: '/api/3d/studio?job=%20%20nope', body: null }));+ expect(status).toBe(400);+ expectValidError(body, 'invalid_job');+ });++ it('429 rate_limited on the free generation cap, with retry_after', async () => {+ freeOk = false;+ const { status, body } = await dispatch(makeReq({ body: { prompt: 'a low-poly fox' } }));+ expect(status).toBe(429);+ expectValidError(body, 'generate rate_limited');+ expect(Number.isInteger(body.retry_after)).toBe(true);+ });++ it('429 rate_limited on the poll cap, with retry_after', async () => {+ statusOk = false;+ const { status, body } = await dispatch(makeReq({ method: 'GET', url: POLL_URL, body: null }));+ expect(status).toBe(429);+ expectValidError(body, 'poll rate_limited');+ expect(Number.isInteger(body.retry_after)).toBe(true);+ });++ it('429 rate_limited when the upstream lane itself is saturated', async () => {+ stubForge({ message: 'the free 3D generator is busy', retry_after: 12 }, { status: 429 });+ const { status, body } = await dispatch(makeReq({ body: { prompt: 'a low-poly fox' } }));+ expect(status).toBe(429);+ expectValidError(body, 'lane busy');+ });++ it('502 generation_failed when the lane refuses the job', async () => {+ stubForge({ message: 'no healthy backend' }, { status: 500 });+ const { status, body } = await dispatch(makeReq({ body: { prompt: 'a low-poly fox' } }));+ expect(status).toBe(502);+ expectValidError(body, 'generation_failed');+ });++ it('503 not_configured when no lane is deployed', async () => {+ stubForge({ message: '3D generation is not configured' }, { status: 503 });+ const { status, body } = await dispatch(makeReq({ body: { prompt: 'a low-poly fox' } }));+ expect(status).toBe(503);+ expectValidError(body, 'not_configured');+ });+});++describe('the schema describes requests the handler actually accepts', () => {+ it('the documented request example passes both the schema and the handler', async () => {+ const example = spec.paths['/api/3d/studio'].post.requestBody.content['application/json'].examples.fox.value;+ expect(validateGenerateBody(example), why(validateGenerateBody)).toBe(true);+ stubForge(FORGE_DONE);+ const { status } = await dispatch(makeReq({ body: example }));+ expect(status).toBe(200);+ });++ it('every tier the schema advertises is accepted by the handler', async () => {+ for (const tier of spec.paths['/api/3d/studio'].post.requestBody.content['application/json'].schema.properties.tier.enum) {+ stubForge(FORGE_QUEUED);+ const { status, body } = await dispatch(makeReq({ body: { prompt: 'a low-poly fox', tier } }));+ expect(status, `tier ${tier}`).toBe(200);+ expectValidState(body, `tier ${tier}`);+ }+ });++ it('the documented response examples are themselves valid GenerationState objects', () => {+ const post = spec.paths['/api/3d/studio'].post.responses['200'].content['application/json'].examples;+ const get = spec.paths['/api/3d/studio'].get.responses['200'].content['application/json'].examples;+ for (const [name, ex] of [...Object.entries(post), ...Object.entries(get)]) {+ expectValidState(ex.value, `example ${name}`);+ }+ });++ it('the poll path a pending response hands back matches the documented job pattern', async () => {+ stubForge(FORGE_QUEUED);+ const { body } = await dispatch(makeReq({ body: { prompt: 'a low-poly fox' } }));+ const jobParam = spec.paths['/api/3d/studio'].get.parameters.find((p) => p.name === 'job');+ const validateJob = ajv.compile(jobParam.schema);+ const emitted = new URL(body.poll, 'https://three.ws').searchParams.get('job');+ expect(validateJob(emitted), why(validateJob)).toBe(true);+ expect(emitted).toBe(body.job);+ });+});diff --git a/tests/api/3d-studio-openapi.test.js b/tests/api/3d-studio-openapi.test.jsindex ac26b5025..e6fe33461 100644--- a/tests/api/3d-studio-openapi.test.js+++ b/tests/api/3d-studio-openapi.test.js@@ -39,13 +39,34 @@ describe('3d-studio-openapi served schema', () => {expect(doc.components?.securitySchemes ?? {}).toEqual({});});- it('exposes only the free generation action (POST generate + GET poll)', () => {- expect(Object.keys(doc.paths)).toEqual(['/api/3d/studio']);+ it('exposes only the free studio surface (generate + poll + AR launch)', () => {+ expect(Object.keys(doc.paths)).toEqual(['/api/3d/studio', '/api/ar']);expect(doc.paths['/api/3d/studio'].post?.operationId).toBe('generate3DModel');expect(doc.paths['/api/3d/studio'].get?.operationId).toBe('checkModelJob');+ expect(doc.paths['/api/ar'].get?.operationId).toBe('openModelInAR');+ // Nothing but GET is exposed on the AR launch endpoint.+ expect(Object.keys(doc.paths['/api/ar'])).toEqual(['get']);// No action may be flagged consequential (nothing charges or mutates state).expect(doc.paths['/api/3d/studio'].post['x-openai-isConsequential']).toBe(false);expect(doc.paths['/api/3d/studio'].get['x-openai-isConsequential']).toBe(false);+ expect(doc.paths['/api/ar'].get['x-openai-isConsequential']).toBe(false);+ });++ it('documents the AR launch parameters api/ar.js actually reads', () => {+ // Bind the schema to the handler's real query contract, so renaming a+ // parameter on one side without the other fails here instead of in AR.+ const handler = readFileSync(resolve(ROOT, 'api/ar.js'), 'utf8');+ const readParams = [...handler.matchAll(/searchParams\.get\(['"]([^'"]+)['"]\)/g)].map((m) => m[1]);+ const params = doc.paths['/api/ar'].get.parameters;+ const byName = Object.fromEntries(params.map((p) => [p.name, p]));+ expect([...new Set(readParams)].sort()).toEqual(Object.keys(byName).sort());+ expect(Object.keys(byName).sort()).toEqual(['kind', 'src', 'title']);+ expect(byName.src.required).toBe(true);+ expect(byName.src.in).toBe('query');+ expect(byName.title.required).toBe(false);+ expect(byName.kind.schema.enum).toEqual(['avatar']);+ // The AR page is a human surface: it answers in HTML, never JSON.+ expect(Object.keys(doc.paths['/api/ar'].get.responses['200'].content)).toEqual(['text/html']);});it('uses the canonical no-.html legal URLs', () => {diff --git a/tests/api/ar-endpoint.test.js b/tests/api/ar-endpoint.test.jsnew file mode 100644index 000000000..9d4040282--- /dev/null+++ b/tests/api/ar-endpoint.test.js@@ -0,0 +1,207 @@+// Integration tests for GET /api/ar, the "View in your space" / "Bring it to+// life" endpoint every generation links to (shapeSubmit's arUrl, the export_ar+// MCP tool, the /forge and /ar pages).+//+// The routing core is pure and unit-tested in tests/ar-export.test.js. What was+// never pinned is the HTTP surface a reviewer actually hits: the User-Agent+// branch (Android intent redirect vs iOS/desktop launch page vs the avatar IRL+// handoff), the designed error page for a bad src, and the cache/Vary headers+// that keep a CDN from serving a desktop page to an Android phone.+//+// No network and no mocks: the handler is invoked directly with mocked req/res+// objects (the pattern used by tests/api/avatar-og.test.js), so every assertion+// runs against the real handler, the real planArLaunch, and the real HTML.++import { describe, it, expect } from 'vitest';++const { default: handler } = await import('../../api/ar.js');++// Real-world User-Agent strings, one per branch the handler routes on.+const UA = {+ android: 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36',+ iphone: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1',+ ipad: 'Mozilla/5.0 (iPad; CPU OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1',+ desktop: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',+};++const GLB = 'https://pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev/forge/anon/fox.glb';++function mkReq({ src = GLB, title = '', kind = '', ua = UA.desktop, method = 'GET', headers = {} } = {}) {+ const q = new URLSearchParams();+ if (src !== null) q.set('src', src);+ if (title) q.set('title', title);+ if (kind) q.set('kind', kind);+ const qs = q.toString();+ return {+ method,+ url: `/api/ar${qs ? `?${qs}` : ''}`,+ headers: { host: 'three.ws', 'x-forwarded-proto': 'https', ...(ua ? { 'user-agent': ua } : {}), ...headers },+ };+}++function mkRes() {+ return {+ statusCode: 200,+ _h: {},+ _body: undefined,+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(b) { this._body = b; this.writableEnded = true; },+ };+}++async function get(opts) {+ const req = mkReq(opts);+ const res = mkRes();+ await handler(req, res);+ return res;+}++describe('GET /api/ar - Android Scene Viewer branch', () => {+ it('302s a static model straight into the ARCore Scene Viewer intent', async () => {+ const res = await get({ ua: UA.android, title: 'a low-poly fox' });+ expect(res.statusCode).toBe(302);+ const loc = res._h.location;+ expect(loc.startsWith('intent://arvr.google.com/scene-viewer/1.2?')).toBe(true);+ expect(loc).toContain(`file=${encodeURIComponent(GLB)}`);+ expect(loc).toContain('mode=ar_preferred');+ expect(loc).toContain('package=com.google.ar.core');+ // Browser fallback lands on the WebGL viewer when ARCore is absent.+ expect(loc).toContain(`S.browser_fallback_url=${encodeURIComponent(`https://three.ws/viewer?src=${encodeURIComponent(GLB)}&title=${encodeURIComponent('a low-poly fox')}`)}`);+ });++ it('never caches the redirect (the target is UA-specific)', async () => {+ const res = await get({ ua: UA.android });+ expect(res._h['cache-control']).toBe('no-store');+ expect(res._body).toBeFalsy();+ });+});++describe('GET /api/ar - iOS and desktop launch page', () => {+ it('serves the HTML launch page to iPhone with the model wired into model-viewer', async () => {+ const res = await get({ ua: UA.iphone });+ expect(res.statusCode).toBe(200);+ expect(res._h['content-type']).toBe('text/html; charset=utf-8');+ expect(res._body).toContain(`<model-viewer id="mv" src="${GLB}"`);+ // Quick Look is what iOS enters; model-viewer converts the GLB in-page.+ expect(res._body).toContain('ar-modes="webxr scene-viewer quick-look"');+ expect(res._body).toContain('id="ar-btn"');+ expect(res._body).toContain('View in your space');+ });++ it('serves the same page to iPad and to desktop, with the 3D viewer fallback link', async () => {+ for (const ua of [UA.ipad, UA.desktop]) {+ const res = await get({ ua });+ expect(res.statusCode).toBe(200);+ expect(res._body).toContain(`href="https://three.ws/viewer?src=${encodeURIComponent(GLB)}"`);+ expect(res._body).toContain('Open in 3D viewer');+ }+ });++ it('renders the title into the document title and the name chip, HTML-escaped', async () => {+ const res = await get({ ua: UA.desktop, title: '<img src=x onerror=alert(1)>' });+ expect(res.statusCode).toBe(200);+ expect(res._body).not.toContain('<img src=x');+ expect(res._body).toContain('<img src=x onerror=alert(1)>');+ expect(res._body).toContain('class="name"');+ });++ it('unfurls with a real render of THIS model, not a logo', async () => {+ const res = await get({ ua: UA.desktop, title: 'a fox' });+ expect(res._body).toContain(+ `content="https://three.ws/api/render/glb?glbUrl=${encodeURIComponent(GLB)}&width=1200&height=630"`,+ );+ expect(res._body).toContain('<meta property="og:url" content="https://three.ws/api/ar?src=');+ });++ it('honours the forwarded host so the page links back to the origin that served it', async () => {+ const req = mkReq({ ua: UA.desktop, headers: { 'x-forwarded-host': 'staging.three.ws' } });+ const res = mkRes();+ await handler(req, res);+ expect(res._body).toContain('https://staging.three.ws/viewer?src=');+ expect(res._body).toContain('https://staging.three.ws/api/render/glb?');+ });+});++describe('GET /api/ar - kind=avatar IRL handoff', () => {+ it('keeps Android on the launch page so the living-agent path stays visible', async () => {+ const res = await get({ ua: UA.android, kind: 'avatar' });+ expect(res.statusCode).toBe(200);+ expect(res._h.location).toBeUndefined();+ expect(res._body).toContain(`href="https://three.ws/irl?avatar=${encodeURIComponent(GLB)}"`);+ expect(res._body).toContain('Bring it to life');+ // Static placement stays available alongside the living handoff.+ expect(res._body).toContain('Place in your space');+ });++ it('offers the IRL handoff on iOS and desktop too', async () => {+ for (const ua of [UA.iphone, UA.desktop]) {+ const res = await get({ ua, kind: 'avatar' });+ expect(res.statusCode).toBe(200);+ expect(res._body).toContain('/irl?avatar=');+ expect(res._body).toContain('This is a living agent.');+ }+ });++ it('a static model gets no IRL link at all', async () => {+ const res = await get({ ua: UA.desktop });+ expect(res._body).not.toContain('/irl?avatar=');+ expect(res._body).not.toContain('Bring it to life');+ });+});++describe('GET /api/ar - designed error page for bad input', () => {+ const cases = [+ { name: 'a missing src', src: '', message: 'Provide a valid https URL to a .glb model.' },+ { name: 'a non-URL src', src: 'not a url', message: 'Provide a valid https URL to a .glb model.' },+ { name: 'a non-https src', src: 'http://cdn.example/fox.glb', message: 'The model URL must be https.' },+ { name: 'a non-GLB src', src: 'https://cdn.example/fox.png', message: 'The model URL must point at a .glb or .gltf file.' },+ { name: 'a javascript: src', src: 'javascript:alert(1)//a.glb', message: 'The model URL must be https.' },+ ];++ for (const c of cases) {+ it(`400s ${c.name} with the designed page, never a crash`, async () => {+ const res = await get({ src: c.src, ua: UA.desktop });+ expect(res.statusCode).toBe(400);+ expect(res._h['content-type']).toBe('text/html; charset=utf-8');+ expect(res._h['cache-control']).toBe('no-store');+ expect(res._body).toContain("Can't open this in AR");+ expect(res._body).toContain(c.message);+ // The error state is actionable: it offers the way forward.+ expect(res._body).toContain('Create a 3D model');+ // A rejected asset never reaches the page.+ expect(res._body).not.toContain('<model-viewer');+ });+ }++ it('rejects .gltf lookalikes but accepts a real .gltf with a query string', async () => {+ const bad = await get({ src: 'https://cdn.example/fox.glb.exe', ua: UA.desktop });+ expect(bad.statusCode).toBe(400);+ const ok = await get({ src: 'https://cdn.example/scene.gltf?v=2', ua: UA.desktop });+ expect(ok.statusCode).toBe(200);+ expect(ok._body).toContain('https://cdn.example/scene.gltf?v=2');+ });+});++describe('GET /api/ar - caching and CORS headers', () => {+ it('varies the cached page on user-agent so an Android phone cannot be served a desktop page', async () => {+ const res = await get({ ua: UA.desktop });+ expect(res._h.vary).toBe('user-agent');+ expect(res._h['cache-control']).toBe('public, max-age=60, s-maxage=600');+ });++ it('answers the CORS preflight with 204 and no body', async () => {+ const res = await get({ method: 'OPTIONS', ua: UA.desktop });+ expect(res.statusCode).toBe(204);+ expect(res._h['access-control-allow-methods']).toBe('GET,OPTIONS');+ expect(res._body).toBeFalsy();+ });++ it('treats an absent User-Agent as desktop rather than failing', async () => {+ const res = await get({ ua: '' });+ expect(res.statusCode).toBe(200);+ expect(res._body).toContain('<model-viewer');+ });+});