Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(cad): rate-limit the MCP tools, keep built parts through writer outages, and finish the page's loading and error states

nirholasc870fd2aacac
diff --git a/.env.example b/.env.example
index cc3dd67de..8aebeb4bb 100644
--- a/.env.example
+++ b/.env.example
@@ -1473,6 +1473,16 @@ GCP_REMESH_URL=
GCP_TEXTURE_URL=
# workers/segment → part segmentation (GLB → segmented GLB + parts manifest)
GCP_SEGMENT_URL=
+# workers/cad-forge → build123d program → STEP/STL/GLB/SVG (CAD Forge, /cad).
+# Authenticated with its own secret (cad-forge-key), not GCP_RECONSTRUCTION_KEY,
+# because it runs model-written code; the API falls back to the shared key
+# only when CAD_FORGE_KEY is unset.
+GCP_CAD_FORGE_URL=
+CAD_FORGE_KEY=
+# Optional: the NVIDIA NIM model that leads the CAD program writer ladder
+# (default moonshotai/kimi-k3), and the global hourly design ceiling (default 400).
+CAD_WRITER_MODEL=
+CAD_FORGE_GLOBAL_HOURLY=
# Magic Brush region inpainting model (workers/texture /retexture_region). SDXL
# inpaint checkpoint loaded lazily on first region edit. Override only to pin a
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 75f870838..7b88aea78 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -44,7 +44,7 @@ bottom.
| Avatar builder (full app) | [character-studio/](character-studio) | Fork of [m3-org/CharacterStudio](https://github.com/M3-org/CharacterStudio), MIT, see [character-studio/LICENSE](character-studio/LICENSE) | Web-first character creator |
| Scene Studio (3D scene editor) | [src/scene-studio/](src/scene-studio) `→ /scene`: boot [main.js](src/scene-studio/main.js), shared GLB loader [loader.js](src/scene-studio/loader.js), action bar [actions.js](src/scene-studio/actions.js), first-run overlay [empty-state.js](src/scene-studio/empty-state.js), icon-button labels [toolbar-a11y.js](src/scene-studio/toolbar-a11y.js), chrome [studio.css](src/scene-studio/studio.css) | Vendored [mrdoob/three.js](https://github.com/mrdoob/three.js) r184 editor, MIT, see [src/scene-studio/vendor/README.md](src/scene-studio/vendor/README.md) | Import GLBs, compose scenes, edit materials/lights, export. The sibling modules never touch `vendor/**`: they add the Import-from-Forge / Export-presets / Share bar (which docks beside the resizable sidebar rather than over its tabs), the empty-state card a brand-new scene needs, accessible names plus `aria-pressed` on the icon-only translate/rotate/scale buttons and names on the animation timeline's play/pause/stop transport, and toast-based failures in place of native `alert()`/`prompt()`. Below 600px the sidebar dock drops the vendored `.TabbedPanel` 335px floor so it fits a 320px screen instead of hanging 15px off it, and the empty-state card starts below the action bar and caps itself at the viewport region. Pinned under the nav by `--nav-h` (the real injected-header height), not `--header-h`. Deep links: `?model=<glb_url>`, `?handoff=1` from `/pose`, `#file=<url>`. Docs: [docs/scene-studio.md](docs/scene-studio.md), [src/scene-studio/README.md](src/scene-studio/README.md). Tests: [tests/scene-studio-actions.test.js](tests/scene-studio-actions.test.js) |
| Diorama (text → 3D world) | [src/diorama/](src/diorama) `→ /diorama` | In-repo · backend [api/diorama.js](api/diorama.js) | One sentence → an explorable 3D diorama: Claude composes the scene, each object is forged to a real GLB, assembled live, saved to a public gallery + shareable permalink |
-| CAD Forge (text → parametric CAD) | Page [pages/cad.html](pages/cad.html) + [src/cad/](src/cad) `→ /cad` and `→ /cad/:id` (controller [main.js](src/cad/main.js), viewer [viewer.js](src/cad/viewer.js), shared parameter contract [params.js](src/cad/params.js)), API [api/cad.js](api/cad.js) `→ /api/cad` over [api/_lib/cad/](api/_lib/cad) (writer ladder, write/build/repair loop, store, service), MCP tools [api/_mcp3d/tools/cad.js](api/_mcp3d/tools/cad.js) (`cad_generate`, `cad_rebuild`), sandboxed kernel worker [workers/cad-forge/](workers/cad-forge) | Live · worker deploys from its own cloudbuild | A sentence becomes a build123d program the OpenCascade kernel has accepted: kernel errors go back to the writer (Kimi K3 on NIM first) until it builds, and the page streams each real stage. Key dimensions are annotated constants that become sliders; each value set rebuilds on the kernel and is cached under its own link. Downloads STEP, STL, GLB (true scale), a four-view SVG drawing and the Python program; handoffs to AR, Materialize and Scene Studio; refinements are linked designs. Parts join cross-entity search as type `part`. The worker runs model-written code with a static policy, seccomp, an unprivileged uid and rlimits, under a zero-role service account. Docs: [docs/cad-forge.md](docs/cad-forge.md). Tests: [tests/cad-forge.test.js](tests/cad-forge.test.js) plus the worker's in-image gate |
+| CAD Forge (text → parametric CAD) | Page [pages/cad.html](pages/cad.html) + [src/cad/](src/cad) `→ /cad` and `→ /cad/:id` (controller [main.js](src/cad/main.js), viewer [viewer.js](src/cad/viewer.js), shared parameter contract [params.js](src/cad/params.js)), API [api/cad.js](api/cad.js) `→ /api/cad` over [api/_lib/cad/](api/_lib/cad) (writer ladder, write/build/repair loop, store, service), MCP tools [api/_mcp3d/tools/cad.js](api/_mcp3d/tools/cad.js) (`cad_generate`, `cad_rebuild`), sandboxed kernel worker [workers/cad-forge/](workers/cad-forge) | Built and verified locally · worker deploy pending (deploy it before the API image that carries `/cad`) | A sentence becomes a build123d program the OpenCascade kernel has accepted: kernel errors go back to the writer (Kimi K3 on NIM first) until it builds, and the page streams each real stage. Key dimensions are annotated constants that become sliders; each value set rebuilds on the kernel and is cached under its own link. Downloads STEP, STL, GLB (true scale), a four-view SVG drawing and the Python program; handoffs to AR, Materialize and Scene Studio; refinements are linked designs. Parts join cross-entity search as type `part`. The worker runs model-written code with a static policy, seccomp, an unprivileged uid and rlimits, under a zero-role service account. Docs: [docs/cad-forge.md](docs/cad-forge.md). Tests: [tests/cad-forge.test.js](tests/cad-forge.test.js) plus the worker's in-image gate |
| Scene Composer (dress an avatar) | [pages/compose.html](pages/compose.html) `→ /compose` + [src/scene-compose.js](src/scene-compose.js) | Live | Forge props from text and parent them to a rigged avatar's skeleton bones, then Export GLB or save them back onto the avatar record as `appearance.attachments`. Bones are grouped into readable regions and stripped of rig prefixes; transform gizmos, 50-deep undo, grid snap, camera presets. Feeds off [api/forge.js](api/forge.js), [api/forge-gallery.js](api/forge-gallery.js) (own creations, falling back to the community showcase for a first-time visitor), [api/explore.js](api/explore.js) `?source=avatar&only3d=1` for the avatar picker, and `PATCH /api/avatars/:id` for Save outfit. Below 900px the scene panel becomes a drawer. Docs: [docs/compose.md](docs/compose.md) |
| Splat Viewer (photoreal Gaussian avatars) | [pages/splat.html](pages/splat.html) `→ /splat` + page module [src/splat-viewer.js](src/splat-viewer.js), renderer [src/splat-stage.js](src/splat-stage.js) | Live | Renders Gaussian-splat and radiance-field scenes in the browser, the photoreal output of capture engines like GaussianAvatars and HumanGaussian. Loads a `.ply`, `.spz`, `.splat`, `.ksplat` or `.sog` by URL, by upload, by drag-and-drop onto the stage, or from a `?src=` deep link, plus two procedurally generated samples; decoding is entirely client-side and nothing is uploaded. The format is sniffed from the bytes rather than the filename, and the URL loader rewrites GitHub `blob`/`raw`, Hugging Face `/blob/` and Dropbox links to their CORS-enabled raw form so a pasted human-facing link still fetches. [src/splat-stage.js](src/splat-stage.js) is shared with the Forge Studio Lab ([src/forge-studio/lab/mesh-to-splat.js](src/forge-studio/lab/mesh-to-splat.js)) and wraps [Spark](https://github.com/sparkjsdev/spark) (`@sparkjsdev/spark`, MIT), lazy-loaded on first render and torn down explicitly (the WebGL context is released by hand on every scene swap, which Spark's own dispose stops short of). Every state is designed: idle/drop, engine load, fetch, decode, sort, error, and a live HUD carrying the scene label, its real splat count, a recenter control and a download of the loaded buffer. Docs: [docs/splat.md](docs/splat.md) |
| Creator portfolio (human profile) | [pages/profile.html](pages/profile.html) `→ /u/:username` (self-view `/profile`), backend [api/users/[username].js](api/users/%5Busername%5D.js) + paginated [api/users/[username]/creations.js](api/users/%5Busername%5D/creations.js) `→ /api/users/:username/creations` | Live | Every three.ws user's public portfolio: avatars, agents, widgets, skills, plugins, coins, memories, items for sale, and (added 2026-07-12, extended 2026-07-23) a **Creations** tab merging forged 3D models + Scene Studio worlds + Material Studio restyles — real, live, spinning `<model-viewer>` cards, cursor-paginated for 100+ items. `/forge`, `/diorama`, and `/restyle` all stay anonymous by default (no login required); a signed-in creator's `user_id` is attached to `forge_creations`/`dioramas` rows at generation/save time (migration [api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql](api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql)) and to a new `material_restyles` row per AI restyle or colorway variant (migration [api/_lib/migrations/20260723140000_material_restyles.sql](api/_lib/migrations/20260723140000_material_restyles.sql), store [api/_lib/material-restyle-store.js](api/_lib/material-restyle-store.js)) so those creations surface here. The same opt-in attribution now links back from the diorama viewer HUD, the diorama gallery cards, and the forge result bar ("by @user") whenever a creation's creator is known. `/@:handle` ([pages/handle.html](pages/handle.html)) is a separate, narrower agent-embed page — not the human portfolio. |
diff --git a/api/_lib/cad/forge.js b/api/_lib/cad/forge.js
index 0065d1595..e451744ac 100644
--- a/api/_lib/cad/forge.js
+++ b/api/_lib/cad/forge.js
@@ -1,8 +1,8 @@
// CAD Forge: sentence → build123d program → real B-rep part.
//
-// The loop text-to-cad popularised, run server-side: a model writes the
-// program, workers/cad-forge builds it in a sandbox, and when the kernel
-// rejects it the real error (kind, message, failing line) goes back to the
+// The agentic CAD loop, run server-side: a model writes the program,
+// workers/cad-forge builds it in a sandbox, and when the kernel rejects it
+// the real error (kind, message, failing line) goes back to the
// model for a repair round. A design only ever reaches the user once the
// geometry kernel has accepted it, so nothing shown is a guess.
//
@@ -141,9 +141,16 @@ export async function forgeDesign({ prompt, baseCode = null, onEvent = () => {},
if (attempt > MAX_REPAIRS || deadline - Date.now() < 40_000) break;
const last = attempts[attempts.length - 1].error;
onEvent({ stage: 'repairing', attempt: attempt + 1, error: last });
- written = written.code
- ? await writeImpl({ user: repairMessage({ request: prompt, code: written.code, error: last }), track, deadline })
- : await writeImpl({ user: baseCode ? refineMessage(prompt, baseCode) : generateMessage(prompt), track, deadline });
+ try {
+ written = written.code
+ ? await writeImpl({ user: repairMessage({ request: prompt, code: written.code, error: last }), track, deadline })
+ : await writeImpl({ user: baseCode ? refineMessage(prompt, baseCode) : generateMessage(prompt), track, deadline });
+ } catch (err) {
+ // A part the kernel already accepted is never thrown away because a
+ // later repair round could not reach a writer.
+ if (fallback) break;
+ throw err;
+ }
}
if (fallback) {
diff --git a/api/_lib/cad/store.js b/api/_lib/cad/store.js
index e4272b27d..5376f7d50 100644
--- a/api/_lib/cad/store.js
+++ b/api/_lib/cad/store.js
@@ -43,12 +43,10 @@ async function ensureTables() {
model text,
user_id uuid,
views bigint not null default 0,
- featured boolean not null default false,
created_at timestamptz not null default now()
)
`;
await sql`create index if not exists cad_designs_created_idx on cad_designs (created_at desc)`;
- await sql`create index if not exists cad_designs_featured_idx on cad_designs (featured, created_at desc)`;
await sql`create index if not exists cad_designs_user_idx on cad_designs (user_id, created_at desc)`;
await sql`create index if not exists cad_designs_parent_idx on cad_designs (parent_id)`;
await sql`
@@ -121,7 +119,6 @@ function toDesign(row) {
adjustments: Array.isArray(row.adjustments) ? row.adjustments : [],
model: row.model || null,
views: Number(row.views) || 0,
- featured: Boolean(row.featured),
creatorUsername: row.creator_username || null,
createdAt: row.created_at instanceof Date ? row.created_at.toISOString() : row.created_at,
};
@@ -149,7 +146,7 @@ export async function saveDesign(design) {
recordDailyActivity(design.userId).catch(() => {});
maybeAwardFirstCreation(design.userId).catch(() => {});
}
- return { ...design, views: 0, featured: false, createdAt };
+ return { ...design, views: 0, createdAt };
}
export async function getDesign(id) {
@@ -203,31 +200,21 @@ export async function bumpViews(id) {
}
}
-/** Gallery cards: index columns and the thumbnail only, never the program. */
-export async function listDesigns({ scope = 'recent', limit = 24, q, userId } = {}) {
+/** Gallery cards, newest first: index columns and the thumbnail only, never the program. */
+export async function listDesigns({ limit = 24, q } = {}) {
if (!(await ensureTables())) return [];
const lim = Math.min(60, Math.max(1, Number(limit) || 24));
const search = typeof q === 'string' && q.trim() ? `%${q.trim().slice(0, 120)}%` : null;
try {
- const rows = userId
+ const rows = search
? await sql`
select id, title, summary, prompt, files->>'thumb_svg' as thumb, metrics->'size_mm' as size_mm, views, created_at
- from cad_designs where user_id = ${userId}
+ from cad_designs where title ilike ${search} or prompt ilike ${search}
order by created_at desc limit ${lim}`
- : scope === 'featured'
- ? await sql`
- select id, title, summary, prompt, files->>'thumb_svg' as thumb, metrics->'size_mm' as size_mm, views, created_at
- from cad_designs where featured
- order by created_at desc limit ${lim}`
- : search
- ? await sql`
- select id, title, summary, prompt, files->>'thumb_svg' as thumb, metrics->'size_mm' as size_mm, views, created_at
- from cad_designs where title ilike ${search} or prompt ilike ${search}
- order by created_at desc limit ${lim}`
- : await sql`
- select id, title, summary, prompt, files->>'thumb_svg' as thumb, metrics->'size_mm' as size_mm, views, created_at
- from cad_designs
- order by created_at desc limit ${lim}`;
+ : await sql`
+ select id, title, summary, prompt, files->>'thumb_svg' as thumb, metrics->'size_mm' as size_mm, views, created_at
+ from cad_designs
+ order by created_at desc limit ${lim}`;
return rows.map((r) => ({
id: r.id,
title: r.title,
diff --git a/api/_lib/cross-search.js b/api/_lib/cross-search.js
index 3dd569398..5a1778433 100644
--- a/api/_lib/cross-search.js
+++ b/api/_lib/cross-search.js
@@ -187,7 +187,7 @@ export async function searchWorlds({ q, limit = 12 } = {}) {
// ── parts (CAD Forge designs) ─────────────────────────────────────────────────
export async function searchParts({ q, limit = 12 } = {}) {
- const rows = await listDesigns({ scope: 'recent', limit, q });
+ const rows = await listDesigns({ limit, q });
return rows.map((r) => ({
type: 'part',
id: r.id,
diff --git a/api/_mcp3d/tools/cad.js b/api/_mcp3d/tools/cad.js
index 6acccc34c..c129e6868 100644
--- a/api/_mcp3d/tools/cad.js
+++ b/api/_mcp3d/tools/cad.js
@@ -12,6 +12,21 @@
import { CadForgeError } from '../../_lib/cad/forge.js';
import { cleanPrompt, createDesign, loadParent, rebuildVariant } from '../../_lib/cad/service.js';
import { buildSpatialArtifact } from '../../_lib/spatial-mcp.js';
+import { limits } from '../../_lib/rate-limit.js';
+
+// The same buckets as POST /api/cad, keyed by the MCP principal: a signed-in
+// caller runs these operator-funded, and one design is up to four model calls
+// plus kernel builds, so the server-wide mcpUser ceiling is far too loose.
+function rateKey(auth) {
+ return auth?.userId || auth?.rateKey || 'anon';
+}
+
+async function limit(limiter, key) {
+ const rl = await limiter(key);
+ if (rl.success) return;
+ const retryAfter = Math.max(1, Math.ceil((rl.reset - Date.now()) / 1000));
+ throw new CadForgeError('rate_limited', `CAD Forge rate limit reached. Retry in ${retryAfter} s.`, 429, { retry_after: retryAfter });
+}
function failure(err) {
const known = err instanceof CadForgeError;
@@ -19,7 +34,13 @@ function failure(err) {
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 } : {}) },
+ structuredContent: {
+ error: true,
+ code: known ? err.code : 'internal_error',
+ message,
+ ...(kernel ? { kernelError: kernel } : {}),
+ ...(known && err.code === 'rate_limited' ? { retry_after: err.detail?.retry_after } : {}),
+ },
isError: true,
};
}
@@ -67,6 +88,8 @@ export const toolDefs = [
async handler(args, auth) {
try {
const prompt = cleanPrompt(args.prompt);
+ await limit(limits.cadForgeIp, rateKey(auth));
+ await limit(() => limits.cadForgeGlobal(), 'global');
const parent = await loadParent(args.parent_id);
const { design, attempts } = await createDesign({
prompt,
@@ -133,9 +156,13 @@ export const toolDefs = [
},
},
},
- async handler(args) {
+ async handler(args, auth) {
try {
- const { variant, cached, design } = await rebuildVariant({ id: args.id, values: args.values });
+ const { variant, cached, design } = await rebuildVariant({
+ id: args.id,
+ values: args.values,
+ beforeBuild: () => limit(limits.cadRebuildIp, rateKey(auth)),
+ });
return {
content: [
{
diff --git a/api/cad.js b/api/cad.js
index 81d6f063a..d007a670e 100644
--- a/api/cad.js
+++ b/api/cad.js
@@ -19,7 +19,7 @@
*
* GET /api/cad?id=<uuid>[&v=<key>] → { design, lineage, variant? }
* GET /api/cad?id=<uuid>&format=py[&v=] → the program as a .py download
- * GET /api/cad?list=recent|featured[&q=][&limit=] → { designs }
+ * GET /api/cad?list=recent[&q=][&limit=] → { designs }, newest first
*
* No mocks: when the builder or the writer is unreachable the caller gets a
* designed 503, never a fabricated part. Every part returned has been accepted
@@ -85,9 +85,7 @@ async function handleGet(req, res) {
}
if (list !== null) {
- const scope = list === 'featured' ? 'featured' : 'recent';
const designs = await listDesigns({
- scope,
limit: Number(url.searchParams.get('limit')) || 24,
q: url.searchParams.get('q') || undefined,
});
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 7ee464bd4..0fcfd3aac 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -2638,7 +2638,7 @@ as its own real, validated GLB**, not just a live preview swap.
## AI API: text to parametric CAD
-`POST /api/cad` turns a description into a kernel-checked build123d part (`action: "generate"`, optionally streamed over SSE) or rebuilds a saved design at new dimension values (`action: "rebuild"`). `GET /api/cad?id=` reads a design, its lineage and a cached configuration; `&format=py` downloads the program; `?list=recent|featured` returns the gallery. Every design carries STEP, STL, GLB and SVG drawing URLs plus the kernel's measurements. Full request and response shapes, errors and limits: [CAD Forge](./cad-forge.md#http-api).
+`POST /api/cad` turns a description into a kernel-checked build123d part (`action: "generate"`, optionally streamed over SSE) or rebuilds a saved design at new dimension values (`action: "rebuild"`). `GET /api/cad?id=` reads a design, its lineage and a cached configuration; `&format=py` downloads the program; `?list=recent` returns the gallery. Every design carries STEP, STL, GLB and SVG drawing URLs plus the kernel's measurements. Full request and response shapes, errors and limits: [CAD Forge](./cad-forge.md#http-api).
```bash
curl -s https://three.ws/api/cad -H 'content-type: application/json' \
diff --git a/docs/cad-forge.md b/docs/cad-forge.md
index c41368fd8..4eb6d6c77 100644
--- a/docs/cad-forge.md
+++ b/docs/cad-forge.md
@@ -137,7 +137,7 @@ Returns `{ "ok": true, "variant": { "key", "values", "metrics", "files", "adjust
| `GET /api/cad?id=<uuid>` | `{ design, lineage: { parent, children }, variant: null }` |
| `GET /api/cad?id=<uuid>&v=<key>` | The same plus the cached `variant` |
| `GET /api/cad?id=<uuid>&format=py[&v=<key>]` | The program as a `.py` download, at the variant's values if given |
-| `GET /api/cad?list=recent\|featured[&q=][&limit=]` | `{ designs: [card], available }`, cards carry `thumb` and `sizeMm` |
+| `GET /api/cad?list=recent[&q=][&limit=]` | `{ designs: [card], available }`, newest first; cards carry `thumb` and `sizeMm` |
## MCP
@@ -152,7 +152,7 @@ The program is written by a model from a request anyone can send, so the builder
| Variable | Where | Purpose |
| --- | --- | --- |
| `GCP_CAD_FORGE_URL` | three-ws-api | Base URL of the cad-forge Cloud Run service |
-| `CAD_FORGE_KEY` | three-ws-api | Bearer secret for the worker (`cad-forge-key` in Secret Manager) |
+| `CAD_FORGE_KEY` | three-ws-api | Bearer secret for the worker (`cad-forge-key` in Secret Manager). Falls back to `GCP_RECONSTRUCTION_KEY` when unset, for a worker deployed with the shared key. |
| `CAD_WRITER_MODEL` | three-ws-api, optional | Override the leading NIM writer model |
| `CAD_FORGE_GLOBAL_HOURLY` | three-ws-api, optional | Global hourly design ceiling (default 400) |
diff --git a/pages/cad.html b/pages/cad.html
index c9471c428..1978e788d 100644
--- a/pages/cad.html
+++ b/pages/cad.html
@@ -95,6 +95,7 @@
<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>
+ <span id="cadViewLoading" class="cad-badge" role="status" hidden>Loading the part</span>
</div>
<aside class="cad-panel">
diff --git a/src/cad/cad.css b/src/cad/cad.css
index 4744f39ba..6913838bb 100644
--- a/src/cad/cad.css
+++ b/src/cad/cad.css
@@ -532,10 +532,24 @@
}
.cad-design__body.is-loading {
- opacity: 0.4;
pointer-events: none;
}
+/* Skeleton: each panel card keeps its shape and shimmers until the design
+ arrives, instead of showing empty headings and controls. */
+.cad-design__body.is-loading .cad-panel__head,
+.cad-design__body.is-loading .cad-section {
+ min-height: 120px;
+ 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;
+}
+
+.cad-design__body.is-loading .cad-panel__head > *,
+.cad-design__body.is-loading .cad-section > * {
+ visibility: hidden;
+}
+
.cad-stage {
position: sticky;
top: 76px;
@@ -645,6 +659,15 @@
transition: background 0.15s ease, color 0.15s ease;
}
+.cad-seg button:hover:not(:disabled):not([aria-pressed='true']) {
+ background: var(--scrim-strong);
+ color: var(--on-scrim-bright, #fff);
+}
+
+.cad-seg button:active:not(:disabled) {
+ transform: scale(0.97);
+}
+
.cad-seg button[aria-pressed='true'] {
background: var(--on-scrim-bright, #fff);
color: #111;
@@ -669,6 +692,15 @@
cursor: pointer;
}
+.cad-toggle:hover {
+ background: var(--scrim-strong);
+}
+
+.cad-toggle:focus-within {
+ outline: 2px solid var(--cad-blue);
+ outline-offset: 2px;
+}
+
.cad-toggle input {
accent-color: var(--cad-blue);
}
@@ -691,6 +723,29 @@
background: var(--scrim-strong);
}
+.cad-icon-btn:active,
+.cad-mass:active,
+.cad-card:active {
+ transform: scale(0.97);
+}
+
+.cad-link:active,
+.cad-back:active {
+ opacity: 0.7;
+}
+
+.cad-back:focus-visible {
+ outline: 2px solid var(--cad-blue);
+ outline-offset: 2px;
+ border-radius: 4px;
+}
+
+.cad-param input[type='range']:focus-visible {
+ outline: 2px solid var(--cad-blue);
+ outline-offset: 4px;
+ border-radius: 4px;
+}
+
.cad-badge {
position: absolute;
z-index: 2;
diff --git a/src/cad/main.js b/src/cad/main.js
index 1a0f39230..64bd95f34 100644
--- a/src/cad/main.js
+++ b/src/cad/main.js
@@ -274,12 +274,18 @@ function current() {
async function openDesign(id, variantKey) {
$('#cadDesignError').hidden = true;
+ $('#cadDesignBody').hidden = false;
$('#cadDesignBody').classList.add('is-loading');
+ $('#cadViewLoading').hidden = false;
+ $('#cadViewportError').hidden = true;
+ setMode('model');
let payload;
try {
payload = await fetchDesign(id, variantKey);
} catch (err) {
$('#cadDesignBody').classList.remove('is-loading');
+ $('#cadDesignBody').hidden = true;
+ $('#cadViewLoading').hidden = true;
const box = $('#cadDesignError');
const missing = err instanceof CadApiError && err.status === 404;
box.replaceChildren(
@@ -310,6 +316,8 @@ async function openDesign(id, variantKey) {
viewer.reframe();
} catch {
$('#cadViewportError').hidden = false;
+ } finally {
+ $('#cadViewLoading').hidden = true;
}
}
@@ -476,6 +484,10 @@ function renderOutputs() {
const drawing = $('#cadDrawingImg');
if (files.drawing_svg) drawing.src = files.drawing_svg;
+ else {
+ drawing.removeAttribute('src');
+ setMode('model');
+ }
$('#cadModeDrawing').disabled = !files.drawing_svg;
}
diff --git a/tests/cad-forge.test.js b/tests/cad-forge.test.js
index 5fdd63b06..3e66959a0 100644
--- a/tests/cad-forge.test.js
+++ b/tests/cad-forge.test.js
@@ -116,6 +116,22 @@ describe('CAD Forge write, build, repair loop', () => {
expect(design.build.metrics.solids).toBe(1);
});
+ it('keeps an accepted multi-body part when a later repair cannot reach a writer', async () => {
+ let writes = 0;
+ const builds = [ok(2), fail('boolean failed')];
+ const design = await forgeDesign({
+ prompt: 'a bracket',
+ buildImpl: async () => builds.shift(),
+ writeImpl: async () => {
+ writes++;
+ if (writes === 3) throw new CadForgeError('writer_unavailable', 'busy', 503);
+ return program(writes);
+ },
+ });
+ expect(design.title).toBe('Part 1');
+ expect(design.build.metrics.solids).toBe(2);
+ });
+
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);