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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(jobs): compact copies to durable storage; the sweep owns staging deletion
Sidwebworks25b271df92c2
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsxindex ec70ca31dc..e331f159ac 100644--- a/apps/erp/app/components/CadModel.tsx+++ b/apps/erp/app/components/CadModel.tsx@@ -232,6 +232,7 @@ const CadModel = ({awaitingModel={awaitingModel}optimizing={backgroundOptimizing}optimizeFailed={optimizeFailed}+ sourceMissing={artifacts?.sourceAvailable === false}optimizedUrl={artifacts?.optimizedModelPath? // ?v= busts the immutable preview cache on the STABLEdiff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsxindex 01a278b202..79703eace5 100644--- a/apps/mes/app/components/JobOperation/JobOperation.tsx+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx@@ -1792,6 +1792,7 @@ export const JobOperation = ({awaitingModel={modelPending}optimizing={backgroundOptimizing}optimizeFailed={optimizeFailed}+ sourceMissing={artifacts?.sourceAvailable === false}optimizedUrl={artifacts?.optimizedModelPath? // ?v= busts the immutable preview cache on the STABLEdiff --git a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts b/packages/jobs/src/inngest/functions/scheduled/cleanup.tsindex b977aef681..e99b1570bc 100644--- a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts+++ b/packages/jobs/src/inngest/functions/scheduled/cleanup.ts@@ -1,11 +1,12 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";import { NotificationEvent } from "@carbon/notifications";-import { MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";import { inngest } from "../../client";// Raw CAD in `temp-staging` is transient — the optimise/assembly jobs read it,-// then only the gated GLB is kept in `private`. Prune raws over the served cap-// older than this so huge sources never linger; small raws stay (downloadable).+// and the compact pipeline COPIES what must survive into `private` (never an+// instant move/delete: that races concurrent jobs holding a temp-staging+// source pointer). This sweep is the ONLY thing that deletes from staging:+// stale objects that were copied to durable, or that no modelUpload references.const STAGED_RAW_TTL_DAYS = 7;// Agent chat threads are transient — purge after 30 days of inactivity.@@ -23,8 +24,14 @@ type NotifyEvent = {export const cleanupFunction = inngest.createFunction({ id: "cleanup", retries: 2 },- { cron: "0 7,12,17 * * *" },+ { cron: "0 7 * * *" },async ({ step, logger }) => {+ // Jitter: spread the daily run across the hour so every environment+ // sharing infrastructure doesn't hammer storage/DB at exactly 07:00 UTC.+ // The random offset is computed once when the step first executes and+ // memoized in the run state — replays reuse the recorded wake time.+ await step.sleep("jitter", `${Math.floor(Math.random() * 3600)}s`);+const serviceRole = getCarbonServiceRole();await step.run("expire-quotes-and-rfqs", async () => {@@ -378,7 +385,7 @@ export const cleanupFunction = inngest.createFunction(});await step.run("prune-staged-raw-models", async () => {- logger.info("Pruning stale large staged raw models...");+ logger.info("Pruning stale staged raw models...");const cutoff = new Date(Date.now() - STAGED_RAW_TTL_DAYS * 24 * 60 * 60 * 1000).toISOString();@@ -386,7 +393,7 @@ export const cleanupFunction = inngest.createFunction(const stale = await serviceRole.schema("storage").from("objects")- .select("name, metadata")+ .select("name").eq("bucket_id", "temp-staging").lt("created_at", cutoff).limit(1000);@@ -395,70 +402,90 @@ export const cleanupFunction = inngest.createFunction(logger.error("Error listing stale staged raws", { error: stale.error });return;}-- // Prune only UNCOMPACTED fat raws — the compact pipeline replaces a raw- // with `raw.<ext>.zst` / `raw.xbf.zst` (the permanent lazy-plan source,- // never pruned even when its compressed size still exceeds the cap).- const big = (stale.data ?? [])- .filter(- (o) =>- !o.name?.toLowerCase().endsWith(".zst") &&- Number((o.metadata as { size?: number } | null)?.size ?? 0) >- MODEL_RAW_KEEP_MAX_BYTES- )+ const staleNames = (stale.data ?? []).map((o) => o.name).filter((n): n is string => Boolean(n));-- if (big.length === 0) {- logger.info("No large staged raws to prune");+ if (staleNames.length === 0) {+ logger.info("No stale staged raws");return;}- // Orphans only — never delete an object a modelUpload still points at,- // via EITHER column: `modelPath` (a referenced fat raw means compaction- // hasn't succeeded yet) or `originalPath` (xbf compaction repoints- // `modelPath` at the derived `.xbf.zst` but retains the customer's- // original, which must survive for downloads). True strays (upload- // recorded no row, or the row was deleted) are the actual dead weight.- const [referenced, referencedOriginals] = await Promise.all([- serviceRole- .from("modelUpload")- .select("modelPath")- .in("modelPath", big),- serviceRole- .from("modelUpload")- .select("originalPath")- .in("originalPath", big)- ]);- if (referenced.error || referencedOriginals.error) {- logger.error(- "Error resolving referenced staged raws — skipping prune",- {- error: referenced.error ?? referencedOriginals.error- }+ // Rule 1 — RELOCATED: the compact pipeline copies survivors to `private`+ // under the same key (copy, not move — a move races concurrent jobs+ // holding a temp-staging source pointer). Once the durable copy exists,+ // the staged one is redundant regardless of size or references: every+ // reader probes/falls back to `private`.+ const relocated = new Set<string>();+ const CHUNK = 20;+ for (let i = 0; i < staleNames.length; i += CHUNK) {+ const chunk = staleNames.slice(i, i + CHUNK);+ const probes = await Promise.all(+ chunk.map((name) =>+ serviceRole.storage+ .from("private")+ .info(name)+ .then((r) => (!r.error && r.data ? name : null))+ .catch(() => null)+ ));- return;+ for (const name of probes) {+ if (name) relocated.add(name);+ }}- const referencedPaths = new Set([- ...(referenced.data ?? []).map((r) => r.modelPath),- ...(referencedOriginals.data ?? []).map((r) => r.originalPath)- ]);- const orphans = big.filter((n) => !referencedPaths.has(n));- if (orphans.length === 0) {- logger.info("No orphaned large staged raws to prune", {- referenced: big.length++ // Rule 2 — ORPHANED: no modelUpload points at it via EITHER column+ // (`modelPath`: a referenced staging-only raw means compaction hasn't+ // succeeded yet or the object is the only copy of an oversized source;+ // `originalPath`: the retained original behind an xbf compaction). A+ // referenced object with no durable copy is NEVER deleted — it may be+ // the only copy of the customer's file.+ const candidates = staleNames.filter((n) => !relocated.has(n));+ const referencedPaths = new Set<string>();+ if (candidates.length > 0) {+ const [referenced, referencedOriginals] = await Promise.all([+ serviceRole+ .from("modelUpload")+ .select("modelPath")+ .in("modelPath", candidates),+ serviceRole+ .from("modelUpload")+ .select("originalPath")+ .in("originalPath", candidates)+ ]);+ if (referenced.error || referencedOriginals.error) {+ logger.error(+ "Error resolving referenced staged raws — skipping orphan prune",+ { error: referenced.error ?? referencedOriginals.error }+ );+ return;+ }+ for (const r of referenced.data ?? []) {+ if (r.modelPath) referencedPaths.add(r.modelPath);+ }+ for (const r of referencedOriginals.data ?? []) {+ if (r.originalPath) referencedPaths.add(r.originalPath);+ }+ }+ const orphans = candidates.filter((n) => !referencedPaths.has(n));++ const toRemove = [...relocated, ...orphans];+ if (toRemove.length === 0) {+ logger.info("No prunable staged raws", {+ stale: staleNames.length,+ referenced: referencedPaths.size});return;}const removed = await serviceRole.storage.from("temp-staging")- .remove(orphans);+ .remove(toRemove);if (removed.error) {logger.error("Error pruning staged raws", { error: removed.error });} else {- logger.info("Pruned orphaned staged raw models", {- count: orphans.length+ logger.info("Pruned stale staged raws", {+ relocated: relocated.size,+ orphaned: orphans.length});}});diff --git a/packages/jobs/src/inngest/functions/tasks/assembler-client.ts b/packages/jobs/src/inngest/functions/tasks/assembler-client.tsindex f5dc6337ba..8e2727a317 100644--- a/packages/jobs/src/inngest/functions/tasks/assembler-client.ts+++ b/packages/jobs/src/inngest/functions/tasks/assembler-client.ts@@ -85,19 +85,51 @@ 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.+ * COPY a staged object into the durable bucket, same key, server-side (no+ * download — storage-js `copy` with `destinationBucket`). Deliberately not a+ * move: a move deletes the staging object instantly, and a concurrent+ * optimize/convert/plan that already resolved `temp-staging` as its source+ * bucket then signs a path that no longer exists ("Object not found") and+ * fails. The staged copy stays behind and the scheduled cleanup prunes it once+ * it's stale (see cleanup.ts `prune-staged-raw-models`). Idempotent: an+ * already-existing durable copy counts as success. Returns null on success,+ * else the storage error message.*/-export async function moveRawToDurable(+export async function copyRawToDurable(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;+ .copy(path, path, { destinationBucket: RAW_DURABLE_BUCKET });+ if (!error) return null;+ return /already exists|duplicate/i.test(error.message) ? null : error.message;+}++/**+ * Sign a read URL for a job's source object. A missing object throws+ * `NonRetriableError` — the source is gone for good (deleted, staging cleared,+ * or the upload never completed), so retrying only delays the Failed stamp the+ * viewer needs before it can settle. Any other signing failure stays retriable.+ */+export async function signSourceUrl(+ client: SupabaseClient<Database>,+ bucket: string,+ path: string,+ expiresInSeconds: number+): Promise<string> {+ const source = await client.storage+ .from(bucket)+ .createSignedUrl(path, expiresInSeconds);+ if (source.error) {+ if (/not.?found/i.test(source.error.message)) {+ throw new NonRetriableError(+ `Source file no longer exists in storage: ${bucket}/${path}`+ );+ }+ throw new Error(`Failed to sign source URL: ${source.error.message}`);+ }+ return source.data.signedUrl;}/**diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts b/packages/jobs/src/inngest/functions/tasks/assembly-convert.tsindex 9b4b39f0aa..fde12f260a 100644--- a/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts+++ b/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts@@ -6,7 +6,8 @@ import {assemblerEnabled,internalizeStorageUrl,resolveModelSourceBucket,- runAssemblerJob+ runAssemblerJob,+ signSourceUrl} from "./assembler-client";const SIGNED_URL_EXPIRY = 60 * 60; // seconds — the source (read) URL only.@@ -130,12 +131,12 @@ export const assemblyConvertFunction = inngest.createFunction(client,job.modelPath);- const source = await client.storage- .from(sourceBucket)- .createSignedUrl(job.modelPath, SIGNED_URL_EXPIRY);- if (source.error) {- throw new Error(`Failed to sign source URL: ${source.error.message}`);- }+ const signedUrl = await signSourceUrl(+ client,+ sourceBucket,+ job.modelPath,+ SIGNED_URL_EXPIRY+ );// Content identity for the service's result cache: with a contentHash a// repeat convert of unchanged bytes is served without re-downloading the@@ -156,7 +157,7 @@ export const assemblyConvertFunction = inngest.createFunction(return {source: {- url: internalizeStorageUrl(source.data.signedUrl),+ url: internalizeStorageUrl(signedUrl),format: "step",...(contentHash ? { contentHash } : {})},diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts b/packages/jobs/src/inngest/functions/tasks/assembly-plan.tsindex cd3818249a..e82284d0fd 100644--- a/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts+++ b/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts@@ -7,7 +7,8 @@ import {assemblerEnabled,internalizeStorageUrl,resolveModelSourceBucket,- runAssemblerJob+ runAssemblerJob,+ signSourceUrl} from "./assembler-client";import { loadPlanUnits } from "./plan-units";import { updateAssemblyStepMotionsFromPlan } from "./update-step-motions";@@ -201,15 +202,15 @@ export const assemblyPlanFunction = inngest.createFunction(client,job.modelPath);- const source = await client.storage- .from(sourceBucket)- .createSignedUrl(job.modelPath, SIGNED_URL_EXPIRY);- if (source.error) {- throw new Error(`Failed to sign source URL: ${source.error.message}`);- }+ const signedUrl = await signSourceUrl(+ client,+ sourceBucket,+ job.modelPath,+ SIGNED_URL_EXPIRY+ );return {source: {- url: internalizeStorageUrl(source.data.signedUrl),+ url: internalizeStorageUrl(signedUrl),format: "step"},// The service reads planPath (completion pointer) and modelUploadIddiff --git a/packages/jobs/src/inngest/functions/tasks/model-compact.ts b/packages/jobs/src/inngest/functions/tasks/model-compact.tsindex 5afa9de512..3e8f865da3 100644--- a/packages/jobs/src/inngest/functions/tasks/model-compact.ts+++ b/packages/jobs/src/inngest/functions/tasks/model-compact.ts@@ -7,11 +7,12 @@ import { inngest } from "../../client";import {ASSEMBLER_CONCURRENCY,assemblerEnabled,+ copyRawToDurable,internalizeStorageUrl,- moveRawToDurable,RAW_STAGING_BUCKET,resolveModelSourceBucket,- runAssemblerJob+ runAssemblerJob,+ signSourceUrl} from "./assembler-client";const SIGNED_URL_EXPIRY = 60 * 60; // seconds — the source (read) URL only.@@ -25,17 +26,23 @@ const MAX_COMPACT_WAIT_MS = 15 * 60 * 1000;** - 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.+ * COPIES the compacted `.zst` to `private` if it fits the 50 MB served cap.* - The customer's ORIGINAL bytes always survive. xbf compaction is a format* conversion (no CAD tool opens `.xbf`), so the original STEP is kept alongside- * it — relocated to `private` when ≤ 50 MB, else left in staging tracked by+ * it — copied to `private` when ≤ 50 MB, else staging-only, tracked by* `modelUpload.originalPath` (the staged-raw sweep spares both columns). zstd* compaction is pure compression (the `.zst` decompresses byte-identical), so* the `.zst` replaces the original and `originalPath` is cleared.- * - Otherwise (assembler off, non-mesh, or already `.zst`): relocates the raw+ * - Otherwise (assembler off, non-mesh, or already `.zst`): copies the raw* as-is to `private` if it fits; oversized raws stay in staging (never pruned —* they may be the only copy of the customer's file).*+ * This function DELETES NOTHING from staging: an instant move/remove races any+ * concurrent optimize/convert/plan that resolved `temp-staging` as its source+ * bucket moments earlier ("Object not found" → Failed run, zombie viewer). The+ * scheduled cleanup sweep owns staging deletion: stale objects with a durable+ * copy, or referenced by no modelUpload, are pruned after the TTL.+ ** Fired after model-optimize settles (success, failure, or assembler-off skip), so* a failed/skipped optimise still gets its raw persisted. Own retries.*/@@ -109,16 +116,18 @@ export const modelCompactFunction = inngest.createFunction(: {};if (!canCompact) {- // No compaction possible — relocate the raw AS-IS to durable storage. Same+ // No compaction possible — COPY the raw AS-IS to durable storage. Same// key, so `modelPath` (path-only) is unchanged; the artifacts route resolves- // the bucket by probing.+ // the bucket by probing. The staged copy is left for the cleanup sweep —+ // deleting it here races concurrent jobs that resolved `temp-staging`+ // before the copy landed.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);+ const err = await copyRawToDurable(client, model.modelPath);if (err) throw new Error(`relocate raw to durable: ${err}`);- logger.info("raw relocated to durable", {+ logger.info("raw copied to durable", {modelUploadId,modelPath: model.modelPath});@@ -154,14 +163,14 @@ export const modelCompactFunction = inngest.createFunction(logger,buildBody: async () => {const client = getCarbonServiceRole();- const source = await client.storage- .from(RAW_STAGING_BUCKET)- .createSignedUrl(model.modelPath, SIGNED_URL_EXPIRY);- if (source.error) {- throw new Error(`sign source: ${source.error.message}`);- }+ const signedUrl = await signSourceUrl(+ client,+ RAW_STAGING_BUCKET,+ model.modelPath,+ SIGNED_URL_EXPIRY+ );return {- source: { url: internalizeStorageUrl(source.data.signedUrl) },+ source: { url: internalizeStorageUrl(signedUrl) },mode,// The assembler writes the compacted output to staging first; we// relocate it to durable storage (or prune) once we know its size.@@ -194,17 +203,18 @@ export const modelCompactFunction = inngest.createFunction(// and `originalPath` is cleared.const isXbf = mode === "xbf";- // Where the retained original ends up (xbf only): `private` when it fits- // the served cap, else it stays in staging — referenced via `originalPath`- // so the staged-raw sweep won't prune it.+ // Where the retained original ends up (xbf only): COPIED to `private`+ // when it fits the served cap, else staging only — referenced via+ // `originalPath` either way, so the staged-raw sweep won't prune the+ // only copy.const retainOriginal = async () => {const rawSize = model.originalSize ?? model.size;if (rawSize != null && rawSize <= MODEL_RAW_KEEP_MAX_BYTES) {- const err = await moveRawToDurable(client, model.modelPath);+ const err = await copyRawToDurable(client, model.modelPath);// Non-fatal: on failure the original stays in staging, still tracked// by `originalPath` (the download route probes both buckets).if (err) {- logger.warn("original raw not relocated — staying in staging", {+ logger.warn("original raw not copied to durable — staging only", {modelUploadId,originalPath: model.modelPath,error: err@@ -214,13 +224,17 @@ export const modelCompactFunction = inngest.createFunction(};if (fits) {- // Relocate the compacted raw to durable storage and repoint `modelPath`- // at it. xbf: also retain the original; zstd: drop the fat original- // (the `.zst` IS the original, compressed). `size` stays the- // AS-UPLOADED bytes — it feeds every "modelSize" view/RPC and the file- // lists, which must show the customer's file, not an internal artifact.- const err = await moveRawToDurable(client, compactPath);- if (err) throw new Error(`relocate compacted raw to durable: ${err}`);+ // COPY the compacted raw to durable storage and repoint `modelPath` at+ // it. xbf: also retain the original; zstd: the `.zst` IS the original,+ // compressed, so `originalPath` clears. NOTHING is deleted from staging+ // here — an instant delete races concurrent jobs that resolved+ // `temp-staging` as their source bucket before this landed; the+ // scheduled cleanup prunes stale staged copies instead. `size` stays+ // the AS-UPLOADED bytes — it feeds every "modelSize" view/RPC and the+ // file lists, which must show the customer's file, not an internal+ // artifact.+ const err = await copyRawToDurable(client, compactPath);+ if (err) throw new Error(`copy compacted raw to durable: ${err}`);if (isXbf) await retainOriginal();await client.from("modelUpload")@@ -230,12 +244,7 @@ export const modelCompactFunction = inngest.createFunction(...originalSizeUpdate}).eq("id", modelUploadId);- if (!isXbf) {- await client.storage- .from(RAW_STAGING_BUCKET)- .remove([model.modelPath]);- }- logger.info("raw compacted and relocated to durable", {+ logger.info("raw compacted and copied to durable", {modelUploadId,compactPath,mode@@ -245,22 +254,25 @@ export const modelCompactFunction = inngest.createFunction(if (hasGlb) {// Compacted output still exceeds the durable cap, but the GLB preview- // survives → prune the compacted artifact (it is derived and can be- // regenerated). The ORIGINAL stays in staging, still referenced by- // `modelPath` (never repointed on this branch), so downloads and a- // later re-compact keep working.- await client.storage.from(RAW_STAGING_BUCKET).remove([compactPath]);- logger.info("oversized compacted artifact pruned (original kept)", {- modelUploadId,- compactPath- });+ // survives → drop the derived artifact (regenerable). Left in staging+ // unreferenced; the scheduled cleanup sweeps it. The ORIGINAL stays in+ // staging, still referenced by `modelPath` (never repointed on this+ // branch), so downloads and a later re-compact keep working.+ logger.info(+ "oversized compacted artifact left for the sweep (original kept)",+ {+ modelUploadId,+ compactPath+ }+ );return { modelUploadId, status: "KeptInStaging" as const };}// Too big for durable AND no GLB — keep the compacted `.zst` in staging// (best available for the viewer/plan) and repoint. xbf: the original also// stays in staging (tracked by `originalPath` for the sweep + downloads);- // zstd: drop the fat original (the `.zst` has the bytes).+ // zstd: the fat original goes unreferenced and the scheduled cleanup+ // sweeps it (the `.zst` has the bytes).await client.from("modelUpload").update({@@ -269,9 +281,6 @@ export const modelCompactFunction = inngest.createFunction(...originalSizeUpdate}).eq("id", modelUploadId);- if (!isXbf) {- await client.storage.from(RAW_STAGING_BUCKET).remove([model.modelPath]);- }logger.warn("oversized compacted raw with no GLB kept in staging", {modelUploadId,compactPathdiff --git a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts b/packages/jobs/src/inngest/functions/tasks/model-optimize.tsindex 7df77ea1ae..f0b1fba157 100644--- a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts+++ b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts@@ -7,7 +7,8 @@ import {assemblerEnabled,internalizeStorageUrl,resolveModelSourceBucket,- runAssemblerJob+ runAssemblerJob,+ signSourceUrl} from "./assembler-client";const SIGNED_URL_EXPIRY = 60 * 60; // seconds — the source (read) URL only.@@ -168,14 +169,14 @@ export const modelOptimizeFunction = inngest.createFunction(buildBody: async () => {const client = getCarbonServiceRole();// Optimised artifacts are written to `private` (50 MB served cap) below.- const source = await client.storage- .from(model.sourceBucket)- .createSignedUrl(model.modelPath, SIGNED_URL_EXPIRY);- if (source.error) {- throw new Error(`Failed to sign source URL: ${source.error.message}`);- }+ const signedUrl = await signSourceUrl(+ client,+ model.sourceBucket,+ model.modelPath,+ SIGNED_URL_EXPIRY+ );return {- source: { url: internalizeStorageUrl(source.data.signedUrl), format },+ source: { url: internalizeStorageUrl(signedUrl), format },output: { path: optimizedPath }// quality omitted → the service applies its size-adaptive policy: codec// meshopt, merge on, normal quant on, and an auto simplify budget thatdiff --git a/packages/viewer/src/ModelPreview.tsx b/packages/viewer/src/ModelPreview.tsxindex b92a17b1a8..84560bd8c7 100644--- a/packages/viewer/src/ModelPreview.tsx+++ b/packages/viewer/src/ModelPreview.tsx@@ -59,6 +59,10 @@ export type ModelPreviewProps = {rawFile?: File | null;/** Filename for the download-GLB action (defaults to the URL basename). */downloadName?: string;+ /** The source file no longer exists in storage (legacy delete, or the upload+ * never completed) — nothing can render or regenerate. The settled state+ * says so instead of the generate-on-demand invitation. */+ sourceMissing?: boolean;/** Re-run optimise when the model settled with no GLB (shows a Retry button). */onRetry?: () => void;/** Label for the retry action — e.g. "Load Preview" when the model was never@@ -92,6 +96,7 @@ export function ModelPreview({optimizeFailed = false,rawFile = null,downloadName,+ sourceMissing = false,onRetry,retryLabel = "Retry",onCancelWait,@@ -340,6 +345,29 @@ export function ModelPreview({Cancel</button></div>+ ) : inView && sourceMissing ? (+ // The source file is gone from storage — no tier can render and no+ // regenerate can succeed. Say so plainly (a bare "3D preview" card+ // with no action reads as broken) and offer removal when the host+ // allows it, so the dead reference can be cleared.+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-4 p-4 text-center">+ <div className="flex size-11 items-center justify-center rounded-full bg-muted/60">+ <LuBox className="size-5 text-muted-foreground" />+ </div>+ <div className="flex flex-col gap-1">+ <p className="text-sm font-medium text-foreground">+ Model file unavailable+ </p>+ <p className="text-xs text-muted-foreground">+ The source file no longer exists in storage.+ </p>+ </div>+ {onDelete && (+ <Button variant="secondary" onClick={onDelete}>+ Remove model+ </Button>+ )}+ </div>) : inView ? (// Settled with no renderable tier. Framed as an invitation, not a// failure: the preview simply hasn't been generated yet (or the raw is