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
feat(cad): force reoptimize from the size badge; fix regen feedback loop
Sidwebworks9e491dc5498b
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsxindex c11bf0c48e..df5313bac4 100644--- a/apps/erp/app/components/CadModel.tsx+++ b/apps/erp/app/components/CadModel.tsx@@ -30,7 +30,7 @@ import { Trans } from "@lingui/react/macro";import { nanoid } from "nanoid";import { useState } from "react";import { useDropzone } from "react-dropzone";-import { LuCloudUpload, LuZap } from "react-icons/lu";+import { LuCloudUpload, LuRefreshCw, LuZap } from "react-icons/lu";import { useFetcher, useRevalidator } from "react-router";import { useModelUpload, useUser } from "~/hooks";import { getPrivateUrl, getRawModelUrl, path } from "~/utils/path";@@ -86,8 +86,10 @@ const CadModel = ({optimizeFailed,canRetry,optimizeQueued,+ optimizeInFlight,retry: onRetry,retryLabel,+ regenerate,cancel: onCancelWait,actionBusy} = useOptimizedModel({ modelPath, companyId, file });@@ -232,7 +234,13 @@ const CadModel = ({optimizeFailed={optimizeFailed}optimizedUrl={artifacts?.optimizedModelPath- ? getPrivateUrl(artifacts.optimizedModelPath)+ ? // ?v= busts the immutable preview cache on the STABLE+ // optimized.glb path when a re-optimise lands.+ `${getPrivateUrl(artifacts.optimizedModelPath)}${+ artifacts.optimizedAt+ ? `?v=${encodeURIComponent(artifacts.optimizedAt)}`+ : ""+ }`: null}glbUrl={@@ -283,8 +291,36 @@ const CadModel = ({</div>)}{artifacts?.size && artifacts?.optimizedSize ? (- <div className="pointer-events-none absolute bottom-2 left-2 z-10 flex items-center gap-1.5 rounded-md border border-border bg-popover px-2 py-1 text-xs text-muted-foreground shadow-sm">- <LuZap className="size-3 shrink-0 text-emerald-500" />+ <div className="group absolute bottom-2 left-2 z-10 flex items-center gap-1.5 rounded-md border border-border bg-popover px-2 py-1 text-xs text-muted-foreground shadow-sm">+ {artifacts.optimizerAvailable ? (+ // Hovering the badge swaps the lightning for a refresh+ // action: re-run the optimise from the source file (e.g.+ // to pick up improved quality settings).+ <button+ type="button"+ aria-label="Reoptimize from source file"+ title="Reoptimize from source file"+ // Locked while a regen is in flight: rapid re-clicks would+ // race the job's per-model singleton (a burst of events can+ // get wholly skipped on the local Inngest dev server), and+ // the spin is the only signal the silent background regen+ // is running.+ disabled={actionBusy || optimizeInFlight}+ onClick={regenerate}+ className="relative -m-2 flex size-7 shrink-0 items-center justify-center disabled:opacity-50"+ >+ {actionBusy || optimizeInFlight ? (+ <LuRefreshCw className="size-3 animate-spin text-emerald-500" />+ ) : (+ <>+ <LuZap className="size-3 text-emerald-500 group-hover:hidden" />+ <LuRefreshCw className="hidden size-3 text-emerald-500 group-hover:block" />+ </>+ )}+ </button>+ ) : (+ <LuZap className="size-3 shrink-0 text-emerald-500" />+ )}<span>Optimized GLB</span><span className="font-mono tabular-nums">{convertKbToString(Math.round(artifacts.size / 1024))}diff --git a/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts b/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.tsindex e936cb81f6..5e1d81b27b 100644--- a/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts+++ b/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts@@ -19,7 +19,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const model = await client.from("modelUpload").select(- "size, originalSize, optimizedSize, optimizedModelPath, glbPath, thumbnailPath, optimizeStatus, modelPath"+ "size, originalSize, optimizedSize, optimizedModelPath, glbPath, thumbnailPath, optimizeStatus, optimizedAt, modelPath, originalPath").eq("id", modelUploadId).eq("companyId", companyId)@@ -36,29 +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 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.+ // upload when no artifact exists). Prefer the retained ORIGINAL (xbf-compacted+ // rows keep the uploaded STEP at `originalPath` — the `.xbf.zst` itself isn't+ // WASM-renderable); else the uncompacted `modelPath`. 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 → no+ // raw tier (rely on the GLB).let rawPath: string | null = null;let rawBucket = "private";const modelPath = model.data?.modelPath ?? null;- if (modelPath && !modelPath.toLowerCase().endsWith(".zst")) {+ const rawCandidate =+ model.data?.originalPath ??+ (modelPath && !modelPath.toLowerCase().endsWith(".zst") ? modelPath : null);+ if (rawCandidate) {const svc = getCarbonServiceRole();const probe = (bucket: string) =>svc.storage.from(bucket)- .info(modelPath)+ .info(rawCandidate).catch(() => ({ data: null, error: true as const }));const inDurable = await probe("private");if (!inDurable.error && inDurable.data) {- rawPath = modelPath;+ rawPath = rawCandidate;rawBucket = "private";} else {const staged = await probe("temp-staging");if (!staged.error && staged.data) {- rawPath = modelPath;+ rawPath = rawCandidate;rawBucket = "temp-staging";}// Absent in both → pruned/gone; rawPath stays null (rely on the GLB).@@ -83,6 +87,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {// the STORED raw (rewritten to the .zst size after compaction), so prefer// the frozen originalSize; older rows fall back to size.size: model.data?.originalSize ?? model.data?.size ?? null,- optimizedSize: model.data?.optimizedSize ?? null+ optimizedSize: model.data?.optimizedSize ?? null,+ // Cache-buster for the optimised GLB: it lives at a STABLE path behind an+ // immutable-cached preview URL, so a re-optimise would otherwise keep+ // serving the browser-cached old mesh.+ optimizedAt: model.data?.optimizedAt ?? null};}diff --git a/apps/erp/app/routes/api+/model.optimize-cancel.ts b/apps/erp/app/routes/api+/model.optimize-cancel.tsindex e1c5453399..e7a0e3598b 100644--- a/apps/erp/app/routes/api+/model.optimize-cancel.ts+++ b/apps/erp/app/routes/api+/model.optimize-cancel.ts@@ -1,4 +1,5 @@import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";@@ -19,14 +20,25 @@ export async function action({ request }: ActionFunctionArgs) {return data({ success: false }, { status: 400 });}- const cancelled = await client+ // Tenant check with the RLS client, then stamp via service role — the+ // RLS UPDATE policy needs an edit permission, and a viewer-only user's+ // cancel would otherwise silently match zero rows (chip spins forever).+ const owned = await client+ .from("modelUpload")+ .select("id")+ .eq("id", modelUploadId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (owned.error || !owned.data) {+ return data({ success: false }, { status: 404 });+ }+ const cancelled = await getCarbonServiceRole().from("modelUpload").update({optimizeStatus: "Failed",optimizeError: "Cancelled by user"}).eq("id", modelUploadId)- .eq("companyId", companyId).in("optimizeStatus", ["Queued", "Processing"]).select("id");diff --git a/apps/erp/app/routes/api+/model.reoptimize.ts b/apps/erp/app/routes/api+/model.reoptimize.tsindex ead4c96e4b..55e5a714cc 100644--- a/apps/erp/app/routes/api+/model.reoptimize.ts+++ b/apps/erp/app/routes/api+/model.reoptimize.ts@@ -1,4 +1,5 @@import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";import { trigger } from "@carbon/jobs";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";@@ -28,6 +29,20 @@ export async function action({ request }: ActionFunctionArgs) {return data({ success: false }, { status: 404 });}- await trigger("model-optimize", { modelUploadId, companyId, userId });+ // Force mode (the badge's refresh action): re-optimise an already-Successful+ // model — e.g. to pick up improved tessellation/quality settings. The job+ // refuses to redo a Success row (alreadyOptimized guard), so reset the status+ // first. optimizedModelPath is kept: the viewer serves the old GLB until the+ // fresh one overwrites it (same path; the client cache-busts on optimizedAt).+ const force = formData.get("force") === "true";+ if (force) {+ const serviceRole = getCarbonServiceRole();+ await serviceRole+ .from("modelUpload")+ .update({ optimizeStatus: "Queued", optimizeError: null })+ .eq("id", modelUploadId);+ }++ await trigger("model-optimize", { modelUploadId, companyId, userId, force });return { success: true };}diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsxindex 0828ce1785..1869362365 100644--- a/apps/mes/app/components/JobOperation/JobOperation.tsx+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx@@ -1789,7 +1789,13 @@ export const JobOperation = ({optimizeFailed={optimizeFailed}optimizedUrl={artifacts?.optimizedModelPath- ? getPrivateUrl(artifacts.optimizedModelPath)+ ? // ?v= busts the immutable preview cache on the STABLE+ // optimized.glb path when a re-optimise lands.+ `${getPrivateUrl(artifacts.optimizedModelPath)}${+ artifacts.optimizedAt+ ? `?v=${encodeURIComponent(artifacts.optimizedAt)}`+ : ""+ }`: null}glbUrl={diff --git a/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts b/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.tsindex 2fb0f2a727..44d11711b4 100644--- a/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts+++ b/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts@@ -18,7 +18,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const model = await client.from("modelUpload").select(- "size, originalSize, optimizedSize, optimizedModelPath, glbPath, thumbnailPath, optimizeStatus, modelPath"+ "size, originalSize, optimizedSize, optimizedModelPath, glbPath, thumbnailPath, optimizeStatus, optimizedAt, modelPath, originalPath").eq("id", modelUploadId).eq("companyId", companyId)@@ -35,29 +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 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.+ // upload when no artifact exists). Prefer the retained ORIGINAL (xbf-compacted+ // rows keep the uploaded STEP at `originalPath` — the `.xbf.zst` itself isn't+ // WASM-renderable); else the uncompacted `modelPath`. 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 → no+ // raw tier (rely on the GLB).let rawPath: string | null = null;let rawBucket = "private";const modelPath = model.data?.modelPath ?? null;- if (modelPath && !modelPath.toLowerCase().endsWith(".zst")) {+ const rawCandidate =+ model.data?.originalPath ??+ (modelPath && !modelPath.toLowerCase().endsWith(".zst") ? modelPath : null);+ if (rawCandidate) {const svc = getCarbonServiceRole();const probe = (bucket: string) =>svc.storage.from(bucket)- .info(modelPath)+ .info(rawCandidate).catch(() => ({ data: null, error: true as const }));const inDurable = await probe("private");if (!inDurable.error && inDurable.data) {- rawPath = modelPath;+ rawPath = rawCandidate;rawBucket = "private";} else {const staged = await probe("temp-staging");if (!staged.error && staged.data) {- rawPath = modelPath;+ rawPath = rawCandidate;rawBucket = "temp-staging";}// Absent in both → pruned/gone; rawPath stays null (rely on the GLB).@@ -76,6 +80,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {optimizerAvailable: Boolean(ASSEMBLER_SERVICE_URL),optimizeStatus: model.data?.optimizeStatus ?? null,size: model.data?.originalSize ?? model.data?.size ?? null,- optimizedSize: model.data?.optimizedSize ?? null+ optimizedSize: model.data?.optimizedSize ?? null,+ // Cache-buster for the optimised GLB: it lives at a STABLE path behind an+ // immutable-cached preview URL, so a re-optimise would otherwise keep+ // serving the browser-cached old mesh.+ optimizedAt: model.data?.optimizedAt ?? null};}diff --git a/apps/mes/app/routes/api+/model.optimize-cancel.ts b/apps/mes/app/routes/api+/model.optimize-cancel.tsindex 33794046e6..9944c1a91a 100644--- a/apps/mes/app/routes/api+/model.optimize-cancel.ts+++ b/apps/mes/app/routes/api+/model.optimize-cancel.ts@@ -1,5 +1,6 @@import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";@@ -16,14 +17,25 @@ export async function action({ request }: ActionFunctionArgs) {return data({ success: false }, { status: 400 });}- const cancelled = await client+ // Tenant check with the RLS client, then stamp via service role — the+ // RLS UPDATE policy needs an edit permission, and a viewer-only user's+ // cancel would otherwise silently match zero rows (chip spins forever).+ const owned = await client+ .from("modelUpload")+ .select("id")+ .eq("id", modelUploadId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (owned.error || !owned.data) {+ return data({ success: false }, { status: 404 });+ }+ const cancelled = await getCarbonServiceRole().from("modelUpload").update({optimizeStatus: "Failed",optimizeError: "Cancelled by user"}).eq("id", modelUploadId)- .eq("companyId", companyId).in("optimizeStatus", ["Queued", "Processing"]).select("id");diff --git a/apps/mes/app/routes/api+/model.reoptimize.ts b/apps/mes/app/routes/api+/model.reoptimize.tsindex f05c7769dd..2c0d8b8af2 100644--- a/apps/mes/app/routes/api+/model.reoptimize.ts+++ b/apps/mes/app/routes/api+/model.reoptimize.ts@@ -1,4 +1,5 @@import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";import { trigger } from "@carbon/jobs";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";@@ -27,6 +28,19 @@ export async function action({ request }: ActionFunctionArgs) {return data({ success: false }, { status: 404 });}- await trigger("model-optimize", { modelUploadId, companyId, userId });+ // Force mode (the badge's refresh action): re-optimise an already-Successful+ // model — the job refuses to redo a Success row (alreadyOptimized guard), so+ // reset the status first. optimizedModelPath is kept: the viewer serves the+ // old GLB until the fresh one overwrites it (client cache-busts on optimizedAt).+ const force = formData.get("force") === "true";+ if (force) {+ const serviceRole = getCarbonServiceRole();+ await serviceRole+ .from("modelUpload")+ .update({ optimizeStatus: "Queued", optimizeError: null })+ .eq("id", modelUploadId);+ }++ await trigger("model-optimize", { modelUploadId, companyId, userId, force });return { success: true };}diff --git a/packages/jobs/src/inngest/functions/tasks/assembler-client.ts b/packages/jobs/src/inngest/functions/tasks/assembler-client.tsindex 3ba398753c..0c3f86676a 100644--- a/packages/jobs/src/inngest/functions/tasks/assembler-client.ts+++ b/packages/jobs/src/inngest/functions/tasks/assembler-client.ts@@ -405,6 +405,24 @@ export async function runAssemblerJob(});});+ // Fast jobs (small models, warm/cached assembler) can complete — and fire+ // their callback — in the gap between the submit step finishing and this+ // run registering its waitForEvent; the event then matches nothing and the+ // run parks for the FULL timeout. Poll once up front so an already-terminal+ // job returns immediately; the wait only covers genuinely in-flight work.+ const early: PollOutcome = await step.run(`${idPrefix}-early-poll`, () =>+ pollAssemblerJobOnce({ jobId, mintUploadUrls, baseUrl })+ );+ if (early.status === "done") {+ return { result: early.result, stats: early.stats };+ }+ if (early.status === "error") {+ if (early.error === "Job canceled") {+ throw new NonRetriableError(`assembler ${action} canceled`);+ }+ throw new Error(early.error);+ }+const done = await step.waitForEvent(`${idPrefix}-wait`, {event: "carbon/assembler-job-done",timeout: maxWaitMs,diff --git a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts b/packages/jobs/src/inngest/functions/tasks/model-optimize.tsindex 64bf0238c2..7df77ea1ae 100644--- a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts+++ b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts@@ -53,6 +53,7 @@ export const modelOptimizeFunction = inngest.createFunction({ event: "carbon/model-optimize" },async ({ event, step, logger }) => {const { modelUploadId, companyId } = event.data;+ const force = event.data.force === true;// Feature-gated: no assembler configured -> skip before touching the row,// so the viewer just serves the raw model tier (optimizeStatus stays null).@@ -89,6 +90,7 @@ export const modelOptimizeFunction = inngest.createFunction(// client auto-fire, an errant retry — re-running the assembler on a model// that already has its GLB.if (+ !force &&upload.data.optimizeStatus === "Success" &&upload.data.optimizedModelPath) {@@ -145,8 +147,15 @@ export const modelOptimizeFunction = inngest.createFunction(// Where the optimised GLB lands. The service late-mint uploads to this via a// signed URL minted fresh on each poll (below).const optimizedPath = `${companyId}/models/${modelUploadId}/optimized.glb`;- // Idempotent per model — a re-run attaches to the in-flight optimise.- const jobId = `optimize-${modelUploadId}`;+ // Idempotent per model — a re-run attaches to the in-flight optimise. A+ // FORCED regen must not: the assembler's job store keeps completed results+ // (24h TTL), so the stable id would attach to the previous run's cached+ // result and "finish" instantly. Salt the id with the triggering event so+ // each forced regen is a fresh assembler job (retries of the same event+ // keep the same id and still attach to their own in-flight run).+ const jobId = force+ ? `optimize-${modelUploadId}-${event.id ?? event.ts ?? "forced"}`+ : `optimize-${modelUploadId}`;// Router: sync inline on Lambda (default when enabled) or async submit->poll// on the standing service / dev container. Sync off => today's async path.diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.tsindex 2f244dd21a..1d520a8b68 100644--- a/packages/lib/src/events.ts+++ b/packages/lib/src/events.ts@@ -130,6 +130,11 @@ export type Events = {companyId: string;userId: string;// format is derived from the stored file inside the job, not passed here.+ // Force a fresh optimise of an already-Successful model (the badge's+ // refresh action) — bypasses the already-optimized guard and mints a+ // fresh assembler job id (the stable id would attach to the previous+ // run's cached result and finish instantly).+ force?: boolean;};};diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 781b237a82..37376e9e9c 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -8920,6 +8920,9 @@ msgstr "Operatoren können gemeinsame Arbeitsstationen mit PIN-Authentifizierungmsgid "Opportunity"msgstr "Gelegenheit"+msgid "Optimized for fast previews — downloads always serve the original uploaded file"+msgstr ""+msgid "Optional"msgstr "Optional"@@ -10297,8 +10300,8 @@ msgstr "Aktualisieren"msgid "Refresh exchange rate"msgstr "Wechselkurs aktualisieren"-msgid "Regenerate"-msgstr "Regenerieren"+msgid "Regenerate thumbnail from the 3D model"+msgstr ""msgid "Regenerating thumbnail…"msgstr "Miniaturansicht wird neu generiert…"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 1fbb3adc4f..5ac70c46ac 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -8920,6 +8920,9 @@ msgstr "Operators can use shared workstations with PIN authentication."msgid "Opportunity"msgstr "Opportunity"+msgid "Optimized for fast previews — downloads always serve the original uploaded file"+msgstr "Optimized for fast previews — downloads always serve the original uploaded file"+msgid "Optional"msgstr "Optional"@@ -10297,8 +10300,8 @@ msgstr "Refresh"msgid "Refresh exchange rate"msgstr "Refresh exchange rate"-msgid "Regenerate"-msgstr "Regenerate"+msgid "Regenerate thumbnail from the 3D model"+msgstr "Regenerate thumbnail from the 3D model"msgid "Regenerating thumbnail…"msgstr "Regenerating thumbnail…"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 289db94d67..299f4faaf0 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -8920,6 +8920,9 @@ msgstr "Los operadores pueden usar estaciones de trabajo compartidas con autentimsgid "Opportunity"msgstr "Oportunidad"+msgid "Optimized for fast previews — downloads always serve the original uploaded file"+msgstr ""+msgid "Optional"msgstr "Opcional"@@ -10297,8 +10300,8 @@ msgstr "Actualizar"msgid "Refresh exchange rate"msgstr "Actualizar tipo de cambio"-msgid "Regenerate"-msgstr "Regenerar"+msgid "Regenerate thumbnail from the 3D model"+msgstr ""msgid "Regenerating thumbnail…"msgstr "Regenerando miniatura…"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex b21236114a..9a1898e24e 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -8920,6 +8920,9 @@ msgstr "Les opérateurs peuvent utiliser des postes de travail partagés avec aumsgid "Opportunity"msgstr "Opportunité"+msgid "Optimized for fast previews — downloads always serve the original uploaded file"+msgstr ""+msgid "Optional"msgstr "Facultatif"@@ -10297,8 +10300,8 @@ msgstr "Actualiser"msgid "Refresh exchange rate"msgstr "Actualiser le taux de change"-msgid "Regenerate"-msgstr "Régénérer"+msgid "Regenerate thumbnail from the 3D model"+msgstr ""msgid "Regenerating thumbnail…"msgstr "Régénération de la miniature en cours…"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 1ac91279e5..e12fb3f6ba 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -8920,6 +8920,9 @@ msgstr "ऑपरेटर PIN प्रमाणीकरण के साथmsgid "Opportunity"msgstr "अवसर"+msgid "Optimized for fast previews — downloads always serve the original uploaded file"+msgstr ""+msgid "Optional"msgstr "वैकल्पिक"@@ -10297,8 +10300,8 @@ msgstr "ताज़ा करें"msgid "Refresh exchange rate"msgstr "विनिमय दर को ताज़ा करें"-msgid "Regenerate"-msgstr "पुनः जेनरेट करें"+msgid "Regenerate thumbnail from the 3D model"+msgstr ""msgid "Regenerating thumbnail…"msgstr "थंबनेल को पुनः उत्पन्न किया जा रहा है…"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex ebc60bb693..586ec55de1 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -8920,6 +8920,9 @@ msgstr "Gli operatori possono utilizzare workstation condivise con autenticazionmsgid "Opportunity"msgstr "Opportunità"+msgid "Optimized for fast previews — downloads always serve the original uploaded file"+msgstr ""+msgid "Optional"msgstr "Facoltativo"@@ -10297,8 +10300,8 @@ msgstr "Aggiorna"msgid "Refresh exchange rate"msgstr "Aggiorna tasso di cambio"-msgid "Regenerate"-msgstr "Rigenerare"+msgid "Regenerate thumbnail from the 3D model"+msgstr ""msgid "Regenerating thumbnail…"msgstr "Rigenerazione dell'anteprima…"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 9ec9101224..552c03274c 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -8920,6 +8920,9 @@ msgstr "オペレーターはPIN認証を使用して共有ワークステーシmsgid "Opportunity"msgstr "機会"+msgid "Optimized for fast previews — downloads always serve the original uploaded file"+msgstr ""+msgid "Optional"msgstr "オプション"@@ -10297,8 +10300,8 @@ msgstr "更新"msgid "Refresh exchange rate"msgstr "為替レートを更新"-msgid "Regenerate"-msgstr "再生成"+msgid "Regenerate thumbnail from the 3D model"+msgstr ""msgid "Regenerating thumbnail…"msgstr "サムネイルを再生成中…"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex b628a0380d..9481b682d1 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -8920,6 +8920,9 @@ msgstr "작업자는 PIN 인증을 통해 공유 워크스테이션을 사용할msgid "Opportunity"msgstr "기회"+msgid "Optimized for fast previews — downloads always serve the original uploaded file"+msgstr ""+msgid "Optional"msgstr "선택 사항"@@ -10297,8 +10300,8 @@ msgstr "새로고침"msgid "Refresh exchange rate"msgstr "환율 새로고침"-msgid "Regenerate"-msgstr "재생성"+msgid "Regenerate thumbnail from the 3D model"+msgstr ""msgid "Regenerating thumbnail…"msgstr "썸네일 재생성 중…"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 02f03f1d66..1b7428372c 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -8920,6 +8920,9 @@ msgstr "Operatorzy mogą używać wspólnych stanowisk pracy z uwierzytelnianiemmsgid "Opportunity"msgstr "Okazja"+msgid "Optimized for fast previews — downloads always serve the original uploaded file"+msgstr ""+msgid "Optional"msgstr "Opcjonalnie"@@ -10297,8 +10300,8 @@ msgstr "Odśwież"msgid "Refresh exchange rate"msgstr "Odśwież kurs wymiany"-msgid "Regenerate"-msgstr "Regeneruj"+msgid "Regenerate thumbnail from the 3D model"+msgstr ""msgid "Regenerating thumbnail…"msgstr "Ponownie generowanie miniatury…"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 33ae53d1f5..118f7c0cb7 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -8920,6 +8920,9 @@ msgstr "Os operadores podem usar estações de trabalho compartilhadas com autenmsgid "Opportunity"msgstr "Oportunidade"+msgid "Optimized for fast previews — downloads always serve the original uploaded file"+msgstr ""+msgid "Optional"msgstr "Opcional"@@ -10297,8 +10300,8 @@ msgstr "Atualizar"msgid "Refresh exchange rate"msgstr "Atualizar taxa de câmbio"-msgid "Regenerate"-msgstr "Regenerar"+msgid "Regenerate thumbnail from the 3D model"+msgstr ""msgid "Regenerating thumbnail…"msgstr "Regenerando miniatura…"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex c3561c0244..d14c1ec3e6 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -8920,6 +8920,9 @@ msgstr "Операторы могут использовать общие рабmsgid "Opportunity"msgstr "Возможность"+msgid "Optimized for fast previews — downloads always serve the original uploaded file"+msgstr ""+msgid "Optional"msgstr "Опционально"@@ -10297,8 +10300,8 @@ msgstr "Обновить"msgid "Refresh exchange rate"msgstr "Обновить курс обмена"-msgid "Regenerate"-msgstr "Перегенерировать"+msgid "Regenerate thumbnail from the 3D model"+msgstr ""msgid "Regenerating thumbnail…"msgstr "Создание миниатюры…"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 396fa05f7e..a731c4d02e 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -8920,6 +8920,9 @@ msgstr "Operatörler, PIN kimlik doğrulaması ile ortak iş istasyonlarını kumsgid "Opportunity"msgstr "Fırsat"+msgid "Optimized for fast previews — downloads always serve the original uploaded file"+msgstr ""+msgid "Optional"msgstr "İsteğe bağlı"@@ -10297,8 +10300,8 @@ msgstr "Yenile"msgid "Refresh exchange rate"msgstr "Döviz kurunu yenile"-msgid "Regenerate"-msgstr "Yeniden Oluştur"+msgid "Regenerate thumbnail from the 3D model"+msgstr ""msgid "Regenerating thumbnail…"msgstr "Küçük resim yenileniyor…"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 2a295a3951..f49a3f0d7b 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -8920,6 +8920,9 @@ msgstr "操作员可以使用带有PIN身份验证的共享工作站。"msgid "Opportunity"msgstr "机会"+msgid "Optimized for fast previews — downloads always serve the original uploaded file"+msgstr ""+msgid "Optional"msgstr "可选"@@ -10297,8 +10300,8 @@ msgstr "刷新"msgid "Refresh exchange rate"msgstr "刷新汇率"-msgid "Regenerate"-msgstr "重新生成"+msgid "Regenerate thumbnail from the 3D model"+msgstr ""msgid "Regenerating thumbnail…"msgstr "正在重新生成缩略图…"diff --git a/packages/viewer/src/ModelPreview.tsx b/packages/viewer/src/ModelPreview.tsxindex 3e8de57182..b92a17b1a8 100644--- a/packages/viewer/src/ModelPreview.tsx+++ b/packages/viewer/src/ModelPreview.tsx@@ -7,7 +7,8 @@ import {LuMaximize,LuRotateCw,LuTrash2,- LuTriangleAlert+ LuTriangleAlert,+ LuX} from "react-icons/lu";import type { ModelMetrics } from "./ModelCanvas";import { isRawRenderable } from "./raw/formats";@@ -199,7 +200,7 @@ export function ModelPreview({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">+ <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"><svgclassName="size-3 shrink-0 animate-spin"viewBox="0 0 24 24"@@ -221,6 +222,19 @@ export function ModelPreview({/></svg><span>Optimizing…</span>+ {/* Escape hatch: without it, a run that orphans mid-flight (worker+ crash, externally cancelled run) leaves the chip spinning with+ no way out — cancel stamps the row Failed → retry chip shows. */}+ {onCancelWait && (+ <button+ type="button"+ aria-label="Cancel optimization"+ onClick={onCancelWait}+ className="ml-0.5 rounded p-0.5 hover:bg-muted"+ >+ <LuX className="size-3" />+ </button>+ )}</div>)}diff --git a/packages/viewer/src/useOptimizedModel.ts b/packages/viewer/src/useOptimizedModel.tsindex 0c6a53347c..db2c06c481 100644--- a/packages/viewer/src/useOptimizedModel.ts+++ b/packages/viewer/src/useOptimizedModel.ts@@ -8,6 +8,9 @@ import { isRawRenderable } from "./raw/formats";export type ModelArtifacts = {optimizedModelPath: string | null;+ /** When the optimised GLB last landed — the client cache-buster for its+ * stable, immutable-cached URL. */+ optimizedAt?: string | null;lodPath: string | null;glbPath: string | null;thumbnailPath: string | null;@@ -58,9 +61,14 @@ const DEFAULT_PATHS = {cancel: "/api/model/optimize-cancel"};-async function postModelAction(action: string, modelUploadId: string) {+async function postModelAction(+ action: string,+ modelUploadId: string,+ extra?: Record<string, string>+) {const body = new FormData();body.append("modelUploadId", modelUploadId);+ for (const [k, v] of Object.entries(extra ?? {})) body.append(k, v);await fetch(action, { method: "POST", body }).catch(() => {// Best-effort — polling reflects whatever actually happened server-side.});@@ -127,13 +135,17 @@ export function useOptimizedModel({if (q.state.status === "error") return false;const d = q.state.data;if (!d) return POLL_MS;- if (d.optimizedModelPath || d.glbPath) return false;+ // In-flight beats "a GLB already exists": a forced re-optimise runs with+ // the previous GLB still present — polling must continue until the run+ // settles, or the UI freezes on the pre-regen snapshot (stale mesh/sizes,+ // regen spinner stuck forever).const inFlight =d.optimizeStatus === "Queued" || d.optimizeStatus === "Processing";if (inFlight) {gracePolls.current = 0;return POLL_MS;}+ if (d.optimizedModelPath || d.glbPath) return false;// Terminal/idle: keep a short grace window so a just-fired trigger (row// not yet flipped, possibly still showing a STALE Failed from the last// attempt) is picked up instead of polling stopping dead — the@@ -185,11 +197,15 @@ export function useOptimizedModel({const [actionBusy, setActionBusy] = useState(false);const fireOptimize = useCallback(- async (id: string) => {+ async (id: string, force?: boolean) => {gracePolls.current = 0;setOptimisticOptimize(true);setActionBusy(true);- await postModelAction(paths.reoptimize, id);+ await postModelAction(+ paths.reoptimize,+ id,+ force ? { force: "true" } : undefined+ );setActionBusy(false);await queryClient.invalidateQueries({queryKey: ["model-artifacts", companyId, id]@@ -230,6 +246,15 @@ export function useOptimizedModel({void fireOptimize(modelUploadId);}, [enabled, modelUploadId, fireOptimize]);+ // Force a fresh optimise of an already-Successful model (the badge's+ // refresh action) — e.g. to pick up improved tessellation/quality settings.+ // The server resets optimizeStatus so the job's already-optimised guard+ // doesn't skip the run.+ const regenerate = useCallback(() => {+ if (!enabled || !modelUploadId) return;+ void fireOptimize(modelUploadId, true);+ }, [enabled, modelUploadId, fireOptimize]);+const cancel = useCallback(async () => {if (!enabled || !modelUploadId) return;setActionBusy(true);@@ -289,6 +314,7 @@ export function useOptimizedModel({/** Overlay's first step reads as waiting until the job is picked up. */optimizeQueued: artifacts?.optimizeStatus !== "Processing",retry,+ regenerate,retryLabel:artifacts?.optimizeStatus === "Failed" ? "Retry" : "Load Preview",cancel,