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(cad): ship the /cad page, cad_generate and cad_rebuild MCP tools, and a stronger writer loop
nirholasd1759b199ead
diff --git a/api/_lib/cad/forge.js b/api/_lib/cad/forge.jsindex 4d795b378..0065d1595 100644--- a/api/_lib/cad/forge.js+++ b/api/_lib/cad/forge.js@@ -91,6 +91,20 @@ export async function forgeDesign({ prompt, baseCode = null, onEvent = () => {},onEvent({ stage: 'writing', attempt: 1 });let written = await writeImpl({ user: baseCode ? refineMessage(prompt, baseCode) : generateMessage(prompt), track, deadline });const attempts = [];+ let fallback = null;+ const finished = (w, build, tries) => {+ const meta = parseDesign(w.code);+ return {+ code: w.code,+ title: meta.title || titleFromPrompt(prompt),+ summary: meta.summary,+ params: meta.params,+ build,+ attempts: tries,+ model: w.model,+ provider: w.provider,+ };+ };for (let attempt = 1; attempt <= MAX_REPAIRS + 1; attempt++) {if (!written.code) {@@ -99,18 +113,27 @@ export async function forgeDesign({ prompt, baseCode = null, onEvent = () => {},onEvent({ stage: 'building', attempt });const build = await buildImpl(written.code);if (build?.ok) {- const meta = parseDesign(written.code);+ const design = finished(written, build, [...attempts, { attempt, ok: true }]);+ // Several solids that never touch are almost always a feature left+ // floating (a lip modeled beside the plate instead of on it). Ask+ // once for a connected part, keeping this build as the answer if+ // the request really meant several bodies or the repair fails.+ const solids = build.metrics?.solids || 1;+ if (solids > 1 && !fallback && attempt <= MAX_REPAIRS && deadline - Date.now() > 60_000) {+ fallback = design;+ const error = { kind: 'result', message: `The part built as ${solids} separate solids that do not touch. Unless the request asked for separate pieces, every feature must overlap or touch the main body so it is one connected solid.`, line: null };+ attempts.push({ attempt, error });+ onEvent({ stage: 'repairing', attempt: attempt + 1, error });+ try {+ written = await writeImpl({ user: repairMessage({ request: prompt, code: written.code, error }), track, deadline });+ } catch {+ onEvent({ stage: 'built', attempt });+ return design;+ }+ continue;+ }onEvent({ stage: 'built', attempt });- return {- code: written.code,- title: meta.title || titleFromPrompt(prompt),- summary: meta.summary,- params: meta.params,- build,- attempts: [...attempts, { attempt, ok: true }],- model: written.model,- provider: written.provider,- };+ return design;}attempts.push({ attempt, error: build?.error || { kind: 'unknown', message: 'Build failed.' } });}@@ -123,6 +146,10 @@ export async function forgeDesign({ prompt, baseCode = null, onEvent = () => {},: await writeImpl({ user: baseCode ? refineMessage(prompt, baseCode) : generateMessage(prompt), track, deadline });}+ if (fallback) {+ onEvent({ stage: 'built', attempt: fallback.attempts.length });+ return { ...fallback, attempts };+ }const last = attempts[attempts.length - 1]?.error;throw new CadForgeError('design_failed',diff --git a/api/_lib/cad/service.js b/api/_lib/cad/service.jsnew file mode 100644index 000000000..84addc7fb--- /dev/null+++ b/api/_lib/cad/service.js@@ -0,0 +1,102 @@+// CAD Forge service: the two operations every transport shares.+//+// api/cad.js (browser, REST) and the cad_* MCP tools (api/_mcp3d/tools/cad.js)+// both call these, so a design made by an agent and one made on /cad are the+// same record with the same files and the same permalink.++import { CadForgeError, buildProgram, cadWorkerConfigured, forgeDesign } from './forge.js';+import { cadStoreEnabled, getDesign, getVariant, newDesignId, saveDesign, saveVariant, uploadArtifacts } from './store.js';+import { MAX_PROMPT_LEN, applyParams, paramsKey } from '../../../src/cad/params.js';++const SITE = process.env.PUBLIC_BASE_URL || 'https://three.ws';+export const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++export function cadAvailable() {+ return cadWorkerConfigured() && cadStoreEnabled();+}++export function designUrl(id, key) {+ return `${SITE}/cad/${id}${key ? `?v=${key}` : ''}`;+}++export function publicDesign(design) {+ return { ...design, url: designUrl(design.id) };+}++function requireAvailable() {+ if (!cadAvailable()) throw new CadForgeError('cad_unavailable', 'CAD Forge is not configured on this deployment.', 503);+}++export function cleanPrompt(raw) {+ const prompt = String(raw ?? '').slice(0, MAX_PROMPT_LEN).trim();+ if (prompt.length < 3) throw new CadForgeError('prompt_required', 'Describe the part you need.', 400);+ return prompt;+}++/** Resolve a parent design for a refinement, or null. Throws on a bad id. */+export async function loadParent(parentId) {+ if (parentId == null || parentId === '') return null;+ if (!UUID_RE.test(String(parentId))) throw new CadForgeError('invalid_parent', 'Malformed parent design id.', 400);+ const parent = await getDesign(String(parentId));+ if (!parent) throw new CadForgeError('parent_not_found', 'The design you are refining no longer exists.', 404);+ return parent;+}++/**+ * Write, build, export and save a design (fresh, or refining `parent` at+ * `values`). Returns { design, attempts }.+ */+export async function createDesign({ prompt, parent = null, values = {}, user = null, onEvent = () => {} }) {+ requireAvailable();+ const baseCode = parent ? applyParams(parent.code, values || {}).code : null;+ const forged = await forgeDesign({ prompt, baseCode, track: { userId: user?.id ?? null }, onEvent });+ onEvent({ stage: 'saving' });+ const id = newDesignId();+ const files = await uploadArtifacts(`cad/${id}`, forged.build.artifacts);+ const saved = await saveDesign({+ id,+ parentId: parent?.id || null,+ title: forged.title,+ summary: forged.summary,+ prompt,+ code: forged.code,+ params: forged.params,+ metrics: forged.build.metrics,+ files,+ adjustments: forged.build.adjustments || [],+ model: forged.model,+ userId: user?.id ?? null,+ });+ if (!saved) throw new CadForgeError('save_failed', 'The part built but could not be saved. Try again.', 500);+ return {+ design: publicDesign({ ...saved, creatorUsername: user?.username || null }),+ attempts: forged.attempts.length,+ };+}++/**+ * Rebuild a saved design's own program at new values. Cached per value set.+ * Returns { variant, cached }. `beforeBuild` runs only on a cache miss (the+ * HTTP route rate-limits there).+ */+export async function rebuildVariant({ id, values, beforeBuild = async () => {} }) {+ if (!UUID_RE.test(String(id ?? ''))) throw new CadForgeError('invalid_id', 'Malformed design id.', 400);+ requireAvailable();+ const design = await getDesign(String(id));+ if (!design) throw new CadForgeError('not_found', 'No design with that id.', 404);++ const { code, applied } = applyParams(design.code, values || {});+ const key = paramsKey(applied);+ const cached = await getVariant(design.id, key);+ if (cached) return { variant: { ...cached, url: designUrl(design.id, key) }, cached: true, design };++ await beforeBuild();+ const build = await buildProgram(code);+ if (!build?.ok) {+ throw new CadForgeError('rebuild_failed', 'These values do not make a valid part. Try values closer to the original.', 422, build?.error || null);+ }+ const files = await uploadArtifacts(`cad/${design.id}/v/${key}`, build.artifacts);+ const variant = await saveVariant({ designId: design.id, key, values: applied, metrics: build.metrics, files, adjustments: build.adjustments || [] });+ if (!variant) throw new CadForgeError('save_failed', 'The part rebuilt but could not be saved. Try again.', 500);+ return { variant: { ...variant, url: designUrl(design.id, key) }, cached: false, design };+}diff --git a/api/_mcp3d/catalog.js b/api/_mcp3d/catalog.jsindex 8d840fa27..63f4ddef9 100644--- a/api/_mcp3d/catalog.js+++ b/api/_mcp3d/catalog.js@@ -6,6 +6,7 @@ import { priceUsdcForTier } from '../_lib/forge-tiers.js';import { toolDefs as studioDefs } from './tools/studio.js';import { toolDefs as spatialDefs } from './tools/spatial.js';import { toolDefs as arDefs } from './tools/ar.js';+import { toolDefs as cadDefs } from './tools/cad.js';import { toolDefs as provenanceDefs } from './tools/provenance.js';import { toolDefs as simReadinessDefs } from './tools/sim-readiness.js';import { toolDefs as personaIdentityDefs } from './tools/persona-identity.js';@@ -25,7 +26,7 @@ const reusedModelDefs = modelDefs.filter(// The animation library (list_animations + apply_animation) completes the// pipeline: text_to_3d → auto_rig_model → apply_animation. Same retarget engine// the main server exposes — reused here, not duplicated.-const baseDefs = [...studioDefs, ...spatialDefs, ...arDefs, ...provenanceDefs, ...simReadinessDefs, ...personaIdentityDefs, ...preflightDefs, ...reusedModelDefs, ...animationDefs, ...resourceDefs];+const baseDefs = [...studioDefs, ...cadDefs, ...spatialDefs, ...arDefs, ...provenanceDefs, ...simReadinessDefs, ...personaIdentityDefs, ...preflightDefs, ...reusedModelDefs, ...animationDefs, ...resourceDefs];// Free, public entry point — listed first so discovery clients see it up top.// Annotations: a static, local overview built at module load — read-only,diff --git a/api/_mcp3d/pricing.js b/api/_mcp3d/pricing.jsindex d2329a4a7..7e3b56745 100644--- a/api/_mcp3d/pricing.js+++ b/api/_mcp3d/pricing.js@@ -81,6 +81,14 @@ export const TOOL_PRICING = Object.freeze({amount_usdc: 0.01,description: 'Per call — PBR material parameters from a description',},+ cad_generate: {+ amount_usdc: 0.05,+ description: 'Per call: description → kernel-checked parametric CAD part (STEP, STL, GLB, drawing)',+ },+ cad_rebuild: {+ amount_usdc: 0.01,+ description: 'Per call: rebuild a CAD part at new dimensions on the OpenCascade kernel',+ },anchor_provenance: {amount_usdc: 0.05,description: 'Per call — sign a content credential and anchor its hash on Solana',diff --git a/api/_mcp3d/tools/cad.js b/api/_mcp3d/tools/cad.jsnew file mode 100644index 000000000..6acccc34c--- /dev/null+++ b/api/_mcp3d/tools/cad.js@@ -0,0 +1,155 @@+// cad_generate / cad_rebuild: parametric CAD for agents.+//+// The same pipeline as three.ws/cad (api/_lib/cad/service.js): a model writes+// a build123d program, the OpenCascade kernel builds it in the cad-forge+// sandbox, kernel errors go back for repair, and the part is saved with STEP,+// STL, GLB and drawing files plus a permalink. cad_rebuild re-runs a saved+// program at new dimension values with no model involved.+//+// Both answer synchronously. A design usually lands in 20-90 s; agents whose+// MCP client enforces a short per-call timeout should raise it for this tool.++import { CadForgeError } from '../../_lib/cad/forge.js';+import { cleanPrompt, createDesign, loadParent, rebuildVariant } from '../../_lib/cad/service.js';+import { buildSpatialArtifact } from '../../_lib/spatial-mcp.js';++function failure(err) {+ const known = err instanceof CadForgeError;+ const message = known ? err.message : 'CAD Forge could not finish this part. Try again.';+ const kernel = known && err.code === 'design_failed' ? err.detail?.lastError : known && err.code === 'rebuild_failed' ? err.detail : null;+ return {+ content: [{ type: 'text', text: kernel ? `${message}\nLast kernel error: ${kernel.message}${kernel.line ? ` (line ${kernel.line})` : ''}` : message }],+ structuredContent: { error: true, code: known ? err.code : 'internal_error', message, ...(kernel ? { kernelError: kernel } : {}) },+ isError: true,+ };+}++function summarizeParams(params) {+ return params.map((p) => `${p.name} = ${p.value} ${p.unit === 'count' ? '' : p.unit} (${p.label}, ${p.min}..${p.max})`.replace(/\s+\(/, ' (')).join('\n');+}++function sizeLine(metrics) {+ const [x, y, z] = metrics.size_mm;+ return `${x} x ${y} x ${z} mm, ${(metrics.volume_mm3 / 1000).toFixed(2)} cm3, ${metrics.solids} solid${metrics.solids === 1 ? '' : 's'}`;+}++export const toolDefs = [+ {+ name: 'cad_generate',+ title: 'Generate a parametric CAD part (STEP, STL, GLB)',+ annotations: {+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: true,+ },+ description:+ 'Turn a description of a mechanical part into real parametric CAD: a build123d (OpenCascade) program that the ' ++ 'geometry kernel has accepted, saved with STEP (for Fusion, SolidWorks, FreeCAD, Onshape), STL (for 3D printing), ' ++ 'GLB (web and AR, true scale in metres) and an SVG drawing sheet, plus a public page with dimension sliders. ' ++ 'Use it for brackets, enclosures, mounts, gears, knobs, clips, adapters and other functional parts with real ' ++ 'dimensions; use text_to_3d instead for organic or decorative models. Name the key sizes in millimetres and how ' ++ 'the part mounts. Pass parent_id (and optionally values) to refine an existing design. Takes 20-90 seconds.',+ inputSchema: {+ type: 'object',+ additionalProperties: false,+ required: ['prompt'],+ properties: {+ prompt: { type: 'string', minLength: 3, maxLength: 600, description: 'The part to make, or the change to make when refining. Include key dimensions in mm.' },+ parent_id: { type: 'string', format: 'uuid', description: 'Refine this existing CAD Forge design instead of starting fresh.' },+ values: {+ type: 'object',+ additionalProperties: { type: 'number' },+ description: 'With parent_id: the parent parameter values to start the refinement from, e.g. {"WIDTH": 90}.',+ },+ },+ },+ async handler(args, auth) {+ try {+ const prompt = cleanPrompt(args.prompt);+ const parent = await loadParent(args.parent_id);+ const { design, attempts } = await createDesign({+ prompt,+ parent,+ values: args.values,+ user: auth?.userId ? { id: auth.userId } : null,+ });+ const spatial = buildSpatialArtifact({ glbUrl: design.files.glb, kind: 'model', viewerUrl: design.url, title: design.title });+ return {+ content: [+ {+ type: 'text',+ text:+ `${design.title}: ${sizeLine(design.metrics)}. Built on the kernel in ${attempts} attempt${attempts === 1 ? '' : 's'}.\n` ++ `Page with sliders: ${design.url}\nSTEP: ${design.files.step}\nSTL: ${design.files.stl}\nGLB: ${design.files.glb}` ++ (design.files.drawing_svg ? `\nDrawing: ${design.files.drawing_svg}` : '') ++ (design.params.length ? `\nParameters (change with cad_rebuild):\n${summarizeParams(design.params)}` : '') ++ (design.adjustments.length ? `\nKernel adjustments: ${design.adjustments.join('; ')}` : ''),+ },+ ],+ structuredContent: {+ id: design.id,+ title: design.title,+ summary: design.summary,+ url: design.url,+ files: design.files,+ metrics: design.metrics,+ params: design.params.map(({ line: _l, ...p }) => p),+ adjustments: design.adjustments,+ code: design.code,+ spatial,+ },+ };+ } catch (err) {+ return failure(err);+ }+ },+ },+ {+ name: 'cad_rebuild',+ title: 'Rebuild a CAD part with new dimensions',+ annotations: {+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: true,+ openWorldHint: false,+ },+ description:+ 'Rebuild a CAD Forge design (from cad_generate) at new parameter values, e.g. {"WIDTH": 120, "WALL": 3}. Runs the ' ++ "design's own program on the OpenCascade kernel with no model involved, so the result is exact and repeatable. " ++ 'Values are clamped to each parameter\'s range. Returns fresh STEP, STL, GLB and drawing files and a link to this ' ++ 'configuration. Identical values return the cached build instantly.',+ inputSchema: {+ type: 'object',+ additionalProperties: false,+ required: ['id', 'values'],+ properties: {+ id: { type: 'string', format: 'uuid', description: 'The design id returned by cad_generate.' },+ values: {+ type: 'object',+ additionalProperties: { type: 'number' },+ minProperties: 1,+ description: 'Parameter values by name, e.g. {"WIDTH": 120}.',+ },+ },+ },+ async handler(args) {+ try {+ const { variant, cached, design } = await rebuildVariant({ id: args.id, values: args.values });+ return {+ content: [+ {+ type: 'text',+ text:+ `${design.title} at ${Object.entries(variant.values).map(([k, v]) => `${k}=${v}`).join(', ')}: ${sizeLine(variant.metrics)}${cached ? ' (cached)' : ''}.\n` ++ `Page: ${variant.url}\nSTEP: ${variant.files.step}\nSTL: ${variant.files.stl}\nGLB: ${variant.files.glb}`,+ },+ ],+ structuredContent: { id: design.id, key: variant.key, url: variant.url, values: variant.values, files: variant.files, metrics: variant.metrics, cached },+ };+ } catch (err) {+ return failure(err);+ }+ },+ },+];diff --git a/api/cad.js b/api/cad.jsindex 5ede44818..ce2e44294 100644--- a/api/cad.js+++ b/api/cad.js@@ -28,23 +28,11 @@import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { getSessionUser } from './_lib/auth.js';-import { CadForgeError, buildProgram, cadWorkerConfigured, forgeDesign } from './_lib/cad/forge.js';-import {- bumpViews,- cadStoreEnabled,- getDesign,- getLineage,- getVariant,- listDesigns,- newDesignId,- saveDesign,- saveVariant,- uploadArtifacts,-} from './_lib/cad/store.js';-import { MAX_PROMPT_LEN, applyParams, paramsKey } from '../src/cad/params.js';+import { CadForgeError } from './_lib/cad/forge.js';+import { bumpViews, getDesign, getLineage, getVariant, listDesigns } from './_lib/cad/store.js';+import { UUID_RE, cadAvailable, cleanPrompt, createDesign, loadParent, publicDesign, rebuildVariant } from './_lib/cad/service.js';+import { applyParams } from '../src/cad/params.js';-const SITE = process.env.PUBLIC_BASE_URL || 'https://three.ws';-const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;const VARIANT_RE = /^[0-9a-z]{1,16}$/;const KEEPALIVE_MS = 15_000;@@ -62,21 +50,6 @@ export default wrap(async (req, res) => {return json(res, 400, { error: 'unknown_action', message: 'action must be "generate" or "rebuild".' });});-function unavailable(res) {- return json(res, 503, {- error: 'cad_unavailable',- message: 'CAD Forge is not configured on this deployment.',- });-}--function designUrl(id, key) {- return `${SITE}/cad/${id}${key ? `?v=${key}` : ''}`;-}--function publicDesign(design) {- return { ...design, url: designUrl(design.id) };-}-async function handleGet(req, res) {const url = new URL(req.url, 'http://x');const id = url.searchParams.get('id');@@ -120,7 +93,7 @@ async function handleGet(req, res) {return json(res,200,- { designs, available: cadStoreEnabled() && cadWorkerConfigured() },+ { designs, available: cadAvailable() },{ 'cache-control': 'public, max-age=20, s-maxage=60' },);}@@ -151,20 +124,33 @@ function openStream(res) {return { send, close };}-async function handleGenerate(req, res, body) {- const prompt = String(body.prompt ?? '').slice(0, MAX_PROMPT_LEN).trim();- if (prompt.length < 3) {- return json(res, 400, { error: 'prompt_required', message: 'Describe the part you need.' });+function sendError(res, err, stream) {+ const known = err instanceof CadForgeError;+ if (!known) console.error('[cad] request failed:', err?.message);+ const status = known ? err.status : 500;+ const out = {+ error: known ? err.code : 'internal_error',+ message: known ? err.message : 'Something went wrong building this part. Try again.',+ ...(known && err.code === 'design_failed' ? { lastError: err.detail?.lastError || null } : {}),+ ...(known && err.code === 'rebuild_failed' ? { buildError: err.detail || null } : {}),+ };+ if (stream) {+ stream.send('error', { status, ...out });+ stream.close();+ return;}- if (!cadWorkerConfigured() || !cadStoreEnabled()) return unavailable(res);+ return json(res, status, out);+}- let parent = null;- if (body.parentId != null) {- if (!UUID_RE.test(String(body.parentId))) {- return json(res, 400, { error: 'invalid_parent', message: 'Malformed parent design id.' });- }- parent = await getDesign(String(body.parentId));- if (!parent) return json(res, 404, { error: 'parent_not_found', message: 'The design you are refining no longer exists.' });+async function handleGenerate(req, res, body) {+ let prompt;+ let parent;+ try {+ prompt = cleanPrompt(body.prompt);+ if (!cadAvailable()) throw new CadForgeError('cad_unavailable', 'CAD Forge is not configured on this deployment.', 503);+ parent = await loadParent(body.parentId);+ } catch (err) {+ return sendError(res, err, null);}const ip = clientIp(req);@@ -173,37 +159,16 @@ async function handleGenerate(req, res, body) {const globalRl = await limits.cadForgeGlobal();if (!globalRl.success) return rateLimited(res, globalRl, 'CAD Forge is at capacity. Try again shortly.');- const sessionUser = await getSessionUser(req).catch(() => null);- const baseCode = parent ? applyParams(parent.code, body.values || {}).code : null;+ const user = await getSessionUser(req).catch(() => null);const stream = body.stream === true ? openStream(res) : null;-try {- const forged = await forgeDesign({+ const payload = await createDesign({prompt,- baseCode,- track: { userId: sessionUser?.id ?? null },+ parent,+ values: body.values,+ user,onEvent: (event) => stream?.send('stage', event),});- stream?.send('stage', { stage: 'saving' });- const id = newDesignId();- const files = await uploadArtifacts(`cad/${id}`, forged.build.artifacts);- const saved = await saveDesign({- id,- parentId: parent?.id || null,- title: forged.title,- summary: forged.summary,- prompt,- code: forged.code,- params: forged.params,- metrics: forged.build.metrics,- files,- adjustments: forged.build.adjustments || [],- model: forged.model,- userId: sessionUser?.id ?? null,- });- if (!saved) throw new CadForgeError('save_failed', 'The part built but could not be saved. Try again.', 500);- const design = publicDesign({ ...saved, creatorUsername: sessionUser?.username || null });- const payload = { design, attempts: forged.attempts.length };if (stream) {stream.send('done', payload);stream.close();@@ -211,61 +176,23 @@ async function handleGenerate(req, res, body) {}return json(res, 201, payload);} catch (err) {- const known = err instanceof CadForgeError;- if (!known) console.error('[cad] generate failed:', err?.message);- const status = known ? err.status : 500;- const out = {- error: known ? err.code : 'internal_error',- message: known ? err.message : 'Something went wrong building this part. Try again.',- ...(known && err.code === 'design_failed' ? { lastError: err.detail?.lastError || null } : {}),- };- if (stream) {- stream.send('error', { status, ...out });- stream.close();- return;- }- return json(res, status, out);+ return sendError(res, err, stream);}}async function handleRebuild(req, res, body) {- const id = String(body.id ?? '');- if (!UUID_RE.test(id)) return json(res, 400, { error: 'invalid_id', message: 'Malformed design id.' });- if (!cadWorkerConfigured() || !cadStoreEnabled()) return unavailable(res);- const design = await getDesign(id);- if (!design) return json(res, 404, { error: 'not_found', message: 'No design with that id.' });-- const { code, applied } = applyParams(design.code, body.values || {});- const key = paramsKey(applied);- const cached = await getVariant(id, key);- if (cached) return json(res, 200, { variant: { ...cached, url: designUrl(id, key) }, cached: true });-- const rl = await limits.cadRebuildIp(clientIp(req));- if (!rl.success) return rateLimited(res, rl, 'Rebuilding too fast. Give it a moment.');-- let build;try {- build = await buildProgram(code);- } catch (err) {- if (err instanceof CadForgeError) return json(res, err.status, { error: err.code, message: err.message });- throw err;- }- if (!build?.ok) {- return json(res, 422, {- error: 'rebuild_failed',- message: 'These values do not make a valid part. Try values closer to the original.',- buildError: build?.error || null,+ const { variant, cached } = await rebuildVariant({+ id: body.id,+ values: body.values,+ beforeBuild: async () => {+ const rl = await limits.cadRebuildIp(clientIp(req));+ if (!rl.success) throw Object.assign(new CadForgeError('rate_limited', 'Rebuilding too fast. Give it a moment.', 429), { rl });+ },});+ return json(res, 200, { variant, cached });+ } catch (err) {+ if (err?.rl) return rateLimited(res, err.rl, err.message);+ return sendError(res, err, null);}- const files = await uploadArtifacts(`cad/${id}/v/${key}`, build.artifacts);- const variant = await saveVariant({- designId: id,- key,- values: applied,- metrics: build.metrics,- files,- adjustments: build.adjustments || [],- });- if (!variant) return json(res, 500, { error: 'save_failed', message: 'The part rebuilt but could not be saved. Try again.' });- return json(res, 200, { variant: { ...variant, url: designUrl(id, key) }, cached: false });}diff --git a/pages/cad.html b/pages/cad.htmlnew file mode 100644index 000000000..c9471c428--- /dev/null+++ b/pages/cad.html@@ -0,0 +1,168 @@+<!doctype html>+<html lang="en">+<head>+ <script>/* three.ws theme boot: no-flash */(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>CAD Forge · Describe a part, get real CAD · three.ws</title>+ <meta name="description" content="Describe a mechanical part and get real parametric CAD: a build123d program checked by the OpenCascade kernel, with STEP, STL, GLB and drawing downloads, live dimension sliders, and true-scale AR." />+ <link rel="canonical" href="https://three.ws/cad" />+ <meta property="og:type" content="website" />+ <meta property="og:title" content="CAD Forge · three.ws" />+ <meta property="og:description" content="One sentence becomes a dimensioned, manufacturable part: STEP for engineers, STL for printers, sliders for everyone." />+ <meta property="og:url" content="https://three.ws/cad" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=CAD+Forge&d=Describe+a+part%2C+get+real+parametric+CAD%3A+STEP%2C+STL%2C+drawings+and+live+dimension+sliders.&p=%2Fcad" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="CAD Forge · three.ws" />+ <meta name="twitter:description" content="One sentence becomes a dimensioned, manufacturable part: STEP for engineers, STL for printers, sliders for everyone." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=CAD+Forge&d=Describe+a+part%2C+get+real+parametric+CAD%3A+STEP%2C+STL%2C+drawings+and+live+dimension+sliders.&p=%2Fcad" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="CAD Forge, three.ws" />+ <meta name="twitter:site" content="@trythreews" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <link rel="stylesheet" href="/src/cad/cad.css" />+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebApplication","name":"CAD Forge","applicationCategory":"DesignApplication","operatingSystem":"Any","description":"Describe a mechanical part and get real parametric CAD checked by the OpenCascade kernel, with STEP, STL, GLB and drawing downloads.","url":"https://three.ws/cad","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"offers":{"@type":"Offer","price":"0","priceCurrency":"USD"}}]}</script>+</head>+<body class="cad-body">+ <header class="site-header"><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cad">+ <!-- ── /cad: create + gallery ─────────────────────────────────────── -->+ <section id="cadHome" class="cad-home" aria-labelledby="cadHeroTitle">+ <div class="cad-hero">+ <p class="cad-eyebrow"><span class="cad-eyebrow__mark" aria-hidden="true"></span>CAD Forge</p>+ <h1 id="cadHeroTitle">Describe a part. Get real CAD.</h1>+ <p class="cad-lede">Not a mesh guess: a parametric <a href="https://github.com/gumyr/build123d" rel="noopener" target="_blank">build123d</a> program that the OpenCascade kernel has accepted, with exact dimensions you can change, STEP for engineers and STL for printers.</p>++ <form id="cadForm" class="cad-form" autocomplete="off">+ <label for="cadPrompt" class="cad-sr">Describe the part</label>+ <textarea id="cadPrompt" rows="3" placeholder="A wall bracket for a 25 mm pipe with two M5 countersunk holes, 4 mm thick"></textarea>+ <div class="cad-form__foot">+ <span class="cad-hint">Name the part, the key sizes, and how it mounts. <kbd>Ctrl</kbd> <kbd>Enter</kbd> to forge.</span>+ <button id="cadSubmit" type="submit" class="cad-btn cad-btn--primary">+ <span class="cad-btn__label">Forge part</span>+ <span class="cad-btn__spinner" aria-hidden="true"></span>+ </button>+ </div>+ </form>+ <p id="cadOffline" class="cad-notice" hidden>CAD Forge is not available on this deployment right now. Recent parts below still open, measure and download.</p>+ <div id="cadExamples" class="cad-chips" aria-label="Example parts"></div>+ <div id="cadProgress" class="cad-progress-host" hidden></div>++ <ul class="cad-proof" aria-label="What you get">+ <li><strong>Kernel-checked</strong><span>Every part is built on OpenCascade before you see it. Errors go back to the writer until it builds.</span></li>+ <li><strong>Parametric</strong><span>Key dimensions become sliders. Each configuration rebuilds and gets its own link.</span></li>+ <li><strong>Yours to keep</strong><span>Download STEP, STL, GLB, a drawing sheet, and the Python program itself.</span></li>+ </ul>+ </div>++ <section class="cad-gallery" aria-labelledby="cadGalleryTitle">+ <div class="cad-gallery__head">+ <h2 id="cadGalleryTitle">Recently forged</h2>+ <a class="cad-link" href="/docs/cad-forge">How CAD Forge works</a>+ </div>+ <div id="cadGallery" class="cad-grid"></div>+ <div id="cadGalleryStatus" class="cad-empty" hidden></div>+ </section>+ </section>++ <!-- ── /cad/:id: one design ───────────────────────────────────────── -->+ <section id="cadDesign" class="cad-design" hidden aria-labelledby="cadTitle">+ <div id="cadDesignError" class="cad-empty cad-empty--page" hidden></div>+ <div id="cadDesignBody" class="cad-design__body">+ <div class="cad-stage">+ <div id="cadViewTools" class="cad-tools" role="toolbar" aria-label="View">+ <div class="cad-seg">+ <button id="cadModeModel" type="button" aria-pressed="true">3D</button>+ <button id="cadModeDrawing" type="button" aria-pressed="false">Drawing</button>+ </div>+ <label class="cad-toggle"><input id="cadEdges" type="checkbox" checked /> Edges</label>+ <label class="cad-toggle"><input id="cadDims" type="checkbox" checked /> Dimensions</label>+ <button id="cadReframe" type="button" class="cad-icon-btn" aria-label="Reframe the part" title="Reframe">+ <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>+ </button>+ </div>+ <div id="cadViewport" class="cad-viewport" role="img" aria-label="Interactive 3D view of the part. Drag to orbit, scroll to zoom."></div>+ <div id="cadDrawing" class="cad-drawing" hidden><img id="cadDrawingImg" alt="Engineering drawing: front, right, top and isometric views" /></div>+ <p id="cadViewportError" class="cad-viewport__error" hidden>The 3D view could not start in this browser. The downloads and drawing still work.</p>+ <span id="cadRebuilding" class="cad-badge" hidden>Rebuilding on the kernel</span>+ </div>++ <aside class="cad-panel">+ <header class="cad-panel__head">+ <a class="cad-back" href="/cad">CAD Forge</a>+ <h1 id="cadTitle" class="cad-title"></h1>+ <p id="cadSummary" class="cad-summary"></p>+ <blockquote class="cad-asked"><span>Asked for</span> <q id="cadAsked"></q></blockquote>+ <div id="cadMeta" class="cad-meta"></div>+ <p id="cadLineage" class="cad-lineage" hidden></p>+ </header>++ <section id="cadParamsSection" class="cad-section" aria-labelledby="cadParamsTitle">+ <div class="cad-section__head">+ <h2 id="cadParamsTitle">Dimensions</h2>+ <button id="cadReset" type="button" class="cad-link">Reset</button>+ </div>+ <div id="cadParams" class="cad-params"></div>+ <p id="cadParamError" class="cad-inline-error" role="alert" hidden></p>+ </section>++ <section class="cad-section" aria-labelledby="cadMeasureTitle">+ <h2 id="cadMeasureTitle">Measurements</h2>+ <dl id="cadMetrics" class="cad-metrics"></dl>+ <h3 class="cad-sub">Mass if made solid in</h3>+ <div id="cadMass" class="cad-masses"></div>+ </section>++ <section id="cadAdjustmentsSection" class="cad-section" hidden aria-labelledby="cadAdjTitle">+ <h2 id="cadAdjTitle">Kernel adjustments</h2>+ <ul id="cadAdjustments" class="cad-adjustments"></ul>+ </section>++ <section class="cad-section" aria-labelledby="cadFilesTitle">+ <h2 id="cadFilesTitle">Files</h2>+ <div id="cadDownloads" class="cad-downloads"></div>+ <div class="cad-actions">+ <a id="cadAr" class="cad-btn" href="#">View in your space</a>+ <a id="cadPrint" class="cad-btn" href="#">Print it</a>+ <a id="cadScene" class="cad-btn cad-btn--ghost" href="#">Open in Scene Studio</a>+ <button id="cadCopyLink" type="button" class="cad-btn cad-btn--ghost">Copy link</button>+ </div>+ </section>++ <section class="cad-section" aria-labelledby="cadRefineTitle">+ <h2 id="cadRefineTitle">Refine</h2>+ <form id="cadRefine" class="cad-refine">+ <label for="cadRefineInput" class="cad-sr">Describe a change</label>+ <input id="cadRefineInput" type="text" maxlength="600" placeholder="Add a cable slot in the back, make the walls 3 mm" />+ <button id="cadRefineSubmit" type="submit" class="cad-btn cad-btn--primary">Refine</button>+ </form>+ <div id="cadRefineProgress" class="cad-progress-host" hidden></div>+ </section>++ <section class="cad-section" aria-labelledby="cadCodeTitle">+ <div class="cad-section__head">+ <h2 id="cadCodeTitle">Program</h2>+ <button id="cadCopyCode" type="button" class="cad-link">Copy</button>+ </div>+ <p class="cad-note">Plain Python. Runs anywhere with <code>pip install build123d bd_warehouse</code>, including <a href="https://github.com/earthtojake/text-to-cad" rel="noopener" target="_blank">text-to-cad</a>, which uses the same kernel.</p>+ <pre class="cad-code"><code id="cadCode"></code></pre>+ </section>+ </aside>+ </div>+ </section>+ <div id="cadToast" class="cad-toast" role="status" aria-live="polite" hidden></div>+ </main>++ <script type="module" src="/src/cad/main.js"></script>+</body>+</html>diff --git a/public/nav-data.js b/public/nav-data.jsindex df5f7a0c0..693afc56e 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -100,6 +100,13 @@ export const NAV_GROUPS = [badgeTone: 'live',desc: 'Upload a photo (up to 4 angles) → textured GLB of the object',},+ {+ title: 'CAD Forge',+ href: '/cad',+ badge: 'New',+ badgeTone: 'live',+ desc: 'Describe a part → real parametric CAD: STEP, STL, drawings and live dimension sliders',+ },{title: 'Describe it to 3D',href: '/create/prompt',diff --git a/src/cad/api.js b/src/cad/api.jsnew file mode 100644index 000000000..85c1e1dc6--- /dev/null+++ b/src/cad/api.js@@ -0,0 +1,76 @@+// CAD Forge page: the client side of /api/cad.++export class CadApiError extends Error {+ constructor(status, body) {+ super(body?.message || `Request failed (${status})`);+ this.status = status;+ this.code = body?.error || 'request_failed';+ this.body = body || {};+ }+}++async function readJsonResponse(res) {+ const body = await res.json().catch(() => ({}));+ if (!res.ok) throw new CadApiError(res.status, body);+ return body;+}++export async function fetchDesign(id, variantKey = null) {+ const qs = new URLSearchParams({ id });+ if (variantKey) qs.set('v', variantKey);+ return readJsonResponse(await fetch(`/api/cad?${qs}`));+}++export async function fetchGallery({ scope = 'recent', limit = 24, q = '' } = {}) {+ const qs = new URLSearchParams({ list: scope, limit: String(limit) });+ if (q) qs.set('q', q);+ return readJsonResponse(await fetch(`/api/cad?${qs}`));+}++export async function rebuildDesign(id, values, { signal } = {}) {+ const res = await fetch('/api/cad', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ action: 'rebuild', id, values }),+ signal,+ });+ return readJsonResponse(res);+}++/**+ * Generate (or refine) a design, streaming real progress.+ * onStage receives { stage, attempt, error? } as the server reports it.+ * Resolves with { design, attempts }; rejects with CadApiError.+ */+export async function generateDesign({ prompt, parentId = null, values = null, onStage = () => {}, signal } = {}) {+ const res = await fetch('/api/cad', {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'text/event-stream' },+ body: JSON.stringify({ action: 'generate', prompt, parentId, values, stream: true }),+ signal,+ });+ const type = res.headers.get('content-type') || '';+ if (!type.includes('text/event-stream')) return readJsonResponse(res);++ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ let boundary;+ while ((boundary = buffer.indexOf('\n\n')) !== -1) {+ const frame = buffer.slice(0, boundary);+ buffer = buffer.slice(boundary + 2);+ const event = /^event: (.+)$/m.exec(frame)?.[1];+ const data = /^data: (.+)$/m.exec(frame)?.[1];+ if (!event || !data) continue;+ const payload = JSON.parse(data);+ if (event === 'stage') onStage(payload);+ else if (event === 'done') return payload;+ else if (event === 'error') throw new CadApiError(payload.status || 502, payload);+ }+ }+ throw new CadApiError(502, { error: 'stream_ended', message: 'The connection closed before the part finished. Try again.' });+}diff --git a/src/cad/cad.css b/src/cad/cad.cssnew file mode 100644index 000000000..3a61ba16b--- /dev/null+++ b/src/cad/cad.css@@ -0,0 +1,1118 @@+/* CAD Forge (/cad, /cad/:id). Tokens from DESIGN-TOKENS.md. */++.cad-body {+ background: var(--bg-0);+ color: var(--ink);+ --cad-blue: #5b8def;+ --cad-paper: #f6f7f9;+ --cad-paper-ink: #1a1f29;+}++.cad {+ width: 100%;+ box-sizing: border-box;+ max-width: 1440px;+ margin: 0 auto;+ padding: var(--space-lg, 24px) var(--space-md, 16px) var(--space-2xl, 64px);+}++.cad-sr {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+}++/* ── hero + form ─────────────────────────────────────────────────────────── */++.cad-hero {+ max-width: 860px;+ margin: var(--space-xl, 40px) auto var(--space-2xl, 56px);+ text-align: center;+}++.cad-eyebrow {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ font-family: var(--font-mono);+ font-size: 12px;+ letter-spacing: 0.12em;+ text-transform: uppercase;+ color: var(--ink-dim);+ margin: 0 0 var(--space-sm, 12px);+}++.cad-eyebrow__mark {+ width: 14px;+ height: 14px;+ border: 1.5px solid var(--cad-blue);+ border-radius: 3px;+ background: linear-gradient(135deg, transparent 45%, var(--cad-blue) 45% 55%, transparent 55%);+}++.cad-hero h1 {+ font-family: var(--font-display);+ font-size: clamp(32px, 5.4vw, 56px);+ line-height: 1.05;+ letter-spacing: -0.02em;+ color: var(--ink-bright, var(--ink));+ margin: 0 0 var(--space-md, 16px);+}++.cad-lede {+ font-size: 17px;+ line-height: 1.55;+ color: var(--ink-dim);+ max-width: 680px;+ margin: 0 auto var(--space-lg, 28px);+}++.cad-lede a,+.cad-note a,+.cad-lineage a,+.cad-meta a {+ color: var(--ink);+ text-decoration: underline;+ text-decoration-color: var(--stroke-strong);+ text-underline-offset: 3px;+}++.cad-form {+ text-align: left;+ border: 1px solid var(--stroke-strong);+ background: var(--surface-1);+ border-radius: var(--radius-lg, 14px);+ padding: var(--space-sm, 12px);+ transition: border-color 0.2s ease, box-shadow 0.2s ease;+}++.cad-form:focus-within {+ border-color: var(--cad-blue);+ box-shadow: 0 0 0 4px color-mix(in srgb, var(--cad-blue) 18%, transparent);+}++.cad-form textarea {+ width: 100%;+ resize: vertical;+ min-height: 84px;+ border: 0;+ outline: 0;+ background: transparent;+ color: var(--ink);+ font: 16px/1.5 var(--font-body);+ padding: 6px 8px;+}++.cad-form__foot {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-sm, 12px);+ padding-top: 6px;+}++.cad-hint {+ font-size: 13px;+ color: var(--ink-faint);+}++.cad-hint kbd {+ font-family: var(--font-mono);+ font-size: 11px;+ border: 1px solid var(--stroke);+ border-radius: 4px;+ padding: 1px 5px;+}++.cad-notice {+ margin: var(--space-sm, 12px) 0 0;+ padding: 10px 14px;+ border-radius: var(--radius-md, 10px);+ border: 1px solid color-mix(in srgb, var(--warn) 45%, transparent);+ color: var(--warn);+ font-size: 14px;+}++.cad-chips {+ display: flex;+ flex-wrap: wrap;+ justify-content: center;+ gap: 8px;+ margin: var(--space-md, 16px) 0 0;+}++.cad-chip {+ border: 1px solid var(--stroke);+ background: transparent;+ color: var(--ink-dim);+ border-radius: var(--radius-pill, 999px);+ padding: 7px 13px;+ font: 13px var(--font-body);+ cursor: pointer;+ transition: color 0.15s ease, border-color 0.15s ease, background 0.15s ease, transform 0.15s ease;+}++.cad-chip:hover {+ color: var(--ink);+ border-color: var(--stroke-strong);+ background: var(--surface-1);+}++.cad-chip:active {+ transform: scale(0.97);+}++.cad-proof {+ list-style: none;+ padding: 0;+ margin: var(--space-xl, 40px) 0 0;+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: var(--space-md, 16px);+ text-align: left;+}++.cad-proof li {+ border-top: 1px solid var(--stroke);+ padding-top: var(--space-sm, 12px);+ display: grid;+ gap: 4px;+}++.cad-proof strong {+ font-family: var(--font-display);+ color: var(--ink-bright, var(--ink));+}++.cad-proof span {+ color: var(--ink-dim);+ font-size: 14px;+ line-height: 1.5;+}++/* ── buttons ─────────────────────────────────────────────────────────────── */++.cad-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ min-height: 38px;+ padding: 0 16px;+ border-radius: var(--radius-md, 10px);+ border: 1px solid var(--stroke-strong);+ background: var(--surface-2);+ color: var(--ink);+ font: 600 14px var(--font-body);+ text-decoration: none;+ cursor: pointer;+ transition: background 0.15s ease, border-color 0.15s ease, transform 0.12s ease, opacity 0.15s ease;+}++.cad-btn:hover {+ background: var(--surface-3);+}++.cad-btn:active {+ transform: translateY(1px);+}++.cad-btn:focus-visible,+.cad-chip:focus-visible,+.cad-link:focus-visible,+.cad-card:focus-visible,+.cad-dl:focus-visible,+.cad-mass:focus-visible,+.cad-seg button:focus-visible,+.cad-icon-btn:focus-visible {+ outline: 2px solid var(--cad-blue);+ outline-offset: 2px;+}++.cad-btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.cad-btn--primary {+ background: var(--ink-bright, #fff);+ color: var(--bg-0);+ border-color: transparent;+}++.cad-btn--primary:hover {+ background: var(--ink);+}++.cad-btn--ghost {+ background: transparent;+}++.cad-btn__spinner {+ display: none;+ width: 14px;+ height: 14px;+ border-radius: 50%;+ border: 2px solid currentColor;+ border-right-color: transparent;+ animation: cad-spin 0.8s linear infinite;+}++.cad-btn.is-busy .cad-btn__spinner {+ display: inline-block;+}++.cad-link {+ background: none;+ border: 0;+ padding: 0;+ color: var(--ink-dim);+ font: 13px var(--font-body);+ text-decoration: underline;+ text-underline-offset: 3px;+ cursor: pointer;+}++.cad-link:hover {+ color: var(--ink);+}++@keyframes cad-spin {+ to {+ transform: rotate(360deg);+ }+}++/* ── progress ────────────────────────────────────────────────────────────── */++.cad-progress-host {+ margin-top: var(--space-md, 16px);+ text-align: left;+}++.cad-progress {+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg, 14px);+ background: var(--surface-1);+ padding: var(--space-md, 16px);+ animation: cad-rise 0.25s ease;+}++.cad-progress__head {+ display: flex;+ justify-content: space-between;+ align-items: baseline;+ margin-bottom: 10px;+}++.cad-progress__title {+ font-family: var(--font-display);+ font-weight: 600;+ color: var(--ink-bright, var(--ink));+}++.cad-progress__clock {+ font: 12px var(--font-mono);+ color: var(--ink-faint);+}++.cad-steps {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ gap: 8px;+}++.cad-step {+ display: grid;+ grid-template-columns: 14px 1fr;+ gap: 4px 10px;+ align-items: center;+ font-size: 14px;+ color: var(--ink-dim);+ animation: cad-rise 0.2s ease;+}++.cad-step__dot {+ width: 10px;+ height: 10px;+ border-radius: 50%;+ border: 2px solid var(--stroke-strong);+ justify-self: center;+}++.cad-step.is-active {+ color: var(--ink);+}++.cad-step.is-active .cad-step__dot {+ border-color: var(--cad-blue);+ border-right-color: transparent;+ animation: cad-spin 0.9s linear infinite;+}++.cad-step.is-done .cad-step__dot {+ background: var(--success);+ border-color: var(--success);+}++.cad-step.is-warn .cad-step__dot {+ background: var(--warn);+ border-color: var(--warn);+}++.cad-step.is-failed .cad-step__dot {+ background: var(--danger);+ border-color: var(--danger);+}++.cad-step__detail {+ grid-column: 2;+ font: 12px/1.45 var(--font-mono);+ color: var(--ink-faint);+ white-space: pre-wrap;+ word-break: break-word;+}++.cad-progress__error {+ margin: 12px 0 0;+ color: var(--danger);+ font-size: 14px;+ line-height: 1.5;+}++@keyframes cad-rise {+ from {+ opacity: 0;+ transform: translateY(4px);+ }+}++/* ── gallery ─────────────────────────────────────────────────────────────── */++.cad-gallery__head {+ display: flex;+ justify-content: space-between;+ align-items: baseline;+ margin-bottom: var(--space-md, 16px);+}++.cad-gallery h2 {+ font-family: var(--font-display);+ font-size: 22px;+ margin: 0;+}++.cad-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));+ gap: var(--space-md, 16px);+}++.cad-card {+ display: grid;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg, 14px);+ overflow: hidden;+ text-decoration: none;+ color: inherit;+ background: var(--surface-1);+ transition: transform 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease;+}++.cad-card:hover {+ transform: translateY(-2px);+ border-color: var(--stroke-strong);+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.18);+}++.cad-card__paper {+ aspect-ratio: 4 / 3;+ background-color: var(--cad-paper);+ background-image:+ repeating-linear-gradient(0deg, rgba(91, 141, 239, 0.08) 0 1px, transparent 1px 16px),+ repeating-linear-gradient(90deg, rgba(91, 141, 239, 0.08) 0 1px, transparent 1px 16px);+ display: grid;+ place-items: center;+ padding: 14px;+}++.cad-card__paper img {+ max-width: 100%;+ max-height: 100%;+ object-fit: contain;+}++.cad-card__nothumb {+ color: #8a94a6;+ font: 12px var(--font-mono);+}++.cad-card__meta {+ display: grid;+ gap: 2px;+ padding: 10px 12px 12px;+}++.cad-card__meta strong {+ font-size: 14px;+ color: var(--ink-bright, var(--ink));+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.cad-card__meta span {+ font: 12px var(--font-mono);+ color: var(--ink-faint);+}++.cad-card--skeleton {+ min-height: 240px;+ background: linear-gradient(90deg, var(--surface-1), var(--surface-2), var(--surface-1));+ background-size: 200% 100%;+ animation: cad-shimmer 1.4s ease-in-out infinite;+}++@keyframes cad-shimmer {+ to {+ background-position: -200% 0;+ }+}++.cad-empty {+ border: 1px dashed var(--stroke-strong);+ border-radius: var(--radius-lg, 14px);+ padding: var(--space-lg, 24px);+ text-align: center;+ color: var(--ink-dim);+ display: grid;+ gap: 12px;+ justify-items: center;+}++.cad-empty p {+ margin: 0;+}++.cad-empty--page {+ max-width: 560px;+ margin: var(--space-2xl, 64px) auto;+}++.cad-row {+ display: flex;+ gap: 8px;+ flex-wrap: wrap;+ justify-content: center;+}++/* ── design view ─────────────────────────────────────────────────────────── */++.cad-design__body {+ display: grid;+ grid-template-columns: minmax(0, 1fr) 420px;+ gap: var(--space-md, 16px);+ align-items: start;+ transition: opacity 0.2s ease;+}++.cad-design__body.is-loading {+ opacity: 0.4;+ pointer-events: none;+}++.cad-stage {+ position: sticky;+ top: 76px;+ height: calc(100vh - 100px);+ min-height: 420px;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg, 14px);+ overflow: hidden;+ background:+ radial-gradient(ellipse at 50% 35%, color-mix(in srgb, var(--surface-2) 70%, transparent), transparent 70%),+ var(--bg-1, var(--bg-0));+}++.cad-viewport {+ position: absolute;+ inset: 0;+ touch-action: none;+}++.cad-viewport canvas {+ display: block;+ width: 100%;+ height: 100%;+}++.cad-viewport__error {+ position: absolute;+ inset: auto 16px 16px;+ margin: 0;+ padding: 10px 14px;+ border-radius: var(--radius-md, 10px);+ background: var(--scrim);+ color: var(--on-scrim-bright, #fff);+ font-size: 14px;+}++.cad-dims {+ position: absolute;+ inset: 0;+ pointer-events: none;+ overflow: hidden;+}++.cad-dim {+ position: absolute;+ left: 0;+ top: 0;+ font: 600 12px var(--font-mono);+ color: #fff;+ background: var(--cad-blue);+ border-radius: 6px;+ padding: 2px 7px;+ white-space: nowrap;+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);+}++.cad-drawing {+ position: absolute;+ inset: 0;+ display: grid;+ place-items: center;+ padding: 56px 24px 24px;+ background: var(--cad-paper);+ background-image:+ repeating-linear-gradient(0deg, rgba(91, 141, 239, 0.07) 0 1px, transparent 1px 20px),+ repeating-linear-gradient(90deg, rgba(91, 141, 239, 0.07) 0 1px, transparent 1px 20px);+}++.cad-drawing img {+ max-width: 100%;+ max-height: 100%;+}++.cad-tools {+ position: absolute;+ z-index: 2;+ top: 12px;+ left: 12px;+ right: 12px;+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ align-items: center;+}++.cad-tools.is-drawing .cad-toggle,+.cad-tools.is-drawing .cad-icon-btn {+ display: none;+}++.cad-seg {+ display: inline-flex;+ border: 1px solid var(--stroke-strong);+ border-radius: var(--radius-md, 10px);+ overflow: hidden;+ background: var(--scrim);+ backdrop-filter: blur(8px);+}++.cad-seg button {+ border: 0;+ background: transparent;+ color: var(--on-scrim, #ddd);+ font: 600 13px var(--font-body);+ padding: 7px 12px;+ cursor: pointer;+ transition: background 0.15s ease, color 0.15s ease;+}++.cad-seg button[aria-pressed='true'] {+ background: var(--on-scrim-bright, #fff);+ color: #111;+}++.cad-seg button:disabled {+ opacity: 0.45;+ cursor: not-allowed;+}++.cad-toggle {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: 13px;+ color: var(--on-scrim, #ddd);+ background: var(--scrim);+ backdrop-filter: blur(8px);+ border: 1px solid var(--on-scrim-stroke, rgba(255, 255, 255, 0.18));+ border-radius: var(--radius-md, 10px);+ padding: 6px 10px;+ cursor: pointer;+}++.cad-toggle input {+ accent-color: var(--cad-blue);+}++.cad-icon-btn {+ display: inline-grid;+ place-items: center;+ width: 34px;+ height: 34px;+ margin-left: auto;+ border-radius: var(--radius-md, 10px);+ border: 1px solid var(--on-scrim-stroke, rgba(255, 255, 255, 0.18));+ background: var(--scrim);+ color: var(--on-scrim-bright, #fff);+ cursor: pointer;+ transition: background 0.15s ease;+}++.cad-icon-btn:hover {+ background: var(--scrim-strong);+}++.cad-badge {+ position: absolute;+ z-index: 2;+ bottom: 14px;+ left: 50%;+ transform: translateX(-50%);+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 7px 14px;+ border-radius: var(--radius-pill, 999px);+ background: var(--scrim-strong);+ color: var(--on-scrim-bright, #fff);+ font-size: 13px;+ animation: cad-rise 0.2s ease;+}++.cad-badge::before {+ content: '';+ width: 10px;+ height: 10px;+ border-radius: 50%;+ border: 2px solid currentColor;+ border-right-color: transparent;+ animation: cad-spin 0.8s linear infinite;+}++/* ── side panel ──────────────────────────────────────────────────────────── */++.cad-panel {+ display: grid;+ grid-template-columns: minmax(0, 1fr);+ gap: var(--space-md, 16px);+ min-width: 0;+}++.cad-panel__head,+.cad-section {+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg, 14px);+ background: var(--surface-1);+ padding: var(--space-md, 16px);+}++.cad-back {+ font: 12px var(--font-mono);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--ink-faint);+ text-decoration: none;+}++.cad-back::before {+ content: '← ';+}++.cad-back:hover {+ color: var(--ink);+}++.cad-title {+ font-family: var(--font-display);+ font-size: 26px;+ line-height: 1.15;+ margin: 6px 0 6px;+ color: var(--ink-bright, var(--ink));+ overflow-wrap: anywhere;+}++.cad-summary {+ margin: 0 0 10px;+ color: var(--ink-dim);+ line-height: 1.5;+}++.cad-asked {+ margin: 0;+ padding: 8px 12px;+ border-left: 2px solid var(--cad-blue);+ background: var(--surface-2);+ border-radius: 0 var(--radius-sm, 6px) var(--radius-sm, 6px) 0;+ font-size: 14px;+ color: var(--ink);+ overflow-wrap: anywhere;+}++.cad-asked span {+ display: block;+ font: 11px var(--font-mono);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--ink-faint);+ margin-bottom: 2px;+}++.cad-meta {+ display: flex;+ flex-wrap: wrap;+ gap: 4px 14px;+ margin-top: 10px;+ font: 12px var(--font-mono);+ color: var(--ink-faint);+}++.cad-lineage {+ margin: 8px 0 0;+ font-size: 13px;+ color: var(--ink-dim);+ display: grid;+ gap: 4px;+}++.cad-section h2 {+ font-family: var(--font-display);+ font-size: 16px;+ margin: 0 0 12px;+}++.cad-section__head {+ display: flex;+ justify-content: space-between;+ align-items: baseline;+}++.cad-sub {+ font-size: 12px;+ font-weight: 600;+ color: var(--ink-faint);+ letter-spacing: 0.04em;+ text-transform: uppercase;+ margin: 14px 0 8px;+}++.cad-params {+ display: grid;+ gap: 14px;+}++.cad-param__label {+ display: flex;+ justify-content: space-between;+ gap: 8px;+ font-size: 14px;+ color: var(--ink);+ margin-bottom: 4px;+}++.cad-param__label code {+ font: 11px var(--font-mono);+ color: var(--ink-faint);+}++.cad-param__controls {+ display: grid;+ grid-template-columns: minmax(0, 1fr) 76px minmax(30px, auto);+ gap: 8px;+ align-items: center;+}++.cad-param input[type='range'] {+ width: 100%;+ accent-color: var(--cad-blue);+}++.cad-param__num {+ width: 100%;+ min-height: 32px;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-sm, 6px);+ background: var(--surface-2);+ color: var(--ink);+ font: 13px var(--font-mono);+ padding: 0 8px;+}++.cad-param__num:focus {+ outline: 2px solid var(--cad-blue);+ outline-offset: 0;+}++.cad-param__unit {+ font: 12px var(--font-mono);+ color: var(--ink-faint);+}++.cad-inline-error {+ margin: 12px 0 0;+ color: var(--danger);+ font-size: 13px;+ line-height: 1.5;+}++.cad-metrics {+ display: grid;+ gap: 6px;+ margin: 0;+}++.cad-metric {+ display: flex;+ justify-content: space-between;+ gap: 12px;+ font-size: 14px;+}++.cad-metric dt {+ color: var(--ink-dim);+}++.cad-metric dd {+ margin: 0;+ font-family: var(--font-mono);+ font-size: 13px;+ text-align: right;+ color: var(--ink);+}++.cad-metric.is-ok dd {+ color: var(--success);+}++.cad-metric.is-warn dd {+ color: var(--warn);+}++.cad-masses {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 6px;+}++.cad-mass {+ display: grid;+ gap: 2px;+ text-align: left;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md, 10px);+ background: transparent;+ color: var(--ink-dim);+ padding: 8px 10px;+ font: 12px var(--font-body);+ cursor: pointer;+ transition: border-color 0.15s ease, background 0.15s ease;+}++.cad-mass strong {+ font: 600 13px var(--font-mono);+ color: var(--ink);+}++.cad-mass:hover {+ border-color: var(--stroke-strong);+}++.cad-mass.is-on {+ border-color: var(--cad-blue);+ background: color-mix(in srgb, var(--cad-blue) 12%, transparent);+}++.cad-adjustments {+ margin: 0;+ padding-left: 18px;+ color: var(--ink-dim);+ font-size: 13px;+ line-height: 1.5;+}++.cad-downloads {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 8px;+}++.cad-dl {+ display: grid;+ gap: 2px;+ padding: 10px 12px;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md, 10px);+ text-decoration: none;+ color: var(--ink);+ transition: border-color 0.15s ease, background 0.15s ease, transform 0.12s ease;+}++.cad-dl:hover {+ border-color: var(--stroke-strong);+ background: var(--surface-2);+}++.cad-dl:active {+ transform: translateY(1px);+}++.cad-dl strong {+ font-size: 14px;+}++.cad-dl strong::after {+ content: ' ↓';+ color: var(--ink-faint);+}++.cad-dl span {+ font-size: 12px;+ color: var(--ink-faint);+}++.cad-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ margin-top: 12px;+}++.cad-refine {+ display: flex;+ gap: 8px;+}++.cad-refine input {+ flex: 1;+ min-width: 0;+ min-height: 38px;+ border: 1px solid var(--stroke-strong);+ border-radius: var(--radius-md, 10px);+ background: var(--surface-2);+ color: var(--ink);+ font: 14px var(--font-body);+ padding: 0 12px;+}++.cad-refine input:focus {+ outline: 2px solid var(--cad-blue);+ outline-offset: 0;+}++.cad-note {+ margin: 0 0 10px;+ font-size: 13px;+ color: var(--ink-dim);+ line-height: 1.5;+}++.cad-note code {+ font: 12px var(--font-mono);+}++.cad-code {+ margin: 0;+ max-height: 420px;+ overflow: auto;+ padding: 12px;+ border-radius: var(--radius-md, 10px);+ background: var(--bg-0);+ border: 1px solid var(--stroke);+ font: 12px/1.55 var(--font-mono);+ color: var(--ink);+ tab-size: 4;+}++.cad-toast {+ position: fixed;+ left: 50%;+ bottom: 24px;+ transform: translate(-50%, 8px);+ opacity: 0;+ z-index: 50;+ padding: 10px 16px;+ border-radius: var(--radius-pill, 999px);+ background: var(--scrim-strong);+ color: var(--on-scrim-bright, #fff);+ font-size: 14px;+ transition: opacity 0.2s ease, transform 0.2s ease;+ max-width: calc(100vw - 32px);+}++.cad-toast.is-on {+ opacity: 1;+ transform: translate(-50%, 0);+}++/* ── responsive ──────────────────────────────────────────────────────────── */++@media (max-width: 980px) {+ .cad-design__body {+ grid-template-columns: 1fr;+ }++ .cad-stage {+ position: relative;+ top: 0;+ height: 62vh;+ min-height: 340px;+ }+}++@media (max-width: 640px) {+ .cad-hero {+ margin-top: var(--space-md, 16px);+ }++ .cad-proof {+ grid-template-columns: 1fr;+ }++ .cad-form__foot {+ flex-direction: column;+ align-items: stretch;+ }++ .cad-hint {+ display: none;+ }++ .cad-masses,+ .cad-downloads {+ grid-template-columns: 1fr 1fr;+ }++ .cad-refine {+ flex-direction: column;+ }+}++@media (prefers-reduced-motion: reduce) {+ .cad-card,+ .cad-btn,+ .cad-chip,+ .cad-step,+ .cad-progress,+ .cad-badge {+ animation: none;+ transition: none;+ }+}diff --git a/src/cad/main.js b/src/cad/main.jsnew file mode 100644index 000000000..1997f2277--- /dev/null+++ b/src/cad/main.js@@ -0,0 +1,566 @@+// CAD Forge page controller: /cad (create + gallery) and /cad/:id (a design).++import { CadApiError, fetchDesign, fetchGallery, generateDesign, rebuildDesign } from './api.js';+import { MATERIALS, MAX_PROMPT_LEN, applyParams, massGrams } from './params.js';++const EXAMPLES = [+ 'Wall-mounted phone holder with two countersunk screw holes',+ '20-tooth spur gear, module 1.5, with a 5 mm bore and a hub',+ 'Raspberry Pi 4 case base with standoffs and vent slots',+ 'Cable organizer clip for five 6 mm cables',+ 'L bracket, 90 degrees, 3 mm thick, four M4 holes',+ 'Knob for a 6 mm D-shaft with grip ridges',+];++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const REBUILD_DEBOUNCE_MS = 350;++const $ = (sel) => document.querySelector(sel);++const state = {+ design: null,+ variant: null,+ values: {},+ viewer: null,+ viewerReady: null,+ rebuild: null,+ rebuildTimer: 0,+ finish: 'pla',+ busy: false,+};++// ── small DOM helpers ───────────────────────────────────────────────────────++function el(tag, attrs = {}, ...children) {+ const node = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) {+ if (v == null || v === false) continue;+ if (k === 'class') node.className = v;+ else if (k === 'text') node.textContent = v;+ else if (k.startsWith('on')) node.addEventListener(k.slice(2), v);+ else node.setAttribute(k, v === true ? '' : String(v));+ }+ for (const child of children.flat()) {+ if (child == null || child === false) continue;+ node.append(child instanceof Node ? child : document.createTextNode(String(child)));+ }+ return node;+}++function fmtMm(v) {+ return v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toFixed(2);+}++function sizeText(size) {+ return Array.isArray(size) ? `${size.map((v) => fmtMm(Number(v))).join(' × ')} mm` : '';+}++function toast(message) {+ const node = $('#cadToast');+ node.textContent = message;+ node.hidden = false;+ node.classList.add('is-on');+ clearTimeout(toast.timer);+ toast.timer = setTimeout(() => {+ node.classList.remove('is-on');+ node.hidden = true;+ }, 2600);+}++// ── routing ─────────────────────────────────────────────────────────────────++function routeId() {+ const m = /^\/cad\/([0-9a-f-]{36})\/?$/i.exec(location.pathname);+ return m && UUID_RE.test(m[1]) ? m[1] : null;+}++function showView(name) {+ $('#cadHome').hidden = name !== 'home';+ $('#cadDesign').hidden = name !== 'design';+ document.body.dataset.cadView = name;+}++async function route() {+ const id = routeId();+ if (id) {+ showView('design');+ await openDesign(id, new URLSearchParams(location.search).get('v'));+ } else {+ showView('home');+ document.title = 'CAD Forge · Describe a part, get real CAD · three.ws';+ const prefill = new URLSearchParams(location.search).get('prompt');+ if (prefill) $('#cadPrompt').value = prefill.slice(0, MAX_PROMPT_LEN);+ loadGallery();+ }+}++function navigate(path) {+ history.pushState(null, '', path);+ window.scrollTo({ top: 0 });+ route();+}++// ── progress (real server stages) ───────────────────────────────────────────++function createProgress(container) {+ const started = performance.now();+ const list = el('ol', { class: 'cad-steps' });+ const clock = el('span', { class: 'cad-progress__clock', text: '0 s' });+ const panel = el(+ 'div',+ { class: 'cad-progress', role: 'status', 'aria-live': 'polite' },+ el('div', { class: 'cad-progress__head' }, el('span', { class: 'cad-progress__title', text: 'Forging your part' }), clock),+ list,+ );+ container.replaceChildren(panel);+ container.hidden = false;+ const timer = setInterval(() => {+ clock.textContent = `${Math.round((performance.now() - started) / 1000)} s`;+ }, 1000);+ let current = null;++ function step(text, detail = null, tone = 'active') {+ if (current) current.classList.replace('is-active', 'is-done');+ const item = el('li', { class: `cad-step is-${tone}` }, el('span', { class: 'cad-step__dot', 'aria-hidden': 'true' }), el('span', { class: 'cad-step__text', text }));+ if (detail) item.append(el('code', { class: 'cad-step__detail', text: detail }));+ list.append(item);+ current = tone === 'active' ? item : null;+ }++ return {+ stage(event) {+ if (event.stage === 'writing') step('Writing the build123d program');+ else if (event.stage === 'building') step(event.attempt > 1 ? `Rebuilding on the OpenCascade kernel (attempt ${event.attempt})` : 'Building on the OpenCascade kernel');+ else if (event.stage === 'repairing') {+ const e = event.error || {};+ const where = e.line ? `line ${e.line}: ` : '';+ step('The kernel rejected it, so the program is being repaired', `${e.kind || 'error'} · ${where}${String(e.message || '').slice(0, 220)}`, 'warn');+ step('Rewriting the failing feature');+ } else if (event.stage === 'built') step('Kernel accepted the solid');+ else if (event.stage === 'saving') step('Exporting STEP, STL, GLB and drawings');+ },+ finish() {+ clearInterval(timer);+ if (current) current.classList.replace('is-active', 'is-done');+ },+ fail(message) {+ clearInterval(timer);+ if (current) current.classList.replace('is-active', 'is-failed');+ panel.append(el('p', { class: 'cad-progress__error', text: message }));+ },+ };+}++function errorMessage(err) {+ if (err instanceof CadApiError) {+ if (err.code === 'design_failed' && err.body.lastError) {+ const e = err.body.lastError;+ return `${err.message} Last kernel error: ${e.message}${e.line ? ` (line ${e.line})` : ''}.`;+ }+ return err.message;+ }+ if (err?.name === 'AbortError') return 'Cancelled.';+ return 'The connection dropped before the part finished. Check your network and try again.';+}++// ── create ──────────────────────────────────────────────────────────────────++async function submitCreate(event) {+ event?.preventDefault();+ if (state.busy) return;+ const prompt = $('#cadPrompt').value.trim();+ if (prompt.length < 3) {+ $('#cadPrompt').focus();+ toast('Describe the part first: what it is, its key sizes and features.');+ return;+ }+ state.busy = true;+ const button = $('#cadSubmit');+ button.disabled = true;+ button.classList.add('is-busy');+ const progress = createProgress($('#cadProgress'));+ try {+ const { design } = await generateDesign({ prompt, onStage: progress.stage });+ progress.finish();+ navigate(`/cad/${design.id}`);+ } catch (err) {+ progress.fail(errorMessage(err));+ } finally {+ state.busy = false;+ button.disabled = false;+ button.classList.remove('is-busy');+ }+}++function renderExamples() {+ $('#cadExamples').replaceChildren(+ ...EXAMPLES.map((text) =>+ el('button', {+ type: 'button',+ class: 'cad-chip',+ text,+ onclick: () => {+ $('#cadPrompt').value = text;+ $('#cadPrompt').focus();+ },+ }),+ ),+ );+}++// ── gallery ─────────────────────────────────────────────────────────────────++function galleryCard(d) {+ return el(+ 'a',+ { class: 'cad-card', href: `/cad/${d.id}` },+ el('div', { class: 'cad-card__paper' }, d.thumb ? el('img', { src: d.thumb, alt: `Line drawing of ${d.title}`, loading: 'lazy', decoding: 'async' }) : el('span', { class: 'cad-card__nothumb', text: 'No drawing' })),+ el('div', { class: 'cad-card__meta' }, el('strong', { text: d.title }), el('span', { text: sizeText(d.sizeMm) })),+ );+}++async function loadGallery() {+ const grid = $('#cadGallery');+ const status = $('#cadGalleryStatus');+ grid.replaceChildren(...Array.from({ length: 8 }, () => el('div', { class: 'cad-card cad-card--skeleton', 'aria-hidden': 'true' })));+ status.hidden = true;+ try {+ const { designs, available } = await fetchGallery({ limit: 24 });+ setAvailability(available);+ if (!designs.length) {+ grid.replaceChildren();+ status.replaceChildren(el('p', { text: 'No parts forged yet. Pick an example above, or describe the part you need, and yours becomes the first one here.' }));+ status.hidden = false;+ return;+ }+ grid.replaceChildren(...designs.map(galleryCard));+ } catch {+ grid.replaceChildren();+ status.replaceChildren(+ el('p', { text: 'Recent parts could not be loaded.' }),+ el('button', { type: 'button', class: 'cad-btn cad-btn--ghost', text: 'Retry', onclick: loadGallery }),+ );+ status.hidden = false;+ }+}++function setAvailability(available) {+ const notice = $('#cadOffline');+ notice.hidden = available !== false;+ $('#cadSubmit').disabled = available === false;+}++// ── design view ─────────────────────────────────────────────────────────────++async function ensureViewer() {+ if (!state.viewerReady) {+ state.viewerReady = import('./viewer.js').then(({ createCadViewer }) => {+ state.viewer = createCadViewer($('#cadViewport'));+ state.viewer.setFinish(state.finish);+ return state.viewer;+ });+ }+ return state.viewerReady;+}++function current() {+ const v = state.variant;+ return {+ files: v?.files || state.design.files,+ metrics: v?.metrics || state.design.metrics,+ adjustments: v?.adjustments || state.design.adjustments || [],+ };+}++async function openDesign(id, variantKey) {+ $('#cadDesignError').hidden = true;+ $('#cadDesignBody').classList.add('is-loading');+ let payload;+ try {+ payload = await fetchDesign(id, variantKey);+ } catch (err) {+ $('#cadDesignBody').classList.remove('is-loading');+ const box = $('#cadDesignError');+ const missing = err instanceof CadApiError && err.status === 404;+ box.replaceChildren(+ el('h2', { text: missing ? 'This part does not exist' : 'This part could not be loaded' }),+ el('p', { text: missing ? 'The link may be mistyped, or the design was never saved.' : errorMessage(err) }),+ el('div', { class: 'cad-row' },+ missing ? null : el('button', { type: 'button', class: 'cad-btn', text: 'Retry', onclick: () => openDesign(id, variantKey) }),+ el('a', { class: 'cad-btn cad-btn--ghost', href: '/cad', text: 'Forge a new part' })),+ );+ box.hidden = false;+ return;+ }+ state.design = payload.design;+ state.variant = payload.variant || null;+ state.values = Object.fromEntries(state.design.params.map((p) => [p.name, p.value]));+ if (state.variant) Object.assign(state.values, state.variant.values);+ document.title = `${state.design.title} · CAD Forge · three.ws`;++ renderHeader(payload.lineage);+ renderParams();+ renderOutputs();+ renderCode();+ $('#cadDesignBody').classList.remove('is-loading');++ try {+ const viewer = await ensureViewer();+ await viewer.load(current().files.glb, current().metrics.size_mm);+ viewer.reframe();+ } catch {+ $('#cadViewportError').hidden = false;+ }+}++function renderHeader(lineage) {+ const d = state.design;+ $('#cadTitle').textContent = d.title;+ $('#cadSummary').textContent = d.summary || '';+ $('#cadSummary').hidden = !d.summary;+ $('#cadAsked').textContent = d.prompt;+ const meta = $('#cadMeta');+ meta.replaceChildren(+ ...[+ d.creatorUsername ? el('a', { href: `/u/${encodeURIComponent(d.creatorUsername)}`, text: `by @${d.creatorUsername}` }) : null,+ el('span', { text: `${d.views} view${d.views === 1 ? '' : 's'}` }),+ d.model ? el('span', { title: 'The model that wrote the program', text: d.model.split('/').pop() }) : null,+ ].filter(Boolean),+ );+ const lin = $('#cadLineage');+ const parts = [];+ if (lineage?.parent) parts.push(el('span', {}, 'Refined from ', el('a', { href: `/cad/${lineage.parent.id}`, text: lineage.parent.title })));+ if (lineage?.children?.length) {+ parts.push(el('span', {}, 'Refinements: ', ...lineage.children.map((c, i) => [i ? ', ' : '', el('a', { href: `/cad/${c.id}`, text: c.title })])));+ }+ lin.replaceChildren(...parts);+ lin.hidden = !parts.length;+}++function renderParams() {+ const host = $('#cadParams');+ const params = state.design.params;+ $('#cadParamsSection').hidden = !params.length;+ host.replaceChildren(+ ...params.map((p) => {+ const id = `cad-p-${p.name}`;+ const range = el('input', { type: 'range', id, min: p.min, max: p.max, step: p.step, value: state.values[p.name], 'aria-label': p.label });+ const number = el('input', { type: 'number', class: 'cad-param__num', min: p.min, max: p.max, step: p.step, value: state.values[p.name], 'aria-label': `${p.label} value` });+ const sync = (value, commit) => {+ const v = Math.min(p.max, Math.max(p.min, Number(value)));+ if (!Number.isFinite(v)) return;+ range.value = String(v);+ number.value = String(v);+ state.values[p.name] = v;+ if (commit) scheduleRebuild();+ };+ range.addEventListener('input', () => sync(range.value, false));+ range.addEventListener('change', () => sync(range.value, true));+ number.addEventListener('change', () => sync(number.value, true));+ return el(+ 'div',+ { class: 'cad-param' },+ el('label', { for: id, class: 'cad-param__label' }, el('span', { text: p.label }), el('code', { text: p.name })),+ el('div', { class: 'cad-param__controls' }, range, number, el('span', { class: 'cad-param__unit', text: p.unit === 'count' ? '' : p.unit })),+ );+ }),+ );+}++function scheduleRebuild() {+ clearTimeout(state.rebuildTimer);+ state.rebuildTimer = setTimeout(runRebuild, REBUILD_DEBOUNCE_MS);+}++async function runRebuild() {+ state.rebuild?.abort();+ const controller = new AbortController();+ state.rebuild = controller;+ const badge = $('#cadRebuilding');+ const err = $('#cadParamError');+ badge.hidden = false;+ err.hidden = true;+ try {+ const { variant } = await rebuildDesign(state.design.id, state.values, { signal: controller.signal });+ if (controller.signal.aborted) return;+ state.variant = variant;+ const viewer = await ensureViewer();+ await viewer.load(variant.files.glb, variant.metrics.size_mm);+ history.replaceState(null, '', `/cad/${state.design.id}?v=${variant.key}`);+ renderOutputs();+ renderCode();+ } catch (e) {+ if (e?.name === 'AbortError') return;+ const kernel = e instanceof CadApiError ? e.body.buildError : null;+ err.textContent = kernel ? `${e.message} Kernel: ${kernel.message}` : errorMessage(e);+ err.hidden = false;+ } finally {+ if (state.rebuild === controller) {+ badge.hidden = true;+ state.rebuild = null;+ }+ }+}++function resetParams() {+ state.values = Object.fromEntries(state.design.params.map((p) => [p.name, p.value]));+ state.variant = null;+ history.replaceState(null, '', `/cad/${state.design.id}`);+ renderParams();+ renderOutputs();+ renderCode();+ $('#cadParamError').hidden = true;+ ensureViewer().then((v) => v.load(state.design.files.glb, state.design.metrics.size_mm));+}++function renderOutputs() {+ const { files, metrics, adjustments } = current();+ const d = state.design;+ const [x, y, z] = metrics.size_mm;+ $('#cadMetrics').replaceChildren(+ metricRow('Size', `${fmtMm(x)} × ${fmtMm(y)} × ${fmtMm(z)} mm`),+ metricRow('Volume', `${(metrics.volume_mm3 / 1000).toFixed(2)} cm³`),+ metricRow('Surface', `${(metrics.area_mm2 / 100).toFixed(1)} cm²`),+ metricRow('Topology', `${metrics.solids} solid${metrics.solids === 1 ? '' : 's'} · ${metrics.faces} faces · ${metrics.edges} edges`),+ metricRow('Kernel check', metrics.valid ? 'Valid B-rep' : 'Built, with geometry warnings', metrics.valid ? 'ok' : 'warn'),+ );+ $('#cadMass').replaceChildren(+ ...MATERIALS.map((m) =>+ el(+ 'button',+ {+ type: 'button',+ class: `cad-mass${m.id === state.finish ? ' is-on' : ''}`,+ 'aria-pressed': m.id === state.finish ? 'true' : 'false',+ onclick: () => {+ state.finish = m.id;+ state.viewer?.setFinish(m.id);+ renderOutputs();+ },+ },+ el('span', { text: m.label }),+ el('strong', { text: `${massGrams(metrics.volume_mm3, m.density).toFixed(1)} g` }),+ ),+ ),+ );+ const notes = $('#cadAdjustments');+ notes.replaceChildren(...adjustments.map((a) => el('li', { text: a })));+ $('#cadAdjustmentsSection').hidden = !adjustments.length;++ const slug = d.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'part';+ const pyUrl = `/api/cad?id=${d.id}&format=py${state.variant ? `&v=${state.variant.key}` : ''}`;+ $('#cadDownloads').replaceChildren(+ ...[+ download(files.step, `${slug}.step`, 'STEP', 'Fusion, SolidWorks, FreeCAD, Onshape'),+ download(files.stl, `${slug}.stl`, 'STL', 'Any slicer, ready to print'),+ download(files.glb, `${slug}.glb`, 'GLB', 'Web, games, AR, true scale'),+ files.drawing_svg ? download(files.drawing_svg, `${slug}-drawing.svg`, 'Drawing', 'Front, top, right and iso views') : null,+ download(pyUrl, `${slug}.py`, 'Python', 'The build123d program itself'),+ ].filter(Boolean),+ );++ const glb = files.glb;+ $('#cadAr').href = `/api/ar?src=${encodeURIComponent(glb)}&title=${encodeURIComponent(d.title)}`;+ $('#cadPrint').href = `/materialize?glb=${encodeURIComponent(glb)}`;+ $('#cadScene').href = `/scene?model=${encodeURIComponent(glb)}&name=${encodeURIComponent(d.title)}`;++ const drawing = $('#cadDrawingImg');+ if (files.drawing_svg) drawing.src = files.drawing_svg;+ $('#cadModeDrawing').disabled = !files.drawing_svg;+}++function metricRow(label, value, tone = null) {+ return el('div', { class: `cad-metric${tone ? ` is-${tone}` : ''}` }, el('dt', { text: label }), el('dd', { text: value }));+}++function download(href, filename, label, hint) {+ return el('a', { class: 'cad-dl', href, download: filename, rel: 'noopener' }, el('strong', { text: label }), el('span', { text: hint }));+}++function renderCode() {+ $('#cadCode').textContent = applyParams(state.design.code, state.values).code;+}++async function submitRefine(event) {+ event.preventDefault();+ if (state.busy) return;+ const input = $('#cadRefineInput');+ const prompt = input.value.trim();+ if (prompt.length < 3) {+ input.focus();+ return;+ }+ state.busy = true;+ const button = $('#cadRefineSubmit');+ button.disabled = true;+ const progress = createProgress($('#cadRefineProgress'));+ try {+ const { design } = await generateDesign({ prompt, parentId: state.design.id, values: state.values, onStage: progress.stage });+ progress.finish();+ input.value = '';+ $('#cadRefineProgress').hidden = true;+ navigate(`/cad/${design.id}`);+ } catch (err) {+ progress.fail(errorMessage(err));+ } finally {+ state.busy = false;+ button.disabled = false;+ }+}++function setMode(mode) {+ const drawing = mode === 'drawing';+ $('#cadViewport').hidden = drawing;+ $('#cadDrawing').hidden = !drawing;+ $('#cadModeModel').setAttribute('aria-pressed', String(!drawing));+ $('#cadModeDrawing').setAttribute('aria-pressed', String(drawing));+ $('#cadViewTools').classList.toggle('is-drawing', drawing);+}++function wireDesignTools() {+ $('#cadEdges').addEventListener('change', (e) => state.viewer?.setEdges(e.target.checked));+ $('#cadDims').addEventListener('change', (e) => state.viewer?.setDimensions(e.target.checked));+ $('#cadReframe').addEventListener('click', () => state.viewer?.reframe());+ $('#cadModeModel').addEventListener('click', () => setMode('model'));+ $('#cadModeDrawing').addEventListener('click', () => setMode('drawing'));+ $('#cadReset').addEventListener('click', resetParams);+ $('#cadRefine').addEventListener('submit', submitRefine);+ $('#cadCopyLink').addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(location.href);+ toast('Link copied. Anyone with it sees this exact configuration.');+ } catch {+ toast('Copy failed. Select the address bar to copy the link.');+ }+ });+ $('#cadCopyCode').addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText($('#cadCode').textContent);+ toast('Program copied. It runs anywhere build123d is installed.');+ } catch {+ toast('Copy failed. Select the code to copy it.');+ }+ });+}++// ── boot ────────────────────────────────────────────────────────────────────++function boot() {+ renderExamples();+ $('#cadForm').addEventListener('submit', submitCreate);+ $('#cadPrompt').addEventListener('keydown', (e) => {+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) submitCreate(e);+ });+ $('#cadPrompt').maxLength = MAX_PROMPT_LEN;+ wireDesignTools();+ document.addEventListener('click', (e) => {+ const link = e.target.closest?.('a[href^="/cad"]');+ if (!link || e.metaKey || e.ctrlKey || e.shiftKey || link.target === '_blank' || link.hasAttribute('download')) return;+ e.preventDefault();+ navigate(link.getAttribute('href'));+ });+ window.addEventListener('popstate', route);+ route();+}++boot();diff --git a/src/cad/viewer.js b/src/cad/viewer.jsnew file mode 100644index 000000000..520f1410a--- /dev/null+++ b/src/cad/viewer.js@@ -0,0 +1,313 @@+// CAD Forge viewer: a measured, engineering-style look at one part.+//+// CAD Forge GLBs are exported in metres at true scale with Z-up converted to+// glTF's Y-up, so the viewer never rescales the model: the grid is laid out in+// real millimetres and the dimension callouts read the kernel's exact extents+// (passed in by the caller) rather than the tessellated mesh's.+//+// Axis mapping (CAD → three): X → X, Y → -Z, Z → Y.++import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';++export const FINISHES = Object.freeze({+ pla: { color: 0xd8dde6, metalness: 0.0, roughness: 0.62 },+ petg: { color: 0x9fd3e6, metalness: 0.0, roughness: 0.3 },+ nylon: { color: 0xece8de, metalness: 0.0, roughness: 0.85 },+ aluminum: { color: 0xc4cad3, metalness: 0.9, roughness: 0.32 },+ steel: { color: 0x9ea4ad, metalness: 0.95, roughness: 0.38 },+ brass: { color: 0xd6b35c, metalness: 0.95, roughness: 0.3 },+});++const EDGE_THRESHOLD_DEG = 24;++function niceStep(rawMm) {+ const steps = [0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500];+ return steps.find((s) => s >= rawMm) || 1000;+}++function formatMm(mm) {+ if (mm >= 100) return `${mm.toFixed(0)} mm`;+ if (mm >= 10) return `${mm.toFixed(1)} mm`;+ return `${mm.toFixed(2)} mm`;+}++export function createCadViewer(container) {+ const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.05;+ renderer.shadowMap.enabled = true;+ renderer.shadowMap.type = THREE.PCFShadowMap;+ container.appendChild(renderer.domElement);++ const overlay = document.createElement('div');+ overlay.className = 'cad-dims';+ overlay.setAttribute('aria-hidden', 'true');+ container.appendChild(overlay);++ const scene = new THREE.Scene();+ const pmrem = new THREE.PMREMGenerator(renderer);+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;++ const camera = new THREE.PerspectiveCamera(35, 1, 0.0005, 100);+ const controls = new OrbitControls(camera, renderer.domElement);+ controls.enableDamping = true;+ controls.dampingFactor = 0.08;++ const key = new THREE.DirectionalLight(0xffffff, 1.4);+ key.castShadow = true;+ key.shadow.mapSize.set(2048, 2048);+ scene.add(key, new THREE.HemisphereLight(0xffffff, 0x445066, 0.5));++ const stage = new THREE.Group();+ scene.add(stage);++ const loader = new GLTFLoader();+ const state = {+ part: null,+ edges: [],+ meshes: [],+ grid: null,+ shadow: null,+ dimsGroup: null,+ labels: [],+ showEdges: true,+ showDims: true,+ finish: 'pla',+ dirty: true,+ raf: 0,+ disposed: false,+ };++ const edgeMaterial = new THREE.LineBasicMaterial({ color: 0x1a1f29, transparent: true, opacity: 0.85 });+ const dimMaterial = new THREE.LineDashedMaterial({ color: 0x5b8def, dashSize: 1, gapSize: 0.6, transparent: true, opacity: 0.9 });+ const partMaterial = new THREE.MeshStandardMaterial({ ...FINISHES.pla, side: THREE.DoubleSide });++ function clearStage() {+ for (const child of [...stage.children]) {+ stage.remove(child);+ child.traverse?.((o) => {+ if (o.geometry) o.geometry.dispose();+ });+ }+ overlay.replaceChildren();+ state.labels = [];+ state.edges = [];+ state.meshes = [];+ }++ function buildGrid(sizeX, sizeZ) {+ const spanMm = Math.max(sizeX, sizeZ) * 1000 * 1.8;+ const stepMm = niceStep(spanMm / 16);+ const cells = Math.max(8, Math.ceil(spanMm / stepMm));+ const extent = (cells * stepMm) / 1000;+ const grid = new THREE.GridHelper(extent, cells, 0x8a94a6, 0x8a94a6);+ grid.material.transparent = true;+ grid.material.opacity = 0.22;+ grid.position.y = 0.00002;+ const shadow = new THREE.Mesh(+ new THREE.PlaneGeometry(extent, extent),+ new THREE.ShadowMaterial({ opacity: 0.18 }),+ );+ shadow.rotation.x = -Math.PI / 2;+ shadow.receiveShadow = true;+ return { grid, shadow, stepMm };+ }++ function dimLine(a, b) {+ const geometry = new THREE.BufferGeometry().setFromPoints([a, b]);+ const line = new THREE.Line(geometry, dimMaterial);+ line.computeLineDistances();+ return line;+ }++ function buildDimensions(box, sizeMm) {+ const group = new THREE.Group();+ const pad = box.getSize(new THREE.Vector3()).length() * 0.06;+ const { min, max } = box;+ dimMaterial.dashSize = pad * 0.35;+ dimMaterial.gapSize = pad * 0.2;+ // Width along X at the front-bottom edge, depth along Z at the right-bottom+ // edge, height up the front-right corner. Labels sit at each midpoint.+ const specs = [+ { a: new THREE.Vector3(min.x, min.y, max.z + pad), b: new THREE.Vector3(max.x, min.y, max.z + pad), mm: sizeMm[0], axis: 'X' },+ { a: new THREE.Vector3(max.x + pad, min.y, min.z), b: new THREE.Vector3(max.x + pad, min.y, max.z), mm: sizeMm[1], axis: 'Y' },+ { a: new THREE.Vector3(max.x + pad, min.y, max.z + pad), b: new THREE.Vector3(max.x + pad, max.y, max.z + pad), mm: sizeMm[2], axis: 'Z' },+ ];+ for (const spec of specs) {+ group.add(dimLine(spec.a, spec.b));+ const label = document.createElement('span');+ label.className = `cad-dim cad-dim--${spec.axis.toLowerCase()}`;+ label.textContent = formatMm(spec.mm);+ overlay.appendChild(label);+ state.labels.push({ el: label, at: spec.a.clone().add(spec.b).multiplyScalar(0.5) });+ }+ return group;+ }++ function applyFinish() {+ const finish = FINISHES[state.finish] || FINISHES.pla;+ partMaterial.color.setHex(finish.color);+ partMaterial.metalness = finish.metalness;+ partMaterial.roughness = finish.roughness;+ partMaterial.needsUpdate = true;+ state.dirty = true;+ }++ function frame(box) {+ const sphere = box.getBoundingSphere(new THREE.Sphere());+ const radius = Math.max(sphere.radius, 0.001);+ const fov = THREE.MathUtils.degToRad(camera.fov);+ const distance = (radius / Math.sin(fov / 2)) * 1.25;+ const direction = new THREE.Vector3(1, 0.85, 1.25).normalize();+ controls.target.copy(sphere.center);+ camera.position.copy(sphere.center).addScaledVector(direction, distance);+ camera.near = distance / 200;+ camera.far = distance * 50;+ camera.updateProjectionMatrix();+ controls.minDistance = radius * 0.4;+ controls.maxDistance = distance * 6;+ key.position.copy(sphere.center).add(new THREE.Vector3(radius * 2, radius * 4, radius * 3));+ key.target.position.copy(sphere.center);+ key.shadow.camera.left = key.shadow.camera.bottom = -radius * 2;+ key.shadow.camera.right = key.shadow.camera.top = radius * 2;+ key.shadow.camera.near = radius * 0.1;+ key.shadow.camera.far = radius * 12;+ key.shadow.camera.updateProjectionMatrix();+ scene.add(key.target);+ controls.update();+ }++ function updateLabels() {+ if (!state.labels.length) return;+ const rect = renderer.domElement.getBoundingClientRect();+ const v = new THREE.Vector3();+ for (const { el, at } of state.labels) {+ v.copy(at).project(camera);+ const hidden = !state.showDims || v.z > 1;+ el.hidden = hidden;+ if (hidden) continue;+ el.style.transform = `translate(-50%, -50%) translate(${((v.x + 1) / 2) * rect.width}px, ${((1 - v.y) / 2) * rect.height}px)`;+ }+ }++ function render() {+ renderer.render(scene, camera);+ updateLabels();+ }++ function tick() {+ state.raf = requestAnimationFrame(tick);+ const moved = controls.update();+ if (moved || state.dirty) {+ state.dirty = false;+ render();+ }+ }++ function resize() {+ const { clientWidth: w, clientHeight: h } = container;+ if (!w || !h) return;+ renderer.setSize(w, h, false);+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+ state.dirty = true;+ }++ const ro = new ResizeObserver(resize);+ ro.observe(container);+ controls.addEventListener('change', () => {+ state.dirty = true;+ });+ function onVisibility() {+ if (document.hidden) {+ cancelAnimationFrame(state.raf);+ state.raf = 0;+ } else if (!state.raf && !state.disposed) {+ state.dirty = true;+ tick();+ }+ }+ document.addEventListener('visibilitychange', onVisibility);+ resize();+ tick();++ return {+ /** Load a part. sizeMm is the kernel's exact [x, y, z] extent. */+ async load(glbUrl, sizeMm) {+ const gltf = await loader.loadAsync(glbUrl);+ clearStage();+ const part = gltf.scene;+ part.traverse((o) => {+ if (!o.isMesh) return;+ o.material = partMaterial;+ o.castShadow = true;+ o.receiveShadow = true;+ state.meshes.push(o);+ });+ stage.add(part);+ part.updateMatrixWorld(true);+ for (const mesh of state.meshes) {+ const edges = new THREE.LineSegments(new THREE.EdgesGeometry(mesh.geometry, EDGE_THRESHOLD_DEG), edgeMaterial);+ edges.matrixAutoUpdate = false;+ edges.matrix.copy(mesh.matrixWorld);+ edges.visible = state.showEdges;+ stage.add(edges);+ state.edges.push(edges);+ }+ const box = new THREE.Box3().setFromObject(part);+ const size = box.getSize(new THREE.Vector3());+ const { grid, shadow, stepMm } = buildGrid(size.x, size.z);+ grid.position.x = shadow.position.x = (box.min.x + box.max.x) / 2;+ grid.position.z = shadow.position.z = (box.min.z + box.max.z) / 2;+ grid.position.y = box.min.y + 0.00002;+ shadow.position.y = box.min.y;+ stage.add(grid, shadow);+ const dims = buildDimensions(box, sizeMm || [size.x * 1000, size.z * 1000, size.y * 1000]);+ dims.visible = state.showDims;+ stage.add(dims);+ state.dimsGroup = dims;+ const first = !state.part;+ state.part = part;+ if (first) frame(box);+ applyFinish();+ state.dirty = true;+ return { gridStepMm: stepMm };+ },+ reframe() {+ if (!state.part) return;+ frame(new THREE.Box3().setFromObject(state.part));+ state.dirty = true;+ },+ setEdges(on) {+ state.showEdges = Boolean(on);+ for (const e of state.edges) e.visible = state.showEdges;+ state.dirty = true;+ },+ setDimensions(on) {+ state.showDims = Boolean(on);+ if (state.dimsGroup) state.dimsGroup.visible = state.showDims;+ state.dirty = true;+ },+ setFinish(id) {+ state.finish = FINISHES[id] ? id : 'pla';+ applyFinish();+ },+ dispose() {+ state.disposed = true;+ cancelAnimationFrame(state.raf);+ document.removeEventListener('visibilitychange', onVisibility);+ ro.disconnect();+ clearStage();+ controls.dispose();+ pmrem.dispose();+ renderer.dispose();+ renderer.domElement.remove();+ overlay.remove();+ },+ };+}diff --git a/tests/cad-forge.test.js b/tests/cad-forge.test.jsnew file mode 100644index 000000000..5fdd63b06--- /dev/null+++ b/tests/cad-forge.test.js@@ -0,0 +1,128 @@+import { describe, expect, it } from 'vitest';+import { applyParams, massGrams, paramsKey, parseDesign } from '../src/cad/params.js';+import { extractProgram, repairMessage } from '../api/_lib/cad/prompt.js';+import { CadForgeError, forgeDesign } from '../api/_lib/cad/forge.js';++const PROGRAM = `# title: Wall bracket+# summary: A pipe bracket with two screw holes.+from build123d import *+import math++WIDTH = 80 # Overall width [40..160 mm]+WALL = 2.4 # Wall thickness [1.2..6 mm]+SLOTS = 6 # Slot count [2..12 count]+BAD = 5 # Inverted range [9..3 mm]+NOT_A_PARAM = 7+WIDTH = 99 # Duplicate [1..200 mm]++result = Box(WIDTH, 20, WALL)+`;++describe('CAD Forge parameter contract', () => {+ it('parses title, summary and annotated constants into sliders', () => {+ const meta = parseDesign(PROGRAM);+ expect(meta.title).toBe('Wall bracket');+ expect(meta.summary).toBe('A pipe bracket with two screw holes.');+ expect(meta.params.map((p) => p.name)).toEqual(['WIDTH', 'WALL', 'SLOTS', 'BAD']);+ const [width, wall, slots, bad] = meta.params;+ expect(width).toMatchObject({ label: 'Overall width', value: 80, min: 40, max: 160, step: 1, unit: 'mm', line: 6 });+ expect(wall).toMatchObject({ value: 2.4, step: 0.1 });+ expect(slots).toMatchObject({ unit: 'count', step: 1 });+ expect(bad).toMatchObject({ min: 3, max: 9, value: 5 });+ });++ it('rewrites only the annotated value, clamped and snapped', () => {+ const { code, applied } = applyParams(PROGRAM, { WIDTH: 500, WALL: 3.04, SLOTS: 7.6, NOT_A_PARAM: 1, UNKNOWN: 3 });+ expect(applied).toEqual({ WIDTH: 160, WALL: 3, SLOTS: 8 });+ expect(code).toContain('WIDTH = 160 # Overall width [40..160 mm]');+ expect(code).toContain('WALL = 3 # Wall thickness [1.2..6 mm]');+ expect(code).toContain('NOT_A_PARAM = 7');+ expect(code).toContain('WIDTH = 99 # Duplicate [1..200 mm]');+ expect(parseDesign(code).params[0].value).toBe(160);+ });++ it('keys value sets independent of order', () => {+ expect(paramsKey({ A: 1, B: 2 })).toBe(paramsKey({ B: 2, A: 1 }));+ expect(paramsKey({ A: 1 })).not.toBe(paramsKey({ A: 2 }));+ expect(paramsKey({ A: 1 })).toMatch(/^[0-9a-z]{1,16}$/);+ });++ it('estimates mass from kernel volume', () => {+ expect(massGrams(1000, 1.24)).toBeCloseTo(1.24);+ });+});++describe('CAD Forge program extraction', () => {+ it('reads a fenced block, an unterminated one, and bare code', () => {+ expect(extractProgram('Here:\n```python\nresult = 1\n```\nDone')).toBe('result = 1');+ expect(extractProgram('```python\nfrom build123d import *\nresult = Box(1, 1, 1)')).toContain('Box(1, 1, 1)');+ expect(extractProgram('from build123d import *\nresult = Box(1,1,1)')).toContain('result');+ expect(extractProgram('I cannot help with that.')).toBe('');+ });++ it('quotes the failing line back to the writer', () => {+ const msg = repairMessage({ request: 'a box', code: 'a = 1\nb = oops()\n', error: { kind: 'runtime', message: 'NameError', line: 2 } });+ expect(msg).toContain('The failing line 2 is: b = oops()');+ });+});++const ok = (solids = 1) => ({ ok: true, metrics: { solids, size_mm: [1, 1, 1] }, artifacts: {} });+const fail = (message) => ({ ok: false, error: { kind: 'runtime', message, line: 3 } });+const program = (n) => ({ code: `# title: Part ${n}\nWIDTH = 10 # Width [5..20 mm]\nresult = Box(WIDTH, 1, 1)`, model: 'test-model', provider: 'test' });++function scripted(builds) {+ const writes = [];+ const queue = [...builds];+ return {+ writes,+ writeImpl: async ({ user }) => {+ writes.push(user);+ return program(writes.length);+ },+ buildImpl: async () => queue.shift(),+ };+}++describe('CAD Forge write, build, repair loop', () => {+ it('returns the first build the kernel accepts', async () => {+ const s = scripted([ok()]);+ const stages = [];+ const design = await forgeDesign({ prompt: 'a box', ...s, onEvent: (e) => stages.push(e.stage) });+ expect(design.title).toBe('Part 1');+ expect(design.params[0].name).toBe('WIDTH');+ expect(stages).toEqual(['writing', 'building', 'built']);+ });++ it('feeds kernel errors back until the part builds', async () => {+ const s = scripted([fail('fillet failed'), ok()]);+ const design = await forgeDesign({ prompt: 'a box', ...s });+ expect(design.title).toBe('Part 2');+ expect(s.writes[1]).toContain('fillet failed');+ expect(design.attempts).toHaveLength(2);+ });++ it('asks once for a connected part and keeps the first build if the repair fails', async () => {+ const s = scripted([ok(2), fail('boolean failed'), fail('again'), fail('still')]);+ const design = await forgeDesign({ prompt: 'a bracket', ...s });+ expect(s.writes[1]).toContain('2 separate solids');+ expect(design.title).toBe('Part 1');+ expect(design.build.metrics.solids).toBe(2);+ });++ it('prefers the connected repair when it builds', async () => {+ const s = scripted([ok(3), ok(1)]);+ const design = await forgeDesign({ prompt: 'a bracket', ...s });+ expect(design.title).toBe('Part 2');+ expect(design.build.metrics.solids).toBe(1);+ });++ it('gives up with the last kernel error after the repair budget', async () => {+ const s = scripted([fail('a'), fail('b'), fail('c'), fail('d')]);+ const err = await forgeDesign({ prompt: 'a box', ...s }).catch((e) => e);+ expect(err).toBeInstanceOf(CadForgeError);+ expect(err.code).toBe('design_failed');+ expect(err.status).toBe(422);+ expect(err.detail.lastError.message).toBe('d');+ expect(s.writes).toHaveLength(4);+ });+});diff --git a/vercel.json b/vercel.jsonindex 490a12689..9e7132ba9 100644--- a/vercel.json+++ b/vercel.json@@ -1207,6 +1207,14 @@"src": "/diorama/?","dest": "/diorama.html"},+ {+ "src": "/cad/?",+ "dest": "/cad.html"+ },+ {+ "src": "/cad/([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})/?",+ "dest": "/cad.html"+ },{"src": "/api/strategies/(.*)","dest": "/api/strategies"diff --git a/vite.config.js b/vite.config.jsindex 2d3c92dc7..1d4aafd24 100644--- a/vite.config.js+++ b/vite.config.js@@ -830,6 +830,7 @@ const appConfig = {flow: resolve(__dirname, 'pages/flow.html'),symphony: resolve(__dirname, 'pages/symphony.html'),diorama: resolve(__dirname, 'pages/diorama.html'),+ cad: resolve(__dirname, 'pages/cad.html'),receipts: resolve(__dirname, 'pages/receipts.html'),fits: resolve(__dirname, 'pages/fits.html'),viability: resolve(__dirname, 'pages/viability.html'),@@ -1722,6 +1723,8 @@ const appConfig = {'/ui-juice/': resolve(root, 'pages/ui-juice.html'),'/diorama': resolve(root, 'pages/diorama.html'),'/diorama/': resolve(root, 'pages/diorama.html'),+ '/cad': resolve(root, 'pages/cad.html'),+ '/cad/': resolve(root, 'pages/cad.html'),'/trader': resolve(root, 'pages/trader.html'),'/trader/': resolve(root, 'pages/trader.html'),'/trade-rooms': resolve(root, 'pages/trade-room.html'),@@ -2423,6 +2426,12 @@ const appConfig = {// /coin/:id → global coin detail page (CoinGecko slug or Solana mint)else if (!filePath && /^\/coin\/[a-zA-Z0-9][a-zA-Z0-9_-]{0,99}\/?$/.test(path))filePath = resolve(root, 'pages/coin.html');+ // /cad/:id → CAD Forge design page (cad_designs uuid)+ else if (+ !filePath &&+ /^\/cad\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\/?$/.test(path)+ )+ filePath = resolve(root, 'pages/cad.html');// /m/:id → model detail page (forge_creations uuid)else if (!filePath &&