Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(viewer): WASM raw fallback, bounded assembler jobs, durable raw storage (#1214)

Sid0d900a689fa4
diff --git a/.ai/plans/2026-07-23-model-raw-durable-storage.md b/.ai/plans/2026-07-23-model-raw-durable-storage.md
new file mode 100644
index 0000000000..da4223453f
--- /dev/null
+++ b/.ai/plans/2026-07-23-model-raw-durable-storage.md
@@ -0,0 +1,125 @@
+# Move retained model raws off ephemeral temp-staging → durable `private` (or prune)
+
+## Context
+
+`temp-staging` is **ephemeral** storage (transient TUS landing + assembler read
+source). But the retained-raw pipeline currently keeps its **permanent** source
+there: `model-compact` writes the compacted `.zst` **into temp-staging** and
+repoints `modelUpload.modelPath` at it (`model-compact.ts:87,110,138`), and the
+artifacts route serves the raw from there. So every model's raw source (needed for
+re-optimise, lazy assembly-plan/convert, and mesh download) is on ephemeral
+storage — it will be lost when temp-staging is cleared.
+
+Prod exposure today: **13 referenced raws in temp-staging, ~1798 MB, 4 companies,
+all `optimizeStatus = Success`** (so their optimised GLB already lives in durable
+`private` — previews will survive; only the raw source is at risk). 12 are `.zst`
+≤ 50 MB; 1 is `PEDAL 4 BOM.gltf` (1.85 GB, uncompacted).
+
+Decision (user): **don't add a new bucket.** Optimise + compact the raw and try to
+fit it in the durable `private` bucket (50 MB cap); if it doesn't fit, **prune the
+raw** — the optimised GLB in `private` is already the preview.
+
+Grounding facts:
+- `private` bucket already has storage RLS for the `${companyId}/models/...` key
+ layout (SELECT = employee role, INSERT/UPDATE/DELETE = `parts_*`) — see
+ `20240630115404_model-uploads.sql`. **No new bucket or RLS migration needed.**
+- private `file_size_limit` = 50 MB = `MODEL_RAW_KEEP_MAX_BYTES` (`@carbon/utils`)
+ = the same cap the WASM viewer already uses to decide a raw is renderable.
+- Jobs use `getCarbonServiceRole()` (bypass RLS). Viewer reads the raw via
+ `getRawModelUrl(rawBucket, rawPath)` using whatever `rawBucket` the artifacts
+ route returns, through the auth-checked `/file/preview` proxy.
+
+## Design — the new retained-raw lifecycle
+
+`temp-staging` becomes **purely transient** (TUS landing + assembler read source).
+The retained raw lands in **durable `private`** when small enough, else is pruned.
+
+**`model-compact` (assembler on):** compact as today (writes `.zst` to a staging
+path), then in the `persist` step branch on the compacted size:
+- **≤ 50 MB** → copy the `.zst` to `private` at
+ `${companyId}/models/${modelUploadId}.${ext}.zst`, repoint `modelPath` there,
+ delete the temp-staging original(s). Durable. `rawBucket` resolves to `private`.
+- **> 50 MB** → **prune**: delete the temp-staging raw, keep the GLB. Leave
+ `modelPath` as-is in the DB (do NOT null it — the ERP viewer derives the
+ modelUploadId from `modelPath` client-side; nulling it would break GLB
+ resolution). The object is simply gone; the artifacts route reports the raw as
+ absent (below). Safe only because `optimizeStatus = Success` (GLB exists).
+
+**Assembler-off / no-GLB case:** compaction needs the assembler, and with no GLB
+the raw is the *only* copy — pruning would lose the model. So when the assembler
+is unavailable: if the raw is ≤ 50 MB, **copy it to `private`** as-is (no assembler
+needed, WASM renders it); if > 50 MB, leave it (pre-existing limitation — it can't
+render via WASM anyway and there's no GLB; out of scope to fix here, just don't
+make it worse). Wire this into the model-optimize/compact skip path.
+
+**Artifacts route (`model.artifacts.$modelUploadId.ts`, ERP + MES mirror):**
+resolve the raw location by probing **`private` first, then `temp-staging`**
+(reverse of today), and if the object exists in neither, return `rawPath: null`
+(pruned/gone) so the viewer shows no raw tier and relies on the GLB. Return the
+resolved `rawBucket` accordingly.
+
+**Prune (`cleanup.ts` `prune-staged-raw-models`):** once retained raws live in
+`private`, temp-staging holds only in-flight + strays. Keep the orphan guard, but
+the size gate can be dropped over time. Leave logic as-is for now (still correct);
+revisit after the migration drains temp-staging.
+
+## Changes
+
+1. **`packages/jobs/src/inngest/functions/tasks/model-compact.ts`** — in `persist`,
+ after reading `compactedSize`: if `≤ MODEL_RAW_KEEP_MAX_BYTES` copy the `.zst`
+ temp-staging→`private`, repoint `modelPath` to the private path, delete the
+ temp-staging original; else delete the temp-staging raw and leave `modelPath`
+ (pruned). Import `MODEL_RAW_KEEP_MAX_BYTES` from `@carbon/utils`.
+2. **Assembler-off raw persistence** — in `model-optimize.ts` (and/or
+ `model-compact.ts`) skip path when `!assemblerEnabled()`: if the raw ≤ 50 MB,
+ copy temp-staging→`private` and repoint `modelPath`; else leave.
+3. **`apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts`** + MES mirror —
+ probe `private` first, then `temp-staging`; `rawPath: null` when absent.
+4. **Storage move helper** — cross-bucket copy. Verify Supabase JS supports
+ `.copy(from, to, { destinationBucket })` in this version; if not, download +
+ re-upload (objects are ≤ 50 MB, cheap). Put it in the assembler task helpers or
+ a small shared util.
+
+## Data migration — the 13 existing rows: NONE (decided)
+
+Decision (user): **let the existing 13 be pruned without moving.** All 13 have
+`optimizeStatus = Success`, so their optimised GLB already lives in durable
+`private` (the preview survives). Their raw source is expendable, so no backfill is
+built — `temp-staging`'s ephemeral lifecycle clears them, and the code already
+degrades gracefully: the artifacts route probes `private`/staging → `rawPath: null`
+once gone → the viewer renders the GLB. (A SQL migration couldn't move the bytes
+anyway — Supabase keys the physical object by bucket; only the storage API
+`move`/`copy` relocates the file, so a `bucket_id` UPDATE would orphan the bytes.)
+
+Trade-off accepted: those 13 lose re-optimise / assembly-plan source + (for the one
+mesh `.gltf`) the download. Previews are unaffected. New uploads are unaffected —
+they relocate to durable storage within one job cycle via the changes above.
+
+## Open decision (confirm before build)
+
+- **modelPath on prune**: plan keeps `modelPath` non-null (dangling) so ERP's
+ `CadModel` can still derive the modelUploadId; the artifacts route returns
+ `rawPath: null` by existence-probe. Alternative (cleaner, more files): pass an
+ explicit `modelUploadId` to every ERP `<CadModel>` call site (like MES already
+ does) and null `modelPath` on prune. Recommend the dangling-modelPath approach
+ (fewer files, no schema change); flag if you'd rather decouple properly.
+
+## Verification
+
+- `pnpm exec turbo run typecheck --filter=@carbon/jobs --filter=erp --filter=mes`
+- Local: upload a small STEP → optimise+compact → confirm the `.zst` lands in
+ **private** (not temp-staging), `modelPath` points to private, temp-staging
+ original gone, viewer renders (GLB), raw download works.
+- Local: force a > 50 MB compacted result (or stub the size check) → confirm the
+ raw is pruned, `modelPath` retained, viewer still renders the GLB, artifacts
+ `rawPath: null`.
+- Prod: run the one-off migration; re-run the temp-staging census query → expect 0
+ referenced raws remaining (except any skipped no-GLB > 50 MB, logged).
+
+## Critical files
+- `packages/jobs/src/inngest/functions/tasks/model-compact.ts` — compact + persist
+- `packages/jobs/src/inngest/functions/tasks/model-optimize.ts` — assembler-off skip
+- `packages/jobs/src/inngest/functions/tasks/assembler-client.ts` — move helper
+- `apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts` (+ MES mirror) — bucket probe
+- New one-off Inngest fn for the 13-row migration (+ register in `inngest/index.ts`)
+- `packages/jobs/src/inngest/functions/scheduled/cleanup.ts` — prune (unchanged for now)
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsx
index af26311014..3d6da366a1 100644
--- a/apps/erp/app/components/CadModel.tsx
+++ b/apps/erp/app/components/CadModel.tsx
@@ -78,6 +78,9 @@ const CadModel = ({
artifacts,
awaitingModel,
showOptimizeProgress: optimizeProgressActive,
+ backgroundOptimizing,
+ optimizeFailed,
+ canRetry,
optimizeQueued,
retry: onRetry,
retryLabel,
@@ -221,6 +224,8 @@ const CadModel = ({
<ModelPreview
key={modelPath}
awaitingModel={awaitingModel}
+ optimizing={backgroundOptimizing}
+ optimizeFailed={optimizeFailed}
optimizedUrl={
artifacts?.optimizedModelPath
? getPrivateUrl(artifacts.optimizedModelPath)
@@ -248,7 +253,7 @@ const CadModel = ({
}
mode={mode}
className={viewerClassName}
- onRetry={modelPath ? onRetry : undefined}
+ onRetry={modelPath && canRetry ? onRetry : undefined}
retryLabel={retryLabel}
onCancelWait={modelPath ? onCancelWait : undefined}
onDelete={canDelete ? deleteModal.onOpen : undefined}
diff --git a/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts b/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
index 7454365c50..e936cb81f6 100644
--- a/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
+++ b/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { ASSEMBLER_SERVICE_URL } from "@carbon/env";
import type { LoaderFunctionArgs } from "react-router";
// Resolves a model's optimised / preview artifact storage paths for the
@@ -35,20 +36,33 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (!model.data) throw new Response("Not found", { status: 404 });
// Raw-source pointer for the viewer's WASM fallback tier (renders the original
- // upload when no artifact exists). `.zst`-compacted raws are skipped — they
- // only exist after a successful optimise, which means an artifact exists too.
- // Bucket split: current uploads land in `temp-staging`; pre-assembler rows
- // lived in `private` — probe temp-staging and fall back.
+ // upload when no artifact exists). `.zst`-compacted raws are skipped — they only
+ // exist after a successful optimise, which means a GLB artifact exists too.
+ // A retained raw is relocated to the DURABLE `private` bucket; a just-uploaded
+ // one is briefly in ephemeral `temp-staging` before relocation; a pruned one is
+ // in neither (an oversized raw whose GLB preview is enough) → no raw tier.
let rawPath: string | null = null;
- let rawBucket = "temp-staging";
+ let rawBucket = "private";
const modelPath = model.data?.modelPath ?? null;
if (modelPath && !modelPath.toLowerCase().endsWith(".zst")) {
- rawPath = modelPath;
- const staged = await getCarbonServiceRole()
- .storage.from("temp-staging")
- .info(modelPath)
- .catch(() => ({ data: null, error: true as const }));
- if (staged.error || !staged.data) rawBucket = "private";
+ const svc = getCarbonServiceRole();
+ const probe = (bucket: string) =>
+ svc.storage
+ .from(bucket)
+ .info(modelPath)
+ .catch(() => ({ data: null, error: true as const }));
+ const inDurable = await probe("private");
+ if (!inDurable.error && inDurable.data) {
+ rawPath = modelPath;
+ rawBucket = "private";
+ } else {
+ const staged = await probe("temp-staging");
+ if (!staged.error && staged.data) {
+ rawPath = modelPath;
+ rawBucket = "temp-staging";
+ }
+ // Absent in both → pruned/gone; rawPath stays null (rely on the GLB).
+ }
}
return {
@@ -59,6 +73,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
thumbnailPath: model.data?.thumbnailPath ?? null,
rawPath,
rawBucket,
+ // Whether the optimiser is configured at all. When false, the viewer hides
+ // the "Optimize failed · Retry" affordance and never auto-fires an optimise —
+ // retrying against a non-existent assembler just fails again.
+ optimizerAvailable: Boolean(ASSEMBLER_SERVICE_URL),
// Lets the client stop polling once optimisation lands (or fails).
optimizeStatus: model.data?.optimizeStatus ?? null,
// The reduction badge compares as-uploaded vs optimised bytes. `size` is
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index 78c01141c7..3c639b1e54 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -332,6 +332,9 @@ export const JobOperation = ({
artifacts,
awaitingModel: modelPending,
showOptimizeProgress,
+ backgroundOptimizing,
+ optimizeFailed,
+ canRetry,
optimizeQueued,
retry: onModelRetry,
retryLabel: modelRetryLabel,
@@ -1772,6 +1775,8 @@ export const JobOperation = ({
<ModelPreview
key={modelPath}
awaitingModel={modelPending}
+ optimizing={backgroundOptimizing}
+ optimizeFailed={optimizeFailed}
optimizedUrl={
artifacts?.optimizedModelPath
? getPrivateUrl(artifacts.optimizedModelPath)
@@ -1796,7 +1801,7 @@ export const JobOperation = ({
}
mode={mode}
className="rounded-none"
- onRetry={onModelRetry}
+ onRetry={canRetry ? onModelRetry : undefined}
retryLabel={modelRetryLabel}
/>
) : (
diff --git a/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts b/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
index ede5cbb3f6..2fb0f2a727 100644
--- a/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
+++ b/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
@@ -1,3 +1,4 @@
+import { ASSEMBLER_SERVICE_URL } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { LoaderFunctionArgs } from "react-router";
@@ -34,20 +35,33 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (!model.data) throw new Response("Not found", { status: 404 });
// Raw-source pointer for the viewer's WASM fallback tier (renders the original
- // upload when no artifact exists). `.zst`-compacted raws are skipped — they
- // only exist after a successful optimise, which means an artifact exists too.
- // Bucket split: current uploads land in `temp-staging`; pre-assembler rows
- // lived in `private` — probe temp-staging and fall back.
+ // upload when no artifact exists). `.zst`-compacted raws are skipped — they only
+ // exist after a successful optimise, which means a GLB artifact exists too.
+ // A retained raw is relocated to the DURABLE `private` bucket; a just-uploaded
+ // one is briefly in ephemeral `temp-staging` before relocation; a pruned one is
+ // in neither (an oversized raw whose GLB preview is enough) → no raw tier.
let rawPath: string | null = null;
- let rawBucket = "temp-staging";
+ let rawBucket = "private";
const modelPath = model.data?.modelPath ?? null;
if (modelPath && !modelPath.toLowerCase().endsWith(".zst")) {
- rawPath = modelPath;
- const staged = await getCarbonServiceRole()
- .storage.from("temp-staging")
- .info(modelPath)
- .catch(() => ({ data: null, error: true as const }));
- if (staged.error || !staged.data) rawBucket = "private";
+ const svc = getCarbonServiceRole();
+ const probe = (bucket: string) =>
+ svc.storage
+ .from(bucket)
+ .info(modelPath)
+ .catch(() => ({ data: null, error: true as const }));
+ const inDurable = await probe("private");
+ if (!inDurable.error && inDurable.data) {
+ rawPath = modelPath;
+ rawBucket = "private";
+ } else {
+ const staged = await probe("temp-staging");
+ if (!staged.error && staged.data) {
+ rawPath = modelPath;
+ rawBucket = "temp-staging";
+ }
+ // Absent in both → pruned/gone; rawPath stays null (rely on the GLB).
+ }
}
return {
@@ -57,6 +71,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
thumbnailPath: model.data?.thumbnailPath ?? null,
rawPath,
rawBucket,
+ // Whether the optimiser is configured at all. When false, the viewer hides
+ // the "Optimize failed · Retry" affordance and never auto-fires an optimise.
+ optimizerAvailable: Boolean(ASSEMBLER_SERVICE_URL),
optimizeStatus: model.data?.optimizeStatus ?? null,
size: model.data?.originalSize ?? model.data?.size ?? null,
optimizedSize: model.data?.optimizedSize ?? null
diff --git a/packages/jobs/src/inngest/functions/events/queue.ts b/packages/jobs/src/inngest/functions/events/queue.ts
index 07952d00ed..aa0a41e02f 100644
--- a/packages/jobs/src/inngest/functions/events/queue.ts
+++ b/packages/jobs/src/inngest/functions/events/queue.ts
@@ -42,13 +42,19 @@ type QueueJob = {
* The drain loops until the queue is empty, so a single run absorbs a burst.
* `concurrency: 1` serializes runs; bulk writes are coalesced upstream — the
* trigger wakes at most once per transaction (carbon.event_wake_sent GUC).
+ * `singleton: skip` drops the *cross-transaction* pile-up: while a drain is in
+ * flight, every further wake is skipped (not queued) — the running drain already
+ * loops until empty and so absorbs their messages, and the drain's own re-wake +
+ * the pg_cron sweeper cover the narrow race where a wake lands just as it exits.
+ * So 10 wakes coalesce into 1 run instead of 1 run + 9 redundant empty drains.
* This is the critical bridge between PostgreSQL events and inngest handlers.
*/
export const eventQueueFunction = inngest.createFunction(
{
id: "event-queue",
retries: 2,
- concurrency: 1
+ concurrency: 1,
+ singleton: { mode: "skip" }
},
{ event: "carbon/event-queue.process" },
async ({ step }) => {
diff --git a/packages/jobs/src/inngest/functions/tasks/assembler-client.ts b/packages/jobs/src/inngest/functions/tasks/assembler-client.ts
index 5ba57a6d3a..3ba398753c 100644
--- a/packages/jobs/src/inngest/functions/tasks/assembler-client.ts
+++ b/packages/jobs/src/inngest/functions/tasks/assembler-client.ts
@@ -35,6 +35,20 @@ export const assemblerAuthHeaders: Record<string, string> =
? { Authorization: `Bearer ${ASSEMBLER_SERVICE_API_KEY}` }
: {};
+// Shared bounded concurrency queue for EVERY assembler-backed function
+// (optimize, compact, convert, plan). They all park on the assembler completion
+// event (`runAssemblerJob` → `step.waitForEvent`, up to 15 min), and a parked run
+// holds its concurrency slot the whole wait — so without a cap a burst (e.g. the
+// viewer's per-view optimise auto-fire) exhausts account concurrency and starves
+// the `event-queue` drainer + its handlers. One shared `env`-scoped key across all
+// four functions bounds the TOTAL in flight, leaving the rest of the account free.
+// The cap ≈ how many assembler jobs should run at once (the service 429s past its
+// real capacity, so more parked runs buy nothing); the WASM raw tier renders while
+// an optimise waits, so a low cap never blocks a user from viewing a model.
+export const ASSEMBLER_CONCURRENCY: [
+ { scope: "env"; key: string; limit: number }
+] = [{ scope: "env", key: '"assembler"', limit: 6 }];
+
/**
* The assembler feature flag IS the config: unset `ASSEMBLER_SERVICE_URL` means
* the whole pipeline is off. Gate the Inngest functions on this so triggered
@@ -52,6 +66,29 @@ export function assemblerBaseUrl(): string {
return ASSEMBLER_SERVICE_URL;
}
+// Where a retained raw lands: uploads/compaction stage in `temp-staging`
+// (EPHEMERAL, 2.5 GB), and the retained raw is relocated to `private` (DURABLE,
+// 50 MB served cap) so it survives — or pruned when it can't fit and a GLB
+// preview already exists. The 50 MB gate is `MODEL_RAW_KEEP_MAX_BYTES`.
+export const RAW_STAGING_BUCKET = "temp-staging";
+export const RAW_DURABLE_BUCKET = "private";
+
+/**
+ * Relocate a staged object into the durable bucket, same key, server-side (no
+ * download — storage-js `move` with `destinationBucket`). Idempotent-ish: if the
+ * source is already gone (previously moved) it returns the storage error string,
+ * which callers treat as "already durable". Returns null on success.
+ */
+export async function moveRawToDurable(
+ client: SupabaseClient<Database>,
+ path: string
+): Promise<string | null> {
+ const { error } = await client.storage
+ .from(RAW_STAGING_BUCKET)
+ .move(path, path, { destinationBucket: RAW_DURABLE_BUCKET });
+ return error ? error.message : null;
+}
+
/**
* Resolve which bucket a model's raw source lives in. Current uploads land in
* `temp-staging`; rows from before the assembler pipeline live in `private` —
diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts b/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
index 8749fab096..9b4b39f0aa 100644
--- a/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
+++ b/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
@@ -2,6 +2,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Json } from "@carbon/database";
import { inngest } from "../../client";
import {
+ ASSEMBLER_CONCURRENCY,
assemblerEnabled,
internalizeStorageUrl,
resolveModelSourceBucket,
@@ -25,6 +26,7 @@ export const assemblyConvertFunction = inngest.createFunction(
{
id: "assembly-convert",
retries: 2,
+ concurrency: ASSEMBLER_CONCURRENCY,
onFailure: async ({ event }) => {
const { modelUploadId } = event.data.event.data;
const client = getCarbonServiceRole();
diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts b/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
index 6790a2079c..cd3818249a 100644
--- a/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
+++ b/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
@@ -3,6 +3,7 @@ import type { Json } from "@carbon/database";
import type { AssemblyPlan } from "@carbon/viewer/steps";
import { inngest } from "../../client";
import {
+ ASSEMBLER_CONCURRENCY,
assemblerEnabled,
internalizeStorageUrl,
resolveModelSourceBucket,
@@ -32,6 +33,7 @@ export const assemblyPlanFunction = inngest.createFunction(
{
id: "assembly-plan",
retries: 2,
+ concurrency: ASSEMBLER_CONCURRENCY,
onFailure: async ({ event }) => {
const { modelUploadId } = event.data.event.data;
const client = getCarbonServiceRole();
diff --git a/packages/jobs/src/inngest/functions/tasks/model-compact.ts b/packages/jobs/src/inngest/functions/tasks/model-compact.ts
index 480ea7e4c7..b154781c9c 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-compact.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-compact.ts
@@ -1,9 +1,15 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { modelPathOptimizeFormat } from "@carbon/utils";
+import {
+ MODEL_RAW_KEEP_MAX_BYTES,
+ modelPathOptimizeFormat
+} from "@carbon/utils";
import { inngest } from "../../client";
import {
+ ASSEMBLER_CONCURRENCY,
assemblerEnabled,
internalizeStorageUrl,
+ moveRawToDurable,
+ RAW_STAGING_BUCKET,
resolveModelSourceBucket,
runAssemblerJob
} from "./assembler-client";
@@ -12,37 +18,41 @@ const SIGNED_URL_EXPIRY = 60 * 60; // seconds — the source (read) URL only.
const MAX_COMPACT_WAIT_MS = 15 * 60 * 1000;
/**
- * Compact the retained raw so it never lingers as the fat upload. STEP sources
- * become OCCT BinXCAF (`{id}.xbf.zst` — lossless B-rep + assembly tree, far
- * smaller than zstd'd ASCII STEP, same nodeIds when converted); mesh sources
- * are zstd'd in their original format (`{id}.{ext}.zst`, decompresses back to
- * the openable source file). On success `modelPath` is repointed at the
- * compacted raw and the fat original is deleted.
+ * Persist a model's retained raw to DURABLE storage. Uploads and compaction stage
+ * in the EPHEMERAL `temp-staging` bucket; the retained raw (the source for the WASM
+ * fallback, re-optimise, lazy assembly-plan, and mesh download) must not live there
+ * or it is lost when staging is cleared. This function:
+ *
+ * - When the assembler is available and the source is a compactable mesh: compacts
+ * it (STEP → OCCT BinXCAF `{id}.xbf.zst`; mesh → `{id}.{ext}.zst`), then
+ * relocates the compacted `.zst` to `private` if it fits the 50 MB served cap.
+ * - Otherwise (assembler off, non-mesh, or already `.zst`): relocates the raw
+ * as-is to `private` if it fits.
+ * - When it can't fit `private` (> 50 MB): PRUNE the raw if an optimised GLB
+ * preview already exists (the preview is enough); else leave it in staging (a
+ * big model with no GLB can't render anyway, and it's the only copy).
*
- * Decoupled from model-optimize: fired after optimize settles regardless of
- * outcome, so a failed or skipped optimize can't strand a fat raw for the
- * scheduled prune. Own retries — compaction is cheap relative to optimize
- * (zstd only, or a tessellation-free OCCT parse for xbf), so it can succeed
- * where optimize can't.
+ * Fired after model-optimize settles (success, failure, or assembler-off skip), so
+ * a failed/skipped optimise still gets its raw persisted. Own retries.
*/
export const modelCompactFunction = inngest.createFunction(
- { id: "model-compact", retries: 3 },
+ {
+ id: "model-compact",
+ retries: 3,
+ concurrency: ASSEMBLER_CONCURRENCY,
+ singleton: { key: "event.data.modelUploadId", mode: "skip" }
+ },
{ event: "carbon/model-compact" },
async ({ event, step, logger }) => {
const { modelUploadId, companyId } = event.data;
- if (!assemblerEnabled()) {
- logger.info("model compact skipped — assembler is not configured", {
- modelUploadId
- });
- return { modelUploadId, status: "Skipped" as const };
- }
-
const model = await step.run("resolve", async () => {
const client = getCarbonServiceRole();
const upload = await client
.from("modelUpload")
- .select("id, modelPath")
+ .select(
+ "id, modelPath, size, originalSize, optimizeStatus, optimizedModelPath, glbPath"
+ )
.eq("id", modelUploadId)
.eq("companyId", companyId)
.single();
@@ -57,33 +67,84 @@ export const modelCompactFunction = inngest.createFunction(
);
return {
modelPath: upload.data.modelPath,
+ size: upload.data.size as number | null,
+ originalSize: upload.data.originalSize as number | null,
+ optimizeStatus: upload.data.optimizeStatus,
+ optimizedModelPath: upload.data.optimizedModelPath,
+ glbPath: upload.data.glbPath,
format: modelPathOptimizeFormat(upload.data.modelPath),
sourceBucket
};
});
- // Only temp-staging sources compact: the flow writes the .zst there,
- // deletes the fat original there, and the prune covers strays there.
- // Legacy `private` raws predate the pipeline — leave them where they are.
- if (
- model.modelPath.toLowerCase().endsWith(".zst") ||
- model.sourceBucket !== "temp-staging" ||
- !model.format
- ) {
- logger.info("model compact skipped", {
+ // Already durable (in `private`) or gone — nothing to relocate. `private`
+ // rows also cover legacy pre-assembler uploads that already live there.
+ if (model.sourceBucket !== RAW_STAGING_BUCKET) {
+ logger.info("model compact skipped — raw not in staging", {
modelUploadId,
- modelPath: model.modelPath,
sourceBucket: model.sourceBucket
});
return { modelUploadId, status: "Skipped" as const };
}
- // STEP → BinXCAF; everything else → plain zstd of the raw. Flat path
- // mirroring the original raw so the model id stays recoverable from the
- // path (CadModel's `modelIdFromPath`) and the download route resolves the
- // underlying format from the extension.
- const mode = model.format === "step" ? "xbf" : "zstd";
- const compactExt = mode === "xbf" ? "xbf" : model.format;
+ // The optimised GLB preview is the fallback that makes pruning an oversized
+ // raw safe — without it, the raw is the model's only copy.
+ const hasGlb =
+ (model.optimizeStatus === "Success" &&
+ Boolean(model.optimizedModelPath)) ||
+ Boolean(model.glbPath);
+ const isZst = model.modelPath.toLowerCase().endsWith(".zst");
+ const canCompact = assemblerEnabled() && Boolean(model.format) && !isZst;
+
+ // Freeze the as-uploaded bytes into originalSize once (rows from before the
+ // column exist with null); the viewer's reduction badge compares the ORIGINAL.
+ const originalSizeUpdate =
+ model.originalSize == null && model.size != null
+ ? { originalSize: model.size }
+ : {};
+
+ if (!canCompact) {
+ // No compaction possible — relocate the raw AS-IS to durable storage. Same
+ // key, so `modelPath` (path-only) is unchanged; the artifacts route resolves
+ // the bucket by probing.
+ return await step.run("relocate", async () => {
+ const client = getCarbonServiceRole();
+ const rawSize = model.size;
+ if (rawSize != null && rawSize <= MODEL_RAW_KEEP_MAX_BYTES) {
+ const err = await moveRawToDurable(client, model.modelPath);
+ if (err) throw new Error(`relocate raw to durable: ${err}`);
+ logger.info("raw relocated to durable", {
+ modelUploadId,
+ modelPath: model.modelPath
+ });
+ return { modelUploadId, status: "Relocated" as const };
+ }
+ if (hasGlb) {
+ // Too big for `private`, but the GLB preview survives → prune the raw.
+ await client.storage
+ .from(RAW_STAGING_BUCKET)
+ .remove([model.modelPath]);
+ logger.info("oversized raw pruned (GLB preview exists)", {
+ modelUploadId,
+ modelPath: model.modelPath
+ });
+ return { modelUploadId, status: "Pruned" as const };
+ }
+ // Too big AND no GLB — it's the only copy and can't fit durable storage.
+ // Leave it in staging (a > 50 MB raw with no GLB can't render anyway).
+ logger.warn("oversized raw with no GLB left in staging", {
+ modelUploadId,
+ modelPath: model.modelPath,
+ rawSize
+ });
+ return { modelUploadId, status: "KeptInStaging" as const };
+ });
+ }
+
+ const format = model.format as NonNullable<typeof model.format>;
+ const mode = format === "step" ? "xbf" : "zstd";
+ const compactExt = mode === "xbf" ? "xbf" : format;
+ // Flat path mirroring the raw so the id stays recoverable (modelIdFromPath).
const compactPath = `${companyId}/models/${modelUploadId}.${compactExt}.zst`;
const jobId = `compact-${modelUploadId}`;
@@ -96,7 +157,7 @@ export const modelCompactFunction = inngest.createFunction(
buildBody: async () => {
const client = getCarbonServiceRole();
const source = await client.storage
- .from("temp-staging")
+ .from(RAW_STAGING_BUCKET)
.createSignedUrl(model.modelPath, SIGNED_URL_EXPIRY);
if (source.error) {
throw new Error(`sign source: ${source.error.message}`);
@@ -104,13 +165,15 @@ export const modelCompactFunction = inngest.createFunction(
return {
source: { url: internalizeStorageUrl(source.data.signedUrl) },
mode,
+ // The assembler writes the compacted output to staging first; we
+ // relocate it to durable storage (or prune) once we know its size.
output: { path: compactPath }
};
},
mintUploadUrls: async () => {
const client = getCarbonServiceRole();
const upload = await client.storage
- .from("temp-staging")
+ .from(RAW_STAGING_BUCKET)
.createSignedUploadUrl(compactPath, { upsert: true });
const urls: Record<string, string> = {};
if (upload.data)
@@ -121,32 +184,62 @@ export const modelCompactFunction = inngest.createFunction(
const compactedSize =
(compact.stats as { outputBytes?: number } | null)?.outputBytes ?? null;
- await step.run("persist", async () => {
+ return await step.run("persist", async () => {
const client = getCarbonServiceRole();
- // Repoint modelPath at the compacted raw and record its (compressed)
- // stored size so the files list reflects what's actually on disk, then
- // drop the fat original. Freeze the as-uploaded bytes into originalSize
- // first (rows from before the column exist with null) — the viewer's
- // reduction badge compares the ORIGINAL, not the .zst.
- const existing = await client
- .from("modelUpload")
- .select("size, originalSize")
- .eq("id", modelUploadId)
- .maybeSingle();
+ const fits =
+ compactedSize != null && compactedSize <= MODEL_RAW_KEEP_MAX_BYTES;
+
+ if (fits) {
+ // Relocate the compacted raw to durable storage, repoint `modelPath` at
+ // it, then drop the fat original from staging.
+ const err = await moveRawToDurable(client, compactPath);
+ if (err) throw new Error(`relocate compacted raw to durable: ${err}`);
+ await client
+ .from("modelUpload")
+ .update({
+ modelPath: compactPath,
+ ...originalSizeUpdate,
+ size: compactedSize
+ })
+ .eq("id", modelUploadId);
+ await client.storage.from(RAW_STAGING_BUCKET).remove([model.modelPath]);
+ logger.info("raw compacted and relocated to durable", {
+ modelUploadId,
+ compactPath,
+ mode
+ });
+ return { modelUploadId, status: "Success" as const };
+ }
+
+ if (hasGlb) {
+ // Compacted raw still exceeds the durable cap, but the GLB preview
+ // survives → prune both the compacted output and the original.
+ await client.storage
+ .from(RAW_STAGING_BUCKET)
+ .remove([compactPath, model.modelPath]);
+ logger.info("oversized compacted raw pruned (GLB preview exists)", {
+ modelUploadId,
+ compactPath
+ });
+ return { modelUploadId, status: "Pruned" as const };
+ }
+
+ // Too big for durable AND no GLB — keep the compacted `.zst` in staging
+ // (best available), repoint, drop the fat original.
await client
.from("modelUpload")
.update({
modelPath: compactPath,
- ...(existing.data && existing.data.originalSize == null
- ? { originalSize: existing.data.size }
- : {}),
+ ...originalSizeUpdate,
...(compactedSize != null ? { size: compactedSize } : {})
})
.eq("id", modelUploadId);
- await client.storage.from("temp-staging").remove([model.modelPath]);
+ await client.storage.from(RAW_STAGING_BUCKET).remove([model.modelPath]);
+ logger.warn("oversized compacted raw with no GLB kept in staging", {
+ modelUploadId,
+ compactPath
+ });
+ return { modelUploadId, status: "KeptInStaging" as const };
});
-
- logger.info("raw compacted", { modelUploadId, compactPath, mode });
- return { modelUploadId, status: "Success" as const };
}
);
diff --git a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
index 4567354e3e..c4603adc9a 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
@@ -3,6 +3,7 @@ import type { Json } from "@carbon/database";
import { modelPathOptimizeFormat } from "@carbon/utils";
import { inngest } from "../../client";
import {
+ ASSEMBLER_CONCURRENCY,
assemblerEnabled,
internalizeStorageUrl,
resolveModelSourceBucket,
@@ -24,6 +25,13 @@ export const modelOptimizeFunction = inngest.createFunction(
{
id: "model-optimize",
retries: 2,
+ concurrency: ASSEMBLER_CONCURRENCY,
+ // Collapse the viewer's per-view auto-fire: while one optimise for a model is
+ // in flight, duplicate triggers (repeated views, drag re-attach) are skipped
+ // rather than spawning redundant runs. A later Retry after it settles still
+ // runs (nothing in flight). The `alreadyOptimized` guard covers re-fires on an
+ // already-optimised model; this covers the in-flight duplicates.
+ singleton: { key: "event.data.modelUploadId", mode: "skip" },
onFailure: async ({ event }) => {
const { modelUploadId, companyId } = event.data.event.data;
const client = getCarbonServiceRole();
@@ -48,7 +56,14 @@ export const modelOptimizeFunction = inngest.createFunction(
// Feature-gated: no assembler configured -> skip before touching the row,
// so the viewer just serves the raw model tier (optimizeStatus stays null).
+ // Still fire model-compact: it relocates the raw from ephemeral staging to
+ // the durable bucket (no assembler needed for a plain relocation) so an
+ // assembler-off model isn't lost when staging is cleared.
if (!assemblerEnabled()) {
+ await step.sendEvent("compact", {
+ name: "carbon/model-compact",
+ data: { modelUploadId, companyId }
+ });
logger.info("model optimise skipped — assembler is not configured", {
modelUploadId
});
diff --git a/packages/viewer/src/ModelPreview.tsx b/packages/viewer/src/ModelPreview.tsx
index 80e5a7ab81..3e8de57182 100644
--- a/packages/viewer/src/ModelPreview.tsx
+++ b/packages/viewer/src/ModelPreview.tsx
@@ -5,7 +5,9 @@ import {
LuChevronDown,
LuDownload,
LuMaximize,
- LuTrash2
+ LuRotateCw,
+ LuTrash2,
+ LuTriangleAlert
} from "react-icons/lu";
import type { ModelMetrics } from "./ModelCanvas";
import { isRawRenderable } from "./raw/formats";
@@ -16,23 +18,18 @@ const ModelCanvas = lazy(() =>
import("./ModelCanvas").then((m) => ({ default: m.ModelCanvas }))
);
-// Build-time switch for the in-browser raw-CAD (WASM) fallback tier: renders the
-// user's original upload (GLB/STL directly; STEP/IGES via occt-import-js) when
-// no assembler artifact exists. ON by default; a deployment that relies purely on
-// assembler artifacts opts out with VITE_CAD_VIEWER_USE_SERVER=true, and the
-// exact `import.meta.env.X` form is statically replaced by Vite so the whole
-// tier — occt WASM included — is then dead-code-eliminated from the build.
-// Exported so hosts can align their fallback logic (e.g. CadModel only treats
-// a small raw as renderable when the tier actually shipped in this build).
-export const WASM_RAW_ENABLED =
- import.meta.env.VITE_CAD_VIEWER_USE_SERVER !== "true";
-const RawModelCanvas = WASM_RAW_ENABLED
- ? lazy(() =>
- import("./raw/RawModelCanvas").then((m) => ({
- default: m.RawModelCanvas
- }))
- )
- : null;
+// The in-browser raw-CAD (WASM) fallback tier renders the user's original upload
+// (GLB/STL directly; STEP/IGES via occt-import-js) whenever no assembler artifact
+// exists yet — a not-yet-optimised legacy model, or the window while an optimise
+// runs. It is ALWAYS the fallback, independent of whether the assembler is
+// configured: server artifacts stay strictly preferred (`hasServerModel` wins
+// below), the raw tier only renders when there is no server GLB. `RawModelCanvas`
+// is a `lazy()` chunk, so its occt WASM only downloads when a raw actually mounts.
+const RawModelCanvas = lazy(() =>
+ import("./raw/RawModelCanvas").then((m) => ({
+ default: m.RawModelCanvas
+ }))
+);
export type ModelPreviewProps = {
/** True while a server GLB might still arrive (upload / optimise in flight).
@@ -47,8 +44,15 @@ export type ModelPreviewProps = {
/** Static poster image (thumbnail PNG) shown before any 3D loads. */
thumbnailUrl?: string | null;
/** The raw uploaded file's auth-proxied URL — the WASM fallback tier renders
- * it in-browser when no assembler artifact exists (build-flag gated). */
+ * it in-browser when no assembler artifact exists yet. */
rawUrl?: string | null;
+ /** A background optimise is running while the raw tier renders — shows a small
+ * non-blocking "Optimizing" chip so the user knows a better GLB is coming. */
+ optimizing?: boolean;
+ /** The last optimise Failed and won't auto-retry — surfaces a small "Optimize
+ * failed · Retry" chip over the raw tier so the user can re-fire it (otherwise
+ * a Failed model that renders via WASM has no retry affordance at all). */
+ optimizeFailed?: boolean;
/** A just-dropped local File for the same tier — instant preview while the
* upload / optimise is still in flight. */
rawFile?: File | null;
@@ -83,6 +87,8 @@ export function ModelPreview({
glbUrl = null,
thumbnailUrl = null,
rawUrl = null,
+ optimizing = false,
+ optimizeFailed = false,
rawFile = null,
downloadName,
onRetry,
@@ -113,20 +119,19 @@ export function ModelPreview({
const showLodLayer = Boolean(lodUrl && interactiveUrl && !fullLoaded);
const mainUrl = interactiveUrl ?? lodUrl;
const hasServerModel = Boolean(mainUrl);
- // Raw (WASM) fallback tier — only when compiled in, no artifact exists, and
- // the raw source's format is one the in-browser loaders speak.
+ // Raw (WASM) fallback tier — no server artifact exists yet, and the raw
+ // source's format is one the in-browser loaders speak.
const rawFilename = rawFile?.name ?? rawUrl?.split("?")[0] ?? "";
const useRawTier = Boolean(
- !hasServerModel &&
- RawModelCanvas &&
- (rawFile || rawUrl) &&
- isRawRenderable(rawFilename)
+ !hasServerModel && (rawFile || rawUrl) && isRawRenderable(rawFilename)
);
return (
<div
ref={containerRef}
- role="img"
+ // `group`, not `img`: the container holds interactive controls (retry,
+ // download, reset, delete) — an `img` role hides those descendants from AT.
+ role="group"
aria-label="3D model preview"
className={cn(
"relative h-full min-h-[400px] w-full overflow-hidden rounded-lg border border-border bg-gradient-to-bl from-card from-50% via-card to-background shadow-md dark:border-none",
@@ -165,7 +170,7 @@ export function ModelPreview({
className="absolute inset-0 transition-opacity duration-300"
style={{ opacity: fullLoaded || !showLodLayer ? 1 : 0 }}
>
- {useRawTier && RawModelCanvas ? (
+ {useRawTier ? (
<RawModelCanvas
url={rawUrl}
file={rawFile}
@@ -190,6 +195,53 @@ export function ModelPreview({
</Suspense>
)}
+ {/* Background optimise running behind the raw tier — a small,
+ non-blocking hint that a better GLB is on its way. Swaps out for the
+ "Optimized GLB" size badge once the server model arrives. */}
+ {optimizing && useRawTier && (
+ <div className="pointer-events-none absolute bottom-2 left-2 z-20 flex items-center gap-1.5 rounded-md border border-border bg-popover px-2 py-1 text-xs text-muted-foreground shadow-sm">
+ <svg
+ className="size-3 shrink-0 animate-spin"
+ viewBox="0 0 24 24"
+ fill="none"
+ aria-hidden
+ >
+ <circle
+ className="opacity-25"
+ cx="12"
+ cy="12"
+ r="10"
+ stroke="currentColor"
+ strokeWidth="4"
+ />
+ <path
+ className="opacity-75"
+ fill="currentColor"
+ d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"
+ />
+ </svg>
+ <span>Optimizing…</span>
+ </div>
+ )}
+
+ {/* The optimise Failed and won't auto-retry — the raw tier still renders,
+ but without this the user has no way to re-fire the optimise. Mutually
+ exclusive with the Optimizing chip (hidden once a retry is in flight). */}
+ {onRetry && optimizeFailed && !optimizing && useRawTier && (
+ <div className="absolute bottom-2 left-2 z-20 flex items-center gap-1.5 rounded-md border border-border bg-popover px-2 py-1 text-xs text-muted-foreground shadow-sm">
+ <LuTriangleAlert className="size-3 shrink-0 text-amber-500" />
+ <span>Optimize failed</span>
+ <button
+ type="button"
+ onClick={onRetry}
+ className="flex items-center gap-1 font-medium text-foreground underline-offset-2 hover:underline"
+ >
+ <LuRotateCw className="size-3" />
+ Retry
+ </button>
+ </div>
+ )}
+
{/* Measurements + unit toggle (top-left), like the WASM viewer. */}
{metrics && fullLoaded && <ModelMetricsPanel metrics={metrics} />}
diff --git a/packages/viewer/src/raw/RawModelCanvas.tsx b/packages/viewer/src/raw/RawModelCanvas.tsx
index d95e0d421b..d515d9ea77 100644
--- a/packages/viewer/src/raw/RawModelCanvas.tsx
+++ b/packages/viewer/src/raw/RawModelCanvas.tsx
@@ -1,7 +1,7 @@
// The raw (WASM) fallback tier: renders the user's original upload through the
// SAME ModelCanvas as the artifact tiers — one renderer, one set of chrome.
-// Lazy chunk: ships only when the tier is compiled in (VITE_CAD_VIEWER_USE_SERVER
-// unset) and mounts, occt-import-js WASM included.
+// Lazy chunk: its occt-import-js WASM only downloads when this tier actually
+// mounts (i.e. a model with no server artifact yet).
import { useMemo } from "react";
import { ModelCanvas, type ModelCanvasProps } from "../ModelCanvas";
diff --git a/packages/viewer/src/useOptimizedModel.ts b/packages/viewer/src/useOptimizedModel.ts
index 2fc745194c..0b5d81a0d9 100644
--- a/packages/viewer/src/useOptimizedModel.ts
+++ b/packages/viewer/src/useOptimizedModel.ts
@@ -4,7 +4,7 @@ import {
} from "@carbon/utils";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useRef, useState } from "react";
-import { WASM_RAW_ENABLED } from "./ModelPreview";
+import { isRawRenderable } from "./raw/formats";
export type ModelArtifacts = {
optimizedModelPath: string | null;
@@ -15,6 +15,9 @@ export type ModelArtifacts = {
* resolved bucket (temp-staging for current uploads, private for old rows). */
rawPath: string | null;
rawBucket: string;
+ /** Whether the optimiser (assembler) is configured server-side. When false, the
+ * viewer hides the failed-retry affordance and never auto-fires an optimise. */
+ optimizerAvailable?: boolean;
optimizeStatus:
| "Idle"
| "Queued"
@@ -148,13 +151,20 @@ export function useOptimizedModel({
const optimizeInFlight =
artifacts?.optimizeStatus === "Queued" ||
artifacts?.optimizeStatus === "Processing";
- const rawRenderable =
- WASM_RAW_ENABLED &&
- Boolean(
- (artifacts?.rawPath &&
- (artifacts.size ?? 0) <= MODEL_RAW_KEEP_MAX_BYTES) ||
- (file && file.size <= MODEL_RAW_KEEP_MAX_BYTES)
- );
+ // Match ModelPreview's `useRawTier` eligibility exactly, so the hook never
+ // suppresses the blocking progress UI for a raw the renderer won't mount:
+ // require a KNOWN size within the cap (an unknown size must not pass via
+ // `?? 0`) AND a format the in-browser loaders actually speak.
+ const artifactRawName = artifacts?.rawPath?.split("/").pop() ?? "";
+ const rawRenderable = Boolean(
+ (artifacts?.rawPath &&
+ artifacts.size != null &&
+ artifacts.size <= MODEL_RAW_KEEP_MAX_BYTES &&
+ isRawRenderable(artifactRawName)) ||
+ (file &&
+ file.size <= MODEL_RAW_KEEP_MAX_BYTES &&
+ isRawRenderable(file.name))
+ );
// Bridges the fire -> job-visible gap: the row status takes a couple of
// polls to flip, and without this the progress overlay wouldn't appear
@@ -192,6 +202,8 @@ export function useOptimizedModel({
useEffect(() => {
if (!enabled || !artifacts || !modelUploadId || !modelPath) return;
if (autoFiredRef.current === modelUploadId) return;
+ // No optimiser configured → firing reoptimise just no-ops server-side; skip it.
+ if (artifacts.optimizerAvailable === false) return;
if (
hasInteractive ||
optimizeInFlight ||
@@ -241,6 +253,26 @@ export function useOptimizedModel({
!hasInteractive &&
!rawRenderable;
+ // Optimise running behind a rendered raw tier — drives the viewer's small
+ // "Optimizing" chip (as opposed to the full-screen preparing overlay above).
+ const backgroundOptimizing =
+ (optimizeInFlight || optimisticOptimize) &&
+ !hasInteractive &&
+ rawRenderable;
+
+ // Last optimise Failed (auto-fire deliberately won't re-run it) — drives the
+ // viewer's "Optimize failed · Retry" chip so a WASM-rendered model still has a
+ // retry affordance instead of silently sitting on a failed optimise. Suppressed
+ // when the optimiser isn't configured — a retry would just fail again.
+ const optimizeFailed =
+ artifacts?.optimizeStatus === "Failed" &&
+ artifacts?.optimizerAvailable !== false;
+
+ // Whether a manual retry can possibly succeed. When the optimiser isn't
+ // configured, hosts must not wire `onRetry` — otherwise ModelPreview's
+ // settled/no-preview state renders a retry button advertising a dead action.
+ const canRetry = artifacts?.optimizerAvailable !== false;
+
return {
artifacts,
modelUploadId,
@@ -249,6 +281,9 @@ export function useOptimizedModel({
rawRenderable,
optimizeInFlight,
showOptimizeProgress,
+ backgroundOptimizing,
+ optimizeFailed,
+ canRetry,
/** Overlay's first step reads as waiting until the job is picked up. */
optimizeQueued: artifacts?.optimizeStatus !== "Processing",
retry,
diff --git a/packages/viewer/src/vite-env.d.ts b/packages/viewer/src/vite-env.d.ts
index 35206f9a33..5aa08391a8 100644
--- a/packages/viewer/src/vite-env.d.ts
+++ b/packages/viewer/src/vite-env.d.ts
@@ -1,17 +1,6 @@
// This package ships raw source compiled by the consuming app's Vite build.
// Type the Vite-injected globals the source references without depending on
// vite (typecheck runs standalone via tsgo).
-interface ImportMetaEnv {
- /** Build-time flag: "true" = server-artifacts-only viewer (the in-browser
- * raw-CAD WASM tier and its occt-import-js chunk are dead-code-dropped).
- * Unset/false (the default) = the WASM fallback tier is compiled in. */
- readonly VITE_CAD_VIEWER_USE_SERVER?: string;
-}
-
-interface ImportMeta {
- readonly env: ImportMetaEnv;
-}
-
declare module "*.wasm?url" {
const url: string;
export default url;