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(viewer): cancellable optimise wait

Sidwebworkse2b05121d6a0
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsx
index 6ab9dbf848..748795785e 100644
--- a/apps/erp/app/components/CadModel.tsx
+++ b/apps/erp/app/components/CadModel.tsx
@@ -264,6 +264,18 @@ const CadModel = ({
retry();
};
+ // Cancel the in-flight optimise when the user dismisses the preparing
+ // spinner: stamps the row Failed and cancels the assembler job, so the
+ // waiting Inngest run fails fast instead of leaving a stuck Processing row.
+ const onCancelWait = () => {
+ const modelUploadId = modelIdFromPath(modelPath);
+ if (!modelUploadId) return;
+ reoptimizeFetcher.submit(
+ { modelUploadId },
+ { method: "post", action: path.to.api.modelOptimizeCancel }
+ );
+ };
+
const onFileChange = async (file: File | null) => {
const modelId = nanoid();
@@ -367,6 +379,7 @@ const CadModel = ({
mode={mode}
className={viewerClassName}
onRetry={!isReadOnly && modelPath ? onRetry : undefined}
+ onCancelWait={modelPath ? onCancelWait : undefined}
onDelete={canDelete ? deleteModal.onOpen : undefined}
/>
{upload !== null && (
diff --git a/apps/erp/app/routes/api+/model.optimize-cancel.ts b/apps/erp/app/routes/api+/model.optimize-cancel.ts
new file mode 100644
index 0000000000..d27ecbc203
--- /dev/null
+++ b/apps/erp/app/routes/api+/model.optimize-cancel.ts
@@ -0,0 +1,57 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+
+// Cancels an in-flight (or stuck) eager optimise — backs the viewer's spinner
+// "Cancel". Stamps the row Failed so the viewer settles immediately, and
+// best-effort cancels the assembler job, which drops the compute result and
+// fires the completion callback so the waiting Inngest run wakes and fails
+// non-retriably instead of later overwriting the row with a success.
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ update: "parts"
+ });
+
+ const formData = await request.formData();
+ const modelUploadId = formData.get("modelUploadId") as string | null;
+ if (!modelUploadId) {
+ return data({ success: false }, { status: 400 });
+ }
+
+ const cancelled = await client
+ .from("modelUpload")
+ .update({
+ optimizeStatus: "Failed",
+ optimizeError: "Cancelled by user"
+ })
+ .eq("id", modelUploadId)
+ .eq("companyId", companyId)
+ .in("optimizeStatus", ["Queued", "Processing"])
+ .select("id");
+
+ if (cancelled.error) {
+ return data({ success: false }, { status: 500 });
+ }
+
+ // The optimise job id is deterministic (`optimize-${modelUploadId}`), so the
+ // assembler cancel needs no run lookup.
+ if (ASSEMBLER_SERVICE_URL && cancelled.data.length > 0) {
+ await fetch(
+ `${ASSEMBLER_SERVICE_URL}/v1/jobs/optimize-${modelUploadId}/cancel`,
+ {
+ method: "POST",
+ headers: ASSEMBLER_SERVICE_API_KEY
+ ? { Authorization: `Bearer ${ASSEMBLER_SERVICE_API_KEY}` }
+ : {},
+ signal: AbortSignal.timeout(5000)
+ }
+ ).catch(() => {
+ // Best-effort — the row is already stamped Failed. A missed cancel just
+ // means the compute finishes anyway and flips the row to Success, which
+ // is harmless (the artifact is real).
+ });
+ }
+
+ return { success: true, cancelled: cancelled.data.length > 0 };
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index b8285d353a..cfc9c9fe68 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -145,6 +145,7 @@ export const path = {
generatePath(`${api}/model/artifacts/${modelUploadId}`),
modelConvertStatus: (modelUploadId: string) =>
generatePath(`${api}/model/convert-status/${modelUploadId}`),
+ modelOptimizeCancel: `${api}/model/optimize-cancel`,
modelReoptimize: `${api}/model/reoptimize`,
modelUpload: `${api}/model/upload`,
mrp: (locationId?: string) =>
diff --git a/packages/viewer/src/ModelPreview.tsx b/packages/viewer/src/ModelPreview.tsx
index 30c8681abe..975f701257 100644
--- a/packages/viewer/src/ModelPreview.tsx
+++ b/packages/viewer/src/ModelPreview.tsx
@@ -53,6 +53,9 @@ export type ModelPreviewProps = {
downloadName?: string;
/** Re-run optimise when the model settled with no GLB (shows a Retry button). */
onRetry?: () => void;
+ /** Called when the user cancels the "preparing" wait — the host should cancel
+ * the in-flight optimise (job + run) so the row doesn't stay stuck. */
+ onCancelWait?: () => void;
mode?: "dark" | "light";
onDelete?: () => void;
className?: string;
@@ -77,6 +80,7 @@ export function ModelPreview({
rawFile = null,
downloadName,
onRetry,
+ onCancelWait,
mode = "dark",
onDelete,
className
@@ -89,6 +93,12 @@ export function ModelPreview({
// Gate orbit until the user opts in, so scrolling the page over the viewer
// doesn't hijack the wheel (matches the WASM viewer's "click to interact").
const [interactive, setInteractive] = useState(false);
+ // User escape from the "preparing" spinner (optimise can run minutes) —
+ // drops to the settled state early. Re-arms when a retry restarts the wait.
+ const [waitDismissed, setWaitDismissed] = useState(false);
+ useEffect(() => {
+ if (awaitingModel) setWaitDismissed(false);
+ }, [awaitingModel]);
const interactiveUrl = optimizedUrl ?? glbUrl;
// The instant 3D layer: the LOD if it's distinct from the interactive model
@@ -219,9 +229,11 @@ export function ModelPreview({
)}
</div>
</>
- ) : inView && awaitingModel ? (
- // Server GLB still being prepared (upload / optimise in flight) — spinner.
- <div className="absolute inset-0 flex items-center justify-center">
+ ) : inView && awaitingModel && !waitDismissed ? (
+ // Server GLB still being prepared (upload / optimise in flight) —
+ // spinner with a cancel escape (optimise can take minutes; never trap
+ // the user in an unbounded wait).
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-3">
<svg
className="h-6 w-6 animate-spin text-muted-foreground"
viewBox="0 0 24 24"
@@ -242,6 +254,16 @@ export function ModelPreview({
d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"
/>
</svg>
+ <button
+ type="button"
+ onClick={() => {
+ setWaitDismissed(true);
+ onCancelWait?.();
+ }}
+ className="text-xs text-muted-foreground underline-offset-2 opacity-70 transition-opacity hover:opacity-100 hover:underline"
+ >
+ Cancel
+ </button>
</div>
) : inView ? (
// Settled with no server GLB (optimise failed / non-mesh). No in-browser