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.

refactor(viewer): shared TanStack Query model lifecycle + auto-optimise on view

Sidwebworks8e8730eb4bbb
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsx
index 552ce55987..af26311014 100644
--- a/apps/erp/app/components/CadModel.tsx
+++ b/apps/erp/app/components/CadModel.tsx
@@ -23,147 +23,20 @@ import {
MODEL_RAW_KEEP_MAX_BYTES,
supportedModelTypes
} from "@carbon/utils";
-import { ModelPreview, WASM_RAW_ENABLED } from "@carbon/viewer/model-preview";
+import { ModelPreview } from "@carbon/viewer/model-preview";
+import { OptimizeProgress } from "@carbon/viewer/optimize-progress";
+import { useOptimizedModel } from "@carbon/viewer/use-optimized-model";
import { nanoid } from "nanoid";
-import { useEffect, useId, useRef, useState } from "react";
+import { useState } from "react";
import { useDropzone } from "react-dropzone";
import { LuCloudUpload, LuZap } from "react-icons/lu";
import { useFetcher, useRevalidator } from "react-router";
import { useModelUpload, useUser } from "~/hooks";
import { getPrivateUrl, getRawModelUrl, path } from "~/utils/path";
-import { ModelOptimizeProgress } from "./ModelOptimizeProgress";
import { ModelUploadProgress } from "./ModelUploadProgress";
const SIZE_LIMIT = getFileSizeLimit("CAD_MODEL_UPLOAD");
-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;
- /** As-uploaded raw bytes (originalSize; older rows fall back to the stored
- * size) — the loader resolves this so the reduction badge never compares
- * against the compacted `.zst`. */
- size: number | null;
- /** Optimized GLB bytes — surfaced next to `size` to show the reduction. */
- 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) via the `model.artifacts` API loader — keyed by the id derived from
- * `modelPath`, so no summary loader has to carry these columns. While optimise is
- * in flight it polls so the compact GLB swaps into the viewer without a reload;
- * it stops once an interactive artifact lands, optimise fails, or after a bounded
- * window (non-mesh uploads stay `Idle` and are only briefly checked).
- */
-function useModelArtifacts(modelPath: string | null): {
- artifacts: ModelArtifacts | undefined;
- /** True while a server GLB might still arrive (fetch unresolved / 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);
- // Scope the fetcher per model id: a delete or swap gives a DIFFERENT fetcher
- // whose `data` is undefined until its own load resolves — so a previous
- // model's artifacts can never leak into the new one's viewer (the old model
- // flashing before the spinner). The `none:<uid>` key keeps model-less
- // instances from colliding on a shared fetcher.
- 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);
- 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, so a settled
- // model must not wear it for a grace window. Settle on the first response
- // unless the status is actually in flight; the background polling below
- // still catches a later transition (fresh upload flipping to Processing)
- // and re-raises pending then.
- 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);
- 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) — keep polling quietly for a grace period
- // (pending is driven by the data effect above, not this loop).
- 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, reloadKey]);
-
- return {
- artifacts: fetcher.data,
- pending,
- retry: () => setReloadKey((k) => k + 1)
- };
-}
-
type CadModelProps = {
modelPath: string | null;
metadata?: {
@@ -201,49 +74,18 @@ const CadModel = ({
const [isDeleting, setIsDeleting] = useState(false);
const deleteModal = useDisclosure();
- const { artifacts, pending, retry } = useModelArtifacts(modelPath);
- const reoptimizeFetcher = useFetcher<{ success: boolean }>();
- // A server GLB may still be on its way while a fresh file uploads or the
- // optimise job runs. Raws <= MODEL_RAW_KEEP_MAX_BYTES render in-browser (WASM
- // tier) in the meantime; bigger ones show a staged optimise progress overlay
- // until the GLB lands, then "preview unavailable" if it never does.
- const awaitingModel = pending || Boolean(file);
-
- const hasInteractive = Boolean(
- artifacts?.optimizedModelPath || artifacts?.glbPath
- );
- const rawRenderable =
- WASM_RAW_ENABLED &&
- Boolean(
- (artifacts?.rawPath &&
- (artifacts.size ?? 0) <= MODEL_RAW_KEEP_MAX_BYTES) ||
- (file && file.size <= MODEL_RAW_KEEP_MAX_BYTES)
- );
- // Staged progress overlay: an optimise is running and nothing else can
- // render (no artifact yet, raw too big / absent). When the raw tier renders,
- // the optimise runs silently behind it and the GLB swaps in on success.
- const optimizeInFlight =
- artifacts?.optimizeStatus === "Queued" ||
- artifacts?.optimizeStatus === "Processing";
- // Bridges the click -> job-visible gap: the row status takes a couple of
- // polls to flip after Load Preview / Retry, and without this the overlay
- // wouldn't appear until then. Cleared on handover (or a 15s safety timeout
- // if the trigger silently failed).
- const [optimisticOptimize, setOptimisticOptimize] = useState(false);
- useEffect(() => {
- if (!optimisticOptimize) return;
- if (optimizeInFlight || hasInteractive) {
- setOptimisticOptimize(false);
- return;
- }
- const timeout = setTimeout(() => setOptimisticOptimize(false), 15000);
- return () => clearTimeout(timeout);
- }, [optimisticOptimize, optimizeInFlight, hasInteractive]);
- const showOptimizeProgress =
- (optimizeInFlight || optimisticOptimize) &&
- !hasInteractive &&
- !rawRenderable &&
- upload === null;
+ const {
+ artifacts,
+ awaitingModel,
+ showOptimizeProgress: optimizeProgressActive,
+ optimizeQueued,
+ retry: onRetry,
+ retryLabel,
+ cancel: onCancelWait,
+ actionBusy
+ } = useOptimizedModel({ modelPath, companyId, file });
+ // Never on top of the upload progress overlay.
+ const showOptimizeProgress = optimizeProgressActive && upload === null;
const onDelete = async () => {
if (!carbon) {
@@ -304,31 +146,6 @@ const CadModel = ({
metadata?.jobId
);
- // Re-fire the optimise for an existing model (raw still in temp-staging) and
- // restart artifact polling so the GLB swaps in without a reload.
- const onRetry = () => {
- const modelUploadId = modelIdFromPath(modelPath);
- if (isReadOnly || !modelUploadId) return;
- setOptimisticOptimize(true);
- reoptimizeFetcher.submit(
- { modelUploadId },
- { method: "post", action: path.to.api.modelReoptimize }
- );
- 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();
@@ -431,12 +248,8 @@ const CadModel = ({
}
mode={mode}
className={viewerClassName}
- onRetry={!isReadOnly && modelPath ? onRetry : undefined}
- retryLabel={
- artifacts?.optimizeStatus === "Failed"
- ? "Retry"
- : "Load Preview"
- }
+ onRetry={modelPath ? onRetry : undefined}
+ retryLabel={retryLabel}
onCancelWait={modelPath ? onCancelWait : undefined}
onDelete={canDelete ? deleteModal.onOpen : undefined}
/>
@@ -452,10 +265,11 @@ const CadModel = ({
)}
{showOptimizeProgress && modelPath && (
<div className="absolute inset-0 z-30 flex items-center justify-center rounded-lg bg-background/95 p-6">
- <ModelOptimizeProgress
+ <OptimizeProgress
key={`${modelPath}:${artifacts?.optimizeStatus}`}
- modelUploadId={modelIdFromPath(modelPath) ?? ""}
- queued={artifacts?.optimizeStatus !== "Processing"}
+ queued={optimizeQueued}
+ onCancel={onCancelWait}
+ cancelling={actionBusy}
/>
</div>
)}
diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsx
index 85ce2fadbc..1f6adbade1 100644
--- a/apps/erp/app/root.tsx
+++ b/apps/erp/app/root.tsx
@@ -12,17 +12,17 @@ import {
OperatingSystemContextProvider,
Toaster,
TooltipProvider,
- useMode,
- useMount
+ useMode
} from "@carbon/react";
import { RootErrorBoundary } from "@carbon/react/ErrorBoundary";
import type { Theme } from "@carbon/utils";
import { getPreferenceHeaders, modeValidator, themes } from "@carbon/utils";
import { faviconLinks } from "@carbon/utils/favicon";
import { I18nProvider } from "@react-aria/i18n";
-import { QueryClient } from "@tanstack/react-query";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Analytics } from "@vercel/analytics/react";
import type React from "react";
+import { useState } from "react";
import type {
ActionFunctionArgs,
LinksFunction,
@@ -249,32 +249,44 @@ export default function App() {
const appLanguage = resolveLanguage(prefs.locale);
const mode = useMode();
- useMount(() => {
- if (!window.clientCache) {
- window.clientCache = new QueryClient({
- defaultOptions: {
- queries: {
- gcTime: Infinity,
- refetchOnWindowFocus: false,
- staleTime: Infinity
- }
+ // One client for both consumers: the imperative `window.clientCache`
+ // read-through convention (clientLoader/cachedApiQuery) and hook-based
+ // useQuery (e.g. the viewer's useOptimizedModel) via the provider below.
+ // Created in a state initializer (not useMount) so the provider has it on
+ // first render; per-query options override the infinite defaults.
+ const [queryClient] = useState(() => {
+ if (typeof window !== "undefined" && window.clientCache) {
+ return window.clientCache;
+ }
+ const client = new QueryClient({
+ defaultOptions: {
+ queries: {
+ gcTime: Infinity,
+ refetchOnWindowFocus: false,
+ staleTime: Infinity
}
- });
+ }
+ });
+ if (typeof window !== "undefined") {
+ window.clientCache = client;
}
+ return client;
});
return (
- <OperatingSystemContextProvider platform={prefs.platform}>
- <LocaleProvider locale={appLanguage} catalog={linguiCatalog}>
- <I18nProvider locale={prefs.locale}>
- <TooltipProvider delayDuration={200}>
- <Document mode={mode} theme={theme} lang={appLanguage} env={env}>
- <Outlet />
- </Document>
- </TooltipProvider>
- </I18nProvider>
- </LocaleProvider>
- </OperatingSystemContextProvider>
+ <QueryClientProvider client={queryClient}>
+ <OperatingSystemContextProvider platform={prefs.platform}>
+ <LocaleProvider locale={appLanguage} catalog={linguiCatalog}>
+ <I18nProvider locale={prefs.locale}>
+ <TooltipProvider delayDuration={200}>
+ <Document mode={mode} theme={theme} lang={appLanguage} env={env}>
+ <Outlet />
+ </Document>
+ </TooltipProvider>
+ </I18nProvider>
+ </LocaleProvider>
+ </OperatingSystemContextProvider>
+ </QueryClientProvider>
);
}
diff --git a/apps/erp/app/routes/api+/model.optimize-cancel.ts b/apps/erp/app/routes/api+/model.optimize-cancel.ts
index d27ecbc203..e1c5453399 100644
--- a/apps/erp/app/routes/api+/model.optimize-cancel.ts
+++ b/apps/erp/app/routes/api+/model.optimize-cancel.ts
@@ -8,10 +8,10 @@ import { data } from "react-router";
// 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.
+// Employee-level like reoptimize — cancelling your own preview generation
+// is part of viewing, not part editing.
export async function action({ request }: ActionFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- update: "parts"
- });
+ const { client, companyId } = await requirePermissions(request, {});
const formData = await request.formData();
const modelUploadId = formData.get("modelUploadId") as string | null;
diff --git a/apps/erp/app/routes/api+/model.reoptimize.ts b/apps/erp/app/routes/api+/model.reoptimize.ts
index 63f2b2ecbb..ead4c96e4b 100644
--- a/apps/erp/app/routes/api+/model.reoptimize.ts
+++ b/apps/erp/app/routes/api+/model.reoptimize.ts
@@ -6,10 +6,10 @@ import { data } from "react-router";
// Re-fires the eager optimise for an already-uploaded model — the raw still lives
// in `temp-staging`, so no re-upload is needed. Backs the viewer's "Retry" action
// when a model settled with no GLB (optimise failed / was skipped).
+// Any authenticated employee may fire it: the preview auto-generates on
+// view (viewing is the intent), which must not require part-edit rights.
export async function action({ request }: ActionFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {
- update: "parts"
- });
+ const { client, companyId, userId } = await requirePermissions(request, {});
const formData = await request.formData();
const modelUploadId = formData.get("modelUploadId") as string | null;
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index aaa7bfeb26..795b797040 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -57,6 +57,8 @@ import {
MODEL_RAW_KEEP_MAX_BYTES
} from "@carbon/utils";
import { ModelPreview } from "@carbon/viewer/model-preview";
+import { OptimizeProgress } from "@carbon/viewer/optimize-progress";
+import { useOptimizedModel } from "@carbon/viewer/use-optimized-model";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestSingleResponse } from "@supabase/supabase-js";
import { Suspense, useEffect, useMemo, useState } from "react";
@@ -140,7 +142,6 @@ import {
} from "./components/Step";
import { TableSkeleton } from "./components/TableSkeleton";
import { useFiles } from "./hooks/useFiles";
-import { modelIdFromPath, useModelArtifacts } from "./hooks/useModelArtifacts";
import { useOperation } from "./hooks/useOperation";
const log = getLogger("mes", "job-operation");
@@ -325,19 +326,14 @@ export const JobOperation = ({
const modelPath = operation.itemModelPath ?? job.modelPath ?? null;
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();
- };
+ awaitingModel: modelPending,
+ showOptimizeProgress,
+ optimizeQueued,
+ retry: onModelRetry,
+ retryLabel: modelRetryLabel,
+ cancel: onModelCancel,
+ actionBusy: modelActionBusy
+ } = useOptimizedModel({ modelPath, companyId });
const fetcher = useFetcher<Result>();
@@ -1767,7 +1763,7 @@ export const JobOperation = ({
</ScrollArea>
</TabsContent>
<TabsContent value="model">
- <div className="w-full h-[calc(100dvh-var(--header-height)*2)] p-0">
+ <div className="relative w-full h-[calc(100dvh-var(--header-height)*2)] p-0">
{modelPath ? (
<ModelPreview
key={modelPath}
@@ -1797,11 +1793,7 @@ export const JobOperation = ({
mode={mode}
className="rounded-none"
onRetry={onModelRetry}
- retryLabel={
- artifacts?.optimizeStatus === "Failed"
- ? "Retry"
- : "Load Preview"
- }
+ retryLabel={modelRetryLabel}
/>
) : (
<div className="flex h-full w-full items-center justify-center">
@@ -1810,6 +1802,16 @@ export const JobOperation = ({
</p>
</div>
)}
+ {showOptimizeProgress && (
+ <div className="absolute inset-0 z-30 flex items-center justify-center bg-background/95 p-6">
+ <OptimizeProgress
+ key={`${modelPath}:${artifacts?.optimizeStatus}`}
+ queued={optimizeQueued}
+ onCancel={onModelCancel}
+ cancelling={modelActionBusy}
+ />
+ </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
deleted file mode 100644
index 5ef5534582..0000000000
--- a/apps/mes/app/components/JobOperation/hooks/useModelArtifacts.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-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.
-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
- // 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 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);
- 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);
- 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);
- 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) — 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) {
- clearInterval(timer);
- setPending(false);
- return;
- }
- load(url);
- }, 3000);
-
- return () => clearInterval(timer);
- }, [modelUploadId, load, reloadKey]);
-
- return {
- artifacts: fetcher.data,
- pending,
- retry: () => setReloadKey((k) => k + 1)
- };
-}
diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsx
index 9f285d2d50..4c30a71ae7 100644
--- a/apps/mes/app/root.tsx
+++ b/apps/mes/app/root.tsx
@@ -19,8 +19,10 @@ import type { Theme } from "@carbon/utils";
import { getPreferenceHeaders, modeValidator, themes } from "@carbon/utils";
import { faviconLinks } from "@carbon/utils/favicon";
import { I18nProvider } from "@react-aria/i18n";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Analytics } from "@vercel/analytics/react";
import type React from "react";
+import { useState } from "react";
import type {
ActionFunctionArgs,
LoaderFunctionArgs,
@@ -232,18 +234,31 @@ export default function App() {
/* Dark/Light Mode */
const mode = useMode();
+ // Backs hook-based useQuery (the viewer's useOptimizedModel); MES has no
+ // clientLoader cache convention, so this client exists only for hooks.
+ const [queryClient] = useState(
+ () =>
+ new QueryClient({
+ defaultOptions: {
+ queries: { refetchOnWindowFocus: false }
+ }
+ })
+ );
+
return (
- <OperatingSystemContextProvider platform={prefs.platform}>
- <LocaleProvider locale={appLanguage} catalog={linguiCatalog}>
- <I18nProvider locale={prefs.locale}>
- <TooltipProvider delayDuration={200}>
- <Document mode={mode} theme={theme} lang={appLanguage} env={env}>
- <Outlet />
- </Document>
- </TooltipProvider>
- </I18nProvider>
- </LocaleProvider>
- </OperatingSystemContextProvider>
+ <QueryClientProvider client={queryClient}>
+ <OperatingSystemContextProvider platform={prefs.platform}>
+ <LocaleProvider locale={appLanguage} catalog={linguiCatalog}>
+ <I18nProvider locale={prefs.locale}>
+ <TooltipProvider delayDuration={200}>
+ <Document mode={mode} theme={theme} lang={appLanguage} env={env}>
+ <Outlet />
+ </Document>
+ </TooltipProvider>
+ </I18nProvider>
+ </LocaleProvider>
+ </OperatingSystemContextProvider>
+ </QueryClientProvider>
);
}
diff --git a/apps/mes/app/routes/api+/model.optimize-cancel.ts b/apps/mes/app/routes/api+/model.optimize-cancel.ts
new file mode 100644
index 0000000000..33794046e6
--- /dev/null
+++ b/apps/mes/app/routes/api+/model.optimize-cancel.ts
@@ -0,0 +1,52 @@
+import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+
+// Cancels an in-flight (or stuck) eager optimise — backs the model tab's
+// progress Cancel (parity with the ERP api+/model.optimize-cancel route).
+// Stamps the row Failed so the viewer settles immediately, and best-effort
+// cancels the assembler job so the waiting Inngest run fails non-retriably.
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {});
+
+ 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 });
+ }
+
+ 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/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index dad8fb25bf..5b9bb4c5ea 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}`),
+ modelOptimizeCancel: `${api}/model/optimize-cancel`,
modelReoptimize: `${api}/model/reoptimize`,
pickedAllocation: (jobMaterialId: string) =>
generatePath(`${api}/picked-allocation?jobMaterialId=${jobMaterialId}`),
diff --git a/apps/mes/package.json b/apps/mes/package.json
index fc47d7536e..24d5176283 100644
--- a/apps/mes/package.json
+++ b/apps/mes/package.json
@@ -3,6 +3,7 @@
"type": "module",
"dependencies": {
"@carbon/auth": "workspace:*",
+ "@tanstack/react-query": "5.97.0",
"@carbon/database": "workspace:*",
"@carbon/documents": "workspace:*",
"@carbon/ee": "workspace:*",
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 9ceeaa9d16..2f0da09c79 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -13493,7 +13493,6 @@ msgid "Variance in outside processing costs"
msgstr "Varianza en los costos de procesamiento externo"
msgid "Variance only"
-msgstr "Solo con variación"
msgstr "Solo varianza"
msgid "VAT Number"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 6dfb8abb2a..149f774e1a 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -13493,7 +13493,6 @@ msgid "Variance in outside processing costs"
msgstr "Écart dans les coûts de traitement externe"
msgid "Variance only"
-msgstr "Écart uniquement"
msgstr "Écarts uniquement"
msgid "VAT Number"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index e3fae53901..5070d624fd 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -13493,7 +13493,6 @@ msgid "Variance in outside processing costs"
msgstr "बाहरी प्रसंस्करण लागत में विचरण"
msgid "Variance only"
-msgstr "केवल विचरण"
msgstr "केवल भिन्नता"
msgid "VAT Number"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 5cf6d43b4b..bf0be04e88 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -6187,7 +6187,6 @@ msgid "In stock"
msgstr "Disponibile"
msgid "In stock only"
-msgstr "Solo disponibili"
msgstr "Solo in giacenza"
msgid "In the loop together"
@@ -13494,7 +13493,6 @@ msgid "Variance in outside processing costs"
msgstr "Varianza nei costi di lavorazione esterna"
msgid "Variance only"
-msgstr "Solo varianze"
msgstr "Solo scostamento"
msgid "VAT Number"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 730d90b8fa..8380c5a935 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -6187,7 +6187,6 @@ msgid "In stock"
msgstr "在庫あり"
msgid "In stock only"
-msgstr "在庫ありのみ"
msgstr "在庫のみ"
msgid "In the loop together"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 22a6a183e0..0ad235c117 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -6187,7 +6187,6 @@ msgid "In stock"
msgstr "재고 있음"
msgid "In stock only"
-msgstr "재고가 있는 항목만"
msgstr "재고만"
msgid "In the loop together"
@@ -13494,7 +13493,6 @@ msgid "Variance in outside processing costs"
msgstr "외주 가공비 차이"
msgid "Variance only"
-msgstr "차이가 있는 항목만"
msgstr "편차만"
msgid "VAT Number"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index eba7cdb5d1..e6855b18d0 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -6187,7 +6187,6 @@ msgid "In stock"
msgstr "W magazynie"
msgid "In stock only"
-msgstr "Tylko na stanie"
msgstr "Tylko w magazynie"
msgid "In the loop together"
@@ -13494,7 +13493,6 @@ msgid "Variance in outside processing costs"
msgstr "Odchylenie w kosztach przetwarzania zewnętrznego"
msgid "Variance only"
-msgstr "Tylko z odchyleniem"
msgstr "Tylko wariancja"
msgid "VAT Number"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 2d3739eb1e..f0e4393b5b 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -6187,7 +6187,6 @@ msgid "In stock"
msgstr "Em estoque"
msgid "In stock only"
-msgstr "Somente em estoque"
msgstr "Apenas em estoque"
msgid "In the loop together"
@@ -13494,7 +13493,6 @@ msgid "Variance in outside processing costs"
msgstr "Variância em custos de processamento externo"
msgid "Variance only"
-msgstr "Somente com variação"
msgstr "Apenas variância"
msgid "VAT Number"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index eed83a3c9d..2c325fb34f 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -13493,7 +13493,6 @@ msgid "Variance in outside processing costs"
msgstr "Расхождение в затратах на внешнюю обработку"
msgid "Variance only"
-msgstr "Только с расхождениями"
msgstr "Только отклонения"
msgid "VAT Number"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 3e6f8e19d5..cdbeb19930 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -6187,7 +6187,6 @@ msgid "In stock"
msgstr "Stokta"
msgid "In stock only"
-msgstr "Sadece stokta olanlar"
msgstr "Yalnızca stokta"
msgid "In the loop together"
@@ -13494,7 +13493,6 @@ msgid "Variance in outside processing costs"
msgstr "Dış işleme maliyetlerinde varyans"
msgid "Variance only"
-msgstr "Sadece farkı olanlar"
msgstr "Yalnızca fark"
msgid "VAT Number"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index c3388c6b8d..6e9b6ff3d4 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -6187,7 +6187,6 @@ msgid "In stock"
msgstr "有库存"
msgid "In stock only"
-msgstr "仅显示有库存"
msgstr "仅库存"
msgid "In the loop together"
@@ -13494,7 +13493,6 @@ msgid "Variance in outside processing costs"
msgstr "外部加工成本的差异"
msgid "Variance only"
-msgstr "仅显示有差异"
msgstr "仅差异"
msgid "VAT Number"
diff --git a/packages/viewer/package.json b/packages/viewer/package.json
index 79b3f63979..46007733f6 100644
--- a/packages/viewer/package.json
+++ b/packages/viewer/package.json
@@ -2,6 +2,8 @@
"name": "@carbon/viewer",
"dependencies": {
"@carbon/react": "workspace:*",
+ "@carbon/utils": "workspace:*",
+ "@tanstack/react-query": "5.97.0",
"@react-three/drei": "9.122.0",
"@react-three/fiber": "8.18.0",
"occt-import-js": "0.0.23",
@@ -25,7 +27,9 @@
".": "./src/index.ts",
"./steps": "./src/steps.ts",
"./canvas": "./src/ModelCanvas.tsx",
- "./model-preview": "./src/ModelPreview.tsx"
+ "./model-preview": "./src/ModelPreview.tsx",
+ "./optimize-progress": "./src/OptimizeProgress.tsx",
+ "./use-optimized-model": "./src/useOptimizedModel.ts"
},
"peerDependencies": {
"react": "catalog:",
diff --git a/apps/erp/app/components/ModelOptimizeProgress.tsx b/packages/viewer/src/OptimizeProgress.tsx
similarity index 79%
rename from apps/erp/app/components/ModelOptimizeProgress.tsx
rename to packages/viewer/src/OptimizeProgress.tsx
index 6534261262..ab16ffc2a4 100644
--- a/apps/erp/app/components/ModelOptimizeProgress.tsx
+++ b/packages/viewer/src/OptimizeProgress.tsx
@@ -1,8 +1,6 @@
import { BarProgress, Button, cn } from "@carbon/react";
import { useEffect, useState } from "react";
import { LuCheck, LuLoaderCircle } from "react-icons/lu";
-import { useFetcher } from "react-router";
-import { path } from "~/utils/path";
const STEPS = [
"Reading the CAD file",
@@ -22,21 +20,21 @@ function formatElapsed(seconds: number) {
}
/**
- * Staged checklist for a running model optimise (same visual language as
- * ModelConvertProgress). Shown while the eager optimise runs and no preview
- * tier can render. Cancel stamps the row Failed and cancels the assembler job.
+ * Staged checklist for a running model optimise — presentational; the host
+ * wires Cancel to its own optimise-cancel route (ERP CadModel, MES model tab).
*/
-export function ModelOptimizeProgress({
- modelUploadId,
+export function OptimizeProgress({
queued = false,
+ onCancel,
+ cancelling = false,
className
}: {
- modelUploadId: string;
/** Job accepted but not picked up yet — first step reads as waiting. */
queued?: boolean;
+ onCancel?: () => void;
+ cancelling?: boolean;
className?: string;
}) {
- const cancelFetcher = useFetcher<{ success: boolean }>();
const [elapsed, setElapsed] = useState(0);
useEffect(() => {
@@ -100,21 +98,17 @@ export function ModelOptimizeProgress({
<p className="text-xs tabular-nums text-muted-foreground">
{formatElapsed(elapsed)}
</p>
- <cancelFetcher.Form
- method="post"
- action={path.to.api.modelOptimizeCancel}
- >
- <input type="hidden" name="modelUploadId" value={modelUploadId} />
+ {onCancel && (
<Button
- type="submit"
size="sm"
variant="ghost"
- isLoading={cancelFetcher.state !== "idle"}
- isDisabled={cancelFetcher.state !== "idle"}
+ onClick={onCancel}
+ isLoading={cancelling}
+ isDisabled={cancelling}
>
Cancel
</Button>
- </cancelFetcher.Form>
+ )}
</div>
</div>
);
diff --git a/packages/viewer/src/useOptimizedModel.ts b/packages/viewer/src/useOptimizedModel.ts
new file mode 100644
index 0000000000..e7ad4d0bfb
--- /dev/null
+++ b/packages/viewer/src/useOptimizedModel.ts
@@ -0,0 +1,246 @@
+import {
+ MODEL_RAW_KEEP_MAX_BYTES,
+ modelPathOptimizeFormat
+} from "@carbon/utils";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { WASM_RAW_ENABLED } from "./ModelPreview";
+
+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;
+ /** As-uploaded raw bytes (originalSize; older rows fall back to size). */
+ 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.
+ * Retained raws are compacted in place (`${id}.step` → `${id}.step.zst`); the
+ * `.zst` wrapper is peeled before the source extension.
+ */
+export function modelIdFromPath(modelPath: string | null): string | null {
+ if (!modelPath) return null;
+ let base = modelPath.split("/").pop() ?? "";
+ if (base.toLowerCase().endsWith(".zst")) base = base.slice(0, -4);
+ return base.replace(/\.[^.]+$/, "") || null;
+}
+
+const POLL_MS = 3000;
+// `Idle`/null is the brief window before a just-triggered job starts (or a
+// non-mesh upload that never optimises) — poll it only for a short grace
+// window before settling.
+const GRACE_POLLS = 8;
+
+// Same routes in ERP and MES — overridable if a host ever diverges.
+const DEFAULT_PATHS = {
+ artifacts: (modelUploadId: string) => `/api/model/artifacts/${modelUploadId}`,
+ reoptimize: "/api/model/reoptimize",
+ cancel: "/api/model/optimize-cancel"
+};
+
+async function postModelAction(action: string, modelUploadId: string) {
+ const body = new FormData();
+ body.append("modelUploadId", modelUploadId);
+ await fetch(action, { method: "POST", body }).catch(() => {
+ // Best-effort — polling reflects whatever actually happened server-side.
+ });
+}
+
+/**
+ * The full optimise lifecycle for a model preview, shared by ERP CadModel and
+ * the MES model tab so behavior is identical (hosts differ only in chrome —
+ * upload/delete exist in ERP only):
+ *
+ * - TanStack Query polls the artifacts route while an optimise is genuinely in
+ * flight (and through a short grace window otherwise); results are cached and
+ * deduped across viewers of the same model.
+ * - Viewing IS the intent: a model with no artifact and no optimise in flight
+ * auto-fires the optimise on mount. A Failed status never auto-refires (that
+ * would loop a deterministic failure and override an explicit cancel) — the
+ * settled card's Retry covers it.
+ * - retry() re-fires the optimise and resumes polling via invalidation.
+ * - cancel() stamps the row Failed and cancels the assembler job.
+ */
+export function useOptimizedModel({
+ modelPath,
+ companyId,
+ /** A just-dropped local File (ERP upload flow) — counts toward the raw tier. */
+ file = null,
+ /** Disables the auto-fire (and retry/cancel posts) — e.g. no session. */
+ enabled = true,
+ paths = DEFAULT_PATHS
+}: {
+ modelPath: string | null;
+ companyId: string;
+ file?: File | null;
+ enabled?: boolean;
+ paths?: typeof DEFAULT_PATHS;
+}) {
+ const queryClient = useQueryClient();
+ const modelUploadId = modelIdFromPath(modelPath);
+ const gracePolls = useRef(0);
+
+ const query = useQuery<ModelArtifacts>({
+ queryKey: ["model-artifacts", companyId, modelUploadId],
+ enabled: Boolean(modelUploadId),
+ queryFn: async () => {
+ const res = await fetch(paths.artifacts(modelUploadId as string));
+ if (!res.ok) throw new Error(`artifacts ${res.status}`);
+ return res.json();
+ },
+ staleTime: 0,
+ gcTime: 5 * 60 * 1000,
+ refetchInterval: (q) => {
+ const d = q.state.data;
+ if (!d) return POLL_MS;
+ if (d.optimizedModelPath || d.glbPath) return false;
+ const inFlight =
+ d.optimizeStatus === "Queued" || d.optimizeStatus === "Processing";
+ if (inFlight) {
+ gracePolls.current = 0;
+ return POLL_MS;
+ }
+ // 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
+ // "click Load Preview twice" bug in the hand-rolled version.
+ if (gracePolls.current < GRACE_POLLS) {
+ gracePolls.current += 1;
+ return POLL_MS;
+ }
+ return false;
+ }
+ });
+
+ const artifacts = query.data;
+ const hasInteractive = Boolean(
+ artifacts?.optimizedModelPath || artifacts?.glbPath
+ );
+ const optimizeInFlight =
+ artifacts?.optimizeStatus === "Queued" ||
+ artifacts?.optimizeStatus === "Processing";
+ const rawRenderable =
+ WASM_RAW_ENABLED &&
+ Boolean(
+ (artifacts?.rawPath &&
+ (artifacts.size ?? 0) <= MODEL_RAW_KEEP_MAX_BYTES) ||
+ (file && file.size <= MODEL_RAW_KEEP_MAX_BYTES)
+ );
+
+ // Bridges the fire -> job-visible gap: the row status takes a couple of
+ // polls to flip, and without this the progress overlay wouldn't appear
+ // until then. Cleared on handover (or a 15s safety timeout).
+ const [optimisticOptimize, setOptimisticOptimize] = useState(false);
+ useEffect(() => {
+ if (!optimisticOptimize) return;
+ if (optimizeInFlight || hasInteractive) {
+ setOptimisticOptimize(false);
+ return;
+ }
+ const timeout = setTimeout(() => setOptimisticOptimize(false), 15000);
+ return () => clearTimeout(timeout);
+ }, [optimisticOptimize, optimizeInFlight, hasInteractive]);
+
+ const [actionBusy, setActionBusy] = useState(false);
+
+ const fireOptimize = useCallback(
+ async (id: string) => {
+ gracePolls.current = 0;
+ setOptimisticOptimize(true);
+ setActionBusy(true);
+ await postModelAction(paths.reoptimize, id);
+ setActionBusy(false);
+ await queryClient.invalidateQueries({
+ queryKey: ["model-artifacts", companyId, id]
+ });
+ },
+ [companyId, paths.reoptimize, queryClient]
+ );
+
+ // Auto-fire: fires once per model per mount, on the first artifacts response
+ // showing nothing to render and nothing in flight.
+ const autoFiredRef = useRef<string | null>(null);
+ useEffect(() => {
+ if (!enabled || !artifacts || !modelUploadId || !modelPath) return;
+ if (autoFiredRef.current === modelUploadId) return;
+ if (
+ hasInteractive ||
+ optimizeInFlight ||
+ artifacts.optimizeStatus === "Failed"
+ )
+ return;
+ if (!modelPathOptimizeFormat(modelPath)) return;
+ autoFiredRef.current = modelUploadId;
+ void fireOptimize(modelUploadId);
+ }, [
+ enabled,
+ artifacts,
+ modelUploadId,
+ modelPath,
+ hasInteractive,
+ optimizeInFlight,
+ fireOptimize
+ ]);
+
+ const retry = useCallback(() => {
+ if (!enabled || !modelUploadId) return;
+ void fireOptimize(modelUploadId);
+ }, [enabled, modelUploadId, fireOptimize]);
+
+ const cancel = useCallback(async () => {
+ if (!enabled || !modelUploadId) return;
+ setActionBusy(true);
+ await postModelAction(paths.cancel, modelUploadId);
+ setActionBusy(false);
+ await queryClient.invalidateQueries({
+ queryKey: ["model-artifacts", companyId, modelUploadId]
+ });
+ }, [enabled, modelUploadId, companyId, paths.cancel, queryClient]);
+
+ // "A GLB is genuinely on its way" — the viewer renders this as the
+ // preparing state; a settled model must not wear it.
+ const awaitingModel =
+ (query.isLoading && Boolean(modelUploadId)) ||
+ (optimizeInFlight && !hasInteractive) ||
+ Boolean(file);
+
+ // Staged progress overlay: an optimise is running and nothing else can
+ // render. When the raw tier renders, the optimise runs silently behind it
+ // and the GLB swaps in on success.
+ const showOptimizeProgress =
+ (optimizeInFlight || optimisticOptimize) &&
+ !hasInteractive &&
+ !rawRenderable;
+
+ return {
+ artifacts,
+ modelUploadId,
+ awaitingModel,
+ hasInteractive,
+ rawRenderable,
+ optimizeInFlight,
+ showOptimizeProgress,
+ /** Overlay's first step reads as waiting until the job is picked up. */
+ optimizeQueued: artifacts?.optimizeStatus !== "Processing",
+ retry,
+ retryLabel:
+ artifacts?.optimizeStatus === "Failed" ? "Retry" : "Load Preview",
+ cancel,
+ actionBusy
+ };
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d2307a8d93..cd476a25cd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -694,7 +694,7 @@ importers:
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
'@react-router/serve':
specifier: 'catalog:'
@@ -739,7 +739,7 @@ importers:
'@vercel/react-router':
specifier: 'catalog:'
'@visx/responsive':
specifier: 2.17.0
version: 2.17.0([email protected])
@@ -784,7 +784,7 @@ importers:
inngest:
specifier: ^3.52.7
intl-parse-accept-language:
specifier: 'catalog:'
version: 1.0.0
@@ -974,16 +974,16 @@ importers:
'@lingui/vite-plugin':
specifier: 'catalog:'
'@react-router/dev':
specifier: 'catalog:'
'@tailwindcss/typography':
specifier: 'catalog:'
version: 0.5.19([email protected])
'@tailwindcss/vite':
specifier: 'catalog:'
'@types/d3':
specifier: 7.4.3
version: 7.4.3
@@ -1043,13 +1043,13 @@ importers:
version: 5.8.3
vite:
specifier: 'catalog:'
vite-plugin-babel-macros:
specifier: 'catalog:'
vitest:
specifier: 'catalog:'
apps/mes:
dependencies:
@@ -1133,7 +1133,7 @@ importers:
'@lingui/vite-plugin':
specifier: 'catalog:'
'@nanostores/react':
specifier: 'catalog:'
@@ -1145,10 +1145,10 @@ importers:
'@react-router/dev':
specifier: 'catalog:'
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
'@react-router/serve':
specifier: 'catalog:'
@@ -1169,7 +1169,10 @@ importers:
version: 0.5.19([email protected])
'@tailwindcss/vite':
specifier: 'catalog:'
+ '@tanstack/react-query':
+ specifier: 5.97.0
+ version: 5.97.0([email protected])
'@tiptap/core':
specifier: 'catalog:'
version: 2.27.2(@tiptap/[email protected])
@@ -1211,7 +1214,7 @@ importers:
'@vercel/react-router':
specifier: 'catalog:'
'@xyflow/react':
specifier: 12.10.2
@@ -1329,13 +1332,13 @@ importers:
version: 5.8.3
vite:
specifier: 'catalog:'
vite-plugin-babel-macros:
specifier: 'catalog:'
vitest:
specifier: 'catalog:'
wait-on:
specifier: 'catalog:'
version: 7.2.0
@@ -3470,12 +3473,18 @@ importers:
'@carbon/react':
specifier: workspace:*
version: link:../react
+ '@carbon/utils':
+ specifier: workspace:*
+ version: link:../utils
'@react-three/drei':
specifier: 9.122.0
'@react-three/fiber':
specifier: 8.18.0
+ '@tanstack/react-query':
+ specifier: 5.97.0
+ version: 5.97.0([email protected])
occt-import-js:
specifier: 0.0.23
version: 0.0.23
@@ -27052,44 +27061,6 @@ snapshots:
- dependencies:
- '@bufbuild/protobuf': 2.11.0
- '@inngest/ai': 0.1.7
- '@jpwilliams/waitgroup': 2.1.1
- '@opentelemetry/api': 1.9.0
- '@opentelemetry/auto-instrumentations-node': 0.72.0(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))
- '@opentelemetry/context-async-hooks': 2.6.1(@opentelemetry/[email protected])
- '@opentelemetry/exporter-trace-otlp-http': 0.214.0(@opentelemetry/[email protected])
- '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.6.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 2.6.1(@opentelemetry/[email protected])
- '@standard-schema/spec': 1.1.0
- '@traceloop/instrumentation-anthropic': 0.20.0
- '@types/debug': 4.1.13
- '@types/ms': 2.1.0
- canonicalize: 1.0.8
- chalk: 4.1.2
- cross-fetch: 4.1.0([email protected])
- debug: 4.4.3([email protected])
- hash.js: 1.1.7
- json-stringify-safe: 5.0.1
- ms: 2.1.3
- serialize-error-cjs: 0.1.4
- strip-ansi: 5.2.0
- temporal-polyfill: 0.2.5
- ulid: 2.4.0
- zod: 3.25.76
- optionalDependencies:
- express: 4.22.1
- hono: 4.12.14
- typescript: 5.8.3
- transitivePeerDependencies:
- - '@opentelemetry/core'
- - encoding
- - supports-color
-
dependencies:
'@bufbuild/protobuf': 2.11.0