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(mes): render models via ModelPreview with WASM fallback

Sidwebworksfbbbf850c936
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index ff04abd148..b32c4c048d 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -55,7 +55,7 @@ import {
formatDurationMilliseconds,
getItemReadableId
} from "@carbon/utils";
-import { ModelCanvas } from "@carbon/viewer/canvas";
+import { ModelPreview } from "@carbon/viewer/model-preview";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestSingleResponse } from "@supabase/supabase-js";
import { Suspense, useEffect, useMemo, useState } from "react";
@@ -115,7 +115,7 @@ import type {
TrackedInput
} from "~/services/types";
import { useItems } from "~/stores";
-import { path } from "~/utils/path";
+import { getPrivateUrl, getRawModelUrl, path } from "~/utils/path";
import ItemThumbnail from "../ItemThumbnail";
import { OperationChat } from "./components/Chat";
import {
@@ -139,25 +139,11 @@ import {
} from "./components/Step";
import { TableSkeleton } from "./components/TableSkeleton";
import { useFiles } from "./hooks/useFiles";
+import { useModelArtifacts } from "./hooks/useModelArtifacts";
import { useOperation } from "./hooks/useOperation";
const log = getLogger("mes", "job-operation");
-// The new pipeline serves an optimised GLB per model (no client-side
-// tessellation). Derive its private preview URL from the raw modelPath
-// `${co}/models/${id}.ext[.zst]` → `${co}/models/${id}/optimized.glb`.
-function optimizedModelPreviewUrl(rawModelPath: string | null): string | null {
- if (!rawModelPath) return null;
- const slash = rawModelPath.lastIndexOf("/");
- if (slash < 0) return null;
- const dir = rawModelPath.slice(0, slash);
- let base = rawModelPath.slice(slash + 1);
- if (base.toLowerCase().endsWith(".zst")) base = base.slice(0, -4);
- const id = base.replace(/\.[^.]+$/, "");
- if (!id) return null;
- return `/file/preview/private/${dir}/${id}/optimized.glb`;
-}
-
type JobOperationProps = {
events: ProductionEvent[];
expiredEntityPolicy?: "Warn" | "Block" | "BlockWithOverride";
@@ -335,6 +321,9 @@ export const JobOperation = ({
}
: null;
+ const modelPath = operation.itemModelPath ?? job.modelPath ?? null;
+ const { artifacts, pending: modelPending } = useModelArtifacts(modelPath);
+
const fetcher = useFetcher<Result>();
// Lazy creation of Inspection steps for non-conformance actions
@@ -1764,25 +1753,41 @@ export const JobOperation = ({
</TabsContent>
<TabsContent value="model">
<div className="w-full h-[calc(100dvh-var(--header-height)*2)] p-0">
- {(() => {
- const glbUrl = optimizedModelPreviewUrl(
- operation.itemModelPath ?? job.modelPath
- );
- return glbUrl ? (
- <ModelCanvas
- key={glbUrl}
- glbUrl={glbUrl}
- mode={mode}
- className="rounded-none"
- />
- ) : (
- <div className="flex h-full w-full items-center justify-center">
- <p className="text-sm text-muted-foreground">
- 3D preview unavailable
- </p>
- </div>
- );
- })()}
+ {modelPath ? (
+ <ModelPreview
+ key={modelPath}
+ awaitingModel={modelPending}
+ optimizedUrl={
+ artifacts?.optimizedModelPath
+ ? getPrivateUrl(artifacts.optimizedModelPath)
+ : null
+ }
+ glbUrl={
+ artifacts?.glbPath ? getPrivateUrl(artifacts.glbPath) : null
+ }
+ lodUrl={
+ artifacts?.lodPath ? getPrivateUrl(artifacts.lodPath) : null
+ }
+ rawUrl={
+ artifacts?.rawPath
+ ? getRawModelUrl(artifacts.rawBucket, artifacts.rawPath)
+ : null
+ }
+ thumbnailUrl={
+ artifacts?.thumbnailPath
+ ? getPrivateUrl(artifacts.thumbnailPath)
+ : null
+ }
+ mode={mode}
+ className="rounded-none"
+ />
+ ) : (
+ <div className="flex h-full w-full items-center justify-center">
+ <p className="text-sm text-muted-foreground">
+ 3D preview unavailable
+ </p>
+ </div>
+ )}
</div>
</TabsContent>
<TabsContent value="procedure" className="flex flex-grow">
diff --git a/apps/mes/app/components/JobOperation/hooks/useModelArtifacts.tsx b/apps/mes/app/components/JobOperation/hooks/useModelArtifacts.tsx
new file mode 100644
index 0000000000..58451f4bcf
--- /dev/null
+++ b/apps/mes/app/components/JobOperation/hooks/useModelArtifacts.tsx
@@ -0,0 +1,97 @@
+import { useEffect, useId, useRef, useState } from "react";
+import { useFetcher } from "react-router";
+import { path } from "~/utils/path";
+
+export type ModelArtifacts = {
+ optimizedModelPath: string | null;
+ lodPath: string | null;
+ glbPath: string | null;
+ thumbnailPath: string | null;
+ /** Raw upload (non-`.zst`) for the viewer's WASM fallback tier, with its
+ * resolved bucket (temp-staging for current uploads, private for old rows). */
+ rawPath: string | null;
+ rawBucket: string;
+ optimizeStatus:
+ | "Idle"
+ | "Queued"
+ | "Processing"
+ | "Success"
+ | "Failed"
+ | null;
+ size: number | null;
+ optimizedSize: number | null;
+};
+
+// modelUpload.id is the model's filename (`${company}/models/${id}.ext`), so the
+// id — and thus its artifact paths — is recoverable from `modelPath` alone.
+function modelIdFromPath(modelPath: string | null): string | null {
+ if (!modelPath) return null;
+ let base = modelPath.split("/").pop() ?? "";
+ // Retained raws are compacted in place (`${id}.step` → `${id}.step.zst`); peel
+ // the `.zst` wrapper before the source extension so the id resolves either way.
+ if (base.toLowerCase().endsWith(".zst")) base = base.slice(0, -4);
+ return base.replace(/\.[^.]+$/, "") || null;
+}
+
+/**
+ * Resolves a model's assembler artifact paths (optimised / LOD / assembly GLB /
+ * thumbnail / raw source) via the `model.artifacts` API loader, keyed by the id
+ * derived from `modelPath`. While optimise is in flight it polls so the compact
+ * GLB swaps in without a reload; it stops once an interactive artifact lands,
+ * optimise fails, or after a bounded window. Parity with the ERP CadModel hook,
+ * minus the client cache (MES uses a plain fetcher).
+ */
+export function useModelArtifacts(modelPath: string | null): {
+ artifacts: ModelArtifacts | undefined;
+ /** True while a server GLB might still arrive (fetch unresolved / optimise in
+ * flight). */
+ pending: boolean;
+} {
+ const uid = useId();
+ const modelUploadId = modelIdFromPath(modelPath);
+ const fetcher = useFetcher<ModelArtifacts>({
+ key: `model-artifacts:${modelUploadId ?? `none:${uid}`}`
+ });
+ const load = fetcher.load;
+ const dataRef = useRef<ModelArtifacts | undefined>(undefined);
+ dataRef.current = fetcher.data;
+ const [pending, setPending] = useState(true);
+
+ useEffect(() => {
+ if (!modelUploadId) {
+ setPending(false);
+ return;
+ }
+ setPending(true);
+ const url = path.to.api.modelArtifacts(modelUploadId);
+ load(url);
+
+ let attempts = 0;
+ const timer = setInterval(() => {
+ const data = dataRef.current;
+ const hasInteractive = Boolean(data?.optimizedModelPath || data?.glbPath);
+ if (hasInteractive || data?.optimizeStatus === "Failed") {
+ clearInterval(timer);
+ setPending(false);
+ return;
+ }
+ const inFlight =
+ data?.optimizeStatus === "Queued" ||
+ data?.optimizeStatus === "Processing";
+ // `Idle`/undefined is the brief window before the job starts (or a non-mesh
+ // upload that never optimises) — poll it only for a short grace period.
+ const cap = inFlight ? 60 : 8; // ~3min in flight vs ~24s settling
+ attempts += 1;
+ if (attempts > cap) {
+ clearInterval(timer);
+ setPending(false);
+ return;
+ }
+ load(url);
+ }, 3000);
+
+ return () => clearInterval(timer);
+ }, [modelUploadId, load]);
+
+ return { artifacts: fetcher.data, pending };
+}
diff --git a/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts b/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
new file mode 100644
index 0000000000..29ae032c42
--- /dev/null
+++ b/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
@@ -0,0 +1,54 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { LoaderFunctionArgs } from "react-router";
+
+// Resolves a model's optimised / preview artifact storage paths for the
+// progressive ModelPreview (parity with the ERP api+/model.artifacts route).
+// The MES model tab fetches this by modelUploadId (derived from modelPath —
+// modelUpload.id is the model filename) so the viewer only requests artifacts
+// that actually exist, and falls back to the raw upload (WASM tier) otherwise.
+// Returns only paths; the bytes are still served through the auth-checked
+// /file/preview proxy, scoped to the company.
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {});
+ const { modelUploadId } = params;
+ if (!modelUploadId) throw new Response("Not found", { status: 404 });
+
+ const model = await client
+ .from("modelUpload")
+ .select(
+ "size, originalSize, optimizedSize, optimizedModelPath, glbPath, thumbnailPath, optimizeStatus, modelPath"
+ )
+ .eq("id", modelUploadId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ // 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.
+ let rawPath: string | null = null;
+ let rawBucket = "temp-staging";
+ 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";
+ }
+
+ return {
+ optimizedModelPath: model.data?.optimizedModelPath ?? null,
+ lodPath: null as string | null,
+ glbPath: model.data?.glbPath ?? null,
+ thumbnailPath: model.data?.thumbnailPath ?? null,
+ rawPath,
+ rawBucket,
+ optimizeStatus: model.data?.optimizeStatus ?? null,
+ size: model.data?.originalSize ?? model.data?.size ?? null,
+ optimizedSize: model.data?.optimizedSize ?? null
+ };
+}
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index c7d6603ece..f7b48cba12 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -19,6 +19,8 @@ export const path = {
batchNumbers: (itemId: string) =>
generatePath(`${api}/batch-numbers?itemId=${itemId}`),
failureModes: `${api}/failure-modes`,
+ modelArtifacts: (modelUploadId: string) =>
+ generatePath(`${api}/model/artifacts/${modelUploadId}`),
pickedAllocation: (jobMaterialId: string) =>
generatePath(`${api}/picked-allocation?jobMaterialId=${jobMaterialId}`),
qualityIssueTypes: `${api}/quality-issue-types`,
@@ -193,6 +195,12 @@ export const getPrivateUrl = (path: string) => {
return `/file/preview/private/${path}`;
};
+// Raw model source for the viewer's WASM fallback tier — the bucket varies
+// (temp-staging for current uploads, private for pre-assembler rows).
+export const getRawModelUrl = (bucket: string, path: string) => {
+ return `/file/preview/${bucket}/${path}`;
+};
+
export const getStoragePath = (bucket: string, path: string) => {
return `${SUPABASE_URL}/storage/v1/object/public/${bucket}/${path}`;
};