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.

feat(mes): Load Preview on the job-operation model tab

Sidwebworks54314bbeebe7
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index f70de0e6f6..aaa7bfeb26 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -140,7 +140,7 @@ import {
} from "./components/Step";
import { TableSkeleton } from "./components/TableSkeleton";
import { useFiles } from "./hooks/useFiles";
-import { useModelArtifacts } from "./hooks/useModelArtifacts";
+import { modelIdFromPath, useModelArtifacts } from "./hooks/useModelArtifacts";
import { useOperation } from "./hooks/useOperation";
const log = getLogger("mes", "job-operation");
@@ -323,7 +323,21 @@ export const JobOperation = ({
: null;
const modelPath = operation.itemModelPath ?? job.modelPath ?? null;
- const { artifacts, pending: modelPending } = useModelArtifacts(modelPath);
+ const {
+ artifacts,
+ pending: modelPending,
+ retry: retryModelArtifacts
+ } = useModelArtifacts(modelPath);
+ const reoptimizeFetcher = useFetcher<{ success: boolean }>();
+ const onModelRetry = () => {
+ const modelUploadId = modelIdFromPath(modelPath);
+ if (!modelUploadId) return;
+ reoptimizeFetcher.submit(
+ { modelUploadId },
+ { method: "post", action: path.to.api.modelReoptimize }
+ );
+ retryModelArtifacts();
+ };
const fetcher = useFetcher<Result>();
@@ -1782,11 +1796,17 @@ export const JobOperation = ({
}
mode={mode}
className="rounded-none"
+ onRetry={onModelRetry}
+ retryLabel={
+ artifacts?.optimizeStatus === "Failed"
+ ? "Retry"
+ : "Load Preview"
+ }
/>
) : (
<div className="flex h-full w-full items-center justify-center">
<p className="text-sm text-muted-foreground">
- 3D preview unavailable
+ No 3D model attached
</p>
</div>
)}
diff --git a/apps/mes/app/components/JobOperation/hooks/useModelArtifacts.tsx b/apps/mes/app/components/JobOperation/hooks/useModelArtifacts.tsx
index 58451f4bcf..5ef5534582 100644
--- a/apps/mes/app/components/JobOperation/hooks/useModelArtifacts.tsx
+++ b/apps/mes/app/components/JobOperation/hooks/useModelArtifacts.tsx
@@ -24,7 +24,7 @@ export type ModelArtifacts = {
// 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 {
+export 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
@@ -43,9 +43,10 @@ function modelIdFromPath(modelPath: string | null): string | null {
*/
export function useModelArtifacts(modelPath: string | null): {
artifacts: ModelArtifacts | undefined;
- /** True while a server GLB might still arrive (fetch unresolved / optimise in
- * flight). */
+ /** True while a server GLB is genuinely on its way (optimise in flight). */
pending: boolean;
+ /** Restart polling (after a re-optimise is fired) even if it had settled. */
+ retry: () => void;
} {
const uid = useId();
const modelUploadId = modelIdFromPath(modelPath);
@@ -56,7 +57,21 @@ export function useModelArtifacts(modelPath: string | null): {
const dataRef = useRef<ModelArtifacts | undefined>(undefined);
dataRef.current = fetcher.data;
const [pending, setPending] = useState(true);
+ const [reloadKey, setReloadKey] = useState(0);
+ // `pending` must mean "a GLB is genuinely on its way", not "still checking":
+ // the viewer renders it as an optimise-in-progress spinner. Settle on the
+ // first response unless the status is actually in flight; the background
+ // polling below re-raises it on a real transition.
+ useEffect(() => {
+ const data = fetcher.data;
+ if (!data) return;
+ const inFlight =
+ data.optimizeStatus === "Queued" || data.optimizeStatus === "Processing";
+ setPending(inFlight && !(data.optimizedModelPath || data.glbPath));
+ }, [fetcher.data]);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: reloadKey re-runs the effect on retry without being read inside it
useEffect(() => {
if (!modelUploadId) {
setPending(false);
@@ -78,8 +93,9 @@ export function useModelArtifacts(modelPath: string | null): {
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.
+ // `Idle`/undefined is the brief window before the job starts (or a
+ // non-mesh upload that never optimises) — keep polling quietly for a
+ // grace period (pending is driven by the data effect above).
const cap = inFlight ? 60 : 8; // ~3min in flight vs ~24s settling
attempts += 1;
if (attempts > cap) {
@@ -91,7 +107,11 @@ export function useModelArtifacts(modelPath: string | null): {
}, 3000);
return () => clearInterval(timer);
- }, [modelUploadId, load]);
+ }, [modelUploadId, load, reloadKey]);
- return { artifacts: fetcher.data, pending };
+ return {
+ artifacts: fetcher.data,
+ pending,
+ retry: () => setReloadKey((k) => k + 1)
+ };
}
diff --git a/apps/mes/app/routes/api+/model.reoptimize.ts b/apps/mes/app/routes/api+/model.reoptimize.ts
new file mode 100644
index 0000000000..f05c7769dd
--- /dev/null
+++ b/apps/mes/app/routes/api+/model.reoptimize.ts
@@ -0,0 +1,32 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { trigger } from "@carbon/jobs";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+
+// Fires the eager optimise for an already-uploaded model — backs the model
+// tab's "Load Preview" action (parity with the ERP api+/model.reoptimize
+// route). Operators can view models, so any authenticated employee may
+// generate the preview.
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {});
+
+ const formData = await request.formData();
+ const modelUploadId = formData.get("modelUploadId") as string | null;
+ if (!modelUploadId) {
+ return data({ success: false }, { status: 400 });
+ }
+
+ // Confirm the model belongs to this tenant (RLS-scoped read) before firing.
+ const model = await client
+ .from("modelUpload")
+ .select("id")
+ .eq("id", modelUploadId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (model.error || !model.data) {
+ return data({ success: false }, { status: 404 });
+ }
+
+ await trigger("model-optimize", { modelUploadId, companyId, userId });
+ return { success: true };
+}
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index f7b48cba12..dad8fb25bf 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -21,6 +21,7 @@ export const path = {
failureModes: `${api}/failure-modes`,
modelArtifacts: (modelUploadId: string) =>
generatePath(`${api}/model/artifacts/${modelUploadId}`),
+ modelReoptimize: `${api}/model/reoptimize`,
pickedAllocation: (jobMaterialId: string) =>
generatePath(`${api}/picked-allocation?jobMaterialId=${jobMaterialId}`),
qualityIssueTypes: `${api}/quality-issue-types`,