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
fix(assembly): Add Step lands inside an open sub-assembly; parts fade in reliably and fit authored durations
aashuca6db1f113a7
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.tsindex 026b18ddf0..574d88ae8e 100644--- a/apps/erp/app/modules/production/production.models.ts+++ b/apps/erp/app/modules/production/production.models.ts@@ -1396,60 +1396,71 @@ const optionalTiptapDescription = zfdval === undefined || val === "" ? undefined : toTiptapDoc(val));-export const assemblyInstructionStepValidator = z- .object({- id: zfd.text(z.string().optional()),- assemblyInstructionId: z.string().min(1),- title: zfd.text(z.string().optional()),- // Typed-step fields mirror jobOperationStep so steps can eventually be- // copied into job operations- type: zfd.text(z.enum(procedureStepType).optional()),- description: optionalTiptapDescription,- required: zfd.checkbox(),- unitOfMeasureCode: zfd.text(z.string().optional()),- minValue: zfd.numeric(z.number().min(0).optional()),- maxValue: zfd.numeric(z.number().min(0).optional()),- listValues: z.array(z.string()).optional(),- componentNodeIds: jsonField(z.array(z.string()).optional()),- motion: jsonField(motionSchema.optional()),- camera: jsonField(cameraSchema.nullable().optional()),- fastener: jsonField(fastenerSchema.nullable().optional()),- durationSeconds: zfd.numeric(z.number().positive().optional())- })- .superRefine((data, ctx) => {- if (data.type === "Measurement" && !data.unitOfMeasureCode) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ["unitOfMeasureCode"],- message: "Unit of measure is required"- });- }- if (- data.type === "List" &&- !(- Array.isArray(data.listValues) &&- data.listValues.length > 0 &&- data.listValues.every((option) => option.trim() !== "")- )- ) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ["listValues"],- message: "List options are required"- });- }- if (- data.minValue != null &&- data.maxValue != null &&- data.maxValue < data.minValue- ) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ["maxValue"],- message: "Maximum value must be greater than or equal to minimum value"- });- }- });+const assemblyInstructionStepFields = z.object({+ id: zfd.text(z.string().optional()),+ assemblyInstructionId: z.string().min(1),+ title: zfd.text(z.string().optional()),+ // Typed-step fields mirror jobOperationStep so steps can eventually be+ // copied into job operations+ type: zfd.text(z.enum(procedureStepType).optional()),+ description: optionalTiptapDescription,+ required: zfd.checkbox(),+ unitOfMeasureCode: zfd.text(z.string().optional()),+ minValue: zfd.numeric(z.number().min(0).optional()),+ maxValue: zfd.numeric(z.number().min(0).optional()),+ listValues: z.array(z.string()).optional(),+ componentNodeIds: jsonField(z.array(z.string()).optional()),+ motion: jsonField(motionSchema.optional()),+ camera: jsonField(cameraSchema.nullable().optional()),+ fastener: jsonField(fastenerSchema.nullable().optional()),+ durationSeconds: zfd.numeric(z.number().positive().optional())+});++function refineAssemblyInstructionStep(+ data: z.infer<typeof assemblyInstructionStepFields>,+ ctx: z.RefinementCtx+) {+ if (data.type === "Measurement" && !data.unitOfMeasureCode) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["unitOfMeasureCode"],+ message: "Unit of measure is required"+ });+ }+ if (+ data.type === "List" &&+ !(+ Array.isArray(data.listValues) &&+ data.listValues.length > 0 &&+ data.listValues.every((option) => option.trim() !== "")+ )+ ) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["listValues"],+ message: "List options are required"+ });+ }+ if (+ data.minValue != null &&+ data.maxValue != null &&+ data.maxValue < data.minValue+ ) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["maxValue"],+ message: "Maximum value must be greater than or equal to minimum value"+ });+ }+}++export const assemblyInstructionStepValidator =+ assemblyInstructionStepFields.superRefine(refineAssemblyInstructionStep);++/** A new step; `parentStepId` adds it at the end of that sub-assembly. */+export const assemblyInstructionStepNewValidator = assemblyInstructionStepFields+ .extend({ parentStepId: zfd.text(z.string().optional()) })+ .superRefine(refineAssemblyInstructionStep);/*** Partial update for a step's viewer-authored motion path and/or camera pose,diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 5aeecf85d5..b61710b109 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -7287,24 +7287,51 @@ export async function invalidateAssemblyModelCache(.eq("id", modelUploadId);}+type AssemblyStepFields = {+ title?: string | null;+ type?: Database["public"]["Enums"]["procedureStepType"];+ description?: Json;+ required?: boolean;+ unitOfMeasureCode?: string | null;+ minValue?: number | null;+ maxValue?: number | null;+ listValues?: string[] | null;+ componentNodeIds?: string[];+ motion?: z.infer<typeof motionSchema>;+ camera?: z.infer<typeof cameraSchema> | null;+ fastener?: z.infer<typeof fastenerSchema> | null;+ durationSeconds?: number | null;+};++/** A new step's columns, shared by both insert paths. */+function newAssemblyStepColumns(data: AssemblyStepFields) {+ return {+ title: data.title ?? null,+ type: data.type ?? "Task",+ description: data.description ?? {},+ instructionText:+ data.description !== undefined+ ? tiptapToText(data.description as JSONContent) || null+ : null,+ required: data.required ?? false,+ unitOfMeasureCode:+ data.type === "Measurement" ? (data.unitOfMeasureCode ?? null) : null,+ minValue: data.type === "Measurement" ? (data.minValue ?? null) : null,+ maxValue: data.type === "Measurement" ? (data.maxValue ?? null) : null,+ listValues: data.type === "List" ? (data.listValues ?? null) : null,+ componentNodeIds: data.componentNodeIds ?? [],+ motion: (data.motion ?? { type: "none" }) as Json,+ camera: (data.camera ?? null) as Json | null,+ fastener: (data.fastener ?? null) as Json | null,+ durationSeconds: data.durationSeconds ?? null+ };+}+export async function upsertAssemblyInstructionStep(client: SupabaseClient<Database>,- data: {+ data: AssemblyStepFields & {id?: string;assemblyInstructionId: string;- title?: string | null;- type?: Database["public"]["Enums"]["procedureStepType"];- description?: Json;- required?: boolean;- unitOfMeasureCode?: string | null;- minValue?: number | null;- maxValue?: number | null;- listValues?: string[] | null;- componentNodeIds?: string[];- motion?: z.infer<typeof motionSchema>;- camera?: z.infer<typeof cameraSchema> | null;- fastener?: z.infer<typeof fastenerSchema> | null;- durationSeconds?: number | null;sortOrder?: number;companyId: string;createdBy: string;@@ -7370,24 +7397,7 @@ export async function upsertAssemblyInstructionStep(.from("assemblyInstructionStep").insert({assemblyInstructionId: data.assemblyInstructionId,- title: data.title ?? null,- type: data.type ?? "Task",- description: data.description ?? {},- instructionText:- data.description !== undefined- ? tiptapToText(data.description as JSONContent) || null- : null,- required: data.required ?? false,- unitOfMeasureCode:- data.type === "Measurement" ? (data.unitOfMeasureCode ?? null) : null,- minValue: data.type === "Measurement" ? (data.minValue ?? null) : null,- maxValue: data.type === "Measurement" ? (data.maxValue ?? null) : null,- listValues: data.type === "List" ? (data.listValues ?? null) : null,- componentNodeIds: data.componentNodeIds ?? [],- motion: (data.motion ?? { type: "none" }) as Json,- camera: (data.camera ?? null) as Json | null,- fastener: (data.fastener ?? null) as Json | null,- durationSeconds: data.durationSeconds ?? null,+ ...newAssemblyStepColumns(data),sortOrder: data.sortOrder ?? (await getNextStepSortOrder(client, data)),companyId: data.companyId,createdBy: data.createdBy@@ -7643,6 +7653,67 @@ export async function makeAssemblySubAssembly(});}+/**+ * Add a step at the end of the instruction, or at the end of the sub-assembly+ * `parentStepId` names (directly before its header).+ */+export async function insertAssemblyInstructionStep(+ db: Kysely<KyselyDatabase>,+ args: AssemblyStepFields & {+ assemblyInstructionId: string;+ parentStepId?: string;+ companyId: string;+ userId: string;+ }+) {+ const { assemblyInstructionId, parentStepId, companyId, userId } = args;+ return db.transaction().execute(async (trx) => {+ const before = await loadStepStructure(+ trx,+ companyId,+ assemblyInstructionId+ );+ if (+ parentStepId &&+ !before.find((s) => s.id === parentStepId)?.isSubAssembly+ ) {+ throw new Error("Sub-assembly not found");+ }++ const step = await trx+ .insertInto("assemblyInstructionStep")+ .values({+ assemblyInstructionId,+ companyId,+ ...newAssemblyStepColumns(args),+ sortOrder: before.length + 1,+ parentStepId: parentStepId ?? null,+ createdBy: userId+ })+ .returning(["id", "sortOrder", "componentNodeIds"])+ .executeTakeFirstOrThrow();++ const stepRow: StepStructureRow = {+ ...step,+ parentStepId: parentStepId ?? null,+ usedInStepId: null,+ isSubAssembly: false+ };+ const next = parentStepId+ ? before.flatMap((s) => (s.id === parentStepId ? [stepRow, s] : [s]))+ : [...before, stepRow];+ assertValidStepStructure(next);+ await saveStepStructure(trx, {+ companyId,+ userId,+ assemblyInstructionId,+ before: [...before, stepRow],+ next+ });+ return step.id;+ });+}+/*** Rename a sub-assembly and/or set the step that uses it (`null` = it joins the* main build). `undefined` leaves a field unchanged.diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsxindex 7a4d2275ab..95796ddd28 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx@@ -24,6 +24,7 @@ import {} from "@carbon/react";import type { AssemblyGraphIndex } from "@carbon/viewer";import {+ arrivalIndexByNode,describeStep,groupComponentNodeIds,synthesizeFallbackMotion@@ -90,6 +91,8 @@ type AssemblyInstructionExplorerProps = {ownNodeIds: string[];hiddenNodeIds: string[];onSetHiddenComponents: (nodeIds: string[]) => void;+ /** Header id of the open sub-assembly, which Add Step adds to. */+ openSubAssemblyId: string | null;};// Memoized: the parent route re-renders on every motion-drag frame@@ -115,7 +118,8 @@ function AssemblyInstructionExplorer({hasSelectedStep,ownNodeIds,hiddenNodeIds,- onSetHiddenComponents+ onSetHiddenComponents,+ openSubAssemblyId}: AssemblyInstructionExplorerProps) {const { id } = useParams();if (!id) throw new Error("Could not find id");@@ -373,9 +377,10 @@ function AssemblyInstructionExplorer({// Derive the viewer shape once — both stepTitles and searchText need it, and// toViewerStep otherwise runs twice per step per render.+ const viewerSteps = useMemo(() => steps.map(toViewerStep), [steps]);const viewerStepMap = useMemo(- () => new Map(steps.map((step) => [step.id, toViewerStep(step)])),- [steps]+ () => new Map(viewerSteps.map((step) => [step.id, step])),+ [viewerSteps]);// A sub-assembly is named by the author (it installs nothing to derive a@@ -429,16 +434,17 @@ function AssemblyInstructionExplorer({const onAddStep = () => {const formData = new FormData();formData.append("assemblyInstructionId", id);+ if (openSubAssemblyId) formData.append("parentStepId", openSubAssemblyId);// When components are selected, seed the new step with the components and a// basic synthesized insertion animation. Otherwise create an empty// process-only step. The title is left blank on purpose — it derives live// from the components (describeStep) everywhere it is displayed.if (selectedNodeIds.length > 0) {- // The new step appends after every existing step, so its obstacle world- // is everything those steps install ("none" fades in when blocked)+ // The new step comes last in its build, so its obstacle world is+ // everything that build already holds ("none" fades in when blocked)const present = new Set(- steps.flatMap((step) => step.componentNodeIds ?? [])+ arrivalIndexByNode(viewerSteps, openSubAssemblyId).keys());const motion = graphIndex? synthesizeFallbackMotion(graphIndex, selectedNodeIds, present)diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex c61ec999a4..fde0ef30a5 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -1,5 +1,5 @@{- "totalTools": 1560,+ "totalTools": 1561,"modules": 15,"tools": [{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},@@ -792,6 +792,7 @@{"name":"production_getWorkCenterRequiredAbilities","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"7418ea1fc0a7","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getWorkCenterReservationsRange","classification":"READ","paramCount":2,"schema":"99ea73b8e7a1","response":"a7e9bc09d2ab","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getWorkCenterShifts","classification":"READ","paramCount":1,"schema":"e94892850934","response":"2b4835f80e6c","injectAuth":"companyId","permission":"production:view","paginates":false},+ {"name":"production_insertAssemblyInstructionStep","classification":"WRITE","paramCount":1,"schema":"432e9ed9373b","response":"00404e686415","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create","paginates":false},{"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"fea224e085b1","response":"ad63dfd9d877","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},{"name":"production_invalidateAssemblyModelCache","classification":"DESTRUCTIVE","paramCount":1,"schema":"277f7d872d8c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_issueMaterial","classification":"WRITE","paramCount":7,"schema":"0408bd8c9bde","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},@@ -851,7 +852,7 @@{"name":"production_updateQuoteOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_upsertAssemblyComponentMapping","classification":"WRITE","paramCount":4,"schema":"9ed1f38ce764","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},{"name":"production_upsertAssemblyInstruction","classification":"WRITE","paramCount":4,"schema":"a1796f1bd347","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertAssemblyInstructionStep","classification":"WRITE","paramCount":16,"schema":"db59420ad99a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},+ {"name":"production_upsertAssemblyInstructionStep","classification":"WRITE","paramCount":1,"schema":"224cc2443995","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},{"name":"production_upsertAssemblyInstructionStepMaterial","classification":"WRITE","paramCount":5,"schema":"a21b4fac4b90","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},{"name":"production_upsertAssemblyInstructionStepSlide","classification":"WRITE","paramCount":9,"schema":"c6bc69cc2080","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},{"name":"production_upsertAssemblyInstructionStepTool","classification":"WRITE","paramCount":5,"schema":"d64500fd5c94","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.new.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.new.tsxindex 1c714a24b7..70dff3751f 100644--- a/apps/erp/app/routes/x+/assembly+/$id.steps.new.tsx+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.new.tsx@@ -2,20 +2,24 @@ import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validator } from "@carbon/form";+import { getLogger } from "@carbon/logger";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import {- assemblyInstructionStepValidator,- upsertAssemblyInstructionStep+ assemblyInstructionStepNewValidator,+ insertAssemblyInstructionStep} from "~/modules/production";import {logAssemblyStep,readAndLogFormData} from "~/modules/production/assembly-debug.server";+import { getDatabaseClient } from "~/services/database.server";++const logger = getLogger("erp", "assembly-step-new");export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyId, userId } = await requirePermissions(request, {+ const { companyId, userId } = await requirePermissions(request, {create: "production"});@@ -23,9 +27,9 @@ export async function action({ request, params }: ActionFunctionArgs) {if (!assemblyInstructionId) throw new Error("id is not found");const formData = await readAndLogFormData(request, "new.action");- const validation = await validator(assemblyInstructionStepValidator).validate(- formData- );+ const validation = await validator(+ assemblyInstructionStepNewValidator+ ).validate(formData);if (validation.error) {logAssemblyStep("new.validationError", { error: validation.error });@@ -38,25 +42,31 @@ export async function action({ request, params }: ActionFunctionArgs) {// biome-ignore lint/correctness/noUnusedVariables: id is never set on createconst { id, ...rest } = validation.data;- const create = await upsertAssemblyInstructionStep(client, {- ...rest,- companyId,- createdBy: userId- });- logAssemblyStep("new.result", {- createdId: create.data?.id ?? null,- componentNodeIds: rest.componentNodeIds,- error: create.error?.message ?? null- });- if (create.error) {+ try {+ const stepId = await insertAssemblyInstructionStep(getDatabaseClient(), {+ ...rest,+ assemblyInstructionId,+ companyId,+ userId+ });+ logAssemblyStep("new.result", {+ createdId: stepId,+ componentNodeIds: rest.componentNodeIds+ });+ return { success: true, id: stepId };+ } catch (err) {+ logger.error("Failed to insert assembly instruction step", {+ companyId,+ assemblyInstructionId,+ parentStepId: rest.parentStepId ?? null,+ error: err+ });return data({ success: false },await flash(request,- error(create.error, "Failed to insert assembly instruction step")+ error(err, "Failed to insert assembly instruction step")));}-- return { success: true, id: create.data?.id };}diff --git a/apps/erp/app/routes/x+/assembly+/$id.tsx b/apps/erp/app/routes/x+/assembly+/$id.tsxindex 4d38495eb5..9170061da5 100644--- a/apps/erp/app/routes/x+/assembly+/$id.tsx+++ b/apps/erp/app/routes/x+/assembly+/$id.tsx@@ -722,6 +722,7 @@ export default function AssemblyInstructionRoute() {ownNodeIds={selectedOwnNodeIds}hiddenNodeIds={selectedHiddenNodeIds}onSetHiddenComponents={onSetHiddenComponents}+ openSubAssemblyId={openSubAssemblyId}/>}content={diff --git a/packages/viewer/src/AssemblyPlayer.tsx b/packages/viewer/src/AssemblyPlayer.tsxindex 52c294789f..b094205885 100644--- a/packages/viewer/src/AssemblyPlayer.tsx+++ b/packages/viewer/src/AssemblyPlayer.tsx@@ -39,7 +39,7 @@ import {CARRY_IN_GLIDE_SECONDS,displayMotionForStep,naturalizeMotion,- stepTimelineSeconds+ stepClipTiming} from "./motion";import {arrivalIndexByNode,@@ -485,18 +485,19 @@ export const AssemblyPlayer = forwardRef<]);// --- Continuous timeline ---------------------------------------------- // A carry-in step also spends the glide bringing the unit in (unless the- // author set an explicit duration). Steps that don't play (a used- // sub-assembly's header, or outside an opened sub-assembly) take no time.+ // A carry-in step also spends the glide bringing the unit in. Steps that+ // don't play (a used sub-assembly's header, or outside an opened+ // sub-assembly) take no time.const segments = useMemo(() =>displaySteps.map((step, index) =>playable[index]- ? stepTimelineSeconds(step) +- ((carriedPartIds[index]?.length ?? 0) > 0 &&- !(step.durationSeconds && step.durationSeconds > 0)- ? CARRY_IN_GLIDE_SECONDS- : 0)+ ? stepClipTiming(+ step,+ (carriedPartIds[index]?.length ?? 0) > 0+ ? CARRY_IN_GLIDE_SECONDS+ : 0+ ).total: 0),[displaySteps, playable, carriedPartIds]@@ -1296,7 +1297,18 @@ function AssemblyScene({};}, []);- useEffect(() => {+ // Seated fade-in: a step installing parts without an animation fades them in+ // at the seated pose (see the fade effect below). While `fading`, the+ // visual-state pass gives those meshes the fade material; the frame loop+ // only drives its opacity.+ const fadeRef = useRef<{+ entries: { mesh: Mesh; fade: Material | Material[] }[];+ materials: Material[];+ seconds: number;+ fading: boolean;+ } | null>(null);++ const applyVisuals = useCallback(() => {const overrides = overridesRef.current;// Reset: everything visible with its original material@@ -1389,43 +1401,32 @@ function AssemblyScene({});}- // Isolate/focus: when a focus set is active, ONLY the focused components- // render — everything else hides so the selection can be inspected alone.- // Keep the focused node's ANCESTORS visible too: three.js visibility is- // inherited, and every glTF node (including the root wrapper and assembly- // groups) carries a nodeId, so blindly hiding non-focused nodes would hide- // the focused leaf's parents and blank the whole model. Applied before the- // explicit-hide pass so a focused-but-manually-hidden component still hides.- if (focusedSet.size > 0) {+ // Only one set of subtrees renders, everything else hides:+ // - a Components-panel focus, to inspect the selection alone. It wins, and+ // forces its parts visible even where their step would hide them;+ // - otherwise a sub-assembly's parts while one of its steps is active (it is+ // built on its own), unless picking components, which must reach any part.+ // Ancestors are kept too: three.js visibility is inherited and every glTF+ // node carries a nodeId, so hiding a kept leaf's parents would blank it.+ // Only nodeId-stamped nodes are touched — the reset above restores exactly+ // those. Applied before the explicit-hide pass, which still wins.+ const keepOnly =+ focusedSet.size > 0+ ? focusedSet+ : isolateSet.size > 0 && !componentPickerActive+ ? isolateSet+ : null;+ if (keepOnly) {const keep = new Set<Object3D>();- for (const nodeId of focusedSet) {+ for (const nodeId of keepOnly) {const node = nodesById.get(nodeId);if (!node) continue;for (let a: Object3D | null = node; a; a = a.parent) keep.add(a);node.traverse((descendant) => keep.add(descendant));}- // Only touch nodeId-stamped nodes — the reset above restores exactly these- // to visible, so meshes (which inherit) never get stranded hidden. Ancestor- // nodes stay in `keep`, so a focused leaf's parents don't blank it out.+ const forceVisible = keepOnly === focusedSet;for (const node of nodesById.values()) {- node.visible = keep.has(node);- }- }-- // A sub-assembly is built on its own: only its parts render while one of- // its steps is active, in every view. Same ancestor-safe rule as focus, but- // playback doesn't clear it. Picking components shows everything, so the- // author can still reach parts no step has claimed yet.- if (isolateSet.size > 0 && !componentPickerActive) {- const keep = new Set<Object3D>();- for (const nodeId of isolateSet) {- const node = nodesById.get(nodeId);- if (!node) continue;- for (let a: Object3D | null = node; a; a = a.parent) keep.add(a);- node.traverse((descendant) => keep.add(descendant));- }- for (const node of nodesById.values()) {- if (!keep.has(node)) node.visible = false;+ node.visible = keep.has(node) && (forceVisible || node.visible);}}@@ -1452,6 +1453,15 @@ function AssemblyScene({});}+ const fade = fadeRef.current;+ if (fade?.fading) {+ for (const { mesh, fade: material } of fade.entries) {+ mesh.material = material;+ // Draw after opaque components while transparent+ mesh.renderOrder = 1;+ }+ }+// Alt-hover x-ray drill: ghost the occluders in front of the pointer so the// innermost part they hide (the click target) shows through. Applied last so// it wins even over a selected occluder — you're deliberately looking past@@ -1484,6 +1494,9 @@ function AssemblyScene({isolateSet,drill]);+ useEffect(() => applyVisuals(), [applyVisuals]);+ const applyVisualsRef = useRef(applyVisuals);+ applyVisualsRef.current = applyVisuals;// --- Animation -----------------------------------------------------------@@ -1523,6 +1536,7 @@ function AssemblyScene({activeStep.id,JSON.stringify(activeStep.motion),activeStep.componentNodeIds.join(","),+ activeStep.durationSeconds ?? "",isEditingActive,componentPickerActive,carryInKey@@ -1551,19 +1565,20 @@ function AssemblyScene({// A carried-in sub-assembly glides in from beside the build first. Picking// keeps everything seated: a click must select what the BOM tree shows.const carry = componentPickerActive ? null : carryInLiveRef.current;- const clip = buildStepClip(- step,- nodesById,- carry+ const timing = stepClipTiming(step, carry ? CARRY_IN_GLIDE_SECONDS : 0);+ const clip = buildStepClip(step, nodesById, {+ duration: timing.motion,+ holdSeconds: timing.hold,+ ...(carry? {glide: {offset: carry.offset,- seconds: CARRY_IN_GLIDE_SECONDS,+ seconds: timing.glide,nodeIds: carry.nodeIds}}- : {}- );+ : {})+ });if (!clip) {// Nothing to animate (motion "none"), but a static selection must still// land on "step completed": the seated fade below reads this timer, and@@ -1661,88 +1676,61 @@ function AssemblyScene({// --- Seated fade-in ---------------------------------------------------// Steps that install components without an animation fade them in at the// seated pose instead of popping: planner-flagged steps (no collision-free- // path exists) and any non-first step whose display motion resolved to- // "none" (no stored motion and no collision-free fallback). Runs after the- // visual-state pass, which assigns the base materials this overrides.- const fadeRef = useRef<{- meshes: Mesh[];- materials: Material[];- seconds: number;- } | null>(null);-+ // path exists) and any step whose display motion resolved to "none" (no+ // stored motion and no collision-free fallback). Only the step's own parts+ // fade: a carried-in unit glides in, and its parts are never in the step's+ // componentNodeIds.useEffect(() => {const step = steps[activeStepIndex];// Editing this step: keep its components solid at the seated pose, no fade.- if (editMotion && step && editMotion.stepId === step.id) {- fadeRef.current = null;- return;- }- // A carry-in step glides its unit in from the side instead of fading.const fadesIn =step &&+ !(editMotion && editMotion.stepId === step.id) &&step.motion.type === "none" &&- step.componentNodeIds.length > 0 &&- (step.flagged || activeStepIndex > 0) &&- !carryIn;- if (!fadesIn) {- fadeRef.current = null;- return;- }+ step.componentNodeIds.length > 0;+ if (!fadesIn) return;const overrides = overridesRef.current;- const meshes: Mesh[] = [];+ const entries: { mesh: Mesh; fade: Material | Material[] }[] = [];const materials: Material[] = [];for (const nodeId of step.componentNodeIds) {- const node = nodesById.get(nodeId);- if (!node) continue;- node.traverse((object) => {+ nodesById.get(nodeId)?.traverse((object) => {if (!(object as Mesh).isMesh) return;const mesh = object as Mesh;- const override = getOverride(mesh, overrides, "fade");- for (const material of Array.isArray(override)- ? override- : [override]) {+ const fade = getOverride(mesh, overrides, "fade");+ for (const material of Array.isArray(fade) ? fade : [fade]) {material.transparent = true;- material.opacity = 0;material.depthWrite = false;materials.push(material);}- mesh.material = override;- // Draw after opaque components while transparent- mesh.renderOrder = 1;- meshes.push(mesh);+ entries.push({ mesh, fade });});}- if (meshes.length === 0) {- fadeRef.current = null;- return;- }+ if (entries.length === 0) return;const segment = segments[activeStepIndex] ?? 0;- fadeRef.current = {- meshes,- materials,- seconds: segment > 0 ? Math.min(FADE_SECONDS, segment) : FADE_SECONDS- };+ const seconds =+ segment > 0 ? Math.min(FADE_SECONDS, segment) : FADE_SECONDS;+ const progress = Math.min(localElapsedRef.current / seconds, 1);+ for (const material of materials) material.opacity = progress;+ fadeRef.current = { entries, materials, seconds, fading: progress < 1 };+ applyVisualsRef.current();return () => {fadeRef.current = null;- // Materials are reassigned by the visual-state pass on step change- for (const mesh of meshes) mesh.renderOrder = 0;+ applyVisualsRef.current();};- }, [steps, activeStepIndex, nodesById, segments, editMotion, carryIn]);+ }, [steps, activeStepIndex, nodesById, segments, editMotion]);useFrame(() => {const fade = fadeRef.current;if (!fade) return;- const progress =- fade.seconds > 0- ? Math.min(localElapsedRef.current / fade.seconds, 1)- : 1;- for (const material of fade.materials) {- material.opacity = progress;- material.transparent = progress < 1;- material.depthWrite = progress >= 1;+ const progress = Math.min(localElapsedRef.current / fade.seconds, 1);+ for (const material of fade.materials) material.opacity = progress;+ // Finished (or restarted by MES loop): the pass swaps the materials.+ if (fade.fading !== progress < 1) {+ fade.fading = progress < 1;+ applyVisualsRef.current();}});diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.tsindex 43ed4c0ef8..012088ed59 100644--- a/packages/viewer/src/index.ts+++ b/packages/viewer/src/index.ts@@ -32,7 +32,7 @@ export {naturalizeMotion,type Pose,type StepClipOptions,- stepTimelineSeconds+ stepClipTiming} from "./motion";export {type AssemblyPlan,@@ -46,6 +46,7 @@ export {type StepPhase} from "./plan";export {+ arrivalIndexByNode,buildSubAssemblyPlan,displayOrder,isSubAssemblyHeader,diff --git a/packages/viewer/src/motion.test.ts b/packages/viewer/src/motion.test.tsindex 0dfa32c953..1062f47f1d 100644--- a/packages/viewer/src/motion.test.ts+++ b/packages/viewer/src/motion.test.ts@@ -20,6 +20,7 @@ import {naturalizeMotion,type Pose,resampleEased,+ stepClipTiming,waypointsToMotion} from "./motion";import type { AssemblyStep, Motion, Vec3 } from "./types";@@ -921,3 +922,45 @@ describe("motionToWaypoints / waypointsToMotion", () => {expect(back.type).toBe("linear");});});++describe("stepClipTiming", () => {+ const linear: Motion = { type: "linear", direction: [0, 0, 1], distance: 60 };+ const seconds = motionDuration(linear);++ it("plays the natural animation when no duration is authored", () => {+ expect(stepClipTiming({ motion: linear })).toEqual({+ total: seconds + 0.6,+ glide: 0,+ motion: seconds,+ hold: 0.6+ });+ });++ it("adds a carry-in glide before the insertion", () => {+ const timing = stepClipTiming({ motion: linear }, 1.2);+ expect(timing.total).toBeCloseTo(1.2 + seconds + 0.6);+ expect(timing.glide).toBe(1.2);+ });++ it("gives a process-only step a fixed slot plus any glide", () => {+ expect(stepClipTiming({ motion: { type: "none" } }).total).toBe(2);+ expect(stepClipTiming({ motion: { type: "none" } }, 1.2).total).toBe(3.2);+ });++ it("speeds glide, insertion and hold up to fit a shorter authored duration", () => {+ const natural = 1.2 + seconds + 0.6;+ const timing = stepClipTiming(+ { motion: linear, durationSeconds: natural / 2 },+ 1.2+ );+ expect(timing.total).toBe(natural / 2);+ expect(timing.glide + timing.motion + timing.hold).toBeCloseTo(natural / 2);+ expect(timing.glide).toBeCloseTo(0.6);+ });++ it("keeps the natural animation inside a longer authored duration", () => {+ const timing = stepClipTiming({ motion: linear, durationSeconds: 30 });+ expect(timing.total).toBe(30);+ expect(timing.motion).toBe(seconds);+ });+});diff --git a/packages/viewer/src/motion.ts b/packages/viewer/src/motion.tsindex ccbbe184e1..4b76d625cd 100644--- a/packages/viewer/src/motion.ts+++ b/packages/viewer/src/motion.ts@@ -71,19 +71,32 @@ export const DEFAULT_WAYPOINT_DISTANCE = 50;const NONE_STEP_SECONDS = 2;/**- * Seconds a step occupies on the continuous timeline: the explicit- * `durationSeconds` override when set, otherwise the natural animation- * length (motion duration + seated hold), or a fixed slot for process-only- * steps.+ * How a step spends its slot on the continuous timeline (`total`): a+ * carried-in sub-assembly's glide, the insertion, then the seated hold. The+ * slot is the explicit `durationSeconds` when set, otherwise the natural length+ * (a fixed slot for process-only steps). An authored duration shorter than the+ * animation speeds all three up to fit, so the step never ends mid-travel and+ * snaps its parts to their seat.*/-export function stepTimelineSeconds(- step: Pick<AssemblyStep, "motion" | "durationSeconds">-): number {- if (step.durationSeconds && step.durationSeconds > 0) {- return step.durationSeconds;- }- if (step.motion.type === "none") return NONE_STEP_SECONDS;- return motionDuration(step.motion) + DEFAULT_HOLD_SECONDS;+export function stepClipTiming(+ step: Pick<AssemblyStep, "motion" | "durationSeconds">,+ glideSeconds = 0+): { total: number; glide: number; motion: number; hold: number } {+ const motion = step.motion.type === "none" ? 0 : motionDuration(step.motion);+ const natural = glideSeconds + motion + DEFAULT_HOLD_SECONDS;+ const total =+ step.durationSeconds && step.durationSeconds > 0+ ? step.durationSeconds+ : step.motion.type === "none"+ ? glideSeconds + NONE_STEP_SECONDS+ : natural;+ const fit = Math.min(1, total / natural);+ return {+ total,+ glide: glideSeconds * fit,+ motion: motion * fit,+ hold: DEFAULT_HOLD_SECONDS * fit+ };}/** Total travel distance (mm) implied by a motion. */