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
feat(assembly): build sub-assemblies off to the side and carry them in at a join step
aashua45c1fbfb81d
diff --git a/.ai/plans/2026-09-28-assembly-side-panels-ux.md b/.ai/plans/2026-09-28-assembly-side-panels-ux.mdnew file mode 100644index 0000000000..bb2e87c37e--- /dev/null+++ b/.ai/plans/2026-09-28-assembly-side-panels-ux.md@@ -0,0 +1,283 @@+# Assembly editor side panels — small UX changes — implementation plan++**Spec / source:** approved design `/Users/aashu/work/carbon/local-docs/assembly-editor-ux-review.html`, section "The final version" (changes L1–L5, R1–R7). User approved it ("i liked it lets build this one") and chose **glossary terms** (LabelWithHelp) for the ⓘ help.+**Branch:** `feat/asembly-view-isolation` (worktree `/Users/aashu/work/carbon/carbon-feat-asembly-view-isolation`). Never commit without the user's permission.+**Design rules:** `/Users/aashu/work/carbon/carbon/.claude/skills/carbon-design/references/` (`foundations.md`, `status-and-feedback.md`, `forms.md`, `anti-patterns.md`). Quiet chrome, no coloured prose (amber only as an icon), `Subheading` instead of hand-rolled uppercase labels, status colour by lifecycle position from `status-colors.ts`, icon-only status in dense rows + tooltip, help via `termId` → `LabelWithHelp`, every string in Lingui.+**Scope:** left panel (Steps list, Components tree) and right panel (Properties header, Details form, BOM tab, Slides). **Out of scope for every task:** the 3D viewer, `AssemblyPlayer`, the editor header, the instructions list, any service/route/DB change.++## Progress+- [x] Task 1: Glossary terms for the four help icons+- [x] Task 2: Shared assembly-step status colours + status components+- [x] Task 3: Steps list rows (L1, L2, L3)+- [x] Task 4: Components tree rows (L4, L5)+- [x] Task 5: Properties header (R1) + status pill+- [x] Task 6: Details form order, Components + Hidden blocks (R4, part of R3)+- [x] Task 7: One Playback box + compact "Build off to the side" (R2, R3)+- [x] Task 8: Save pinned to the bottom (R5)+- [x] Task 9: BOM tab without the duplicate list (R6)+- [x] Task 10: Slides copy + tooltips (R7)+- [x] Task 11: Lingui extract+- [x] Task 12: End-to-end verification++## Dependencies+Task 1 before Task 6/7. Task 2 before Tasks 3 and 5. Tasks 3, 4, 9, 10 are independent of each other. Tasks 6 → 7 → 8 touch the same file (`AssemblyInstructionProperties.tsx`) — run in order. Task 11 after all code tasks; Task 12 last.++---++## Task 1: Glossary terms for the four help icons++**Depends on:** none+**Files:**+- Modify: `packages/glossary/src/terms.ts` — add four entries.+- Copy from (precedent): existing entries in the same file (e.g. `subassembly`, ~line 89).++**Steps:**+1. Add these keys to the `terms` object (place them next to `subassembly`), one-sentence definitions, no `href`:+ ```ts+ "assembly-step-motion": {+ term: msg`Motion`,+ definition: msg`The path this step's components travel into place during playback; worked out from the model, or drawn by hand with Edit Path.`+ },+ "assembly-step-camera": {+ term: msg`Camera`,+ definition: msg`The view a step plays from; without a saved view the step frames its own components.`+ },+ "assembly-step-build-aside": {+ term: msg`Build off to the side`,+ definition: msg`Builds this step's components beside the model as a group, then carries the group in at a later join step.`+ },+ "assembly-step-hidden-components": {+ term: msg`Hidden on this step`,+ definition: msg`Components hidden only while this step plays, such as a fixture in the way; use the eye in the Components tab to hide one.`+ }+ ```+2. If `terms.test.ts` asserts a fixed count or a list of keys, update it to include the four keys (read it first).++**Verify:**+```bash+pnpm --filter @carbon/glossary typecheck && pnpm --filter @carbon/glossary test+# Expected: no type errors; all tests pass+```+**Out of scope:** any other glossary entry, docs pages.++## Task 2: Shared assembly-step status colours + status components++**Depends on:** none+**Files:**+- Modify: `packages/utils/src/status-colors.ts` — add `ASSEMBLY_STEP_STATUS_COLOR_MAP` and register it.+- Create: `apps/erp/app/modules/production/ui/Assemblies/AssemblyStepStatus.tsx`+- Copy from (precedent): `apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionStatus.tsx` (wrapper) and `packages/react/src/Status.tsx` (icon per colour).++**Steps:**+1. In `status-colors.ts`, next to `JOB_OPERATION_STATUS_COLOR_MAP`:+ ```ts+ /* assemblyInstructionStep.status (production.models.ts `assemblyStepStatuses`):+ * not started → gray, waiting on a reviewer → yellow, finished → green. */+ export const ASSEMBLY_STEP_STATUS_COLOR_MAP = {+ Todo: "gray",+ Review: "yellow",+ Done: "green"+ } as const satisfies Record<string, StatusColor>;+ ```+ and add `assemblyStep: ASSEMBLY_STEP_STATUS_COLOR_MAP,` to `statusColorMaps`.+2. Create `AssemblyStepStatus.tsx` exporting:+ - `assemblyStepStatuses` re-used from `../../production.models` (`assemblyStepStatuses = ["Todo","Review","Done"]`, line ~1209) and `type AssemblyStepStatusValue`.+ - `normalizeStepStatus(status: string | null | undefined): AssemblyStepStatusValue` → the value if it is in the list, else `"Todo"`.+ - `stepStatusLabel(t, status)` returning translated `t\`Todo\`` / `t\`Review\`` / `t\`Done\`` (use `useLingui` inside the components instead if simpler — no raw enum rendering).+ - `AssemblyStepStatus({ status })` → `<Status color={ASSEMBLY_STEP_STATUS_COLOR_MAP[status]}>{label}</Status>` (the header pill).+ - `AssemblyStepStatusIcon({ status, className })` → the same icon `Status` uses per colour (gray `LuCircleDashed`, yellow `LuClock`, green `LuCircleCheck`) with hue classes `text-muted-foreground` / `text-yellow-500` / `text-emerald-500`, `aria-hidden`.+3. Import `ASSEMBLY_STEP_STATUS_COLOR_MAP` from `@carbon/utils` (check how other ERP files import status maps: `grep -rn "STATUS_COLOR_MAP" apps/erp/app | head`; use the same import path).++**Verify:**+```bash+pnpm --filter @carbon/utils test && pnpm --filter @carbon/utils typecheck+# Expected: status-colors tests pass; no type errors+```+**Out of scope:** other status maps; `Status.tsx`.++## Task 3: Steps list rows (L1, L2, L3)++**Depends on:** Task 2+**Files:**+- Modify: `apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx` — `StepStatusDot`, `StepStatusControl`, `StepItem` (lines ~920–1166).+- Copy from (precedent): icon-only status in dense rows per `status-and-feedback.md` §2.5; `TruncatedTooltipText` (`packages/react/src/TruncatedTooltipText.tsx`); existing `LuBoxes` icon span in `StepItem` for icon + tooltip.++**Steps:**+1. Delete the local `stepStatusStyles` map and `StepStatusDot`; use `AssemblyStepStatusIcon` / `normalizeStepStatus` from Task 2.+2. `StepStatusControl`: trigger becomes an icon-only ghost button (`size-6`, `rounded-md`, hover `bg-accent`, focus ring as today) showing `AssemblyStepStatusIcon` (`size-4`), wrapped in `Tooltip` with the translated status label. `aria-label={t\`Step status: ${label}. Change status\`}`. Dropdown items keep icon + translated label. Disabled: the icon alone inside a `Tooltip` (no chip). Keep the optimistic `displayed` logic and the submit path unchanged.+3. `StepItem`:+ - Render `ProcedureStepTypeIcon` only when `(step.type ?? "Task") !== "Task"`.+ - Replace the title `<span title>` with `<TruncatedTooltipText tooltip={title} className="min-w-0 flex-1 truncate text-sm text-foreground">{title}</TruncatedTooltipText>` (check its `className` lands on the truncating span; if not, wrap it in a `min-w-0 flex-1` span).+ - Add a flagged icon: compute `flagged` with `stepPlanWarningsSchema.safeParse(step.warnings).data?.flagged === true` (import from `../../production.models`); render `<LuTriangleAlert className="size-3.5 text-amber-500" />` in a `Tooltip` "No collision-free path" (`role="img"`, translated `aria-label`), placed before the `×count`.+ - Convert the existing `title=` attributes on the `LuHand` and `LuBoxes` spans to `Tooltip`s with the same (translated) text.+ - Translate remaining literals in these components ("Delete Step", "More", "Drag handle", "Double-click to play this step", the component-count title) with `t`/`Trans`.++**Verify:**+```bash+pnpm --filter erp typecheck && pnpm exec biome check apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx+# Expected: no type errors; Biome reports no errors (the 7 existing useExhaustiveDependencies warnings in this file are pre-existing)+```+**Out of scope:** reordering, the explorer's toolbar/footer, generate/re-plan flows.++## Task 4: Components tree rows (L4, L5)++**Depends on:** none+**Files:**+- Modify: `apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx` — unit row (~1115–1131), `UnitChildRow` (~1234–1238), group row (~1609–1614), `ThisStepBadge` (~1657), hover-reveal classes (~1147, 1160, 1632, 1695, 1711).++**Steps:**+1. Unit row: replace the `Auto` `Badge` with `LuSparkles` (`size-3.5 text-muted-foreground`, `role="img"`, translated `aria-label`) in a `Tooltip` "Detected by the motion planner".+2. Replace `ThisStepBadge` with `ThisStepIcon`: `LuCircleDot` `size-3.5 text-blue-500` (blue = the viewer's active-step tint, as the badge comment says) in a `Tooltip` "In this step", `role="img"`, translated `aria-label`.+3. Row counts: in the three tree rows (unit `memberCount`, `UnitChildRow` `count`, group row `group.count`) render the `×N` `Badge` only when the value is `> 1`. Leave the popover detail (~1450) and the unit editor list (~1840) unchanged.+4. Every `opacity-0 group-hover:opacity-100` in these rows also gets `group-focus-within:opacity-100` (keyboard reveal, `anti-patterns.md` §3).+5. Translate the literals touched (`Collapse/Expand …`, `Edit/Delete subassembly …`, `Component details: …`, "Detected by the motion planner").++**Verify:**+```bash+pnpm --filter erp typecheck && pnpm exec biome check apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx+# Expected: no type errors; no Biome errors+```+**Out of scope:** tree data, selection, hide logic, mapping popover content.++## Task 5: Properties header (R1) + status pill++**Depends on:** Task 2+**Files:**+- Modify: `apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx` — header block (~164–199), delete `stepStatusStyles`/`normalizeStatus`/`StepStatusPill` (~296–319), move `planFlag` computation (~429–438) into a shared helper.++**Steps:**+1. Add a module-level helper `getPlanFlag(warnings: unknown, graphIndex: AssemblyGraphIndex | null): { blockers: string[] } | null` with the exact body of today's `planFlag` memo; use it in both the header (memoised) and `StepForm`.+2. Header: `StepStatusPill` → `<AssemblyStepStatus status={normalizeStepStatus(step.status)} />`. "Step N of M" and "components" via Lingui (`<Plural>` for the component count).+3. Flag line: `<span className="inline-flex items-center gap-1 text-muted-foreground"><LuTriangleAlert className="size-3 text-amber-500" />{t\`No clear path\`}</span>`, wrapped in a `Tooltip` whose content is `t\`Blocked by ${blockers.join(", ")}\`` when `blockers.length > 0` (no tooltip otherwise). No amber text.+4. Translate the header/empty-state literals ("Step", "Untitled step", "No step selected", the pick-a-step sentence, tab labels "Details"/"BOM"/"Slides").++**Verify:**+```bash+pnpm --filter erp typecheck && pnpm exec biome check apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx+# Expected: no type errors; no Biome errors+```+**Out of scope:** tabs structure, `StepForm` body (Tasks 6–8).++## Task 6: Details form order, Components + Hidden blocks (R4, part of R3)++**Depends on:** Tasks 1, 5+**Files:**+- Modify: `AssemblyInstructionProperties.tsx` — `StepForm` JSX order (~466–646), `StepComponentsEditor` (~659–776), `StepHiddenComponentsEditor` (~779–886).+- Copy from (precedent): `Subheading` usage already at line ~529; `LabelWithHelp` from `@carbon/react` (`packages/react/src/LabelWithHelp.tsx`).++**Steps:**+1. `StepForm` order becomes: Type, Title, Instruction, [Measurement / List fields], Required, **Components** (`StepComponentsEditor`), **Hidden on this step** (`StepHiddenComponentsEditor`), **Playback** (Task 7), Save (Task 8). Remove the "Playback & components" `Subheading`.+2. Required: `description={t\`Operator must record this step\`}`, `label={t\`Required\`}`. Translate the Type/Title/Instruction/Unit of Measure/Minimum/Maximum/List Options labels. Keep the "Optional" tags (automatic).+3. `StepComponentsEditor`: drop the bordered `bg-muted/40` wrapper box; heading row = `<Subheading variant="heavy">{t\`Components\`} · {count}</Subheading>` (count = number of node ids, tabular-nums) + the existing Add/Done button (labels `t\`Add\`` / `t\`Done Adding\``). Keep the adding-mode hint but shorten it to `t\`Click components in the viewer to add them. Shift-click adds several.\``. Empty state: `t\`No components yet\``. List rows: `×N` badge only when `group.count > 1`; translate the remove aria-label.+4. `StepHiddenComponentsEditor`: drop the wrapper box; heading row = `<Subheading variant="heavy"><LabelWithHelp termId="assembly-step-hidden-components" variant="inline">{t\`Hidden on this step\`}</LabelWithHelp></Subheading>` + (when nothing hidden) a muted `t\`None\`` on the right, else the existing Show all / Hide again buttons. Remove the "Nothing hidden. Use the eye…" paragraph (the glossary help now carries it). List rows: `×N` only when `> 1`.+5. Remove the three hand-rolled `Label className="text-xxs font-medium uppercase tracking-wide …"` usages in these blocks.++**Verify:**+```bash+pnpm --filter erp typecheck && pnpm exec biome check apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx+# Expected: no type errors; no Biome errors+```+**Out of scope:** add/remove/hide behaviour and their fetchers.++## Task 7: One Playback box + compact "Build off to the side" (R2, R3)++**Depends on:** Tasks 1, 6+**Files:**+- Modify: `AssemblyInstructionProperties.tsx` — replace the Motion and Camera boxes (~533–613) with one Playback block.+- Modify: `apps/erp/app/modules/production/ui/Assemblies/AssemblyStepJoin.tsx` — render as a row (no box, no uppercase label, no paragraph).++**Steps:**+1. Playback block: `<Subheading variant="heavy">{t\`Playback\`}</Subheading>` followed by `<div className="w-full divide-y divide-border rounded-lg border border-border bg-card">` with three rows, each `flex items-center justify-between gap-2 px-3 py-2`:+ - **Motion** — left: `<LabelWithHelp termId="assembly-step-motion" variant="inline">` label (`text-xs font-medium text-muted-foreground`) and under it a value line (`text-sm`): `planFlag` → amber `LuTriangleAlert` icon + `t\`No clear path\``; `isEditingMotion` → `t\`Drag the red waypoints in the viewer\``; no components → `t\`Add components first\``; otherwise `t\`Automatic\``. Right: the existing Edit Path / Done Editing Path button (labels translated, same disabled rule, hidden when `isDisabled`).+ - **Camera** — label with `termId="assembly-step-camera"`; value `hasCamera ? t\`Saved view\` : t\`Automatic\``; right: `Button variant="secondary" size="sm"` `t\`Use Current View\`` (same `onSetCamera`) and, when `hasCamera`, ghost `t\`Clear\`` (same `onClearCamera`); hidden when `isDisabled`.+ - **Build off to the side** — `<AssemblyStepJoin … />`.+ Delete the old helper paragraphs ("Edit the path to adjust…", "A saved view frames…", "This step auto-frames…", the long flagged sentence, the waypoint instructions).+2. `AssemblyStepJoin.tsx`: return a row fragment matching the rows above — left `<LabelWithHelp termId="assembly-step-build-aside" variant="inline">{t\`Build off to the side\`}</LabelWithHelp>`; right the control:+ - trigger label `selected ? t\`Joins step ${selected.number}\` : t\`No\``; dropdown items `t\`No, build in place\`` and `t\`Joins step ${number}: ${title}\`` (full title stays in the menu);+ - `locked === "base"` → muted text `t\`No, it's the base\``; `locked === "join"` → `t\`Brings in steps\`` + the existing step-number link buttons; `isDisabled` → the label text.+ Remove the wrapper `VStack` box, the uppercase `Label`, and the helper `<p>`. Keep `joinTargets`, the fetcher submit and the optimistic value exactly as they are. Trigger stays compact (`h-6`, `text-xs`, border, `max-w-[10rem] truncate`).++**Verify:**+```bash+pnpm --filter erp typecheck && pnpm exec biome check apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx apps/erp/app/modules/production/ui/Assemblies/AssemblyStepJoin.tsx+# Expected: no type errors; no Biome errors+```+**Out of scope:** motion editing, camera capture, `joinTargets`, the join route/service.++## Task 8: Save pinned to the bottom (R5)++**Depends on:** Task 7+**Files:**+- Modify: `AssemblyInstructionProperties.tsx` — the `Submit` at the end of `StepForm`.++**Steps:**+1. Wrap `Submit` in `<div className="sticky bottom-0 z-10 -mx-4 w-[calc(100%+2rem)] border-t border-border bg-background/95 px-4 py-3 backdrop-blur">` (mirrors the sticky header's surface at line ~166; the panel `VStack` is the scroll container, and `px-4` comes from the `Tabs` wrapper).+2. Label `<Trans>Save</Trans>` (the ⌘↵ shortcut is Submit's default). Keep `isDisabled`/`isLoading` as they are.+3. If the sticky bar doesn't stick because an ancestor between it and the panel has `overflow` set, STOP and report — do not restructure the panel.++**Verify:**+```bash+pnpm --filter erp typecheck+# Expected: no type errors+```+**Out of scope:** save behaviour, validators, the step route.++## Task 9: BOM tab without the duplicate list (R6)++**Depends on:** none (touches `AssemblyInstructionProperties.tsx` — if Tasks 5–8 are in flight, run after Task 8)+**Files:**+- Modify: `AssemblyInstructionProperties.tsx` — remove `<AssemblyStepBom …/>` from the BOM tab (~259–264) and change the import to `import { ComponentColorSwatch } from "./AssemblyStepBom";`.+- Modify: `AssemblyStepBom.tsx` — delete the now-unused default-export component (keep `ComponentColorSwatch`, used by `AssemblyBomTree.tsx`).++**Steps:** as above; confirm with `grep -rn "AssemblyStepBom" apps/erp/app` that nothing else imports the default export.++**Verify:**+```bash+pnpm --filter erp typecheck+# Expected: no type errors+```+**Out of scope:** `AssemblyStepMaterials`, `AssemblyStepTools`, the Empty component.++## Task 10: Slides copy + tooltips (R7)++**Depends on:** none+**Files:**+- Modify: `apps/erp/app/components/SlidesEditor.tsx` — "No slides" (~236), Add slide / Add model buttons (~210–231). Shared with the BOP step editor; the copy works for both.++**Steps:**+1. `No slides` → `<Trans>No slides yet</Trans>`.+2. Button labels `<Trans>Add Slide</Trans>` / `<Trans>Add Model</Trans>` (Title Case per `content-and-copy.md`); wrap each in a `Tooltip` (`@carbon/react`): `t\`A photo or PDF the operator sees on this step\`` and `t\`A 3D model the operator can turn around\``.++**Verify:**+```bash+pnpm --filter erp typecheck && pnpm exec biome check apps/erp/app/components/SlidesEditor.tsx+# Expected: no type errors; no Biome errors+```+**Out of scope:** upload, annotation and caption logic.++## Task 11: Lingui extract++**Depends on:** Tasks 1–10+**Steps:**+1. `pnpm run lingui:extract` then `pnpm run lingui:clean`.+2. `git diff --stat packages/locale/locales` — only `erp.po`/`mes.po` catalogs should change. New non-English entries stay empty (no translate run).++**Verify:**+```bash+git diff --stat packages/locale/locales | tail -1+# Expected: only files under packages/locale/locales/*/ changed+```++## Task 12: End-to-end verification++**Depends on:** Task 11+**Steps:**+1. `pnpm --filter erp typecheck`, `pnpm --filter @carbon/utils test`, `pnpm --filter @carbon/glossary test`, `pnpm exec biome check apps/erp/app/modules/production/ui/Assemblies apps/erp/app/components/SlidesEditor.tsx packages/utils/src/status-colors.ts packages/glossary/src/terms.ts`.+2. Browser (agent-browser, `DEV_BYPASS_EMAIL` [email protected], `https://erp.asembly-view-isolation.dev/x/assembly/GkCD68SBwhaY5fEY-7two`), screenshot and confirm:+ - rows show full titles ("Add 32006JR Roller"), no Task icon, a status icon with tooltip, Todo gray; step 3 shows the amber warning icon;+ - Components tab: "Main Frame" unit row readable, sparkle + dot icons with tooltips, no ×1 badges;+ - right panel: status pill, "No clear path" grey with tooltip on step 3; order Type/Title/Instruction/Required/Components/Hidden/Playback; ⓘ opens the glossary card; Save visible without scrolling;+ - status change, Add components, Edit path, Use current view and Build off to the side still work (then restore any change made).+3. Update `apps/erp/app/modules/production/AGENTS.md` only if a documented name changed (none expected).++**Verify:** all commands exit 0; screenshots match the checklist above.diff --git a/.ai/plans/2026-09-28-assembly-subassembly-staging.md b/.ai/plans/2026-09-28-assembly-subassembly-staging.mdnew file mode 100644index 0000000000..278b39ed8d--- /dev/null+++ b/.ai/plans/2026-09-28-assembly-subassembly-staging.md@@ -0,0 +1,421 @@+# Sub-assembly staging — implementation plan++**Spec / source:** `.ai/specs/2026-09-28-assembly-subassembly-staging.md`+**Research:** `.ai/research/2026-09-28-assembly-subassembly-staging.md`+**Branch:** `feat/asembly-view-isolation` (worktree `/Users/aashu/work/carbon/carbon-feat-asembly-view-isolation`)++Rules for the executor:++- Never `git commit` (the user commits by hand).+- Never rebuild or reset the database. No migration is needed.+- New user-facing copy uses Lingui (`<Trans>` or `` t`…` ``).+- Validation commands are scoped. Whole-repo typecheck runs out of memory.++## Progress+- [x] Task 1: Viewer contract — `joinStepId` replaces `phase`+- [x] Task 2: Viewer `staging.ts` pure helpers + tests+- [x] Task 3: `buildStepClip` glide option + tests+- [x] Task 4: Wire staging into `AssemblyPlayer`+- [x] Task 5: ERP service — join validation, reorder cleanup, mapper+- [x] Task 6: ERP join route + path helper+- [x] Task 7: ERP step Details — "Build off to the side" select + join summary+- [x] Task 8: ERP explorer badge, Regenerate warning, own-parts in route+- [x] Task 9: MES select + mapper+- [x] Task 10: Lingui extraction+- [x] Task 11: Docs (viewer + production AGENTS.md)+- [ ] Task 12: End-to-end verification++## Dependencies+Tasks 1 → 2 → 3 → 4 run in order (all viewer). Task 5 needs 1. Task 6 needs 5. Tasks 7 and 8 need 2, 5 and 6. Task 9 needs 1 and is independent of 5–8. Task 10 needs 7 and 8. Task 11 can run any time after 4. Task 12 comes last.++---++## Task 1: Viewer contract — `joinStepId` replaces `phase`++**Depends on:** none+**Files:**+- Modify: `packages/viewer/src/types.ts`: in `AssemblyStep` (~line 117), replace the `phase` field and its doc comment.++**Steps:**+1. Delete the `phase?: { id: string; name: string; join: boolean } | null;` field and its comment block.+2. Add in its place:+ ```ts+ /**+ * Built off to the side: the id of the later JOIN step where the group this+ * step builds is carried into the main assembly (DB `parentStepId`).+ * `null`/absent = built in place. See `staging.ts`.+ */+ joinStepId?: string | null;+ ```+3. Leave `StepPhase` and `assignStepPhases` in `plan.ts` untouched. They are a separate, unused plan-side type.++**Verify:**+```bash+pnpm --filter @carbon/viewer typecheck+# Expected: exits 0 with no errors+```++**Out of scope:** `plan.ts`, `CURRENT_PLAN_VERSION`, and any geometry-service contract.++---++## Task 2: Viewer `staging.ts` pure helpers + tests++**Depends on:** 1+**Files:**+- Create: `packages/viewer/src/staging.ts`+- Create: `packages/viewer/src/staging.test.ts`+- Modify: `packages/viewer/src/index.ts`: export the new helpers and types+- Copy from (precedent): `packages/viewer/src/visibility.ts` + `visibility.test.ts` (a pure module with a vitest file), and `graph.test.ts` for building an `AssemblyGraphIndex` fixture via `indexAssemblyGraph`++**Steps:**+1. Create `staging.ts`. It must have no `three` imports. It uses `AssemblyGraphIndex` from `./graph` and `AssemblyStep`/`Vec3` from `./types`.+ ```ts+ /** Seconds the staged group takes to glide from its staging spot to the insertion start. */+ export const STAGING_GLIDE_SECONDS = 1.2;+ /** Gap between the main model and a staging lane, and between lanes, as a fraction of the assembly diagonal. */+ const STAGING_GAP_FRACTION = 0.25;++ export type StagingJoin = {+ /** Index of the join step */+ joinIndex: number;+ /** Every node installed by this join's staged steps, in step order (no dedupe loss: first occurrence wins) */+ nodeIds: string[];+ /** Pure world translation from seat to staging spot */+ offset: Vec3;+ };++ export type Staging = {+ /** Keyed by join step index */+ joins: Map<number, StagingJoin>;+ /** staged step index → its join step index */+ stagedToJoin: Map<number, number>;+ };++ export const EMPTY_STAGING: Staging = { joins: new Map(), stagedToJoin: new Map() };++ /** Ids of the parts a join step carries in: every componentNodeId of the steps pointing at it. */+ export function stagedGroupNodeIds(+ steps: Pick<AssemblyStep, "id" | "componentNodeIds" | "joinStepId">[],+ joinStepId: string+ ): string[];++ export function buildStaging(+ steps: Pick<AssemblyStep, "id" | "componentNodeIds" | "joinStepId">[],+ graphIndex: AssemblyGraphIndex | null+ ): Staging;++ /** nodeId → offset for every node that sits at its staging spot while step `activeIndex` is shown. */+ export function parkedOffsetsAt(+ staging: Staging,+ steps: Pick<AssemblyStep, "componentNodeIds">[],+ activeIndex: number+ ): Map<string, Vec3>;+ ```+2. `buildStaging` rules. Each one is defensive: the viewer ignores bad links rather than throwing.+ - A link counts only when: the join id resolves to a step index `j`; `j > i` (the staged index); `i !== 0`; step `j` has no `joinStepId` of its own; and step `i` is not itself a join target of another step. Otherwise, ignore the link (treat it as built in place).+ - Group `nodeIds`: concatenate `componentNodeIds` of the valid staged steps in index order, and drop duplicates.+ - Offset: with `graphIndex` null, return `EMPTY_STAGING`. Otherwise `root = graphIndex.graph.root.bbox`, `diag = hypot(max-min)`, and `gap = diag * STAGING_GAP_FRACTION`. Walk joins in ascending `joinIndex` with `cursor = root.max[0] + gap`. For each join, compute the group bbox (union of `graphIndex.nodesById.get(id)?.bbox` for its nodeIds, skipping unknown ids; skip the join entirely if none resolve). Set `offset = [cursor - groupMin[0], 0, 0]`, then `cursor += (groupMax[0] - groupMin[0]) + gap`.+3. `parkedOffsetsAt(staging, steps, a)`: for each `[i, j]` of `stagedToJoin` where `i <= a && a < j`, map every id in `steps[i].componentNodeIds` to `staging.joins.get(j).offset` (skip if the join is missing).+4. `staging.test.ts` must cover these cases:+ - Two staged steps pointing at step 3 give one join. `nodeIds` holds the union and the offset x is greater than 0.+ - A link pointing backwards, from the first step, to a staged step (nesting), or to an unknown id is ignored.+ - Two joins get non-overlapping lanes: the second lane's `min x + offset` is at least the first's `max x + offset + gap`.+ - `parkedOffsetsAt` returns nothing before a staged step, includes the staged step's own nodes when it is active, includes earlier staged nodes on later staged steps, and returns nothing at or after the join index.+ - `stagedGroupNodeIds` returns the union for a join id and `[]` for others.+5. Export from `index.ts`: `buildStaging`, `parkedOffsetsAt`, `stagedGroupNodeIds`, `STAGING_GLIDE_SECONDS`, `EMPTY_STAGING`, `type Staging`, and `type StagingJoin`. Also add `stagedGroupNodeIds` to `steps.ts` (the three-free subpath) so server code can use it.++**Verify:**+```bash+pnpm --filter @carbon/viewer test -- staging+# Expected: all staging tests pass+pnpm --filter @carbon/viewer typecheck+# Expected: exits 0+```++**Out of scope:** rendering code and `AssemblyPlayer.tsx`.++---++## Task 3: `buildStepClip` glide option + tests++**Depends on:** 2+**Files:**+- Modify: `packages/viewer/src/motion.ts`: `StepClipOptions` and `buildStepClip` (~line 467)+- Modify: `packages/viewer/src/motion.test.ts`: add cases in `describe("buildStepClip")` (~line 325)++**Steps:**+1. Extend `StepClipOptions` with:+ ```ts+ /** Join step: prepend a straight glide from seat+offset to the insertion start. */+ glide?: { offset: Vec3; seconds: number };+ ```+2. In `buildStepClip`:+ - The early return becomes `if ((step.motion.type === "none" && !options.glide) || step.componentNodeIds.length === 0) return null;`.+ - Per node, compute the insertion keyframes as today. If the motion is `none`, use a single keyframe at the seated pose (`times [0]`).+ - If `glide` is set: `glideStart = seat + offset`, `glideEnd = first insertion keyframe position` (the quaternion stays the seated one). Build `EASE_SAMPLES + 1` eased samples with `easeInOutCubic` over `glide.seconds`, then append the insertion keyframes with times shifted by `glide.seconds` (skip the insertion's t=0 frame because it duplicates `glideEnd`).+ - Clip duration becomes `glide.seconds + insertion duration (0 for none) + hold`.+3. Add these tests:+ - A glide on a linear motion: the first keyframe position is `seat + offset`, the frame at `t = seconds` equals the linear start, the last non-hold frame equals the seat, and `clip.duration` equals `seconds + motionDuration + hold`.+ - A glide on `none`: the clip is not null, it starts at `seat + offset`, and it ends at the seat.+ - Without a glide, the output is unchanged (existing tests still pass).++**Verify:**+```bash+pnpm --filter @carbon/viewer test -- motion+# Expected: all motion tests pass, including the new glide cases+```++**Out of scope:** `naturalizeMotion` (the glide is never clamped), `motionToKeyframes` and `stepTimelineSeconds`.++---++## Task 4: Wire staging into `AssemblyPlayer`++**Depends on:** 3+**Files:**+- Modify: `packages/viewer/src/AssemblyPlayer.tsx`++**Steps:**+1. **Top-level component** (where `displaySteps` is built, ~line 325):+ - `const staging = useMemo(() => buildStaging(steps, graphIndex), [steps, graphIndex]);`+ - In `displaySteps`: for a step index in `staging.joins`, the display step's `componentNodeIds` = `[...own, ...join.nodeIds]` (deduped) BEFORE fallback and naturalize. This way the fallback motion, the naturalized travel, the hidden-set exclusion and the camera all cover the moving group. Add `staging` to the memo deps.+ - `segments`: `displaySteps.map((s, i) => stepTimelineSeconds(s) + (staging.joins.has(i) && !(s.durationSeconds && s.durationSeconds > 0) ? STAGING_GLIDE_SECONDS : 0))`.+ - Pass `staging` to `AssemblyScene` as a new prop `staging: Staging`, typed in the props block with a doc comment.+2. **`AssemblyScene` clip effect** (~line 1289):+ - Add to `clipKey`: `JSON.stringify([...parkedOffsetsAt(staging, steps, activeStepIndex)].sort())` and `JSON.stringify(staging.joins.get(activeStepIndex)?.offset ?? null)`, and add `componentPickerActive`.+ - At the top of the effect body (after the seek bookkeeping and the `!step` return), if `!isEditingActive && !componentPickerActive`, compute `parked = parkedOffsetsAt(staging, stepsLiveRef.current, activeStepIndex)`. Reduce it to TOP-MOST nodes: skip a node whose `Object3D` ancestor chain contains another parked node (walk `node.parent` and check `userData.nodeId`). For each top-most node, save `{node, position, quaternion}`, then move it: compute the world position, add the offset, and convert back to parent-local with `node.parent.worldToLocal(...)`. Call `node.updateWorldMatrix(true, true)` afterwards.+ - Every return path after this point must return a cleanup that restores the parked nodes. Restore the clip's `restore` list FIRST and the parked list SECOND. Restructure the early returns (editing, no clip) so they return a cleanup that restores `parked`.+ - Build the clip with `buildStepClip(step, nodesById, glide)`, where `glide = staging.joins.get(activeStepIndex) ? { glide: { offset: join.offset, seconds: STAGING_GLIDE_SECONDS } } : {}`. Pass the glide only when not editing and not picking.+3. **Fade effect** (~line 1411): add `&& !staging.joins.has(activeStepIndex)` to `fadesIn`, because a join step glides and never fades.+4. **Camera framing effect** (~line 1670):+ - Add a JSON of `parkedOffsetsAt(...)` and the join offset to `framingKey`.+ - When building `componentBox`, translate each node's seated bbox by its parked offset (if any).+ - For a join step, also push the 8 corners of `componentBox` translated by `join.offset` into both `lookPoints` and `actionPoints`, so the frame covers the staging spot and the seat.+ - Where `getAssemblyBox()` is used for the framing center/radius, expand a clone of it by those translated corners when the step is staged or a join.+5. Leave the visual pass (`stepIndexByNode`, `visualForComponent`) unchanged. It already claims the first installing step, and staged steps come before their join.++**Verify:**+```bash+pnpm --filter @carbon/viewer typecheck+# Expected: exits 0+pnpm --filter @carbon/viewer test+# Expected: all suites pass (camera, fallback, graph, motion, plan, staging, visibility)+```+If the parked-restore ordering cannot be made correct inside the single clip effect (for example, a second effect also moves nodes), STOP and report. Do not add a second position-writing effect.++**Out of scope:** `MotionPathEditor`, `visibility.ts` view modes, and the fallback algorithm.++---++## Task 5: ERP service — join validation, reorder cleanup, mapper++**Depends on:** 1+**Files:**+- Modify: `apps/erp/app/modules/production/production.models.ts`: add a validator next to `assemblyInstructionStepHiddenComponentsValidator` (~line 1473)+- Modify: `apps/erp/app/modules/production/production.service.ts`: new `updateAssemblyStepJoin` after `updateAssemblyStepHiddenComponents` (~line 7288); change `updateAssemblyInstructionStepOrder` (~line 7490); map `joinStepId` in `toViewerStep` (~line 9263)+- Modify: `apps/erp/app/routes/x+/assembly+/$id.steps.order.tsx`: pass `params.id`++**Steps:**+1. Validator:+ ```ts+ export const assemblyInstructionStepJoinValidator = z.object({+ joinStepId: zfd.text(z.string().optional())+ });+ ```+ Match whatever `zfd`/`z` import style the file already uses. An empty value means "build in place".+2. Service function. It uses the supabase client and is scoped by `companyId`:+ ```ts+ export async function updateAssemblyStepJoin(+ client: SupabaseClient<Database>,+ data: { stepId: string; joinStepId: string | null; companyId: string; updatedBy: string }+ ): Promise<{ error: string | null }>+ ```+ - Load the step (`id, assemblyInstructionId, sortOrder`) with `.eq("id").eq("companyId")`. If it is missing, return `{ error: "Step not found" }`.+ - If `joinStepId` is set: load all steps of the instruction (`id, sortOrder, parentStepId`) with one query, ordered by `sortOrder`. Reject when:+ - the join is not in that list: "The join step is not in this instruction";+ - the step is the first in the list: "The first step is the base and can't be built aside";+ - `join.sortOrder <= step.sortOrder`: "The join step must come after this step";+ - `join.parentStepId` is not null: "The join step is itself built aside";+ - any row has `parentStepId === step.id`: "This step is a join step, so it can't be built aside".+ - Update `parentStepId`, `updatedBy` and `updatedAt` on the step. Return `{ error: update.error?.message ?? null }`.+ - Doc comment: "parentStepId = the join step this step is built aside for (see the sub-assembly staging spec)."+3. `updateAssemblyInstructionStepOrder(db, assemblyInstructionId, updates)`: after the sortOrder loop, inside the same transaction, clear the links that now point backwards:+ ```ts+ await trx+ .updateTable("assemblyInstructionStep as s")+ .set({ parentStepId: null })+ .where("s.assemblyInstructionId", "=", assemblyInstructionId)+ .where("s.parentStepId", "is not", null)+ .where(({ exists, selectFrom }) =>+ exists(+ selectFrom("assemblyInstructionStep as j")+ .select("j.id")+ .whereRef("j.id", "=", "s.parentStepId")+ .whereRef("j.sortOrder", "<=", "s.sortOrder")+ )+ )+ .execute();+ ```+ Update the only caller, `$id.steps.order.tsx`, to pass `params.id`. Confirm with a `grep -rn "updateAssemblyInstructionStepOrder" apps packages` that there is no other caller. If there is one, STOP and report.+4. `toViewerStep`: add `joinStepId: step.parentStepId ?? null`.+5. Regenerate the MCP digest only if the repo's check requires it after adding a service function: run `pnpm run generate:mcp` if `apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json` is stale. The digest was regenerated in the previous commit on this branch, so follow the same practice.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: typecheck task for erp succeeds+```++**Out of scope:** the DB trigger, migrations and `reassignAssemblyStepComponents`.++---++## Task 6: ERP join route + path helper++**Depends on:** 5+**Files:**+- Create: `apps/erp/app/routes/x+/assembly+/$id.steps.join.$stepId.tsx`+- Modify: `apps/erp/app/utils/path.ts`: add `assemblyInstructionStepJoin` next to `assemblyInstructionStepHiddenComponents` (~line 376)+- Copy from (precedent): `apps/erp/app/routes/x+/assembly+/$id.steps.hidden.$stepId.tsx`++**Steps:**+1. Path helper: `assemblyInstructionStepJoin: (id: string, stepId: string) => generatePath(\`${x}/assembly/${id}/steps/join/${stepId}\`)`.+2. Route: copy the hidden route. Use `requirePermissions(request, { update: "production" })` and also take `companyId` from its result. Validate with `assemblyInstructionStepJoinValidator` and call `updateAssemblyStepJoin(client, { stepId, joinStepId: validation.data.joinStepId || null, companyId, updatedBy: userId })`. On `error`, return `data({ success: false, message: error }, await flash(request, error(null, message)))`. On success, return `{ success: true }`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: succeeds+```++**Out of scope:** any other step route.++---++## Task 7: ERP step Details — "Build off to the side" select + join summary++**Depends on:** 2, 5, 6+**Files:**+- Modify: `apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx`+- Modify: `apps/erp/app/routes/x+/assembly+/$id.tsx`: pass the new props+- Copy from (precedent): `StepStatusControl` in `apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx:928-1000` (autosaving `useFetcher` + `DropdownMenuRadioGroup`, optimistic value). For the box styling, copy the "Camera" box in `AssemblyInstructionProperties.tsx:~562`.++**Steps:**+1. New props on `AssemblyInstructionProperties`: `steps: AssemblyInstructionStepRow[]` (all steps, sortOrder-ordered), plus `onSelectStep: (stepId: string) => void`. Pass them from `$id.tsx`, which already has the steps list and a select-step handler. Find the existing handler name used by the Explorer and reuse it.+2. New component `StepJoinEditor` in the same file, rendered in `StepForm` directly after the Camera box:+ - Label: `<Trans>Build off to the side</Trans>`.+ - Options: "No, build in place" (value `""`), then for each VALID join step (the same rules as the service, computed client-side from `steps`): `t\`Yes, joins at step ${n}: ${title}\``. Use `describeStep` for untitled steps, the same way the header title does.+ - Disabled (plain text chip instead of a dropdown) when `isDisabled`, when this is the first step, or when this step is itself a join step. In those last two cases, show a muted one-line reason: `t\`The first step is the base.\`` / `t\`This step brings in a group, so it's built in place.\``.+ - On change, `fetcher.submit({ joinStepId }, { method: "post", action: path.to.assemblyInstructionStepJoin(instructionId, step.id) })`. Show the optimistic value from `fetcher.formData`.+3. On a join step (other steps point at it), render inside the same box a read-only line: `<Trans>Brings in the group from steps</Trans>` followed by step-number buttons (`Button variant="link" size="sm"`) that call `onSelectStep(id)`.+4. Helper text under the select (muted, `text-xs`): `<Trans>Its parts are built beside the model, then carried in at the join step.</Trans>`++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: succeeds+```++**Out of scope:** the Components and Hidden boxes (Task 8 changes only what they receive).++---++## Task 8: ERP explorer badge, Regenerate warning, own-parts in route++**Depends on:** 2, 5+**Files:**+- Modify: `apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx`: step row (~line 1100) and Regenerate modal (~line 815)+- Modify: `apps/erp/app/routes/x+/assembly+/$id.tsx`: `selectedOwnNodeIds` (~line 298)+- Copy from (precedent): the `needsSupport` icon span in the same step row, for badge placement; `Badge` from `@carbon/react`++**Steps:**+1. Step row: when `step.parentStepId` is set, render `<Badge variant="secondary" className="shrink-0"><Trans>Built aside</Trans></Badge>` before the `×count` span.+2. Regenerate modal body: when any step has `parentStepId`, add a paragraph: `<Trans>Regenerating removes "Build off to the side" settings.</Trans>`+3. `$id.tsx`: extend `selectedOwnNodeIds` to include the staged group when the selected step is a join step:+ ```ts+ const selectedOwnNodeIds = useMemo(() => {+ const own = draftComponentNodeIds ?? selectedStep?.componentNodeIds ?? [];+ if (!selectedStep) return own;+ const staged = stagedGroupNodeIds(viewerSteps, selectedStep.id);+ return staged.length === 0 ? own : [...new Set([...own, ...staged])];+ }, [draftComponentNodeIds, selectedStep, viewerSteps]);+ ```+ (`viewerSteps` is defined further down at ~line 432. Move its `useMemo` above this one.) Check every consumer of `selectedOwnNodeIds` (grep in the file). It must only feed the "This step" badge, the hide eligibility and the hidden-list filter. If it also feeds a SAVE of `componentNodeIds`, STOP and report.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: succeeds+```++**Out of scope:** the BOM-tree "Move / Add a copy" modal.++---++## Task 9: MES select + mapper++**Depends on:** 1+**Files:**+- Modify: `apps/mes/app/services/operations.service.ts:~640`: add `parentStepId` to the select string+- Modify: `apps/mes/app/components/AssemblyView.tsx:190-230`: add `parentStepId: string | null` to the `AssemblyPlayback` step type, and `joinStepId: step.parentStepId ?? null` in `toViewerStep`++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: succeeds+```++**Out of scope:** any MES UI.++---++## Task 10: Lingui extraction++**Depends on:** 7, 8+**Steps:**+1. Run `pnpm run lingui:extract`.+2. `git diff --stat packages/locale` must show only the ERP catalogs (`packages/locale/locales/*/erp.po`) plus any lines the extract touched for the new strings. If unrelated catalogs churn heavily, revert that churn with `git checkout -- <file>` and keep only the new msgids.+3. Run `pnpm run lingui:clean` if the headers changed (the repo's own script).++**Verify:**+```bash+grep -c "Build off to the side" packages/locale/locales/en/erp.po+# Expected: 1 or more+```++---++## Task 11: Docs++**Depends on:** 4+**Files:**+- Modify: `packages/viewer/AGENTS.md`:+ - In the Step concept, replace "subassembly `phase`" with "`joinStepId` (built off to the side, see `staging.ts`)".+ - Fix the stale "must contain an `isolate` view" rule to match `visibility.ts` (Isolate was dropped on this branch).+ - Add `staging.ts` to the key building blocks, and the staging test to the test list.+- Modify: `apps/erp/app/modules/production/AGENTS.md`: one line under Assembly Instructions: "`assemblyInstructionStep.parentStepId` = the join step a step is built aside for (sub-assembly staging); written by `updateAssemblyStepJoin`, cleared on reorder when it points backwards."++**Verify:**+```bash+grep -n "joinStepId" packages/viewer/AGENTS.md+# Expected: at least one match+```++---++## Task 12: End-to-end verification++**Depends on:** all+**Steps:**+1. Run:+ ```bash+ pnpm --filter @carbon/viewer test+ pnpm --filter @carbon/viewer typecheck+ pnpm exec turbo run typecheck --filter=erp --filter=mes+ pnpm run lint+ ```+ Expected: all pass. Report any failure with its output.+2. Browser check (ask the user first, per AGENTS.md "With the user's permission, use the /auth and /test skill"): on an assembly with at least 5 steps, run acceptance criteria 1–5 and 7 from the spec. Take screenshots of step 4 (group at the side) and mid-glide on step 6. Check criterion 6 (MES) only if the MES app is running locally.+3. Tick the Progress list, and add a changelog line to the spec ("implemented").+4. Do NOT commit. Report to the user in 1–3 lines.diff --git a/.ai/playbooks/assembly-subassembly-staging.md b/.ai/playbooks/assembly-subassembly-staging.mdnew file mode 100644index 0000000000..1344b23709--- /dev/null+++ b/.ai/playbooks/assembly-subassembly-staging.md@@ -0,0 +1,13 @@+# Assembly sub-assembly staging ("Build off to the side")++Last tested: 2026-09-28 ([email protected] bypass user, "Carbon Development")+Route: /x/assembly/:id — used "Sync 4 - SA Frame test 2" (Draft, 5 steps, 70 parts)++## Steps+1. /auth, then open /x/production/assemblies and read the instruction link's href (clicking the row lands on the list).+2. `agent-browser set viewport 1600 1000` — at the default size the Details panel clips the new box.+3. Move between steps with the footer "Next step" / "Previous step" buttons. Clicking a step row can hit its status dropdown.+4. Details → "BUILD OFF TO THE SIDE": a button opens a radio menu ("No, build in place" / "Yes, joins at step N: …"). Step 1 and join steps render it as locked text.+5. Replay a step from 0 with `agent-browser dblclick @<step row ref>`. Screenshot ~0.45s and ~0.95s in to catch the glide.+6. Reorder: pointer-drag a "Drag handle" (mouse down, then several moves, then up). HTML5 `drag` doesn't drive framer-motion Reorder.+7. Restore: drag the order back and set each step to "No, build in place".diff --git a/.ai/research/2026-09-28-assembly-subassembly-staging.md b/.ai/research/2026-09-28-assembly-subassembly-staging.mdnew file mode 100644index 0000000000..cc99b723f6--- /dev/null+++ b/.ai/research/2026-09-28-assembly-subassembly-staging.md@@ -0,0 +1,207 @@+# Sub-assembly staging: current-state research++Repo: `/Users/aashu/work/carbon/carbon-feat-asembly-view-isolation` (HEAD `adc20aa2ce`, clean tree).+Paths below are relative to that root. Anything I inferred rather than read is marked **(inference)**.++---++## TL;DR++- **Staging is half-built already.** `packages/viewer/src/plan.ts:460-610` `assignStepPhases` sorts plan step groups into "staged subassembly clusters" plus the step where each one `join`s. `AssemblyStep.phase` is typed at `types.ts:117-123`. The docs say a phase "builds staged off to the side and flies into the main body at its `join` step" (`plan.ts:146-153`).+- **None of it is used.** `generateAssemblyStepsFromPlan` never writes `group.phase` (`production.service.ts:9155-9201`). There is no `phase` column. `toViewerStep` (ERP `production.service.ts:9263-9284`, MES `AssemblyView.tsx:210-230`) never sets it. `AssemblyPlayer.tsx` never reads it: grep finds `phase` only in `types.ts` and `plan.ts`. `plan.test.ts` has no phase tests (grep count 0).+- **Every motion is relative to the node's seated pose and ends at it.** Nothing represents a node resting at a non-seated pose between steps. The player assumes every node sits at its GLB pose except while the active step's clip is playing (`motion.ts:18-21`, `462-463`; `AssemblyPlayer.tsx:1327-1366`).+- **"One node, one step" is not enforced in the DB.** The ERP even has an "Add a copy" (duplicate) path. The viewer's visibility map only counts the *first* step that names a node (`AssemblyPlayer.tsx:1046-1061`). The planner's re-motion mode drops a node that appears in a second group (`pipeline2.rs:1771-1776`).++---++## 1. Data model++### `assemblyInstructionStep` (created in `packages/database/supabase/migrations/20260610151942_assembly-instructions.sql:41-81`)+- `componentNodeIds TEXT[] NOT NULL DEFAULT '{}'` (`:60`): the leaf `nodeId`s this step installs.+- `motion JSONB NOT NULL DEFAULT '{"type": "none"}'` (`:61`). It holds one Motion object for the whole step, not one per component (see section 2).+- `camera JSONB` (`:62`), `fastener JSONB` (`:64`), `warnings JSONB` (`:65`; holds `{flagged, blockedBy, needsSupport}`, written at `production.service.ts:9182-9192`).+- `planConfidence` `high|low|manual` (`:66`), `durationSeconds` (`:67`).+- **`explode JSONB` (`:63`) is an unused column.** The design spec calls it "per-step exploded offsets" (`.ai/specs/2026-07-04-animated-work-instructions-design.md:148`). No app or viewer code reads or writes it. A grep for `explode` in apps/packages only hits the generated types (`packages/database/src/types.ts:3614`) and MCP tool metadata.+- **`parentStepId` (`:44`, FK `:76`) is unused.** The design spec says "subassembly grouping" (`design.md:144`). Its only use is being remapped during version copy (`production.service.ts:6701-6703`).+- Later additions:+ - `status` Todo/Review/Done (`20260610183947_assembly-step-status.sql:5-8`).+ - `buildWave INTEGER` (`20260712180545_assembly-step-build-wave.sql:6`).+ - `rootStepId` for version lineage (`20260910093006_assembly-step-lineage.sql:12-14`).+ - `hiddenComponentNodeIds TEXT[] NOT NULL DEFAULT '{}'` (`20260925063121_assembly-step-hidden-components.sql:5-6`). A BEFORE INSERT/UPDATE trigger removes the step's own `componentNodeIds` from that list and dedupes it (`:11-29`).+- Version copy spreads `...rest` from `select("*")` (`production.service.ts:6693-6711`), so any new column is copied automatically.+- Child tables keyed by `stepId`: `assemblyInstructionStepMaterial` (`20260610191824_assembly-step-requirements.sql:149-...`), `assemblyInstructionStepSlide` and `assemblyInstructionStepTool` (`20260721170301_assembly-step-slides-and-tools.sql:13-44, 93-118`).++### `assemblyUnit` (`20260611134652_assembly-editor-parity.sql:1-38`)+- Columns: `modelUploadId`, `name`, `componentNodeIds TEXT[]`, `itemId`. It is scoped to the model upload, not the instruction.+- Header comment (`:1-6`): "sets of model leaf nodes the motion planner treats as one rigid body". It is a user override on top of auto derivation. "A subassembly with its own build steps is simply the child item's own instruction — no child link here."+- `sourceGroupId` (`20260712163840_assembly-unit-source-group.sql:7-11`): NULL means the user authored it. `swarm:<host>` means the planner detected it. UNIQUE `(modelUploadId, sourceGroupId)`.+- How units are used:+ 1. **Planning input.** `loadPlanUnits` sends only units with more than one member as `options.units` (`packages/jobs/src/inngest/functions/tasks/plan-units.ts:19-47`). The planner merges them into one rigid body (`crates/planner/src/steps.rs:190-200`, `pipeline2.rs:1259-1290`). They come back as `plan.groups[gid]` with one shared motion (`packages/viewer/src/plan.ts:66-74`), and `buildAssemblyStepGroups` gives each group exactly one step (`plan.ts:306-309`, `317-326`).+ 2. **Materialized.** Detected swarm groups become `assemblyUnit` rows at step generation (`production.service.ts:9083-9144`).+ 3. **Step titles.** If a step's components exactly match a unit's set, `describeStep` titles it "Add <unit name>" (`packages/viewer/src/describe.ts:28-35, 62-82`). Generation writes the planner group `name`, falling back to `describeStep` (`production.service.ts:9146-9173`).+ 4. **Kept in sync on reassign.** Moving a part into a step that installs a unit also adds it to that unit (`production.service.ts:7382-7451`).+- A unit is a *planning* concept only: "one rigid body, one step". Nothing gives a unit a separate build sequence or pose.++## 2. Motion type and playback++### Type (`packages/viewer/src/types.ts:13-65`)+- `linear {direction, distance}`, `L {segments[]}`, `helix {axis, origin, pitch, turns, approach}`, `path {keyframes[{t, position, quaternion}]}`, `none`.+- The doc comment says it describes the INSERTION; "the viewer derives removal (the reverse) and start poses from it" (`:56-59`).+- linear, L and helix are **relative translations/screws anchored at the seated pose**.+- `path` keyframes are **absolute world poses**, and "the last keyframe must equal the component's final (seated) pose" (`:40-49`).+- The ERP Zod schema mirrors this (`apps/erp/app/modules/production/production.models.ts:1218-1258`).+- The Rust planner only emits `None | Linear | L`, all pure translation (`crates/planner/src/types.rs:188-210`).++### One motion per step, applied to each node+- `buildStepClip` loops over `step.componentNodeIds`. For each node it takes the node's CURRENT world pose as the `basePose` (the seated pose) and builds keyframes from the one shared `step.motion` (`motion.ts:467-497`).+- Its doc says: "Nodes are assumed to currently sit at their final (seated) pose" (`motion.ts:462-463`).+- Start pose:+ - linear: `seated - direction*distance` (`motion.ts:305-317`).+ - L: walks backward from the seated pose through the segments (`:319-348`).+ - helix: unscrews and retracts from the seated pose (`:350-414`).+ - path: the absolute keyframes, which must end at that node's seated pose or the code throws (`:416-452`).+- **(inference)** A `path` motion on a step with more than one node throws for every node except one, because each node has a different seated pose while the step has one keyframe list. This is why the editor writes relative `linear`/`L` "so it applies to every component in a rigid-group step" (`motion.ts:599-606`).+- It does not use the `explode` column or any stored offset. The only "start pose" is the one the motion implies.++### Display-only changes in the player (`AssemblyPlayer.tsx:318-380`)+- **Fallback motion.** Steps saved with `none` that are neither flagged nor the first step get an AABB fallback via `displayMotionForStep` (`motion.ts:129-150`). Its obstacle world is the set of nodes installed by earlier steps, at their seated poses (`AssemblyPlayer.tsx:335-340`).+- **Travel is clamped.** `naturalizeMotion` limits linear/L travel to at most `min(3*diag+5, 0.35*assemblyDiagonal)`, with a floor for small parts (`motion.ts:152-234`). **A long staging-to-seat translation stored as linear/L would be shortened on screen.**++### Timeline and pose at a given time+- Each step's segment length comes from `stepTimelineSeconds`: `durationSeconds`, otherwise motion duration plus a 0.6 s hold, otherwise 2 s for `none` (`motion.ts:68-76`, `51-60`). Start times are cumulative (`AssemblyPlayer.tsx:382-398`).+- Only the ACTIVE step has a clip. The effect saves the seated transforms of the active step's nodes, plays the clip `LoopOnce` with clamp, and restores the seated transforms on cleanup (`AssemblyPlayer.tsx:1291-1377`). Scrubbing inside a step sets `action.time` (`:1384-1397`).+- A static selection snaps to the end of the clip, i.e. seated (`:1347-1356`).+- Every node outside the active step keeps its GLB seated transform. Nothing else in the player writes `node.position`/`quaternion`: the only writes are the restore at `:1363-1365`; `:1552` and `:1653` move the camera.+- Flagged steps, or `none` steps after the first, fade in at the seated pose (`:1403-1487`).+- Camera framing uses `insertionStartOffset(step.motion)` to include the travel start in the view (`:1752-1771`, `2221-2247`).++## 3. Motion planning++- **Who runs it.** ERP route `apps/erp/app/routes/x+/assembly+/$id.plan.rerun.tsx:14-185` triggers Inngest `assembly-plan` (`packages/jobs/src/inngest/functions/tasks/assembly-plan.ts:34-320`). That calls the Rust assembler service `/plan` (`apps/assembler`, planner crate `crates/planner`). The result is `plan.json` in storage (`assembly-plan.ts:156`, `257-283`).+- **Modes:**+ - **Fresh.** Used when there are no steps, or when `fresh=1` ("Regenerate"). It derives both the order and the motions. Inputs are `options.units` (`assembly-plan.ts:178-187, 227-231`). Steps are then built by `generateAssemblyStepsFromPlan` (`production.service.ts:9001-9256`) through `buildAssemblyStepGroups` (`plan.ts:274-458`).+ - **Re-motion.** Used when steps exist. It keeps the order. The input is `options.sequence`, the ordered array of each step's `componentNodeIds` (`assembly-plan.ts:158-177`). `plan_fixed_sequence` merges each group into one rigid body and plans its insertion against the union of EARLIER groups at their SEATED poses (`crates/planner/src/pipeline2.rs:1746-1920`). `updateAssemblyStepMotionsFromPlan` then writes `motion`, `camera` (unless it was set manually), `warnings` and `planConfidence` back, matching steps to groups by component-set equality and skipping Done steps (`packages/jobs/.../update-step-motions.ts:30-137`).+- **Inputs:** the STEP source URL, `units` or `sequence`, and deflection/clearance/tolerance options (`apps/assembler/src/actions/plan.rs:171-215`; `crates/planner/src/steps.rs:171-185`).+- **Outputs:** plan.json with `sequence`, `components{motion, confidence, blockedBy, tier, groupId, mergedInto, wave, viewDirection}`, `groups`, `contacts` and `warnings` (`plan.ts:12-83`). `contacts` is written at `steps.rs:400-420`. The comment there says it is "Used by the step grouping's floater fold + phase partition" (`:404-405`).+- **Can it plan from an arbitrary (staging) start pose? No, as built.**+ - It is "assembly-by-disassembly": it searches removal directions from the seated state (`greedy.rs:120-140`, `353-363`) and returns an insertion that ends at the seat.+ - It never takes a start/target pose as input. The motion enum can only express translations from the seat (`types.rs:188-194`).+ - Re-motion's obstacle world is "all earlier groups, seated" (`pipeline2.rs:1846-1871`). A sub-assembly built at a staging spot would be wrongly counted as an obstacle at its seated location. **(inference)**+ - Re-motion also drops a node that appears in a later group: "already belongs to an earlier group; dropped" (`pipeline2.rs:1771-1776`). So a join step that repeats the bearing and circlip nodes would plan as empty or partial.+ - A pure-translation staging offset *could* be written as a relative `L` motion (seat → offset). But the planner would not choose that offset, and the player's `naturalizeMotion` would clamp it (see section 2).++## 4. Per-step visibility++- `stepIndexByNode` maps each node, **including its descendants**, to "the first step that installs it". It only claims a node if it isn't already claimed (`AssemblyPlayer.tsx:1040-1061`). **This is the main place that assumes one step per node.** A node repeated on a later step is still treated as installed from its first step.+- `visualForComponent(stepIndex, activeStepIndex, futureMode, installedMode)` returns `solid|ghost|hidden` for earlier steps, `active` for the current step, and follows `futureMode` for later or never-installed nodes (`visibility.ts:59-90`).+- `occluderWeight` must agree with it (`visibility.ts:92-124`; rule stated in `packages/viewer/AGENTS.md:20`).+- Named views: build = installed solid, future hidden; focus = installed ghost, future hidden; full = everything solid (`visibility.ts:18-39`).+- The visual pass (`AssemblyPlayer.tsx:1083-1252`):+ 1. Resets every node.+ 2. Applies `visualForComponent` per node in `stepIndexByNode`.+ 3. Treats unassigned leaves as future.+ 4. Applies external highlight, then focus/isolate, then **hides everything in `hiddenSet`**, then selection, then drill-ghost.+- `hiddenSet = stepHiddenNodeIds(activeStep)`: the active step's list minus its own components (`visibility.ts:126-138`, `AssemblyPlayer.tsx:1017`). The DB trigger enforces the same rule (see section 1).+- Other places that assume a node's pose/presence comes from a single step:+ - `displaySteps` builds `present` by adding each step's nodes cumulatively, all seated (`AssemblyPlayer.tsx:335-340`).+ - The re-motion obstacle world (section 3).+ - `buildStepClip` assumes a seated start (`motion.ts:462-463`).+- Stale docs:+ - `packages/viewer/AGENTS.md:21` still says the view table must contain an `isolate` view. `visibility.ts:25-27` says Isolate was dropped.+ - The contracts spec says "Parts in no step are always shown solid" (`.ai/specs/2026-07-04-animated-work-instructions-contracts.md` §5, end). The code treats them as future (`visibility.ts:61-65`).++## 5. ERP authoring UI++- **Route** `apps/erp/app/routes/x+/assembly+/$id.tsx`.+ - Add-mode: `onStartAddComponents` (`:404-408`). Picks union into the active step's draft and autosave through `saveComponentNodeIds`, which posts to `$id.steps.components.$stepId.tsx` (`:269-283`, `363-384`).+ - Remove: `:415-430`.+ - Hidden list: `onSetHiddenComponents` posts to `$id.steps.hidden.$stepId.tsx` (`:285-320`).+ - `viewerSteps = steps.map(toViewerStep)` (`:432-442`).+ - The player receives `componentPickerActive={isAddingComponents}` (`:635-664`).+- **Components autosave** (`$id.steps.components.$stepId.tsx:15-77`) calls `updateAssemblyStepComponents` (`production.service.ts:7266-7284`) and then syncs materials for newly added nodes. It does not check whether a node is already on another step.+- **BOM-tree assign** (`AssemblyBomTree.tsx:397-459`, modal `:966-1013`, "Move or add a copy?"):+ - `duplicate` ("Add a copy") vs `move` ("Move here").+ - Service `reassignAssemblyStepComponents` (`production.service.ts:7308-7453`): "`duplicate` unions them onto the target only (a component may live on several steps)" (`:7308-7313`).+ - `move` strips the nodes from other steps and deletes any step that becomes empty (`:7354-7369`).+ - **So multi-step membership is already allowed and authored. It just has no motion or pose meaning.**+- **New step** (`AssemblyInstructionExplorer.tsx:502-529`) seeds `componentNodeIds` from the selection plus `synthesizeFallbackMotion` against all nodes already on steps.+- **Motion editing** (`$id.steps.motion.$stepId.tsx:16-64` calls `updateAssemblyStepMotion`, `production.service.ts:7232-7261`). The drag editor turns waypoints into relative linear/L (`motion.ts:560-639`), anchored at the centroid of the seated nodes (`AssemblyPlayer.tsx:988-1013`, `2178-2182`).+- **Units:**+ - Created from the BOM tree through "Plan as one component" (`AssemblyBomTree.tsx:1255-1300`, posts to `path.to.newAssemblyUnit`; route `$id.units.new.tsx`).+ - Edit and delete: `:1329-1409`. The toast after editing says "Subassembly updated — re-run motion planning to apply the change" (`:960-962`).+ - The tree shows units as virtual rows (`:142-150`, `1018-1170`). `stepUsage` lists every step that uses a component group, so it already handles more than one step (`:279-300`).+- **Step titles:** `describeStep(toViewerStep(step), graphIndex, namedUnits)` (`AssemblyBomTree.tsx:384-395`; Explorer `:407-437`).+- **Materials:** seeded per step from that step's `componentNodeIds` (`deriveAssemblyStepMaterialSeeds`, `production.service.ts:7754-7795`). **(inference)** If a join step repeats the bearing and circlip nodes, it would seed those BOM items again, so the same parts would be consumed twice in BOP/MES.++## 6. MES viewing++- `apps/mes/app/services/operations.service.ts:608-651` (`getAssemblyPlaybackByOperationId`) selects these step fields: `id, title, instructionText, componentNodeIds, hiddenComponentNodeIds, motion, camera, fastener, durationSeconds, warnings`, ordered by `sortOrder` (`:637-643`).+- `apps/mes/app/components/AssemblyView.tsx`:+ - The local `AssemblyPlayback` type (`:190-205`) and a separate MES `toViewerStep` (`:210-230`). It duplicates the ERP mapper and sets `flagged` from `warnings.flagged`. It has no `phase` or `explode`.+ - `playbackIndex` maps the BOP step to its instruction step through `assemblyInstructionStepId` (`:1082-1088`).+ - The player runs with `autoPlay loop readOnly hideCaption` (`:1975-1989`).+- Any new step field must be added in three places: the MES select, the MES type/mapper, and the ERP `toViewerStep` (`production.service.ts:9263-9284`).++## 7. Existing specs, plans and docs++- `.ai/specs/2026-07-04-animated-work-instructions-contracts.md`: shared contracts. Covers nodeId, graph.json, the `/plan` API, plan.json groups, the Motion JSON (§4, `:295+`) and viewer step shape plus playback semantics (§5, `:333+`).+- `.ai/specs/2026-07-04-animated-work-instructions-design.md`: original design. Promises "exploded views", the `explode JSONB` "per-step exploded offsets", and `parentStepId` "subassembly grouping" (`:7, 88, 144-148`).+- `.ai/specs/2026-07-04-assembly-editor-requirements.md` §4: parity wish-list. A subassembly would be a child instruction whose parent step animates it "as a unit … from their exploded state to their final pose" (`:166-174`). The `assemblyGroup` proposal (`:176-183`) was later superseded.+- `.ai/plans/2026-07-06-bom-driven-subassembly-planning.md`: D0 collapses the grouping taxonomy into one Subassembly unit. It drops `childInstructionId` ("parent never spawns or links child instructions; it just consumes the subassembly as one part") and rescopes the unit to `modelUploadId` (`:40-58`).+- `.ai/plans/2026-07-06-order-preserving-motion-replan.md`: the design behind re-motion with fixed order and forward collision.+- `.ai/plans/2026-07-06-assembly-visual-motion-camera-editor.md`: drag-waypoint motion editor plus per-step camera.+- `.ai/plans/2026-07-05-assembly-planner-v3.md`, `2026-07-06-planner-secured-last-and-gaskets.md`, `2026-07-06-planner-regression-fix.md`, `2026-07-09-assembly-sequence-connectivity.md`: planner ordering. Connectivity covers floating islands and base selection.+- `.ai/specs/2026-09-17-viewer-installed-component-visibility.md` plus its plan: `installedMode` and named views.+- `.ai/specs/2026-09-25-assembly-step-hidden-components.md` plus its plan: the per-step `hiddenComponentNodeIds` on this branch.+- `.ai/specs/2026-07-15-assembler-deployment.md`, `2026-07-15-assembler-model-pipeline.md`, `.ai/plans/2026-07-10-geometry-service-rust-rewrite.md`: assembler service infrastructure.+- `.ai/research/animated-work-instructions.md` §5: suggests exploding along the planner's removal directions with offset = bbox clearance × a constant, and flags auto-explode patents US 9,053,258 and US 7,295,201 (`:85-93`).+- `.ai/lessons.md`:+ - "Assembly viewer camera + animation principles" (`:79`): constant zoom, exaggerate small parts, manual motion as an escape hatch.+ - "Never fabricate a best-effort motion through geometry" (`:144`).+ - "Verify what actually rendered before root-causing a bad motion report" (`:222`).+- `packages/viewer/AGENTS.md`:+ - Lists `phase` as part of Step and says `./steps` exports `assignStepPhases` (`:9, 16, 46`).+ - "Ask first" before changing `types.ts` or `CURRENT_PLAN_VERSION` (`:23-26`).+ - Never fabricate motion for flagged parts, and never let overlapping corridors animate at the same time (`:28-32`).+- `apps/erp/app/modules/production/AGENTS.md`:+ - Assembly Instructions concept and versioning (`:15`).+ - Table list (`:73-77`).+ - Service docs for `generateAssemblyStepsFromPlan` (floater fold, `:110`) and unit derivation (`:113`).+ - No mention of phases or staging.+- `apps/assembler/AGENTS.md`: planner crate layout.+- I found no spec or plan about sub-assembly *staging*, *phases*, or moving a node more than once. A grep for "staged off / off to the side / assignStepPhases / subassembly phase" across `.ai` and `docs` returned nothing.++## 8. Existing notions of multi-step nodes, pose, offset, staging and explode++- **Staging/phase:** `plan.ts:146-153, 180-185, 452-456, 460-610` and `types.ts:117-123`. Computed but not persisted or played (see TL;DR). Details of the algorithm (`plan.ts:471-480`):+ - It replays the sequence and tracks which bodies connect to the base (the first group).+ - A group that touches nothing already placed starts a staged "island".+ - A later group touching both the base and an island is that island's `join` step.+ - Islands that touch each other merge.+ - Ids are `p0..pn` in "staging lane order" (`:594`).+ - It needs `plan.contacts`, which only v3 plans have.+- **Floater fold:** `plan.ts:390-447`. Today's workaround for detached parts: fold a floating group into the next step that touches it, so they install as one rigid step.+- **Node on more than one step:** allowed by the DB and the BOM-tree "Add a copy" (section 5). The player ignores repeat appearances for visibility (first step wins, `AssemblyPlayer.tsx:1049`). **(inference)** A repeat step would still build a clip for it and fly it in again from motion-start to seated, because `buildStepClip` animates every node in `componentNodeIds` (`motion.ts:480-553`). The planner's fixed-sequence mode drops repeats (`pipeline2.rs:1771-1776`).+- **Pose:** the only pose type is `Pose {position, quaternion}` inside keyframe math (`motion.ts:24-28`). The seated pose always comes from the GLB node transform. No non-seated rest pose is stored anywhere.+- **Offset:** only as the start offset implied by a motion (`AssemblyPlayer.tsx:2221-2247`) and as naturalize clamping (`motion.ts:170-234`).+- **Explode/exploded:** the `explode JSONB` column (unused) and documentation only (design spec, requirements §4.3, research §5).+- **`parentStepId`:** exists but unused, apart from the version-copy remap.++## Implications for "sub-assembly staging" (inference, for design)++- The cheapest foundation is to persist the computed `phase` and wire it through. `phase` is already in the viewer contract. It needs a column (or a JSON field), then `generateAssemblyStepsFromPlan`, both `toViewerStep` mappers, and the MES select.+- The player needs a per-node "rest transform per step" concept: a staging offset applied to nodes whose phase hasn't joined yet. It also needs a join-step clip that moves the whole staged cluster from its staging transform to seated, and `naturalizeMotion` must not clamp that move. The unused `explode` column is a natural home for a per-phase or per-step offset.+- `stepIndexByNode`'s "first step wins" rule works for visibility if the join step re-lists the nodes. The clip, the materials seeding and the re-motion planner all need a way to tell "moves an already-built group" apart from "installs".+- Within a phase, the planner's collision world would need the staged cluster in its own frame. Otherwise, re-plan the cluster's internal steps against only that cluster. `plan_fixed_sequence` currently treats every earlier group as seated.++---++## 9. How other tools handle sub-assemblies (web, 2026-09-28)++- **SOLIDWORKS Composer.** Each step is a saved view. Parts ("actors") can be moved freely away from their mated positions and hidden or shown. Authors often build the sequence backwards from the finished product, so a sub-assembly can be shown built aside and then inserted. Sources: [Javelin: panel instructions](https://www.javelin-tech.com/blog/2024/09/panel-assembly-instructions-using-solidworks-electrical-composer/), [Javelin: Composer sub-assemblies](https://www.javelin-tech.com/blog/2019/07/solidworks-composer-sub-assemblies/).+- **LEGO / BrickLink Studio.** A submodel's steps go in a callout box ("build this separately"), and the finished submodel is attached in a main step. Sources: [Rebrickable Studio guide](https://rebrickable.com/help/studio-instructions/), [Open L-Gauge guide](https://open-l-gauge.eu/making-building-instructions-in-studio/).+- **Dozuki.** The sub-assembly is its own guide, embedded in the main guide as a "prerequisite". Source: [Dozuki prerequisite guides](https://www.dozuki.com/blog/feature-spotlight-prerequisite-guides).+- **Cortona3D RapidAuthor.** Recommends splitting large assemblies into logical sub-assemblies, and sometimes showing where a sub-assembly fits in the whole. Source: [Cortona3D best practices](https://www.cortona3d.com/en/working-large-assemblies-best-practices).+- **Siemens Teamcenter Easy Plan.** Sub-assemblies are lines in the manufacturing BOM, each with its own process steps. Source: [Siemens Easy Plan](https://www.siemens.com/en-gb/products/tecnomatix/offerings/teamcenter-easy-plan/).++**Takeaway.** Composer and LEGO both use the same pattern inside ONE sequence: build the group aside, then place it as a whole in a later step. We adopt that pattern. Dozuki's separate-guide model already matches Carbon's "child item has its own instruction" design, so it needs no new work.diff --git a/.ai/runs/2026-09-28-thermo-nuclear-review-staging.md b/.ai/runs/2026-09-28-thermo-nuclear-review-staging.mdnew file mode 100644index 0000000000..706ae2c379--- /dev/null+++ b/.ai/runs/2026-09-28-thermo-nuclear-review-staging.md@@ -0,0 +1,90 @@+# Thermo-nuclear review: sub-assembly staging (uncommitted)++- **Scope:** working-tree diff on `feat/asembly-view-isolation` plus the new files `staging.ts`, `staging.test.ts` and `$id.steps.join.$stepId.tsx`. The `.po` catalogs and the MCP digest are excluded.+- **Verdict:** **Not approved yet.** Behaviour is right (133 viewer tests pass, browser-checked), but there are three blockers: a file pushed past 1k lines, the same rule written in three places, and staging checks scattered through the player.++## Blockers++### B1. The join rules exist in three places (SSOT)+The "which step may this step join?" rule is written three times, and each copy is phrased differently:+- the viewer: `validLinks` (`packages/viewer/src/staging.ts:~95`);+- the ERP service: `updateAssemblyStepJoin` (`production.service.ts`, five `if`s);+- the ERP UI: the `options`, `isBase` and `isJoin` filters in `StepJoinEditor` (`AssemblyInstructionProperties.tsx:~690`).++They already disagree: the viewer ignores a nested chain completely, while the UI and the service stop you creating one. The next rule change will drift them further apart.++**Code judo:** add ONE pure, three-free function to `staging.ts`, exported from `@carbon/viewer/steps`:+```ts+joinTargets(steps, stepId): { targets: string[]; lockedReason: "base" | "join" | null }+```+- The UI renders its options and locked text straight from it.+- The service calls it and rejects any `joinStepId` that is not in `targets`.+- `validLinks` becomes "keep a link only if its target is in `joinTargets(...).targets`".++That deletes five `if`s and two filters, and leaves one tested rule.++### B2. `AssemblyInstructionProperties.tsx` goes from 893 to 1056 lines+The whole ~150-line `StepJoinEditor` was added to a file that already holds four editors. The module already has a pattern for this: `AssemblyStepMaterials.tsx`, `AssemblyStepSlides.tsx` and `AssemblyStepTools.tsx` each live in their own file. Move it to `AssemblyStepJoin.tsx`. With B1 it also shrinks to the dropdown plus the "Brings in" line.++### B3. Staging checks are scattered through `AssemblyPlayer.tsx` (2646 → 2823 lines)+Staging reaches the player in eight separate places:+- the `staging` memo;+- a union branch and a `path`-shift branch inside the `displaySteps` memo;+- `segments`;+- a new `staging` prop plus `stagingLiveRef`;+- `stagingKey`, re-stringified on every render;+- park/glide in the clip effect;+- `!staging.joins.has(i)` in the fade effect;+- park/join shifts in the framing effect.++Every consumer has to know about a separate `Staging` object and look things up by index.++**Code judo:** `displaySteps` is already the "display-only adjustments" layer, so make staging part of the display step:+```ts+type DisplayStep = AssemblyStep & {+ parked: ReadonlyMap<string, Vec3>; // parts at a staging spot while this step shows+ glide: Vec3 | null; // join step: offset to glide in from+};+```+Build it in one pure helper, `stageSteps(steps, staging): DisplayStep[]` in `staging.ts`. It does the union, the path shift, `parked` and `glide`, and is unit-tested. Then:+- the `staging` prop, `stagingLiveRef` and `stagingKey` all disappear, because the scene reads `step.parked` and `step.glide`;+- `stepTimelineSeconds` adds `GLIDE` when `step.glide` is set, so the timeline rule lives in `motion.ts` and not in the player;+- the fade check becomes `!step.glide`;+- framing reads `step.parked` and `step.glide` directly.++`parkNodes` is three.js pose code, so move it beside `buildStepClip` in `motion.ts`. The player should end up adding ~40 lines instead of 177.++## Should fix++### S1. `updateAssemblyStepJoin`: two sequential queries, a non-standard return, and no ownership check+- **Two queries:** it loads the step and then its instruction's steps. The route already has the instruction id (`params.id`), so pass it in, load the instruction's steps ONCE, and find the step in that list. That removes a round trip and also proves the step belongs to that instruction.+- **Return shape:** it returns `{ error: string | null }`, but `conventions-services.md` says services return supabase `{ data, error }`. Match the siblings, like `updateAssemblyStepHiddenComponents`.+- **Race:** the check and the write are separate calls, so two authors could race. It's low risk here, but with B1 the whole rule becomes one small function. That makes a later move into the reorder's Kysely transaction trivial if it is ever needed.++### S2. A 5th copy of the step-title rule+`titleOf` in `StepJoinEditor` re-derives `title || describeStep(toStepDescriptor(...)) || "Untitled step"`. The same rule already lives in `Properties:139`, `Explorer:432` and `AssemblyBomTree:297/390`. Extract `assemblyStepTitle(row, graphIndex, units)` once, next to `toViewerStep`, and use it in all five places. At the least, don't add the fifth copy.++### S3. `$id.tsx` maps rows to viewer steps by hand+`selectedOwnNodeIds` builds `{ id, componentNodeIds, joinStepId: step.parentStepId }` itself, while `toViewerStep` (and the `viewerSteps` memo in the same file) already does exactly that mapping. Hoist `viewerSteps` above it and pass it in. One mapper, one place that knows `parentStepId` means `joinStepId`.++### S4. `staging.ts` relies on "magic" identity+`cursors` is a `Map<Vec3, number>` keyed by array identity. That only works because `stagingAxis` returns the same element of `STAGING_AXES`. The axis index is also recovered with `k = axis[0] !== 0 ? 0 : 2`. Model the axis as `{ index: 0 | 2; sign: 1 | -1 }` and key the lanes by `${index}${sign}`. That makes the identity trick and the index recovery unnecessary.++## Nits / comments++- **N1. Too many long comments.** Several new blocks are narration: the `displaySteps` "world" paragraph, the `stagingKey` comment, "A join step glides its group in…", "Keep the staging spot inside the standing distance…". After B3 most of them go away. Keep one comment on the park/unpark pairing, because that invariant is genuinely non-obvious.+- **N2. `none` special cases.** `buildStepClip` now special-cases `none` twice (`duration = 0` and a synthetic single keyframe). That's acceptable. A small `seatedKeyframes(pose)` helper would read better than the inline object literal.+- **N3. Brittle test lookup.** The `motion.test.ts` glide test finds the glide end by float time (`< 1e-5`). Asserting the position at index `EASE_SAMPLES` is less brittle.++## Good++- The reorder cleanup runs inside the existing Kysely transaction: atomic, and one statement.+- `staging.ts` has no three.js dependency and is well tested, including chains, stale ids, lanes and the camera side.+- No migration; the feature reuses the existing `parentStepId` foreign key, `ON DELETE SET NULL` and the version-copy remap.+- MES needs only a two-line change.++## Suggested order+1. B1: `joinTargets` in `staging.ts`, used by the service, the UI and `validLinks`, with tests.+2. B2: move the editor to `AssemblyStepJoin.tsx`, using B1.+3. B3: `DisplayStep` plus `stageSteps`; delete the `staging` prop, `stagingKey` and `stagingLiveRef`; move `parkNodes` to `motion.ts`.+4. S1, S3 and S4 together; S2 as its own small change if you want it.diff --git a/.ai/specs/2026-09-28-assembly-subassembly-staging.md b/.ai/specs/2026-09-28-assembly-subassembly-staging.mdnew file mode 100644index 0000000000..d5ab645ade--- /dev/null+++ b/.ai/specs/2026-09-28-assembly-subassembly-staging.md@@ -0,0 +1,252 @@+# Assembly instructions: build a sub-assembly off to the side++- **Status:** Implemented (MES playback not browser-checked)+- **Date:** 2026-09-28+- **Branch:** `feat/asembly-view-isolation`+- **Source:** customer ask in Slack, requirement 2 ("assemble the group, then show the group being assembled to a larger group"). Dom's example is SA-0033: bearing and circlip into the trailing arm; bearing, circlip and brake disc onto the front hub; front hub assembly onto the trailing arm assembly.+- **Research:** `.ai/research/2026-09-28-assembly-subassembly-staging.md` (current code, sections 1–8; other tools, section 9)++## Summary++An author can mark some steps of an assembly instruction as "built off to the+side", and name the later step where that group joins the main assembly (the+**join step**). In the 3D player, the parts those steps install appear at a+staging spot beside the main model. At the join step, the finished group glides+from the staging spot to just outside its seat, then does a normal insertion.+The ERP is where this is authored. MES plays it back and has no controls.++This is the pattern SOLIDWORKS Composer and LEGO instructions use (research §9).++## Goals++- Show a sub-assembly (e.g. the front hub with bearing, circlip and disc) being+ built away from the main assembly, then carried in as one piece.+- The author sets it up with one field per step in the ERP. Nothing new to+ model in CAD, and no new STEP file.+- MES shows exactly what the ERP authored.+- Each part's BOM materials are still consumed once, on the step that installs it.++## Non-goals++- **Nested sub-assemblies** (a group built aside inside another group built+ aside). A join step cannot itself be built aside in v1.+- **Dragging the staging spot.** The spot is computed automatically in v1 (Q2).+- **Planner support.** Motion planning (fresh or re-run) does not know about+ staging in v1. See "Planner" below for what that means in practice.+- **Automatic detection** of sub-assemblies (the unused `assignStepPhases` in+ `packages/viewer/src/plan.ts`). It stays unused (Q1).+- **Separate instructions per sub-assembly item.** Carbon already supports a+ child item having its own instruction; nothing changes there.+- Any control in MES.++## Design++### Terms++- **Staged step:** a step whose `parentStepId` points at a join step.+- **Join step:** a later step that one or more staged steps point at.+- **Staged group:** every part installed by the staged steps of one join step+ (descendants included, matching `stepIndexByNode`).+- **Moving parts of a join step:** its own `componentNodeIds` plus its staged+ group.++### Data model++No migration. `assemblyInstructionStep.parentStepId` already exists, with a+self-FK `ON DELETE SET NULL` (`20260610151942_assembly-instructions.sql:44,76`).+It has never been written by app code, and version copy already remaps it+(`production.service.ts:6701-6703`). It gets this meaning:++> `parentStepId` = the join step this step is built aside for. NULL = built in place.++Rules, enforced in the service layer on write (the route returns a field error):++1. The join step belongs to the same instruction.+2. The join step comes later (`sortOrder` greater than the staged step's).+3. The join step is not itself a staged step (no nesting), and a step that is+ already a join step cannot become a staged step.+4. The first step of the instruction (the base) cannot be staged.++When steps are reordered (`updateAssemblyInstructionStepOrder`), any link that+breaks rule 2 is cleared in the same write. Deleting a join step clears its+links through the existing FK. Regenerate steps replaces the steps, so links go+with them.++The unused `explode` column is **not** used in v1. The staging spot is computed+(Q2), so there is nothing to store yet. If dragging is added later, the offset+belongs in the join step's `explode` column.++### Viewer contract (`packages/viewer`)++`types.ts` changes (the viewer AGENTS.md says to ask before changing it; this+spec is that ask):++- `AssemblyStep` gains `joinStepId?: string | null`. It maps from `parentStepId`.+ The viewer name says what it means, and the DB name stays as it is.+- The typed but unused `phase` field is removed. It is never set by any mapper,+ and keeping two sub-assembly concepts on one type invites confusion.+ `assignStepPhases` itself stays in `plan.ts`, untouched.++New pure helpers in a new `packages/viewer/src/staging.ts`, unit-tested:++- `buildStaging(steps, graphIndex)` returns, per join step index, its staged+ group's node ids and its offset, plus a staged-step → join-step index map.+ Placement: beside the main model's bounding box, with a gap of 25% of the+ assembly diagonal, along whichever of +X or +Z is most side-on to the+ saved cameras of the staged and join steps (+X when none are saved). It is+ never above or below the model, since the viewer is Y-up. Several groups get+ their own lanes, stacked outward in join order. The offset is always a pure translation, so parts keep+ their orientation.+- `parkedOffsetsAt(staging, steps, activeIndex)` returns the parts that sit at+ a staging spot while a given step is shown.+- `stagedGroupNodeIds(steps, joinStepId)` returns the parts a join step carries+ in. The ERP uses it for the "This step" badge and the hide rules.++### Player behaviour (`AssemblyPlayer.tsx`, `motion.ts`)++Given active step index `a`, for a part in the staged group of join step `j`:++| When | Where the part is drawn |+|---|---|+| `a` < the staged step that installs it | not installed yet; follows the future mode, as today |+| installing step ≤ `a` < `j` | at seat + staging offset |+| `a` = `j` | animates: glides from seat + offset to the insertion start, then does the join step's insertion |+| `a` > `j` | at seat, as today |++- **Staged steps animate at the staging spot.** A staged step's own motion is+ relative to the seat (linear, L, helix), so playing it with the whole group+ translated by the offset gives the right picture with no motion changes.+ A `path` motion (absolute keyframes) gets the offset added to every keyframe.+- **Join step motion** = glide + insertion.+ - The insertion is the join step's saved `motion`, applied to all its moving+ parts, as today's shared step motion.+ - If the saved motion is `none`, the existing fallback (`displayMotionForStep`)+ synthesises one for the moving parts against the parts already seated.+ If that also fails, the group glides straight to the seat.+ - The glide is a straight translation from seat + offset to seat + insertion+ start offset, lasting 1.2 s. It is not clamped by `naturalizeMotion`.+ Only the insertion part is.+ - The join step's timeline length = glide + insertion + the existing hold.+- **Visibility.** `stepIndexByNode` still says which step installs a part. That+ controls whether it is drawn, so installed/ghost/focus modes behave as today.+ Only its position changes.+- **Per-step hiding.** At a join step, its moving parts cannot be hidden. They+ count as the step's own parts, both in the viewer (`stepHiddenNodeIds`) and in+ the ERP Components panel (the "This step" badge and the disabled eye).+ On staged steps, hiding works as today, so the author can hide the arm while+ the hub is being built.+- **Camera.** Auto-framing a staged step frames its parts at the staging spot.+ Auto-framing the join step includes the staging spot and the seat. A saved+ manual camera is used as-is.+- **Component picking and seated transforms.** Picking parts (add-components+ mode) still shows everything at its seat, so clicking a part always selects+ what the author expects. Staging positions apply only in play/preview.++### ERP authoring++In the step Details tab (`AssemblyInstructionProperties.tsx`), a new+**"Build off to the side"** field:++- A select: "No, build in place" (default), or "Yes, joins at: Step N – title",+ listing only valid join steps (rules 1–4).+- Saved through a new route `x+/assembly+/$id.steps.join.$stepId.tsx`, calling a+ new service function `updateAssemblyStepJoin(client, { stepId, joinStepId, companyId, userId })`.+ It validates the rules and scopes by `companyId`.+- Disabled when the instruction is not editable (same `isDisabled` as the other+ fields).++On a join step, Details shows a read-only line: **"Brings in the group from+steps 3, 4"**, with each step number linking to that step.++In the step list (`AssemblyInstructionExplorer.tsx`), staged steps get a small+"Built aside" icon with a tooltip, so the structure is visible without opening+each step. It is an icon, not a text badge, because a badge pushed the title out+of the narrow row.++All new copy uses Lingui (`<Trans>` / `t`) and gets extracted into every+`packages/locale/locales/*/erp.po`.++### MES++- `getAssemblyPlaybackByOperationId` (`apps/mes/app/services/operations.service.ts:637-643`)+ adds `parentStepId` to its select.+- The MES `toViewerStep` (`AssemblyView.tsx:210-230`) maps it to `joinStepId`.+- No UI change. The player does the rest.++The ERP `toViewerStep` (`production.service.ts:9263-9284`) gets the same mapping.++### Planner++No planner change in v1. What happens today stays true:++- Re-run motion planning plans staged steps as if the group were built in place.+ Their relative motions still look right at the staging spot. Their collision+ checks count the main model as an obstacle even though it isn't there, which+ can only make a motion more cautious than it needs to be, never wrong.+- A join step with no parts of its own sends an empty group. Re-run leaves its+ motion alone, so the player's fallback or the author's hand-edited motion is used.+- Regenerate (fresh plan) replaces all steps and drops every staging link. The+ "Regenerate" confirm dialog gets one extra sentence when the instruction has+ staged steps: "Regenerating removes 'Build off to the side' settings."++## Design decisions++| Decision | Choice | Why |+|---|---|---|+| How a sub-assembly is marked | Per step, "joins at" a later step (Q1) | Explicit, fits SA-0033, author can fix it. The planner's automatic phases only work on fresh plans. |+| Where the link is stored | Existing `parentStepId` column | Already typed, FK'd, `ON DELETE SET NULL`, and remapped by version copy. No migration. |+| Where the group sits | Auto spot to the right of the model, one lane per group (Q2) | No author work. Dragging can come later via `explode`. |+| What the join step lists | Its own parts only; it moves the staged group automatically (Q3) | Materials are never seeded twice, and the planner never sees a repeated node (it drops repeats, `pipeline2.rs:1771-1776`). |+| Join step motion | Glide to the insertion start, then the step's insertion (Q4) | Reads like a hand carrying the part in, and reuses the existing motion editor for the last move. |+| Nesting | Not in v1 | SA-0033 needs one level. Nesting multiplies the lane and validation rules. |+| Viewer field name | `joinStepId` (maps from `parentStepId`) | Says what it means at the call site. |+| Unused `phase` type | Removed | Never populated. Two sub-assembly concepts on one type would confuse. |+| Picking mode positions | Always at the seat | Clicking must select what the author sees in the BOM tree. |+| Planner | Unchanged in v1 | Its failure mode (overly cautious staged motions) is harmless. Real support needs Rust changes to plan a group in its own frame. |++## Acceptance criteria++Set up from SA-0033 (or the seeded demo assembly with an equivalent structure):+step 1 trailing arm (base), step 2 bearing + circlip into arm, step 3 bearing into+hub, step 4 circlip into hub, step 5 brake disc onto hub, step 6 front hub into arm.++1. In the ERP, set steps 3, 4 and 5 to "Build off to the side, joins at Step 6".+ The select on each offers only step 6 as a valid join step. Step 1 has the+ select disabled. Steps 3–5 show the "Built aside" icon (with a tooltip) in the step list.+ Step 6's Details reads "Brings in the group from steps 3, 4, 5".+2. Reload the page. The settings are still there.+3. Select step 4 in the ERP player. The hub, bearing and circlip are drawn to the+ right of the arm, not at their seats. Playing step 4 animates the circlip+ into the hub at that spot.+4. Select step 6 and play it. The hub group glides from the side to just outside+ the arm, then inserts and ends seated. Step 6 shows no extra BOM materials+ for the bearing, circlip or disc.+5. On step 6, the hub group's rows show "This step" in the Components panel, and+ their eye button is disabled. On step 4, hiding the trailing arm works and is+ saved.+6. Open the job operation linked to step 4 and then step 6 in MES. They look and+ animate the same as in the ERP, with no new controls.+7. Try to set step 6 to join at step 3. Rejected with a field error. Drag step 5+ above step 3, then reload. Step 5's link is kept, since it still comes before+ step 6. Drag step 6 above step 5. Step 5's link is cleared.+8. Create a new version of the instruction. Links point at the new version's+ step 6, not the old one.+9. `pnpm --filter @carbon/viewer test` passes, including new tests for+ `buildStaging` and `stagingOffsets`. The ERP and MES typecheck passes.++## Open questions (resolved)++- [x] Q1. How does the author mark a sub-assembly? — **Answer:** Pick the steps+ that build the group and point them at the later join step. Explicit and fixable,+ unlike automatic detection. The UI is one "joins at" select per step.+- [x] Q2. Where does the group sit while being built? — **Answer:** An automatic+ spot beside the main model. No dragging in v1.+- [x] Q3. Does the join step re-list the moved parts? — **Answer:** No. It moves+ the staged group automatically, and its own component list is only for new parts.+- [x] Q4. How does the group travel at the join step? — **Answer:** Glide to just+ outside the seat, then do the step's normal insertion.++## Changelog++- 2026-09-28: first draft, after Q1–Q4.+- 2026-09-28: implemented (tasks 1–11 of `.ai/plans/2026-09-28-assembly-subassembly-staging.md`). Deviations: a nested chain (a step that is both built aside and a join step) makes the viewer ignore BOTH links; a staged step's fallback motion only avoids the parts of its own group; a rejected join shows a toast rather than a field error (the select only offers valid steps). Browser-checked 2026-09-28 on a 5-step Draft assembly: criteria 1, 2, 3, 5 and 7 pass, criterion 6 (MES) was not checked. The first check found a fixed +X side hidden by a saved camera looking down X, so the side is now chosen from the saved cameras. The "Built aside" text badge hid step titles in the list, so it became an icon with a tooltip.diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex a51838a356..33e77b5409 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -13,6 +13,7 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced- **Operation Batch** (`jobOperationBatch`) — N job operations sharing one run on a **batchable process** (`process.batchable`: laser table, furnace, plating; `process.batchType` `Sequential`/`Simultaneous` = the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned duration `setup(max) + Σ|max(run)` via `@carbon/utils` `batchDuration`). Jobs are never merged and the BOM is never modified; each member stays a first-class `jobOperation`. Time/cost split **proportional to `operationQuantity`**, materialized at completion as per-member `productionEvent` slices, so job costing/GL post per job with no special-casing. Status **`Planned → Active → Completing → Completed`** (no `Cancelled` — dissolve deletes a pre-start batch instead). `Planned` is the pre-floor state: composed in the builder from ANY live job's unstarted ops (the planner RPC no longer requires released jobs), fully editable (add/remove/work-center widened to Planned+Active pre-event), invisible to MES. **`Active` displays as "Released"** (exactly like job `Ready`); the `release` edge-fn intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and releasing it RELEASES its Draft/Planned member jobs through the job page's own path — `releaseBatchMemberJobs` → `releaseJobs` (`production.server.ts`: recalc, MRP, status Ready, outside-operation POs via `create` `purchaseOrderFromJob`, releasedDate) after `getJobReleaseReadiness` validates EVERY such job (assemblies without operations, manufacturing blocked, or an outside operation whose supplier can't be resolved — `resolveOperationSupplier`: its own supplier process, else the process's only supplier — refuse the whole batch untouched; there is no per-operation supplier picker on batch release); a supplier's first new PO is reused for the later jobs so a batch lands on one PO per supplier. The `BatchReleaseModal` (drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulk `batches/release` passes no choice, so a batch needing a fix or with Draft POs to choose from is skipped and named. Then it notifies the scheduler; `unrelease` (`Active → Planned`) is allowed only before the first production event. **Membership-handoff floor rule**: an op in a batch is floor-visible iff its BATCH is Released (`Active`/`Completing`) — even when its job is Draft/Planned; an op in no batch follows its JOB's release (the pre-batching rule — a released job's un-batched batchable op always remains runnable, never blocked; removing it from a batch is the escape hatch). Enforced in `get_active_job_operations_by_location`, MES `getOpenJobs`, AND server-side in the MES operation loader + start route (list visibility alone was the leak). **Scheduling**: a Released batch is ONE scheduling unit — the batch pre-pass (`packages/planning/src/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, edge-fn-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split` (Deno mirror under `supabase/functions/shared/`). Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Mutations go through the `batch-operations` edge function (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01 at Sid's direction, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the edge fn's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the edge fn uses ids through the same value-agnostic fold, so they always agree. The edge fn's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the edge fn is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` edge fn — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (per-type plan buckets = max member setup + Σ|max labor/machine by `process.batchType`; the "Planned time" total = shared setup + Σ|max of each member's run `max(labor, machine)`, matching the scheduler's reservation and MES batch mode via `@carbon/utils` `batchPlanBreakdown`) with a pulsing timer-running badge and the batch's production-event history (`getJobOperationBatchWithMembers` + `getJobOperationBatchEvents`; completed batches show the per-member slices, which keep the batch tag). The Batches list also bulk-RELEASES via selectable rows → a "Release N batches" bulk action posting the selected **Planned** ids to the `batches/release` route (one release per id, mirroring the single-batch `batching.update` release branch: `releaseBatchMemberJobs` → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`; per-batch edge-fn refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the edge fn's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Active ids to the `batches/dissolve` route (one edge-fn dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). **Materials and output lots (2026-09-16):** the MES batch-mode materials panel shows each item's summed BATCH requirement alongside the member's own (`getBatchMaterialTotals`), and ONE pick covers the whole batch — `issue` case `trackedEntitiesToBatch` splits the picked lot(s) **pro-rata by each member's REMAINING requirement** (`splitPickAcrossMembers` in `@carbon/utils` `batch-pick-split`, largest-remainder so shares sum exactly) and records each member's own consumption against its own WIP entity, so cost and lot genealogy stay per job while the operator acts once; the pick modal's default quantity is the batch remaining, NOT the member's share (defaulting to one member's share splits it again across all of them and satisfies none). Completion finalizes each member's produced lot via the lean `issue` case `jobOperationBatchOutput` (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`, WITHOUT that case's `productionQuantity` insert and backflush — Phase 1 and the Phase-2 issue step already did both), under lot numbers PLANNED AT CREATION — the builder's Output section (`ui/Batches/BatchOutputLots.tsx`) either sets each member's lot (written to its WIP `trackedEntity.readableId` by the `batch-operations` create) or, when every member makes the same batch-tracked item, "Combine output into one lot" (`jobOperationBatch.mergeOutput` + `outputLotNumber`, migration `20260918094217_batch-output-lot-at-creation.sql`); the operator never edits lots at completion. A merged batch's member lots are combined right after completion (and the batch drawer's "Merge output lots" covers a Completed batch kept separate) into ONE lot via `issue` `mergeTrackedEntities` — genealogy keeps every source job, so the merged lot is strictly more traceable than a single directly-produced one. Both entry points derive the parent ids SERVER-SIDE from the batch's membership: these routes invoke `issue` with the service role, so the edge fn's `inventory` permission check validates the service role rather than the operator. Eligibility gained a `producedItem` dimension in `BATCH_RULE_DIMENSIONS` (default `ignore`) so a process can require members to make the same item. Serial-tracked members are unchanged — batch mode still disables tracked activity for them. Job surfaces show live-batch membership: a Batches column on the jobs table (loader-side lookup), a badge on the `JobBillOfProcess` operation row (`jobOperationBatch` embed), and a chip on the MES job DAG node.- **Procedure** — versioned work instructions linked to operations via `processId`. Statuses: Draft/Active/Archived.- **Assembly Instructions** — 3D animated work instructions, available to all users. (Previously gated to Carbon-internal emails via `requireAssembliesInternal` / `useFlags().isInternal`; that gate was removed to ship publicly.) **Versioned** (Draft/Published/Archived) as **row-per-version**, not an in-place counter: sibling versions are grouped by a self-referential `assemblyInstruction.rootInstructionId` (NULL = "I am the root"; group root = `rootInstructionId ?? id`, siblings = `id = root OR rootInstructionId = root`). `copyAssemblyInstructionAsVersion` spins a new editable **Draft** as a perfect copy (`version = max+1`, deep-copies steps with `parentStepId` remapped + each step's materials/slides/tools). `activateAssemblyInstructionVersion` makes a version active: publishes it, **archives the prior Published sibling**, and repoints `jobOperation.assemblyInstructionId` from other group versions to it — but only for active operations (status ≠ Done/Canceled) on active jobs (`!isJobLocked`). Only Draft is editable; the header exposes a "Versions" switcher + Make Active / New Version. `updateAssemblyInstructionStatus` no longer bumps `version`. The **list** (`getAssemblyInstructions`) reads the `assemblyInstructions` **view** (not the base table): it collapses each group to its latest version (`WHERE version = MAX(version)` per `rootInstructionId ?? id`) and rolls every sibling into a `versions` jsonb array, mirroring the `procedures` view — the table shows a `Version N` subtitle on the name plus a "Versions" hover card. Migration `20260730153412_assembly-instructions-view.sql`.+- **Sub-assembly staging** — `assemblyInstructionStep.parentStepId` = the later JOIN step a step is built aside for (NULL = built in place); written only by `updateAssemblyStepJoin` (one level, base step never staged, join must come later), cleared by `updateAssemblyInstructionStepOrder` when a reorder makes it point backwards. The join step's own `componentNodeIds` never re-list the carried-in parts, so BOM materials are seeded once. Viewer side: `packages/viewer/src/staging.ts`.- **Maintenance Dispatch** — reactive/scheduled repair for work centers with comments, events, items, and linked work centers.- **Scheduling** — forecast-first finite scheduling run **IN-PROCESS in Node** via `runLocationSchedule` / `runExpediteWhatIf` from `@carbon/planning` (the ERP app and `@carbon/jobs` call it directly — no edge cold-start/HTTP hop; the `schedule` Deno edge function was DELETED, and the engine now lives in `packages/planning/src/scheduling/`). It regenerates a **whole LOCATION** in one deterministic FORWARD-ASAP pass (no backward JIT pass in placement, no `initial`/`reschedule` modes). Machine availability comes from a per-work-center ladder: `workCenter.alwaysOn` = 24×7 lights-out → explicit `workCenterShift` rows → the location's `shift` rows → a stock Mon–Fri 8h week; open maintenance dispatches flagged `takesWorkCenterOffline` subtract downtime from those windows. Work centers are finite (capacity 1 — one op at a time) AND, for ability-gated processes, qualified PEOPLE are finite: work only accumulates while a qualified employee is on shift (`employeeShift` ⋈ `shift`; no shift assignment = the job location's calendar) and not reserved elsewhere. Started ops net **remaining work** only — labor+machine scaled by `(1 − quantityComplete/operationQuantity)`, setup done once any `productionEvent` exists. Placements persist as `capacityReservation` rows (a materialized output: delete-by-job + bulk insert per run, `scenarioId IS NULL`; `WorkCenter` + `Employee` kinds — `OperatorPool` is read-tolerated legacy, never written); the run also writes `job.projectedCompletionAt` (forecast finish) and clears the job's schedule-outdated stamps. **Dual dates** (`20260818031629_dual-dates.sql`, spec `.ai/specs/2026-08-15-dual-dates-due-vs-projected.md`): every regen writes each op's forward projection — `startDate` (projected start day) + `jobOperation.projectedCompletionAt` (projected finish instant) — and DIFF-writes `jobOperation.dueDate` from a backward demand-anchored need-by pass (`computeNeedByDates`, `packages/planning/src/scheduling/need-by-calculator.ts` — a pure pre-placement step: reverse-topo from `job.dueDate`, `operationLeadTime` + assembly lead times, day lengths from the work centers' real calendars). Targets NEVER floor placement; `manuallyScheduled` = a human owns the need-by (the pin is taken as-is, propagates upstream, and is never overwritten — pinned ops still place normally; the old frozen-window branch is gone). An op projected past its need-by gets an informational amber behind-target state (BOP rows, ops-board `ItemCard`, MES operation detail) — never per-op `hasConflict`; when the job is late, the cause sentence appends "First behind target: {op} (due X, projected Y)". `jobOperation.priority` = the per-work-center placement order (reservation start ascending) — one source of truth for dispatch order (there is no configurable dispatch-sequencing policy). **People assignments** (manning board, `peopleAssignment`) make a staffed station a TEAM: the station still runs ONE op at a time, but the whole team present is booked on that op together — labor is parallelized across the present people (two people halve the labor wall-clock; setup and machine time are never compressed). Gated ops team-book people∩qualified on their assigned dates, falling back to an any-qualified single-person relay — but the board is a COMMITMENT, not a soft preference: the fallback may only draw on true FLOATERS (people with NO board assignment anywhere in the horizon, via `assignmentsByEmployee.has(id)`). A person you have manned anywhere is spoken for and is never pulled to a station they weren't assigned to — so moving your only welder off a station makes that station's op an unschedulable placeholder (visible on the Forecast) rather than silently double-booking the welder or shoving the op onto an unmanned weekend. A blank board leaves every qualified person a floater ⇒ classic any-qualified fallback, unchanged. Ungated ops at a staffed station are manned the same way with machine-only fallback. **Require-staffing policy** (`location.requiresStaffing`, per-location, default off, edited on the Production settings page (Settings → Production → Scheduling)): when ON, the scheduler places work ONLY where an operator is manned — the gated floater fallback and the ungated machine-only fallback are both removed, EXCEPT lights-out (`workCenter.alwaysOn`) stations keep running unattended. An op with no manned coverage (and not lights-out) becomes an unschedulable placeholder, so work routes to the staffed work centers and unstaffed ones get nothing. Threaded through `provider.getLocationRequiresStaffing` + `getAlwaysOnWorkCenterIds` → `FiniteSchedulingContext.requiresStaffing` + `capacity.workCenter.alwaysOn`. `peopleAbsence` subtracts the person's availability for that date everywhere; `peopleAssignment.overtimeHours` lengthens the person's day (window extension) and `peopleAssignment.hours` splits deal the day out per station sequentially — all as pure window edits before allocation. A blank board changes nothing. To reschedule, call `notifyScheduleInputsChanged` (stamps jobs; the debounced wave regenerates the whole location) — never direct date writes. An expedite what-if (`expediteJobId`) re-runs the sim with one job first, simulate-only, and returns its projected completion.- **Ability requirements** — resolved through the operation's PROCESS: `process.requiresAbility` → the ability linked 1:1 to the process (`ability.processId`) → **presence-based** `employeeAbility` qualification (a row exists ∧ not expired; no `active`/`trainingCompleted` gate). Gates both the scheduler's operator pools and MES operation start. There are no operation-level ability tables.diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.tsindex 0f2a81b775..016d430ea0 100644--- a/apps/erp/app/modules/production/production.models.ts+++ b/apps/erp/app/modules/production/production.models.ts@@ -1474,6 +1474,11 @@ export const assemblyInstructionStepHiddenComponentsValidator = z.object({hiddenComponentNodeIds: jsonField(z.array(z.string()))});+/** Sub-assembly staging: the later step this one is built aside for. Empty = built in place. */+export const assemblyInstructionStepJoinValidator = z.object({+ joinStepId: zfd.text(z.string().optional())+});+export const assemblyStepComponentsReassignValidator = z.object({// Absent for "remove" (unassign from every step); required otherwise.diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 58f270d1bf..eebb859fc6 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -26,7 +26,8 @@ import {CURRENT_PLAN_VERSION,describeStep,groupComponentNodeIds,- indexAssemblyGraph+ indexAssemblyGraph,+ joinTargets} from "@carbon/viewer";import { parseDate } from "@internationalized/date";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";@@ -7305,6 +7306,57 @@ export async function updateAssemblyStepHiddenComponents(.single();}+// Sub-assembly staging: `parentStepId` = the later JOIN step this step is built+// aside for (NULL = built in place). Which links are allowed is `joinTargets`,+// the one rule the select and playback share.+export async function updateAssemblyStepJoin(+ client: SupabaseClient<Database>,+ data: {+ assemblyInstructionId: string;+ stepId: string;+ joinStepId: string | null;+ companyId: string;+ updatedBy: string;+ }+) {+ const steps = await client+ .from("assemblyInstructionStep")+ .select("id, parentStepId")+ .eq("assemblyInstructionId", data.assemblyInstructionId)+ .eq("companyId", data.companyId)+ .order("sortOrder", { ascending: true });+ if (steps.error) return { data: null, error: steps.error };++ const rows = steps.data.map((row) => ({+ id: row.id,+ joinStepId: row.parentStepId+ }));+ if (!rows.some((row) => row.id === data.stepId)) {+ return { data: null, error: { message: "Step not found" } };+ }+ if (+ data.joinStepId &&+ !joinTargets(rows, data.stepId).targets.includes(data.joinStepId)+ ) {+ return {+ data: null,+ error: { message: "That step can't be the join step for this one" }+ };+ }++ return client+ .from("assemblyInstructionStep")+ .update({+ parentStepId: data.joinStepId,+ updatedBy: data.updatedBy,+ updatedAt: new Date().toISOString()+ })+ .eq("id", data.stepId)+ .eq("companyId", data.companyId)+ .select("id")+ .single();+}+// Assign a set of component instances to a target step. `duplicate` unions them// onto the target only (a component may live on several steps). `move` unions// them onto the target AND strips them from every other step, so the component@@ -7489,6 +7541,7 @@ export async function updateAssemblyInstructionStepStatus(export async function updateAssemblyInstructionStepOrder(db: Kysely<KyselyDatabase>,+ assemblyInstructionId: string,updates: { id: string; sortOrder: number; updatedBy: string }[]) {return db.transaction().execute(async (trx) => {@@ -7499,6 +7552,22 @@ export async function updateAssemblyInstructionStepOrder(.where("id", "=", id).execute();}+ // A step built aside must still come before its join step; a reorder that+ // breaks that turns it back into a built-in-place step.+ await trx+ .updateTable("assemblyInstructionStep as s")+ .set({ parentStepId: null })+ .where("s.assemblyInstructionId", "=", assemblyInstructionId)+ .where("s.parentStepId", "is not", null)+ .where(({ exists, selectFrom }) =>+ exists(+ selectFrom("assemblyInstructionStep as j")+ .select("j.id")+ .whereRef("j.id", "=", "s.parentStepId")+ .whereRef("j.sortOrder", "<=", "s.sortOrder")+ )+ )+ .execute();});}@@ -9272,6 +9341,7 @@ export function toViewerStep(step: AssemblyInstructionStepRow): AssemblyStep {instructionText: step.instructionText,componentNodeIds: step.componentNodeIds ?? [],hiddenComponentNodeIds: step.hiddenComponentNodeIds ?? [],+ joinStepId: step.parentStepId ?? null,motion: motion.success ? motion.data : { type: "none" },camera: camera.success ? camera.data : null,fastener: fastener.success ? fastener.data : null,diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsxindex 5775ac2ec4..b8aef75ef7 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx@@ -21,6 +21,10 @@ import {TabsContent,TabsList,TabsTrigger,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+ TruncatedTooltipText,useDebounce,useInterval,VStack@@ -31,12 +35,13 @@ import {groupComponentNodeIds,synthesizeFallbackMotion} from "@carbon/viewer";+import { Trans, useLingui } from "@lingui/react/macro";import type { DragControls } from "framer-motion";import { MotionConfig, Reorder, useDragControls } from "framer-motion";import type { ReactNode } from "react";import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";import {- LuChevronDown,+ LuBoxes,LuCirclePlus,LuEllipsisVertical,LuGripVertical,@@ -58,7 +63,11 @@ import { ProcedureStepTypeIcon } from "~/components/Icons";import { ConfirmDelete } from "~/components/Modals";import { usePermissions, useRealtime } from "~/hooks";import { path } from "~/utils/path";-import { isAssemblyPlanRunning } from "../../production.models";+import {+ assemblyStepStatuses,+ isAssemblyPlanRunning,+ stepPlanWarningsSchema+} from "../../production.models";import type { FlattenedBomMaterial } from "../../production.service";import { toViewerStep } from "../../production.service";import type {@@ -67,6 +76,12 @@ import type {AssemblyUnit} from "../../types";import AssemblyBomTree from "./AssemblyBomTree";+import type { AssemblyStepStatusValue } from "./AssemblyStepStatus";+import {+ AssemblyStepStatusIcon,+ normalizeStepStatus,+ useStepStatusLabel+} from "./AssemblyStepStatus";type AssemblyInstructionExplorerProps = {steps: AssemblyInstructionStepRow[];@@ -818,6 +833,14 @@ function AssemblyInstructionExplorer({motion plan — titles, descriptions, and other edits on thecurrent steps are lost. Refused if any step is manually authoredor marked Done.+ {steps.some((step) => step.parentStepId) && (+ <>+ {" "}+ <Trans>+ Regenerating removes "Build off to the side" settings.+ </Trans>+ </>+ )}</ModalDescription></ModalHeader><ModalFooter>@@ -907,43 +930,28 @@ function AssemblyInstructionExplorer({);}-const stepStatusOrder = ["Todo", "Review", "Done"] as const;-type StepStatus = (typeof stepStatusOrder)[number];--const stepStatusStyles: Record<StepStatus, string> = {- Todo: "bg-red-500",- Review: "bg-yellow-500",- Done: "bg-green-500"-};--const StepStatusDot = ({ status }: { status: StepStatus }) => (- <span- className={cn(- "block size-2 shrink-0 rounded-full",- stepStatusStyles[status] ?? stepStatusStyles.Todo- )}- />-);-function StepStatusControl({stepId,status,isDisabled}: {stepId: string;- status: StepStatus;+ status: AssemblyStepStatusValue;isDisabled: boolean;}) {const { id } = useParams();if (!id) throw new Error("Could not find id");+ const { t } = useLingui();+ const statusLabel = useStepStatusLabel();const fetcher = useFetcher<{ success: boolean }>();// Optimistic: show the in-flight status while the fetcher is busyconst displayed =fetcher.state !== "idle" && fetcher.formData- ? ((fetcher.formData.get("status") as StepStatus) ?? status)+ ? normalizeStepStatus(fetcher.formData.get("status") as string | null): status;+ const label = statusLabel(displayed);const onSelect = (value: string) => {if (value === status) return;@@ -955,42 +963,52 @@ function StepStatusControl({});};- // Non-interactive: a labeled chip so the status is legible without the dot- // color code (published/archived instructions can't be edited)+ // Published/archived instructions can't be edited: the icon alone, named by its tooltipif (isDisabled) {return (- <span className="inline-flex h-6 shrink-0 items-center gap-1.5 rounded-md border border-border px-1.5 text-xs text-foreground">- <StepStatusDot status={displayed} />- {displayed}- </span>+ <Tooltip>+ <TooltipTrigger asChild>+ <span+ role="img"+ aria-label={t`Step status: ${label}`}+ className="inline-flex size-6 shrink-0 items-center justify-center"+ >+ <AssemblyStepStatusIcon status={displayed} />+ </span>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>);}return (<DropdownMenu>- <DropdownMenuTrigger asChild>- <button- type="button"- aria-label={`Step status: ${displayed}. Change status`}- className="inline-flex h-6 shrink-0 items-center gap-1.5 rounded-md border border-border bg-card px-1.5 text-xs text-foreground shadow-button-base hover:bg-accent focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 active:scale-[0.98]"- onClick={(e) => e.stopPropagation()}- >- <StepStatusDot status={displayed} />- {displayed}- <LuChevronDown className="size-3 text-muted-foreground" />- </button>- </DropdownMenuTrigger>+ <Tooltip>+ <TooltipTrigger asChild>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label={t`Step status: ${label}. Change status`}+ className="inline-flex size-6 shrink-0 items-center justify-center rounded-md hover:bg-accent focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 active:scale-[0.96]"+ onClick={(e) => e.stopPropagation()}+ >+ <AssemblyStepStatusIcon status={displayed} />+ </button>+ </DropdownMenuTrigger>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip><DropdownMenuContent- align="start"+ align="end"className="min-w-[8rem]"onClick={(e) => e.stopPropagation()}><DropdownMenuRadioGroup value={displayed} onValueChange={onSelect}>- {stepStatusOrder.map((option) => (+ {assemblyStepStatuses.map((option) => (<DropdownMenuRadioItem key={option} value={option}><span className="flex items-center gap-2">- <StepStatusDot status={option} />- {option}+ <AssemblyStepStatusIcon status={option} className="size-3.5" />+ {statusLabel(option)}</span></DropdownMenuRadioItem>))}@@ -1046,12 +1064,16 @@ function StepItem({onDelete}: StepItemProps) {const permissions = usePermissions();+ const { t } = useLingui();if (!step) return null;const componentCount = step.componentNodeIds?.length ?? 0;+ const stepType = step.type ?? "Task";const needsSupport = (step.warnings as { needsSupport?: boolean } | null)?.needsSupport;+ const flagged =+ stepPlanWarningsSchema.safeParse(step.warnings).data?.flagged === true;return (<div@@ -1061,7 +1083,7 @@ function StepItem({)}onClick={onSelect}onDoubleClick={onPreview}- title="Double-click to play this step"+ title={t`Double-click to play this step`}>{isSelected && (<span@@ -1070,7 +1092,7 @@ function StepItem({/>)}<IconButton- aria-label="Drag handle"+ aria-label={t`Drag handle`}icon={<LuGripVertical />}variant="ghost"size="sm"@@ -1084,43 +1106,54 @@ function StepItem({<span className="w-5 shrink-0 text-right text-xs tabular-nums text-muted-foreground">{index + 1}</span>- <ProcedureStepTypeIcon- type={step.type ?? "Task"}- className="size-3.5 shrink-0 text-muted-foreground"- />- <span+ {/* Only a non-default type earns an icon — the same Task icon on every row said nothing */}+ {stepType !== "Task" && (+ <ProcedureStepTypeIcon+ type={stepType}+ className="size-3.5 shrink-0 text-muted-foreground"+ />+ )}+ <TruncatedTooltipText+ tooltip={title}className="min-w-0 flex-1 truncate text-sm text-foreground"- title={title}>{title}- </span>+ </TruncatedTooltipText>+ {flagged && (+ <RowIcon label={t`No collision-free path`}>+ <LuTriangleAlert className="size-3.5 text-amber-500" />+ </RowIcon>+ )}{needsSupport && (- <span- className="shrink-0 text-amber-600 dark:text-amber-500"- title="A part in this step may tip once placed — consider a fixture or a second person."+ <RowIcon+ label={t`A part in this step may tip once placed — consider a fixture or a second person.`}>- <LuHand className="size-3.5" />- </span>+ <LuHand className="size-3.5 text-amber-500" />+ </RowIcon>)}- <span- className="shrink-0 text-xs tabular-nums text-muted-foreground"- title={`${componentCount} component${componentCount === 1 ? "" : "s"}`}- >+ {step.parentStepId && (+ <RowIcon+ label={t`Built off to the side, then carried in at its join step`}+ >+ <LuBoxes className="size-3.5 text-muted-foreground" />+ </RowIcon>+ )}+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">×{componentCount}</span><StepStatusControlstepId={step.id}- status={step.status ?? "Todo"}+ status={normalizeStepStatus(step.status)}isDisabled={isDisabled}/>{!isDisabled && (<DropdownMenu><DropdownMenuTrigger asChild><IconButton- aria-label="More"+ aria-label={t`More options`}size="sm"variant="ghost"- className="size-6 shrink-0 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"+ className="size-6 shrink-0 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 data-[state=open]:opacity-100"icon={<LuEllipsisVertical />}onClick={(e) => e.stopPropagation()}/>@@ -1135,7 +1168,7 @@ function StepItem({}}><DropdownMenuIcon icon={<LuTrash />} />- Delete Step+ <Trans>Delete Step</Trans></DropdownMenuItem></DropdownMenuContent></DropdownMenu>@@ -1144,4 +1177,18 @@ function StepItem({);}+/** A small meaning-carrying icon in a step row, named by its tooltip. */+function RowIcon({ label, children }: { label: string; children: ReactNode }) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <span role="img" aria-label={label} className="inline-flex shrink-0">+ {children}+ </span>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ );+}+export default memo(AssemblyInstructionExplorer);diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsxindex 5751c55e14..a27479574a 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx@@ -16,17 +16,25 @@ import {HStack,IconButton,Label,+ LabelWithHelp,Subheading,Tabs,TabsContent,TabsList,TabsTrigger,+ Tooltip,+ TooltipContent,+ TooltipTrigger,VStack} from "@carbon/react";import { Editor } from "@carbon/react/Editor";-import type { AssemblyGraphIndex, NamedUnit } from "@carbon/viewer";+import type {+ AssemblyGraphIndex,+ AssemblyStep,+ NamedUnit+} from "@carbon/viewer";import { describeStep, groupComponentNodeIds } from "@carbon/viewer";-import { Trans, useLingui } from "@lingui/react/macro";+import { Plural, Trans, useLingui } from "@lingui/react/macro";import { memo, useEffect, useMemo, useState } from "react";import {LuCirclePlus,@@ -53,9 +61,12 @@ import type {AssemblyStepSlide,AssemblyStepTool} from "../../types";-import AssemblyStepBom, { ComponentColorSwatch } from "./AssemblyStepBom";+import PlaybackRow from "./AssemblyPlaybackRow";+import { ComponentColorSwatch } from "./AssemblyStepBom";+import AssemblyStepJoin from "./AssemblyStepJoin";import AssemblyStepMaterials from "./AssemblyStepMaterials";import AssemblyStepSlides from "./AssemblyStepSlides";+import { AssemblyStepStatus, normalizeStepStatus } from "./AssemblyStepStatus";import AssemblyStepTools from "./AssemblyStepTools";type AssemblyInstructionPropertiesProps = {@@ -89,6 +100,9 @@ type AssemblyInstructionPropertiesProps = {onStopEditMotion: () => void;onSetCamera: (stepId: string) => void;onClearCamera: (stepId: string) => void;+ /** Every step of the instruction, in order — for the "Build off to the side" select */+ viewerSteps: AssemblyStep[];+ onSelectStep: (stepId: string) => void;};const AssemblyInstructionProperties = ({@@ -115,10 +129,13 @@ const AssemblyInstructionProperties = ({onEditMotion,onStopEditMotion,onSetCamera,- onClearCamera+ onClearCamera,+ viewerSteps,+ onSelectStep}: AssemblyInstructionPropertiesProps) => {const { id: instructionId } = useParams();if (!instructionId) throw new Error("Could not find id");+ const { t } = useLingui();const componentCount = (draftComponentNodeIds ?? step?.componentNodeIds ?? []).length;@@ -126,10 +143,11 @@ const AssemblyInstructionProperties = ({(step &&(step.title ||describeStep(toStepDescriptor(step), graphIndex, units))) ||- "Untitled step";- const flagged =- step != null &&- stepPlanWarningsSchema.safeParse(step.warnings).data?.flagged === true;+ t`Untitled step`;+ const planFlag = useMemo(+ () => (step ? getPlanFlag(step.warnings, graphIndex) : null),+ [step, graphIndex]+ );// BOM parts the author can @-mention in a step's instruction — mirrors the// step-description editor in JobBillOfProcess (scoped to the item's BOM).@@ -159,45 +177,47 @@ const AssemblyInstructionProperties = ({<HStack className="w-full min-w-0 items-center justify-between gap-2"><Subheading variant="heavy" className="shrink-0 tabular-nums">{stepIndex != null- ? `Step ${stepIndex + 1} of ${stepCount}`- : "Step"}+ ? t`Step ${stepIndex + 1} of ${stepCount}`+ : t`Step`}</Subheading>- <StepStatusPill status={normalizeStatus(step.status)} />+ <AssemblyStepStatus status={normalizeStepStatus(step.status)} /></HStack><h3 className="w-full min-w-0 truncate text-sm font-medium text-foreground">{title}</h3><HStack className="w-full min-w-0 items-center gap-1.5 text-xs text-muted-foreground tabular-nums"><span>- {componentCount}{" "}- {componentCount === 1 ? "component" : "components"}+ <Plural+ value={componentCount}+ one="# component"+ other="# components"+ /></span>- {flagged && (+ {planFlag && (<><span aria-hidden>·</span>- <span className="inline-flex items-center gap-1 text-amber-600 dark:text-amber-500">- <LuTriangleAlert className="size-3" />- No collision-free path- </span>+ <PlanFlagNote blockers={planFlag.blockers} /></>)}</HStack></VStack>) : (- <Subheading variant="heavy">Step</Subheading>+ <Subheading variant="heavy">+ <Trans>Step</Trans>+ </Subheading>)}</div>{step ? (<Tabs defaultValue="details" className="w-full px-4 pb-2 pt-3"><TabsList className="w-full mb-4"><TabsTrigger className="flex-1" value="details">- Details+ <Trans>Details</Trans></TabsTrigger><TabsTrigger className="flex-1" value="bom">- BOM+ <Trans>BOM</Trans></TabsTrigger><TabsTrigger className="flex-1" value="slides">- Slides+ <Trans>Slides</Trans></TabsTrigger></TabsList>{/* forceMount keeps unsaved form edits alive while the BOM tab is open */}@@ -227,6 +247,8 @@ const AssemblyInstructionProperties = ({onStopEditMotion={onStopEditMotion}onSetCamera={onSetCamera}onClearCamera={onClearCamera}+ viewerSteps={viewerSteps}+ onSelectStep={onSelectStep}/></TabsContent><TabsContent value="bom">@@ -244,12 +266,6 @@ const AssemblyInstructionProperties = ({tools={stepTools}isDisabled={isDisabled}/>- <AssemblyStepBom- componentNodeIds={- draftComponentNodeIds ?? step.componentNodeIds ?? []- }- graphIndex={graphIndex}- /></VStack></TabsContent><TabsContent value="slides">@@ -269,11 +285,13 @@ const AssemblyInstructionProperties = ({<LuMousePointerClick className="size-5" /></div><p className="text-sm font-medium text-foreground">- No step selected+ <Trans>No step selected</Trans></p><p className="max-w-[30ch] text-xs text-muted-foreground">- Pick a step from the list to edit its details, components, and- materials.+ <Trans>+ Pick a step from the list to edit its details, components, and+ materials.+ </Trans></p></div>)}@@ -281,29 +299,40 @@ const AssemblyInstructionProperties = ({);};-const stepStatusStyles: Record<string, string> = {- Todo: "bg-red-500",- Review: "bg-yellow-500",- Done: "bg-green-500"-};--function normalizeStatus(status: string | null | undefined): string {- return status && status in stepStatusStyles ? status : "Todo";+/**+ * Planner flag: no collision-free path exists for these components. The player+ * fades them in at the seated pose; a manual motion overrides the flag.+ */+function getPlanFlag(+ warnings: unknown,+ graphIndex: AssemblyGraphIndex | null+): { blockers: string[] } | null {+ const parsed = stepPlanWarningsSchema.safeParse(warnings);+ if (!parsed.success || parsed.data.flagged !== true) return null;+ const blockers = (parsed.data.blockedBy ?? [])+ .map((nodeId) => graphIndex?.nodesById.get(nodeId)?.name)+ .filter((name): name is string => Boolean(name));+ return { blockers: [...new Set(blockers)] };}-/** Compact status chip for the panel header — mirrors the Explorer's status dot. */-function StepStatusPill({ status }: { status: string }) {- return (- <span className="inline-flex h-5 shrink-0 items-center gap-1.5 rounded-md border border-border px-1.5 text-xxs font-medium text-foreground">- <span- className={cn(- "block size-1.5 shrink-0 rounded-full",- stepStatusStyles[status] ?? stepStatusStyles.Todo- )}- />- {status}+/** "No clear path" in plain muted text; the blocking parts live in the tooltip. */+function PlanFlagNote({ blockers }: { blockers: string[] }) {+ const { t } = useLingui();+ const note = (+ <span className="inline-flex items-center gap-1 text-muted-foreground">+ <LuTriangleAlert className="size-3 shrink-0 text-amber-500" />+ <Trans>No clear path</Trans></span>);+ if (blockers.length === 0) return note;+ return (+ <Tooltip>+ <TooltipTrigger asChild>{note}</TooltipTrigger>+ <TooltipContent className="max-w-xs">+ {t`Blocked by ${blockers.join(", ")}`}+ </TooltipContent>+ </Tooltip>+ );}/** The minimal descriptor `describeStep` needs to derive a title. */@@ -338,7 +367,9 @@ function StepForm({onEditMotion,onStopEditMotion,onSetCamera,- onClearCamera+ onClearCamera,+ viewerSteps,+ onSelectStep}: {step: AssemblyInstructionStepRow;draftComponentNodeIds: string[] | null;@@ -359,10 +390,13 @@ function StepForm({onStopEditMotion: () => void;onSetCamera: (stepId: string) => void;onClearCamera: (stepId: string) => void;+ viewerSteps: AssemblyStep[];+ onSelectStep: (stepId: string) => void;}) {const { id: instructionId } = useParams();if (!instructionId) throw new Error("Could not find id");+ const { t } = useLingui();const permissions = usePermissions();const fetcher = useFetcher<{ success: boolean }>();@@ -410,16 +444,10 @@ function StepForm({);}, [componentNodeIds, step.fastener, graphIndex, units]);- // Planner flag: no collision-free path exists for these components. The player- // fades them in at the seated pose; a manual motion overrides the flag.- const planFlag = useMemo(() => {- const parsed = stepPlanWarningsSchema.safeParse(step.warnings);- if (!parsed.success || parsed.data.flagged !== true) return null;- const blockers = (parsed.data.blockedBy ?? [])- .map((nodeId) => graphIndex?.nodesById.get(nodeId)?.name)- .filter((name): name is string => Boolean(name));- return { blockers: [...new Set(blockers)] };- }, [step.warnings, graphIndex]);+ const planFlag = useMemo(+ () => getPlanFlag(step.warnings, graphIndex),+ [step.warnings, graphIndex]+ );return (<ValidatedForm@@ -450,7 +478,7 @@ function StepForm({<VStack spacing={4} className="w-full pb-4"><SelectControlledname="type"- label="Type"+ label={t`Type`}options={typeOptions}value={stepType}isReadOnly={isDisabled}@@ -462,11 +490,13 @@ function StepForm({/><Inputname="title"- label="Title"- placeholder={derivedTitle ?? "Untitled step"}+ label={t`Title`}+ placeholder={derivedTitle ?? t`Untitled step`}/><VStack spacing={2} className="w-full">- <Label>Instruction</Label>+ <Label>+ <Trans>Instruction</Trans>+ </Label><EditorinitialValue={(step.description as JSONContent) ?? {}}onUpload={onUploadImage}@@ -480,11 +510,14 @@ function StepForm({{stepType === "Measurement" && (<VStack spacing={2} className="w-full">- <UnitOfMeasure name="unitOfMeasureCode" label="Unit of Measure" />+ <UnitOfMeasure+ name="unitOfMeasureCode"+ label={t`Unit of Measure`}+ /><div className="grid grid-cols-2 gap-2 w-full"><Numbername="minValue"- label="Minimum"+ label={t`Minimum`}formatOptions={{minimumFractionDigits: 0,maximumFractionDigits: 10@@ -492,7 +525,7 @@ function StepForm({/><Numbername="maxValue"- label="Maximum"+ label={t`Maximum`}formatOptions={{minimumFractionDigits: 0,maximumFractionDigits: 10@@ -502,97 +535,14 @@ function StepForm({</VStack>)}{stepType === "List" && (- <ArrayInput name="listValues" label="List Options" />+ <ArrayInput name="listValues" label={t`List Options`} />)}<BooleanInputname="required"- label="Required"- description="Operators must record this step to complete the operation"+ label={t`Required`}+ description={t`Operator must record this step`}/>- <Subheading as="h4" variant="heavy" className="block w-full pt-1">- Playback & components- </Subheading>- <VStack- spacing={2}- className="w-full rounded-lg border border-border bg-muted/40 p-3"- >- <HStack className="w-full justify-between">- <Label className="text-xxs font-medium uppercase tracking-wide text-muted-foreground">- Motion- </Label>- {!isDisabled && (- <Button- variant={isEditingMotion ? "primary" : "secondary"}- size="sm"- isDisabled={componentNodeIds.length === 0}- onClick={() =>- isEditingMotion ? onStopEditMotion() : onEditMotion(step.id)- }- >- {isEditingMotion ? "Done editing path" : "Edit path"}- </Button>- )}- </HStack>- {componentNodeIds.length === 0 ? (- <p className="text-xs text-muted-foreground">- Assign components to this step to edit its motion path.- </p>- ) : isEditingMotion ? (- <p className="text-xs text-muted-foreground">- Drag the red waypoints in the viewer to shape the insertion path.- Double-click the path to add a waypoint; select one and press- Delete to remove it.- </p>- ) : planFlag ? (- <p className="text-xs text-muted-foreground">- No collision-free insertion path was found- {planFlag.blockers.length > 0- ? ` — blocked by ${planFlag.blockers.join(", ")}`- : ""}- . Edit the path to author one.- </p>- ) : (- <p className="text-xs text-muted-foreground">- Edit the path to adjust how these components move into place.- </p>- )}- </VStack>-- <VStack- spacing={2}- className="w-full rounded-lg border border-border bg-muted/40 p-3"- >- <Label className="text-xxs font-medium uppercase tracking-wide text-muted-foreground">- Camera- </Label>- <p className="text-xs text-muted-foreground">- {hasCamera- ? "A saved view frames this step during playback."- : "This step auto-frames during playback. Orbit to the angle you want, then save it."}- </p>- {!isDisabled && (- <HStack spacing={2}>- <Button- variant="secondary"- size="sm"- onClick={() => onSetCamera(step.id)}- >- Set camera to current view- </Button>- {hasCamera && (- <Button- variant="ghost"- size="sm"- onClick={() => onClearCamera(step.id)}- >- Clear view- </Button>- )}- </HStack>- )}- </VStack>-<StepComponentsEditorcomponentNodeIds={componentNodeIds}graphIndex={graphIndex}@@ -612,12 +562,100 @@ function StepForm({onSetHiddenComponents={onSetHiddenComponents}/>- <Submit- isDisabled={cannotSave || fetcher.state !== "idle"}- isLoading={fetcher.state !== "idle"}- >- Save Step- </Submit>+ <VStack spacing={2} className="w-full">+ <Subheading as="h4" variant="heavy">+ <Trans>Playback</Trans>+ </Subheading>+ <div className="w-full divide-y divide-border rounded-lg border border-border bg-card">+ <PlaybackRow+ label={+ <LabelWithHelp termId="assembly-step-motion" variant="inline">+ <Trans>Motion</Trans>+ </LabelWithHelp>+ }+ value={+ planFlag ? (+ <span className="inline-flex items-center gap-1">+ <LuTriangleAlert className="size-3.5 shrink-0 text-amber-500" />+ <Trans>No clear path</Trans>+ </span>+ ) : isEditingMotion ? (+ <Trans>Drag the red waypoints in the viewer</Trans>+ ) : componentNodeIds.length === 0 ? (+ <Trans>Add components first</Trans>+ ) : (+ <Trans>Automatic</Trans>+ )+ }+ >+ {!isDisabled && (+ <Button+ variant={isEditingMotion ? "primary" : "secondary"}+ size="sm"+ isDisabled={componentNodeIds.length === 0}+ onClick={() =>+ isEditingMotion ? onStopEditMotion() : onEditMotion(step.id)+ }+ >+ {isEditingMotion ? (+ <Trans>Done Editing Path</Trans>+ ) : (+ <Trans>Edit Path</Trans>+ )}+ </Button>+ )}+ </PlaybackRow>+ <PlaybackRow+ label={+ <LabelWithHelp termId="assembly-step-camera" variant="inline">+ <Trans>Camera</Trans>+ </LabelWithHelp>+ }+ value={+ hasCamera ? <Trans>Saved view</Trans> : <Trans>Automatic</Trans>+ }+ >+ {!isDisabled && (+ <HStack spacing={1}>+ {hasCamera && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => onClearCamera(step.id)}+ >+ <Trans>Clear</Trans>+ </Button>+ )}+ <Button+ variant="secondary"+ size="sm"+ onClick={() => onSetCamera(step.id)}+ >+ <Trans>Use Current View</Trans>+ </Button>+ </HStack>+ )}+ </PlaybackRow>+ <AssemblyStepJoin+ stepId={step.id}+ steps={viewerSteps}+ graphIndex={graphIndex}+ units={units}+ isDisabled={isDisabled}+ onSelectStep={onSelectStep}+ />+ </div>+ </VStack>++ {/* Pinned so Save is always on screen; the panel is the scroll container */}+ <div className="sticky bottom-0 z-10 -mx-4 w-[calc(100%+2rem)] border-t border-border bg-background/95 px-4 py-3 backdrop-blur">+ <Submit+ isDisabled={cannotSave || fetcher.state !== "idle"}+ isLoading={fetcher.state !== "idle"}+ >+ <Trans>Save</Trans>+ </Submit>+ </div></VStack></ValidatedForm>);@@ -662,15 +700,14 @@ function StepComponentsEditor({[selectedNodeIds]);+ const { t } = useLingui();+return (- <VStack- spacing={2}- className="w-full rounded-lg border border-border bg-muted/40 p-3"- >+ <VStack spacing={2} className="w-full"><HStack className="w-full justify-between">- <Label className="text-xxs font-medium uppercase tracking-wide text-muted-foreground">- Components- </Label>+ <Subheading as="h4" variant="heavy" className="tabular-nums">+ <Trans>Components</Trans> · {componentNodeIds.length}+ </Subheading>{!isDisabled && (<Buttonvariant={isAddingComponents ? "primary" : "secondary"}@@ -682,21 +719,25 @@ function StepComponentsEditor({: onStartAddComponents()}>- {isAddingComponents ? "Done adding" : "Add components"}+ {isAddingComponents ? (+ <Trans>Done Adding</Trans>+ ) : (+ <Trans>Add</Trans>+ )}</Button>)}</HStack>{isAddingComponents && (<p className="text-xs text-muted-foreground">- Click components in the viewer or the Components panel to add them to- this step. Shift-click to add several.+ <Trans>+ Click components in the viewer to add them. Shift-click adds+ several.+ </Trans></p>)}{groups.length === 0 ? (<p className="text-xs text-muted-foreground">- {isAddingComponents- ? "No components yet — pick components in the viewer to add them."- : "No components assigned. Click Add components, then pick components in the viewer."}+ <Trans>No components yet</Trans></p>) : (<ul className="max-h-64 w-full divide-y divide-border overflow-y-auto rounded-lg border border-border scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">@@ -725,12 +766,14 @@ function StepComponentsEditor({<span className="min-w-0 flex-1 truncate" title={group.name}>{group.name}</span>- <Badge variant="secondary" className="tabular-nums">- ×{group.count}- </Badge>+ {group.count > 1 && (+ <Badge variant="secondary" className="tabular-nums">+ ×{group.count}+ </Badge>+ )}{!isDisabled && (<IconButton- aria-label={`Remove ${group.name} from this step`}+ aria-label={t`Remove ${group.name} from this step`}icon={<LuX />}variant="ghost"size="sm"@@ -796,33 +839,32 @@ function StepHiddenComponentsEditor({};return (- <VStack- spacing={2}- className="w-full rounded-lg border border-border bg-muted/40 p-3"- >+ <VStack spacing={2} className="w-full"><HStack className="w-full justify-between">- <Label className="text-xxs font-medium uppercase tracking-wide text-muted-foreground">- <Trans>Hidden on this step</Trans>- </Label>- {!isDisabled &&+ <Subheading as="h4" variant="heavy">+ <LabelWithHelp+ termId="assembly-step-hidden-components"+ variant="inline"+ >+ <Trans>Hidden on this step</Trans>+ </LabelWithHelp>+ </Subheading>+ {groups.length === 0 ? (+ <span className="text-xs text-muted-foreground">+ <Trans>None</Trans>+ </span>+ ) : (+ !isDisabled &&(isUndoPending ? (<HideAgainButton onClick={onHideAgain} />) : (- groups.length > 0 && (- <Button variant="secondary" size="sm" onClick={onShowAll}>- <Trans>Show all</Trans>- </Button>- )- ))}+ <Button variant="secondary" size="sm" onClick={onShowAll}>+ <Trans>Show All</Trans>+ </Button>+ ))+ )}</HStack>- {groups.length === 0 ? (- <p className="text-xs text-muted-foreground">- <Trans>- Nothing hidden. Use the eye in the Components panel to hide parts on- this step.- </Trans>- </p>- ) : (+ {groups.length === 0 ? null : (<ul className="max-h-64 w-full divide-y divide-border overflow-y-auto rounded-lg border border-border scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">{groups.map((group) => (<li@@ -839,9 +881,11 @@ function StepHiddenComponentsEditor({>{group.name}</span>- <Badge variant="secondary" className="tabular-nums">- ×{group.count}- </Badge>+ {group.count > 1 && (+ <Badge variant="secondary" className="tabular-nums">+ ×{group.count}+ </Badge>+ )}{!isDisabled && !isUndoPending && (<IconButtonaria-label={t`Show ${group.name}`}@@ -886,7 +930,7 @@ function HideAgainButton({ onClick }: { onClick: () => void }) {}}/><span className="relative">- <Trans>Hide again</Trans>+ <Trans>Hide Again</Trans></span></Button>);diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsxindex 4096699417..b1b8e44804 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx@@ -1,71 +1,3 @@-import { Badge, VStack } from "@carbon/react";-import type { AssemblyGraphIndex } from "@carbon/viewer";-import { groupComponentNodeIds } from "@carbon/viewer";-import { useMemo } from "react";-import { Empty } from "~/components";--type AssemblyStepBomProps = {- componentNodeIds: string[];- graphIndex: AssemblyGraphIndex | null;-};--/** Components used by the selected step, grouped by identical geometry. */-export default function AssemblyStepBom({- componentNodeIds,- graphIndex-}: AssemblyStepBomProps) {- const groups = useMemo(- () =>- graphIndex- ? groupComponentNodeIds(componentNodeIds, graphIndex).sort((a, b) =>- a.name.localeCompare(b.name)- )- : [],- [componentNodeIds, graphIndex]- );-- if (!graphIndex) {- return (- <Empty className="border-none">- <p className="text-sm text-muted-foreground">- The model graph has not loaded yet- </p>- </Empty>- );- }-- if (groups.length === 0) {- return (- <Empty className="border-none">- <p className="text-sm text-muted-foreground max-w-[320px] text-center">- Click components in the viewer to assign them to this step- </p>- </Empty>- );- }-- return (- <VStack spacing={2} className="w-full py-2">- <ul className="w-full divide-y divide-border">- {groups.map((group) => (- <li- key={group.key}- className="flex w-full items-center gap-2 py-2 text-sm"- >- <ComponentColorSwatch color={group.color} />- <span className="min-w-0 flex-1 truncate" title={group.name}>- {group.name}- </span>- <Badge variant="secondary" className="tabular-nums">- ×{group.count}- </Badge>- </li>- ))}- </ul>- </VStack>- );-}-export function ComponentColorSwatch({color}: {diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepJoin.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepJoin.tsxnew file mode 100644index 0000000000..b8643d825e--- /dev/null+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepJoin.tsx@@ -0,0 +1,147 @@+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuTrigger,+ HStack,+ LabelWithHelp+} from "@carbon/react";+import type {+ AssemblyGraphIndex,+ AssemblyStep,+ NamedUnit+} from "@carbon/viewer";+import { describeStep, joinTargets } from "@carbon/viewer";+import { Trans, useLingui } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { LuChevronDown } from "react-icons/lu";+import { useFetcher, useParams } from "react-router";+import { path } from "~/utils/path";+import PlaybackRow from "./AssemblyPlaybackRow";++type AssemblyStepJoinProps = {+ stepId: string;+ /** Every step of the instruction, in order */+ steps: AssemblyStep[];+ graphIndex: AssemblyGraphIndex | null;+ units: NamedUnit[];+ isDisabled: boolean;+ onSelectStep: (stepId: string) => void;+};++/**+ * "Build off to the side", one row of the step's Playback box: point this step+ * at a later join step so its parts are built beside the model and carried in+ * there. Autosaves like the step status. On a join step, lists the steps whose+ * group it brings in.+ */+export default function AssemblyStepJoin({+ stepId,+ steps,+ graphIndex,+ units,+ isDisabled,+ onSelectStep+}: AssemblyStepJoinProps) {+ const { t } = useLingui();+ const { id: instructionId } = useParams();+ if (!instructionId) throw new Error("Could not find id");+ const fetcher = useFetcher<{ success: boolean }>();++ const { targets, locked } = joinTargets(steps, stepId);+ const numbered = steps.map((step, index) => ({+ step,+ number: index + 1,+ title: describeStep(step, graphIndex, units) ?? t`Untitled step`+ }));+ const options = numbered.filter(({ step }) => targets.includes(step.id));+ const broughtIn = numbered.filter(({ step }) => step.joinStepId === stepId);++ const saved = steps.find((step) => step.id === stepId)?.joinStepId ?? "";+ const value =+ fetcher.state !== "idle" && fetcher.formData+ ? ((fetcher.formData.get("joinStepId") as string | null) ?? saved)+ : saved;+ const selected = numbered.find(({ step }) => step.id === value);+ const shortLabel = selected ? t`Joins step ${selected.number}` : t`No`;++ const onChange = (next: string) => {+ if (next === value) return;+ const formData = new FormData();+ formData.append("joinStepId", next);+ fetcher.submit(formData, {+ method: "post",+ action: path.to.assemblyInstructionStepJoin(instructionId, stepId)+ });+ };++ let control: ReactNode;+ if (locked === "base") {+ control = (+ <span className="text-xs text-muted-foreground">+ <Trans>No, it's the base</Trans>+ </span>+ );+ } else if (locked === "join") {+ control = (+ <HStack spacing={1} className="flex-wrap items-center text-xs">+ <span className="text-muted-foreground">+ <Trans>Brings in steps</Trans>+ </span>+ {broughtIn.map(({ step, number }) => (+ <Button+ key={step.id}+ variant="link"+ size="sm"+ className="h-auto px-0.5 tabular-nums"+ onClick={() => onSelectStep(step.id)}+ >+ {number}+ </Button>+ ))}+ </HStack>+ );+ } else if (isDisabled) {+ control = <span className="text-xs text-foreground">{shortLabel}</span>;+ } else {+ control = (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ className="inline-flex h-6 max-w-[10rem] items-center gap-1 rounded-md border border-border bg-card px-2 text-xs text-foreground shadow-button-base hover:bg-accent focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50"+ >+ <span className="truncate">{shortLabel}</span>+ <LuChevronDown className="size-3 shrink-0 text-muted-foreground" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="min-w-[16rem]">+ <DropdownMenuRadioGroup value={value} onValueChange={onChange}>+ <DropdownMenuRadioItem value="">+ <Trans>No, build in place</Trans>+ </DropdownMenuRadioItem>+ {options.map(({ step, number, title }) => (+ <DropdownMenuRadioItem key={step.id} value={step.id}>+ {t`Joins step ${number}: ${title}`}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ );+ }++ return (+ <PlaybackRow+ label={+ <LabelWithHelp termId="assembly-step-build-aside" variant="inline">+ <Trans>Build off to the side</Trans>+ </LabelWithHelp>+ }+ >+ {control}+ </PlaybackRow>+ );+}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 5c46d84d68..f4d1869be4 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": 1548,+ "totalTools": 1549,"modules": 15,"tools": [{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},@@ -814,15 +814,16 @@{"name":"production_setPeopleOvertimeBulk","classification":"WRITE","paramCount":6,"schema":"8f082483561d","response":"577d7088b794","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_syncAssemblyInstructionToOperation","classification":"DESTRUCTIVE","paramCount":2,"schema":"8160f8d92b1b","response":"4348d3bad80b","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},{"name":"production_syncAssemblyStepMaterialsFromMappings","classification":"WRITE","paramCount":4,"schema":"7f7346bb3bd0","response":"5815c4dbf43d","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_toViewerStep","classification":"WRITE","paramCount":1,"schema":"3f809a44cba0","response":"933dfe307d06","injectAuth":"companyId","permission":"production:update","paginates":false},+ {"name":"production_toViewerStep","classification":"WRITE","paramCount":1,"schema":"3f809a44cba0","response":"fc07d477afea","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_unassignPeopleWeek","classification":"DESTRUCTIVE","paramCount":4,"schema":"06ead5d3d9ce","response":"9658926b2cd2","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_unreleaseJobOperationBatch","classification":"WRITE","paramCount":1,"schema":"979f64cb9229","response":"none","injectAuth":"companyId+userId","permission":"production:update","paginates":false},{"name":"production_updateAssemblyInstructionStatus","classification":"WRITE","paramCount":2,"schema":"e43955681d7c","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateAssemblyInstructionStepMaterialOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyInstructionStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyInstructionStepOrder","classification":"WRITE","paramCount":2,"schema":"5a4d7dc208a5","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateAssemblyInstructionStepStatus","classification":"WRITE","paramCount":2,"schema":"9291eed55a4a","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateAssemblyStepComponents","classification":"WRITE","paramCount":2,"schema":"d7ea6b1800f7","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateAssemblyStepHiddenComponents","classification":"WRITE","paramCount":2,"schema":"d5e5982cfa52","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyStepJoin","classification":"WRITE","paramCount":3,"schema":"fe25857086d1","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateAssemblyStepMotion","classification":"WRITE","paramCount":3,"schema":"6665a9b53a17","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateInspectionDocumentSampling","classification":"WRITE","paramCount":7,"schema":"e85058fba971","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},{"name":"production_updateJob","classification":"WRITE","paramCount":21,"schema":"e224c0a5aa29","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.join.$stepId.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.join.$stepId.tsxnew file mode 100644index 0000000000..32afc30f15--- /dev/null+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.join.$stepId.tsx@@ -0,0 +1,51 @@+import { assertIsPost, error, notFound } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validator } from "@carbon/form";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";+import {+ assemblyInstructionStepJoinValidator,+ updateAssemblyStepJoin+} from "~/modules/production";++// Autosave target for a step's "Build off to the side" select; touches only+// the step's join link (parentStepId).+export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "production"+ });++ const { id, stepId } = params;+ if (!id) throw notFound("id is not found");+ if (!stepId) throw notFound("step id is not found");++ const validation = await validator(+ assemblyInstructionStepJoinValidator+ ).validate(await request.formData());++ if (validation.error) {+ return data(+ { success: false },+ await flash(request, error(validation.error, "Failed to update step"))+ );+ }++ const update = await updateAssemblyStepJoin(client, {+ assemblyInstructionId: id,+ stepId,+ joinStepId: validation.data.joinStepId || null,+ companyId,+ updatedBy: userId+ });++ if (update.error) {+ return data(+ { success: false },+ await flash(request, error(update.error, update.error.message))+ );+ }++ return { success: true };+}diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.order.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.order.tsxindex 6e833642f8..ff28c17d29 100644--- a/apps/erp/app/routes/x+/assembly+/$id.steps.order.tsx+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.order.tsx@@ -31,7 +31,11 @@ export async function action({ request, params }: ActionFunctionArgs) {);try {- await updateAssemblyInstructionStepOrder(getDatabaseClient(), updates);+ await updateAssemblyInstructionStepOrder(+ getDatabaseClient(),+ params.id,+ updates+ );} catch (err) {return data({ success: false },diff --git a/apps/erp/app/routes/x+/assembly+/$id.tsx b/apps/erp/app/routes/x+/assembly+/$id.tsxindex b88ffe2137..7747ca12b3 100644--- a/apps/erp/app/routes/x+/assembly+/$id.tsx+++ b/apps/erp/app/routes/x+/assembly+/$id.tsx@@ -16,7 +16,11 @@ import type {CameraPose,Motion} from "@carbon/viewer";-import { AssemblyPlayer, indexAssemblyGraph } from "@carbon/viewer";+import {+ AssemblyPlayer,+ indexAssemblyGraph,+ stagedGroupNodeIds+} from "@carbon/viewer";import { msg } from "@lingui/core/macro";import { useCallback, useMemo, useRef, useState } from "react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";@@ -295,10 +299,26 @@ export default function AssemblyInstructionRoute() {[hiddenFetcher, id]);- const selectedOwnNodeIds = useMemo(- () => draftComponentNodeIds ?? selectedStep?.componentNodeIds ?? [],- [draftComponentNodeIds, selectedStep]+ // The selected step shows its hidden draft before the autosave round-trips.+ const viewerSteps = useMemo(+ () =>+ steps.map((step) => {+ const viewerStep = toViewerStep(step);+ return draftHiddenNodeIds && step.id === selectedStep?.id+ ? { ...viewerStep, hiddenComponentNodeIds: draftHiddenNodeIds }+ : viewerStep;+ }),+ [steps, draftHiddenNodeIds, selectedStep]);++ // A join step also "owns" the group built aside for it: those parts move on+ // it, so they get the This-step badge and can't be hidden there.+ const selectedOwnNodeIds = useMemo(() => {+ const own = draftComponentNodeIds ?? selectedStep?.componentNodeIds ?? [];+ if (!selectedStep) return own;+ const staged = stagedGroupNodeIds(viewerSteps, selectedStep.id);+ return staged.length === 0 ? own : [...new Set([...own, ...staged])];+ }, [draftComponentNodeIds, selectedStep, viewerSteps]);// Mirrors the DB trigger for the in-flight drafts: a part the step installs is// never listed as hidden on it (e.g. right after adding it to the step).const selectedHiddenNodeIds = useMemo(() => {@@ -429,18 +449,6 @@ export default function AssemblyInstructionRoute() {[isDisabled, selectedStep, draftComponentNodeIds, saveComponentNodeIds]);- // The selected step shows its hidden draft before the autosave round-trips.- const viewerSteps = useMemo(- () =>- steps.map((step) => {- const viewerStep = toViewerStep(step);- return draftHiddenNodeIds && step.id === selectedStep?.id- ? { ...viewerStep, hiddenComponentNodeIds: draftHiddenNodeIds }- : viewerStep;- }),- [steps, draftHiddenNodeIds, selectedStep]- );-// Per-step slides/tools/materials for the properties panel — memoized so a// per-frame motion-drag re-render (draftMotion) doesn't hand the panel new// array identities and re-render it.@@ -740,6 +748,8 @@ export default function AssemblyInstructionRoute() {stepSlides={selectedStepSlides}stepTools={selectedStepTools}bomMaterials={bomMaterials}+ viewerSteps={viewerSteps}+ onSelectStep={onSelectStep}/>}/>diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 435badd694..d077eedb80 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -375,6 +375,8 @@ export const path = {generatePath(`${x}/assembly/${id}/steps/components/reassign`),assemblyInstructionStepHiddenComponents: (id: string, stepId: string) =>generatePath(`${x}/assembly/${id}/steps/hidden/${stepId}`),+ assemblyInstructionStepJoin: (id: string, stepId: string) =>+ generatePath(`${x}/assembly/${id}/steps/join/${stepId}`),assemblyInstructionStepMotion: (id: string, stepId: string) =>generatePath(`${x}/assembly/${id}/steps/motion/${stepId}`),assemblyInstructionStepOrder: (id: string) =>diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsxindex d1771a8253..15e4e55565 100644--- a/apps/mes/app/components/AssemblyView.tsx+++ b/apps/mes/app/components/AssemblyView.tsx@@ -196,6 +196,8 @@ type AssemblyPlayback = {instructionText: string | null;componentNodeIds: string[] | null;hiddenComponentNodeIds: string[] | null;+ /** The join step this step is built aside for (sub-assembly staging) */+ parentStepId: string | null;motion: Json;camera: Json | null;fastener: Json | null;@@ -216,6 +218,7 @@ function toViewerStep(step: AssemblyPlayback["steps"][number]): AssemblyStep {instructionText: step.instructionText,componentNodeIds: step.componentNodeIds ?? [],hiddenComponentNodeIds: step.hiddenComponentNodeIds ?? [],+ joinStepId: step.parentStepId ?? null,motion:motion &&typeof motion === "object" &&diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 660e614490..c59156fec7 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -637,7 +637,7 @@ export async function getAssemblyPlaybackByOperationId(const steps = await client.from("assemblyInstructionStep").select(- "id, title, instructionText, componentNodeIds, hiddenComponentNodeIds, motion, camera, fastener, durationSeconds, warnings"+ "id, title, instructionText, componentNodeIds, hiddenComponentNodeIds, parentStepId, motion, camera, fastener, durationSeconds, warnings").eq("assemblyInstructionId", instructionId).order("sortOrder", { ascending: true });diff --git a/packages/viewer/AGENTS.md b/packages/viewer/AGENTS.mdindex 43555ec85d..e7dcde6569 100644--- a/packages/viewer/AGENTS.md+++ b/packages/viewer/AGENTS.md@@ -6,7 +6,8 @@- **graph.json** (`AssemblyGraph`) — assembly tree written by the geometry service `/convert`; leaf nodes carry a stable `nodeId` (also baked into GLB node extras as `userData.nodeId`). All joins between steps, plans, and scene objects are by `nodeId`.- **plan.json** (`AssemblyPlan`) — per-component insertion `Motion`, sequence, subassembly `groups`, and body-level `contacts`, written by the geometry service `/plan`. `CURRENT_PLAN_VERSION` (currently `3`) — stored plans below it are STALE and must be treated as absent so the pipeline re-plans.-- **Step** (`AssemblyStep`) — one build instruction: `componentNodeIds`, a `Motion`, optional `camera`, `fastener`, and subassembly `phase`. Built from a plan by `buildAssemblyStepGroups`.+- **Step** (`AssemblyStep`) — one build instruction: `componentNodeIds`, a `Motion`, optional `camera`, `fastener`, per-step `hiddenComponentNodeIds`, and `joinStepId`. Built from a plan by `buildAssemblyStepGroups`.+- **Sub-assembly staging** (`staging.ts`) — a step with `joinStepId` (DB `parentStepId`) is built OFF TO THE SIDE: its parts sit at a computed staging spot (beside the model along +X or +Z — never above/below, Y is up — whichever is most side-on to the saved cameras of the steps involved, +X by default; one lane per group) until the later JOIN step, which glides the whole group in (`STAGING_GLIDE_SECONDS`, `buildStepClip`'s `glide`) and then plays its own insertion. The player's clip effect is the ONLY place that moves parked nodes (`parkNodes`), so park/unpark stay paired with the clip's save/restore. Picking and path editing always show parts seated. Invalid links (backwards, from the base step, nested chains, unknown ids) play as built in place.- **Motion** — discriminated union `linear | L | helix | path | none`. Insertion motion; the player derives removal (reverse) and start poses. `flagged`/`blockedBy` steps use `none` and fade in (no collision-free path exists — a synthesized path would clip through geometry).- **Artifact tiers** — a model renders from best-available: LOD GLB → optimised GLB → lossless GLB → raw WASM (in-browser occt-import-js) fallback.@@ -18,7 +19,7 @@- MUST keep this package free of `@carbon/react` router/i18n peers in the pure/motion/plan modules — `cn` is re-implemented locally in `utils.ts` for that reason. (`ModelPreview.tsx` is the one component that does import `@carbon/react`.)- MUST prefer server artifacts over the raw tier — the raw WASM fallback renders only when there is no server GLB.- MUST keep `visualForComponent` and `occluderWeight` (`visibility.ts`) in agreement: anything the first renders `"hidden"` the second must score `null` (not an occluder). They are two views of the same timeline — what the operator sees, and what the camera's AABB view-direction scoring treats as in the way. When they drift, the camera frames around geometry it is not drawing. `visibility.test.ts` asserts the invariant across every mode combination; a component **no step installs** counts as future in BOTH (it is never "already there"), which is exactly where the two previously disagreed.-- MUST expose visibility to the user as the named views in `ASSEMBLY_VIEWS` / `VIEW_MODES` (`visibility.ts`), not as the two raw axes. The axes are the renderer's model; nine combinations, most of them meaningless, is not a control anyone can read — an earlier two-icon-triplet toolbar was rejected for exactly that. A new view means a new entry in that table (and `VIEW_LABELS` in `AssemblyPlayer.tsx`), never a new axis or a fourth rendering mode. The table must always contain a view that renders the active step ALONE (`isolate` today: both sides hidden) — "how do I just see the part I am fitting?" is the question the viewer exists to answer, and a three-view table that ghosted rather than hid was shipped once and rejected for having no answer to it. `viewForModes` seats the initial view from the still-axis-shaped `default*Mode` props, falling back to `"build"` for an unnamed pair.+- MUST expose visibility to the user as the named views in `ASSEMBLY_VIEWS` / `VIEW_MODES` (`visibility.ts`), not as the two raw axes. The axes are the renderer's model; nine combinations, most of them meaningless, is not a control anyone can read — an earlier two-icon-triplet toolbar was rejected for exactly that. A new view means a new entry in that table (and `VIEW_LABELS` in `AssemblyPlayer.tsx`), never a new axis or a fourth rendering mode. The table is Build / Focus / Full: an `isolate` view (both sides hidden) was dropped — Focus shows the step in place, and the author's per-step hidden parts (`hiddenComponentNodeIds`) remove the clutter they choose. `viewForModes` seats the initial view from the still-axis-shaped `default*Mode` props, falling back to `"build"` for an unnamed pair.## Ask First@@ -34,7 +35,7 @@## Validation Commands```bash-pnpm --filter @carbon/viewer test # vitest — camera, fallback, graph, motion, plan, visibility+pnpm --filter @carbon/viewer test # vitest — camera, fallback, graph, motion, plan, staging, visibilitypnpm --filter @carbon/viewer typecheck # tsgo --noEmit```@@ -49,7 +50,7 @@ pnpm --filter @carbon/viewer typecheck # tsgo --noEmit| `./optimize-progress` | `OptimizeProgress` — optimise-status chip || `./use-optimized-model` | `useOptimizedModel` — TanStack Query polling of the model optimise lifecycle (shared by ERP `CadModel` + MES model tab) |-Key non-exported building blocks: `useAssembly` (loads meshopt GLB + graph.json, indexes nodes by nodeId), `motion.ts` (`buildStepClip`, `motionToKeyframes`, `naturalizeMotion`), `fallback.ts` (`synthesizeFallbackMotion` — AABB escape for legacy `none` motions), `camera.ts` (`fitFraming` — live frustum fit around the planner's baked view direction), `raw/` (WASM fallback tier: `loadRawModel` via occt-import-js).+Key non-exported building blocks: `useAssembly` (loads meshopt GLB + graph.json, indexes nodes by nodeId), `motion.ts` (`buildStepClip`, `motionToKeyframes`, `naturalizeMotion`), `fallback.ts` (`synthesizeFallbackMotion` — AABB escape for legacy `none` motions), `staging.ts` (`buildStaging` / `parkedOffsetsAt` / `stagedGroupNodeIds` / `joinTargets` — sub-assemblies built aside; `joinTargets` is THE link rule the ERP service, the ERP select and playback share, and it and `stagedGroupNodeIds` are also on `./steps`), `camera.ts` (`fitFraming` — live frustum fit around the planner's baked view direction), `raw/` (WASM fallback tier: `loadRawModel` via occt-import-js).## Cross-Referencesdiff --git a/packages/viewer/src/AssemblyPlayer.tsx b/packages/viewer/src/AssemblyPlayer.tsxindex 21624eb7ab..0f21d6cfb2 100644--- a/packages/viewer/src/AssemblyPlayer.tsx+++ b/packages/viewer/src/AssemblyPlayer.tsx@@ -40,6 +40,12 @@ import {naturalizeMotion,stepTimelineSeconds} from "./motion";+import {+ buildStaging,+ parkedOffsetsAt,+ STAGING_GLIDE_SECONDS,+ type Staging+} from "./staging";import type {AssemblyGraph,AssemblyStep,@@ -315,6 +321,13 @@ export const AssemblyPlayer = forwardRef<return () => window.removeEventListener("keydown", onKeyDown);}, [readOnly, onSelectComponents, graphIndex, nodesById]);+ // Sub-assemblies built off to the side (`joinStepId`): which steps stage,+ // where each group sits, and which step carries it in.+ const staging = useMemo(+ () => buildStaging(steps, graphIndex),+ [steps, graphIndex]+ );+// Display-only motion adjustments — the stored data is untouched:// 1. Non-flagged steps saved with motion "none" (legacy plans, manual// steps) get an AABB-synthesized insertion so components never pop into@@ -331,13 +344,55 @@ export const AssemblyPlayer = forwardRef<root.max[2] - root.min[2]);// Fallback synthesis sees only the components already installed by earlier- // steps — the parts actually on the canvas when this step plays+ // steps — the parts actually on the canvas when this step plays. A group+ // built aside has its own world (only its earlier parts, at the staging+ // spot) until its join step carries it onto the main one.const present = new Set<string>();- return steps.map((step, index) => {+ const stagedPresent = new Map<number, Set<string>>();+ return steps.map((original, index) => {+ // A join step moves its own parts AND the group built aside for it, so+ // every per-step consumer (clip, fallback, framing, hidden list) sees+ // the whole moving set.+ const join = staging.joins.get(index);+ const joinIndex = staging.stagedToJoin.get(index);+ const stagedOffset =+ joinIndex === undefined+ ? null+ : (staging.joins.get(joinIndex)?.offset ?? null);+ let step = original;+ if (join) {+ step = {+ ...step,+ componentNodeIds: [+ ...new Set([...step.componentNodeIds, ...join.nodeIds])+ ]+ };+ }+ // Path keyframes are absolute; a staged step plays at its staging spot.+ if (stagedOffset && step.motion.type === "path") {+ step = {+ ...step,+ motion: {+ ...step.motion,+ keyframes: step.motion.keyframes.map((keyframe) => ({+ ...keyframe,+ position: keyframe.position.map(+ (value, axis) => value + (stagedOffset[axis] ?? 0)+ ) as Vec3+ }))+ }+ };+ }++ const world =+ joinIndex === undefined+ ? present+ : (stagedPresent.get(joinIndex) ?? new Set<string>());const baseMotion = suppressFallbackMotions? step.motion- : displayMotionForStep(step, index, graphIndex, present);- for (const nodeId of step.componentNodeIds) present.add(nodeId);+ : displayMotionForStep(step, index, graphIndex, world);+ for (const nodeId of step.componentNodeIds) world.add(nodeId);+ if (joinIndex !== undefined) stagedPresent.set(joinIndex, world);let minBox: [number, number, number] | null = null;let maxBox: [number, number, number] | null = null;@@ -377,12 +432,22 @@ export const AssemblyPlayer = forwardRef<);return motion === step.motion ? step : { ...step, motion };});- }, [steps, graphIndex, suppressFallbackMotions]);+ }, [steps, graphIndex, suppressFallbackMotions, staging]);// --- Continuous timeline ---------------------------------------------+ // A join step also spends the glide carrying its group in from the side+ // (unless the author set an explicit duration).const segments = useMemo(- () => displaySteps.map(stepTimelineSeconds),- [displaySteps]+ () =>+ displaySteps.map(+ (step, index) =>+ stepTimelineSeconds(step) ++ (staging.joins.has(index) &&+ !(step.durationSeconds && step.durationSeconds > 0)+ ? STAGING_GLIDE_SECONDS+ : 0)+ ),+ [displaySteps, staging]);const startTimes = useMemo(() => {let elapsed = 0;@@ -525,6 +590,7 @@ export const AssemblyPlayer = forwardRef<cameraMode={cameraMode}onFreeCamera={handleFreeCamera}componentPickerActive={componentPickerActive}+ staging={staging}/>)}</AssemblyViewer>@@ -864,7 +930,8 @@ function AssemblyScene({onBoxRect,cameraMode,onFreeCamera,- componentPickerActive+ componentPickerActive,+ staging}: {scene: Object3D;nodesById: Map<string, Object3D>;@@ -922,6 +989,8 @@ function AssemblyScene({/** Picking components to add to a step — ghost every not-yet-installed part so* un-animated parts are visible and clickable */componentPickerActive: boolean;+ /** Sub-assemblies built aside: parked at a staging spot until their join step */+ staging: Staging;}) {const camera = useThree((state) => state.camera);const controls = useThree(@@ -1277,13 +1346,25 @@ function AssemblyScene({startTimesLiveRef.current = startTimes;const segmentsLiveRef = useRef(segments);segmentsLiveRef.current = segments;+ const stagingLiveRef = useRef(staging);+ stagingLiveRef.current = staging;+ // Where groups built aside sit for this step, and the glide of a join step —+ // part of the signature so a staging change re-parks and rebuilds the clip.+ const stagingKey = JSON.stringify([+ [...parkedOffsetsAt(staging, steps, activeStepIndex)].sort(([a], [b]) =>+ a < b ? -1 : a > b ? 1 : 0+ ),+ staging.joins.get(activeStepIndex)?.offset ?? null+ ]);const clipKey = activeStep? [activeStepIndex,activeStep.id,JSON.stringify(activeStep.motion),activeStep.componentNodeIds.join(","),- isEditingActive+ isEditingActive,+ componentPickerActive,+ stagingKey].join("|"): `none|${activeStepIndex}`;@@ -1302,11 +1383,42 @@ function AssemblyScene({if (!step) return;+ // Groups built aside sit at their staging spot until their join step. This+ // effect is the one place that moves them, so park and unpark stay paired+ // with the clip's own save/restore. Picking and path editing keep+ // everything seated: a click must select what the BOM tree shows.+ const seatedOnly = isEditingActive || componentPickerActive;+ const parked = seatedOnly+ ? []+ : parkNodes(+ parkedOffsetsAt(+ stagingLiveRef.current,+ stepsLiveRef.current,+ activeStepIndex+ ),+ nodesById+ );+ const unpark = () => {+ for (const { node, position } of parked) {+ node.position.copy(position);+ node.updateMatrixWorld(true);+ }+ };+// Editing this step's path: keep components at their seated pose, skip the clip// so the animation doesn't fight the drag handles.- if (isEditingActive) return;-- const clip = buildStepClip(step, nodesById);+ if (isEditingActive) return unpark;++ const join = seatedOnly+ ? undefined+ : stagingLiveRef.current.joins.get(activeStepIndex);+ const clip = buildStepClip(+ step,+ nodesById,+ join+ ? { glide: { offset: join.offset, seconds: STAGING_GLIDE_SECONDS } }+ : {}+ );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@@ -1321,7 +1433,7 @@ function AssemblyScene({playheadRef.current =(startTimesLiveRef.current[activeStepIndex] ?? 0) + settled;}- return;+ return unpark;}// Save seated transforms so we can restore them when the step changes@@ -1364,6 +1476,7 @@ function AssemblyScene({node.position.copy(position);node.quaternion.copy(quaternion);}+ unpark();};}, [mixer,@@ -1371,6 +1484,7 @@ function AssemblyScene({clipKey,activeStepIndex,isEditingActive,+ componentPickerActive,loop,seekRef,playheadRef@@ -1419,11 +1533,13 @@ function AssemblyScene({fadeRef.current = null;return;}+ // A join step glides its group in from the side instead of fading.const fadesIn =step &&step.motion.type === "none" &&step.componentNodeIds.length > 0 &&- (step.flagged || activeStepIndex > 0);+ (step.flagged || activeStepIndex > 0) &&+ !staging.joins.has(activeStepIndex);if (!fadesIn) {fadeRef.current = null;return;@@ -1470,7 +1586,7 @@ function AssemblyScene({// Materials are reassigned by the visual-state pass on step changefor (const mesh of meshes) mesh.renderOrder = 0;};- }, [steps, activeStepIndex, nodesById, segments, editMotion]);+ }, [steps, activeStepIndex, nodesById, segments, editMotion, staging]);useFrame(() => {const fade = fadeRef.current;@@ -1686,7 +1802,8 @@ function AssemblyScene({JSON.stringify(step.motion),futureMode,installedMode,- [...hiddenSet].sort().join(",")+ [...hiddenSet].sort().join(","),+ stagingKey].join("|");if (framingKey === lastFramedKeyRef.current) return;lastFramedKeyRef.current = framingKey;@@ -1715,25 +1832,31 @@ function AssemblyScene({if (step.componentNodeIds.length === 0) return;- const assemblyBox = getAssemblyBox();+ // Groups built aside: frame the parts where they are drawn (the staging+ // spot), and a join step from the staging spot to its seat.+ const parkedOffsets = parkedOffsetsAt(staging, steps, activeStepIndex);+ const joinOffset = staging.joins.get(activeStepIndex)?.offset ?? null;++ const assemblyBox = getAssemblyBox().clone();if (assemblyBox.isEmpty()) return;- const center = assemblyBox.getCenter(new Vector3());- const radius = assemblyBox.getSize(new Vector3()).length() / 2;- const fov = camera instanceof PerspectiveCamera ? camera.fov : 45;- const distance = Math.max(- (radius / Math.tan(((fov / 2) * Math.PI) / 180)) * 1.25,- radius * 2- );const componentBox = new Box3();for (const nodeId of step.componentNodeIds) {const seated = seatedBoundsById?.get(nodeId);if (seated) {+ const parkedOffset = parkedOffsets.get(nodeId);+ const shift = parkedOffset+ ? new Vector3(...parkedOffset)+ : new Vector3();componentBox.expandByPoint(- new Vector3(...(seated.bbox.min as [number, number, number]))+ new Vector3(...(seated.bbox.min as [number, number, number])).add(+ shift+ ));componentBox.expandByPoint(- new Vector3(...(seated.bbox.max as [number, number, number]))+ new Vector3(...(seated.bbox.max as [number, number, number])).add(+ shift+ ));continue;}@@ -1741,6 +1864,19 @@ function AssemblyScene({if (node) componentBox.expandByObject(node);}if (componentBox.isEmpty()) return;+ const joinShift = joinOffset ? new Vector3(...joinOffset) : null;+ // Keep the staging spot inside the standing distance, not just the target.+ assemblyBox.union(componentBox);+ if (joinShift) {+ assemblyBox.union(componentBox.clone().translate(joinShift));+ }+ const center = assemblyBox.getCenter(new Vector3());+ const radius = assemblyBox.getSize(new Vector3()).length() / 2;+ const fov = camera instanceof PerspectiveCamera ? camera.fov : 45;+ const distance = Math.max(+ (radius / Math.tan(((fov / 2) * Math.PI) / 180)) * 1.25,+ radius * 2+ );const componentCenter = componentBox.getCenter(new Vector3());// Aim mostly at the assembly (context) with a nudge toward the component@@ -1762,6 +1898,7 @@ function AssemblyScene({const lookPoints = [componentCenter];for (let i = 0; i < 8; i++) {lookPoints.push(boxCorner(componentBox, i, null));+ if (joinShift) lookPoints.push(boxCorner(componentBox, i, joinShift));}if (startOffset) {lookPoints.push(@@ -1869,6 +2006,7 @@ function AssemblyScene({const actionPoints: Vector3[] = [];for (let i = 0; i < 8; i++) {actionPoints.push(boxCorner(componentBox, i, null));+ if (joinShift) actionPoints.push(boxCorner(componentBox, i, joinShift));if (startOffset)actionPoints.push(boxCorner(componentBox, i, startOffset));}@@ -1913,7 +2051,9 @@ function AssemblyScene({stepIndexByNode,futureMode,installedMode,- cameraMode+ cameraMode,+ staging,+ stagingKey]);// --- Selection -------------------------------------------------------------@@ -2644,3 +2784,40 @@ const VIEW_LABELS: Record<},full: { label: "Full", description: "Show every component solid" }};++/**+ * Moves each node to seat + offset (a world-space translation) and returns+ * the seated local positions to restore. A node inside another parked node+ * already moves with it, so only the top-most ones are shifted.+ */+function parkNodes(+ offsets: ReadonlyMap<string, Vec3>,+ nodesById: Map<string, Object3D>+): { node: Object3D; position: Vector3 }[] {+ const parked: { node: Object3D; position: Vector3 }[] = [];+ for (const [nodeId, offset] of offsets) {+ const node = nodesById.get(nodeId);+ if (!node) continue;+ let ancestor = node.parent;+ let nested = false;+ while (ancestor) {+ const ancestorId = ancestor.userData?.nodeId;+ if (typeof ancestorId === "string" && offsets.has(ancestorId)) {+ nested = true;+ break;+ }+ ancestor = ancestor.parent;+ }+ if (nested) continue;++ node.updateWorldMatrix(true, false);+ const world = new Vector3()+ .setFromMatrixPosition(node.matrixWorld)+ .add(new Vector3(...offset));+ parked.push({ node, position: node.position.clone() });+ if (node.parent) node.parent.worldToLocal(world);+ node.position.copy(world);+ node.updateMatrixWorld(true);+ }+ return parked;+}diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.tsindex d9fab9d034..6b47532ac5 100644--- a/packages/viewer/src/index.ts+++ b/packages/viewer/src/index.ts@@ -45,6 +45,17 @@ export {planMotionForComponents,type StepPhase} from "./plan";+export {+ buildStaging,+ EMPTY_STAGING,+ type JoinTargets,+ joinTargets,+ parkedOffsetsAt,+ STAGING_GLIDE_SECONDS,+ type Staging,+ type StagingJoin,+ stagedGroupNodeIds+} from "./staging";export type {AssemblyGraph,AssemblyGraphNode,diff --git a/packages/viewer/src/motion.test.ts b/packages/viewer/src/motion.test.tsindex 90f12f53e8..31c6bbb3e1 100644--- a/packages/viewer/src/motion.test.ts+++ b/packages/viewer/src/motion.test.ts@@ -394,6 +394,60 @@ describe("buildStepClip", () => {expect(times[times.length - 2]).toBeCloseTo(2);});+ it("glides a join step from its staging spot, then inserts", () => {+ const { nodesById } = makeAssembly();+ const motion: Motion = {+ type: "linear",+ direction: [1, 0, 0],+ distance: 10+ };+ const clip = buildStepClip(makeStep(motion, ["node-a"]), nodesById, {+ duration: 2,+ holdSeconds: 0.5,+ glide: { offset: [0, 100, 0], seconds: 1.2 }+ });+ if (!clip) throw new Error("expected clip");+ expect(clip.duration).toBeCloseTo(1.2 + 2 + 0.5);++ const [positionTrack] = clip.tracks;+ if (!positionTrack) throw new Error("expected tracks");+ const values = [...positionTrack.values];+ const times = [...positionTrack.times];+ // Seated world [6,2,3] + offset [0,100,0] → parent-local [1,102,3]+ expectVectorClose(values.slice(0, 3), [1, 102, 3]);+ // Glide ends at the linear insertion start: world [-4,2,3] → local [-9,2,3]+ const glideEnd = times.findIndex((time) => Math.abs(time - 1.2) < 1e-5);+ expect(glideEnd).toBeGreaterThan(0);+ expectVectorClose(values.slice(glideEnd * 3, glideEnd * 3 + 3), [-9, 2, 3]);+ // Still ends seated, with the hold+ expectVectorClose(values.slice(-6, -3), [1, 2, 3]);+ expect(times[times.length - 2]).toBeCloseTo(3.2);+ for (let i = 1; i < times.length; i++) {+ expect(times[i]).toBeGreaterThan(+ times[i - 1] ?? Number.POSITIVE_INFINITY+ );+ }+ });++ it("glides a none-motion join step straight to the seat", () => {+ const { nodesById } = makeAssembly();+ const clip = buildStepClip(+ makeStep({ type: "none" }, ["node-a"]),+ nodesById,+ {+ holdSeconds: 0,+ glide: { offset: [50, 0, 0], seconds: 1.2 }+ }+ );+ if (!clip) throw new Error("expected clip");+ expect(clip.duration).toBeCloseTo(1.2);+ const [positionTrack] = clip.tracks;+ if (!positionTrack) throw new Error("expected tracks");+ const values = [...positionTrack.values];+ expectVectorClose(values.slice(0, 3), [51, 2, 3]);+ expectVectorClose(values.slice(-3), [1, 2, 3]);+ });+it("converts world-space motion into the local space of a rotated parent", () => {const root = new Group();const parent = new Group();diff --git a/packages/viewer/src/motion.ts b/packages/viewer/src/motion.tsindex 41b96e63e7..e2ccf2301b 100644--- a/packages/viewer/src/motion.ts+++ b/packages/viewer/src/motion.ts@@ -46,6 +46,12 @@ export type MotionKeyframeOptions = {export type StepClipOptions = MotionKeyframeOptions & {/** Seconds to hold the seated pose at the end of each loop. */holdSeconds?: number;+ /**+ * Join step of a sub-assembly built aside: prepend a straight glide from+ * seat + `offset` (the staging spot) to where the insertion starts. Never+ * clamped like the insertion travel is — the staging spot is far by design.+ */+ glide?: { offset: Vec3; seconds: number };};const INSERTION_SPEED_MM_PER_S = 60;@@ -460,20 +466,33 @@ export function motionToKeyframes(* uuid so duplicate node names cannot collide. World-space keyframes are* converted into each node's parent-local space, so nested assembly* transforms are respected. Nodes are assumed to currently sit at their- * final (seated) pose.+ * final (seated) pose — or at their staging spot for a step built aside, which+ * is the pose the insertion then ends at.*- * Returns `null` for `none` motions or when no component resolves to a node.+ * With `glide`, every node first glides from seat + offset to its insertion+ * start (a `none` motion glides straight to the seat).+ *+ * Returns `null` for `none` motions without a glide, or when no component+ * resolves to a node.*/export function buildStepClip(step: AssemblyStep,nodesById: Map<string, Object3D>,options: StepClipOptions = {}): AnimationClip | null {- if (step.motion.type === "none" || step.componentNodeIds.length === 0) {+ const { glide } = options;+ if (+ (step.motion.type === "none" && !glide) ||+ step.componentNodeIds.length === 0+ ) {return null;}- const duration = options.duration ?? motionDuration(step.motion);+ const duration =+ step.motion.type === "none"+ ? 0+ : (options.duration ?? motionDuration(step.motion));+ const glideSeconds = glide ? glide.seconds : 0;const holdSeconds = options.holdSeconds ?? DEFAULT_HOLD_SECONDS;const tracks: (VectorKeyframeTrack | QuaternionKeyframeTrack)[] = [];@@ -487,22 +506,33 @@ export function buildStepClip(const worldScale = new Vector3();node.matrixWorld.decompose(worldPosition, worldQuaternion, worldScale);- const rawKeyframes = motionToKeyframes(- step.motion,- {- position: worldPosition.toArray() as Vec3,- quaternion: toQuat(worldQuaternion)- },- { ...options, duration }- );+ const seatedPose: Pose = {+ position: worldPosition.toArray() as Vec3,+ quaternion: toQuat(worldQuaternion)+ };+ // A `none` motion only happens with a glide: the insertion is the seat itself.+ const rawKeyframes =+ step.motion.type === "none"+ ? {+ times: [0],+ positions: [...seatedPose.position],+ quaternions: [...seatedPose.quaternion]+ }+ : motionToKeyframes(step.motion, seatedPose, {+ ...options,+ duration+ });if (!rawKeyframes) continue;// Ease the straight insertion approaches (accelerate off the start, settle// into the seat). Helix threads at a constant rate (mechanically correct)// and paths carry their own timing, so leave those raw.- const keyframes =+ const insertion =step.motion.type === "linear" || step.motion.type === "L"? resampleEased(rawKeyframes): rawKeyframes;+ const keyframes = glide+ ? prependGlide(insertion, glide.offset, seatedPose, glide.seconds)+ : insertion;const parentWorldInverse = node.parent? node.parent.matrixWorld.clone().invert()@@ -554,7 +584,47 @@ export function buildStepClip(}if (tracks.length === 0) return null;- return new AnimationClip(`step:${step.id}`, duration + holdSeconds, tracks);+ return new AnimationClip(+ `step:${step.id}`,+ glideSeconds + duration + holdSeconds,+ tracks+ );+}++/**+ * Prepends an eased straight glide from seat + `offset` to the insertion's+ * first pose, and shifts the insertion to start when the glide ends. The part+ * holds the insertion's starting orientation while it glides (staging is a+ * pure translation), so a helix that starts unscrewed doesn't snap.+ */+function prependGlide(+ insertion: MotionKeyframes,+ offset: Vec3,+ seatedPose: Pose,+ seconds: number+): MotionKeyframes {+ const end = new Vector3().fromArray(insertion.positions, 0);+ const start = toVector3(seatedPose.position).add(toVector3(offset));+ const quaternion = new Quaternion().fromArray(insertion.quaternions, 0);++ const times: number[] = [];+ const positions: number[] = [];+ const quaternions: number[] = [];+ const point = new Vector3();+ for (let j = 0; j <= EASE_SAMPLES; j++) {+ const u = j / EASE_SAMPLES;+ point.copy(start).lerp(end, easeInOutCubic(u));+ times.push(u * seconds);+ positions.push(point.x, point.y, point.z);+ quaternions.push(quaternion.x, quaternion.y, quaternion.z, quaternion.w);+ }+ // The insertion's first frame is where the glide ended — skip the duplicate.+ for (let i = 1; i < insertion.times.length; i++) {+ times.push(seconds + (insertion.times[i] ?? 0));+ positions.push(...insertion.positions.slice(i * 3, i * 3 + 3));+ quaternions.push(...insertion.quaternions.slice(i * 4, i * 4 + 4));+ }+ return { times, positions, quaternions };}/**diff --git a/packages/viewer/src/staging.test.ts b/packages/viewer/src/staging.test.tsnew file mode 100644index 0000000000..1fc1e66e4e--- /dev/null+++ b/packages/viewer/src/staging.test.ts@@ -0,0 +1,272 @@+import { describe, expect, it } from "vitest";+import { indexAssemblyGraph } from "./graph";+import {+ buildStaging,+ EMPTY_STAGING,+ joinTargets,+ parkedOffsetsAt,+ stagedGroupNodeIds+} from "./staging";+import type {+ AssemblyGraph,+ AssemblyGraphNode,+ AssemblyStep,+ Vec3+} from "./types";++const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];++function leaf(nodeId: string, min: Vec3, max: Vec3): AssemblyGraphNode {+ return {+ nodeId,+ name: nodeId,+ isAssembly: false,+ geometryHash: nodeId,+ transform: IDENTITY,+ bbox: { min, max },+ volume: 1,+ color: null,+ children: []+ };+}++// SA-0033-shaped: a trailing arm with a front hub (bearing, circlip, disc).+const graph: AssemblyGraph = {+ version: 1,+ unit: "mm",+ sourceUnit: "mm",+ componentCount: 6,+ root: {+ nodeId: "root",+ name: "Trailing arm assembly",+ isAssembly: true,+ geometryHash: null,+ transform: IDENTITY,+ bbox: { min: [0, 0, 0], max: [100, 50, 50] },+ volume: null,+ color: null,+ children: [+ leaf("arm", [0, 0, 0], [100, 50, 50]),+ leaf("hub", [40, 10, 10], [60, 40, 40]),+ leaf("bearing", [45, 15, 15], [55, 35, 35]),+ leaf("circlip", [48, 20, 20], [52, 30, 30]),+ leaf("disc", [30, 0, 0], [70, 50, 50]),+ leaf("bolt", [90, 0, 0], [95, 5, 5])+ ]+ }+};+const index = indexAssemblyGraph(graph);+const DIAGONAL = Math.hypot(100, 50, 50);+const GAP = DIAGONAL * 0.25;++type Step = Pick<+ AssemblyStep,+ "id" | "componentNodeIds" | "joinStepId" | "camera"+>;++function step(+ id: string,+ componentNodeIds: string[],+ joinStepId?: string+): Step {+ return { id, componentNodeIds, joinStepId: joinStepId ?? null, camera: null };+}++// 0 arm (base) · 1 hub · 2 bearing · 3 circlip · 4 disc · 5 join (hub group into arm)+const steps: Step[] = [+ step("s0", ["arm"]),+ step("s1", ["hub"], "s5"),+ step("s2", ["bearing"], "s5"),+ step("s3", ["circlip"], "s5"),+ step("s4", ["disc"], "s5"),+ step("s5", [])+];++describe("buildStaging", () => {+ it("groups the staged steps under their join step", () => {+ const staging = buildStaging(steps, index);+ expect([...staging.joins.keys()]).toEqual([5]);+ const join = staging.joins.get(5);+ expect(join?.nodeIds).toEqual(["hub", "bearing", "circlip", "disc"]);+ // The group's left edge (disc, x=30) lands one gap right of the model.+ expect(join?.offset[0]).toBeCloseTo(100 + GAP - 30);+ expect(join?.offset[1]).toBe(0);+ expect(join?.offset[2]).toBe(0);+ expect([...staging.stagedToJoin]).toEqual([+ [1, 5],+ [2, 5],+ [3, 5],+ [4, 5]+ ]);+ });++ it("ignores backwards, base and unknown links", () => {+ const staging = buildStaging(+ [+ step("s0", ["arm"], "s2"), // the base can't be staged+ step("s1", ["hub"], "s0"), // backwards+ step("s2", ["bearing"], "missing"), // unknown id+ step("s3", ["circlip"]),+ step("s4", ["disc"], "s5"),+ step("s5", [])+ ],+ index+ );+ expect([...staging.stagedToJoin]).toEqual([[4, 5]]);+ expect(staging.joins.get(5)?.nodeIds).toEqual(["disc"]);+ });++ it("builds a nested chain in place — neither link counts", () => {+ // s1 → s2 → s3: s2 is both a join target and staged. The ERP refuses this;+ // a row that slips through plays as if nothing were staged.+ const staging = buildStaging(+ [+ step("s0", ["arm"]),+ step("s1", ["hub"], "s2"),+ step("s2", ["bearing"], "s3"),+ step("s3", [])+ ],+ index+ );+ expect(staging).toBe(EMPTY_STAGING);+ });++ it("gives several groups their own non-overlapping lanes", () => {+ const staging = buildStaging(+ [+ step("s0", ["arm"]),+ step("s1", ["hub"], "s2"),+ step("s2", []),+ step("s3", ["bolt"], "s4"),+ step("s4", [])+ ],+ index+ );+ const first = staging.joins.get(2);+ const second = staging.joins.get(4);+ if (!first || !second) throw new Error("expected two joins");+ const firstMax = 60 + first.offset[0];+ const secondMin = 90 + second.offset[0];+ expect(secondMin).toBeCloseTo(firstMax + GAP);+ });++ it("stages beside the model, side-on to a saved camera", () => {+ // The join step's saved view looks straight down X: staging along X would+ // hide the group behind the model, so it goes along Z instead.+ const staging = buildStaging(+ [+ step("s0", ["arm"]),+ step("s1", ["hub"], "s2"),+ {+ ...step("s2", []),+ camera: { position: [500, 25, 25], target: [50, 25, 25], fov: 45 }+ }+ ],+ index+ );+ const offset = staging.joins.get(2)?.offset;+ expect(offset?.[0]).toBe(0);+ expect(offset?.[1]).toBe(0);+ // Hub's near face (z=10) lands one gap past the model's far face (z=50).+ expect(offset?.[2]).toBeCloseTo(50 + GAP - 10);+ });++ it("never stages above or below the model", () => {+ // A camera looking straight down Y is side-on to every horizontal axis.+ const staging = buildStaging(+ [+ step("s0", ["arm"]),+ step("s1", ["hub"], "s2"),+ {+ ...step("s2", []),+ camera: { source: "plan", direction: [0, 1, 0] }+ }+ ],+ index+ );+ expect(staging.joins.get(2)?.offset[1]).toBe(0);+ expect(staging.joins.get(2)?.offset[0]).toBeGreaterThan(0);+ });++ it("is empty without a graph or without links", () => {+ expect(buildStaging(steps, null)).toBe(EMPTY_STAGING);+ expect(+ buildStaging([step("s0", ["arm"]), step("s1", ["hub"])], index)+ ).toBe(EMPTY_STAGING);+ });++ it("skips a join whose parts no longer resolve", () => {+ const staging = buildStaging(+ [step("s0", ["arm"]), step("s1", ["gone"], "s2"), step("s2", [])],+ index+ );+ expect(staging.joins.size).toBe(0);+ expect(staging.stagedToJoin.size).toBe(0);+ });+});++describe("parkedOffsetsAt", () => {+ const staging = buildStaging(steps, index);+ const offset = staging.joins.get(5)?.offset;++ it("parks nothing before the first staged step", () => {+ expect(parkedOffsetsAt(staging, steps, 0).size).toBe(0);+ });++ it("parks the active staged step's own parts and the earlier staged parts", () => {+ expect([...parkedOffsetsAt(staging, steps, 1).keys()]).toEqual(["hub"]);+ const atCirclip = parkedOffsetsAt(staging, steps, 3);+ expect([...atCirclip.keys()]).toEqual(["hub", "bearing", "circlip"]);+ expect(atCirclip.get("bearing")).toEqual(offset);+ });++ it("parks nothing at or after the join step", () => {+ expect(parkedOffsetsAt(staging, steps, 5).size).toBe(0);+ });+});++describe("stagedGroupNodeIds", () => {+ it("returns the carried-in parts for a join step and nothing otherwise", () => {+ expect(stagedGroupNodeIds(steps, "s5")).toEqual([+ "hub",+ "bearing",+ "circlip",+ "disc"+ ]);+ expect(stagedGroupNodeIds(steps, "s2")).toEqual([]);+ expect(stagedGroupNodeIds(steps, "missing")).toEqual([]);+ });+});++describe("joinTargets", () => {+ it("locks the base step", () => {+ expect(joinTargets(steps, "s0")).toEqual({ targets: [], locked: "base" });+ });++ it("locks a join step", () => {+ expect(joinTargets(steps, "s5")).toEqual({ targets: [], locked: "join" });+ });++ it("offers later steps that aren't built aside themselves", () => {+ // s2–s4 are staged (they point at s5), so s1 may only join s5.+ expect(joinTargets(steps, "s1")).toEqual({ targets: ["s5"], locked: null });+ expect(+ joinTargets(+ [+ step("s0", ["arm"]),+ step("s1", ["hub"]),+ step("s2", []),+ step("s3", [])+ ],+ "s1"+ )+ ).toEqual({ targets: ["s2", "s3"], locked: null });+ });++ it("offers nothing for an unknown step", () => {+ expect(joinTargets(steps, "missing")).toEqual({+ targets: [],+ locked: null+ });+ });+});diff --git a/packages/viewer/src/staging.ts b/packages/viewer/src/staging.tsnew file mode 100644index 0000000000..1a70d83f5d--- /dev/null+++ b/packages/viewer/src/staging.ts@@ -0,0 +1,219 @@+import type { AssemblyGraphIndex } from "./graph";+import type { AssemblyStep, Vec3 } from "./types";++/**+ * Sub-assembly staging: steps that point at a later JOIN step (`joinStepId`)+ * build their parts off to the side of the main model; the join step carries+ * the finished group in. Pure — no three.js — so it is unit-testable in node.+ *+ * Bad links (backwards, from the base step, nested, unknown id) are ignored+ * here rather than thrown: the ERP validates on write, and a stale row must+ * still play as "built in place".+ */++/** Seconds the staged group takes to glide from its staging spot to the insertion start. */+export const STAGING_GLIDE_SECONDS = 1.2;+/** Gap between the main model and a staging lane, and between lanes, as a fraction of the assembly diagonal. */+const STAGING_GAP_FRACTION = 0.25;++type StagingStep = Pick<+ AssemblyStep,+ "id" | "componentNodeIds" | "joinStepId"+> & { camera?: AssemblyStep["camera"] };++/** Unit target→eye direction of a saved camera, or null when the step auto-frames. */+function viewDirection(camera: StagingStep["camera"]): Vec3 | null {+ if (!camera) return null;+ const raw: Vec3 =+ "source" in camera+ ? camera.direction+ : [+ camera.position[0] - camera.target[0],+ camera.position[1] - camera.target[1],+ camera.position[2] - camera.target[2]+ ];+ const length = Math.hypot(raw[0], raw[1], raw[2]);+ return length > 1e-9+ ? [raw[0] / length, raw[1] / length, raw[2] / length]+ : null;+}++/**+ * The side a group is staged on: +X or +Z (never above/below — the viewer is+ * Y-up), whichever is most side-on to every saved view of the steps involved+ * so a fixed camera never looks straight along it; +X on a tie or with no+ * saved views. Auto-framed steps adapt on their own.+ */+function stagingAxis(views: Vec3[]): 0 | 2 {+ const along = (axis: 0 | 2) =>+ Math.max(0, ...views.map((view) => Math.abs(view[axis])));+ return along(2) < along(0) - 1e-6 ? 2 : 0;+}++export type StagingJoin = {+ joinIndex: number;+ /** Every node installed by this join's staged steps, in step order, deduped */+ nodeIds: string[];+ /** Pure world translation from seat to staging spot (along one side axis) */+ offset: Vec3;+};++export type Staging = {+ /** Keyed by join step index */+ joins: Map<number, StagingJoin>;+ /** Staged step index → its join step index */+ stagedToJoin: Map<number, number>;+};++export const EMPTY_STAGING: Staging = {+ joins: new Map(),+ stagedToJoin: new Map()+};++export type JoinTargets = {+ /** Ids of the steps this one may be built aside for, in order */+ targets: string[];+ /** Why the step can't be built aside at all: the base step, or a join step */+ locked: "base" | "join" | null;+};++/**+ * THE rule for sub-assembly links, shared by the ERP select, the ERP service+ * and playback: one level only — the base step and join steps build in place,+ * and a step joins a LATER step that isn't itself built aside.+ */+export function joinTargets(+ steps: Pick<AssemblyStep, "id" | "joinStepId">[],+ stepId: string+): JoinTargets {+ const index = steps.findIndex((step) => step.id === stepId);+ if (index === 0) return { targets: [], locked: "base" };+ if (steps.some((step) => step.joinStepId === stepId)) {+ return { targets: [], locked: "join" };+ }+ if (index < 0) return { targets: [], locked: null };+ return {+ targets: steps+ .slice(index + 1)+ .filter((step) => !step.joinStepId)+ .map((step) => step.id),+ locked: null+ };+}++/** Staged step index → join step index, for the links `joinTargets` allows. */+function validLinks(steps: StagingStep[]): Map<number, number> {+ const indexById = new Map(steps.map((step, index) => [step.id, index]));+ const links = new Map<number, number>();+ steps.forEach((step, index) => {+ const joinIndex = step.joinStepId+ ? indexById.get(step.joinStepId)+ : undefined;+ if (joinIndex === undefined) return;+ if (!joinTargets(steps, step.id).targets.includes(step.joinStepId ?? "")) {+ return;+ }+ links.set(index, joinIndex);+ });+ return links;+}++/** Ids of the parts a join step carries in: every componentNodeId of the steps pointing at it. */+export function stagedGroupNodeIds(+ steps: StagingStep[],+ joinStepId: string+): string[] {+ const joinIndex = steps.findIndex((step) => step.id === joinStepId);+ if (joinIndex < 0) return [];+ const nodeIds = new Set<string>();+ for (const [stagedIndex, target] of validLinks(steps)) {+ if (target !== joinIndex) continue;+ for (const nodeId of steps[stagedIndex]?.componentNodeIds ?? []) {+ nodeIds.add(nodeId);+ }+ }+ return [...nodeIds];+}++export function buildStaging(+ steps: StagingStep[],+ graphIndex: AssemblyGraphIndex | null+): Staging {+ if (!graphIndex) return EMPTY_STAGING;+ const links = validLinks(steps);+ if (links.size === 0) return EMPTY_STAGING;++ const groups = new Map<number, Set<string>>();+ for (const [stagedIndex, joinIndex] of [...links].sort(([a], [b]) => a - b)) {+ const group = groups.get(joinIndex) ?? new Set<string>();+ for (const nodeId of steps[stagedIndex]?.componentNodeIds ?? []) {+ group.add(nodeId);+ }+ groups.set(joinIndex, group);+ }++ const root = graphIndex.graph.root.bbox;+ const diagonal = Math.hypot(+ root.max[0] - root.min[0],+ root.max[1] - root.min[1],+ root.max[2] - root.min[2]+ );+ const gap = diagonal * STAGING_GAP_FRACTION;+ // One lane cursor per axis: the next free coordinate past the model along it.+ const cursors = new Map<0 | 2, number>();++ const joins = new Map<number, StagingJoin>();+ for (const joinIndex of [...groups.keys()].sort((a, b) => a - b)) {+ const nodeIds = [...(groups.get(joinIndex) ?? [])];+ const views: Vec3[] = [];+ for (const [stagedIndex, target] of links) {+ if (target !== joinIndex) continue;+ const view = viewDirection(steps[stagedIndex]?.camera);+ if (view) views.push(view);+ }+ const joinView = viewDirection(steps[joinIndex]?.camera);+ if (joinView) views.push(joinView);++ const axis = stagingAxis(views);+ let min = Number.POSITIVE_INFINITY;+ let max = Number.NEGATIVE_INFINITY;+ for (const nodeId of nodeIds) {+ const node = graphIndex.nodesById.get(nodeId);+ if (!node) continue;+ min = Math.min(min, node.bbox.min[axis]);+ max = Math.max(max, node.bbox.max[axis]);+ }+ // Nothing resolves (stale nodeIds after a re-upload): build in place.+ if (!Number.isFinite(min) || !Number.isFinite(max)) continue;++ const cursor = cursors.get(axis) ?? root.max[axis] + gap;+ const offset: Vec3 = [0, 0, 0];+ offset[axis] = cursor - min;+ joins.set(joinIndex, { joinIndex, nodeIds, offset });+ cursors.set(axis, cursor + (max - min) + gap);+ }++ const stagedToJoin = new Map<number, number>();+ for (const [stagedIndex, joinIndex] of links) {+ if (joins.has(joinIndex)) stagedToJoin.set(stagedIndex, joinIndex);+ }+ return { joins, stagedToJoin };+}++/** nodeId → offset for every node that sits at its staging spot while step `activeIndex` is shown. */+export function parkedOffsetsAt(+ staging: Staging,+ steps: Pick<AssemblyStep, "componentNodeIds">[],+ activeIndex: number+): Map<string, Vec3> {+ const parked = new Map<string, Vec3>();+ for (const [stagedIndex, joinIndex] of staging.stagedToJoin) {+ if (stagedIndex > activeIndex || activeIndex >= joinIndex) continue;+ const join = staging.joins.get(joinIndex);+ if (!join) continue;+ for (const nodeId of steps[stagedIndex]?.componentNodeIds ?? []) {+ parked.set(nodeId, join.offset);+ }+ }+ return parked;+}diff --git a/packages/viewer/src/steps.ts b/packages/viewer/src/steps.tsindex 8f4be4ee3f..6660895f86 100644--- a/packages/viewer/src/steps.ts+++ b/packages/viewer/src/steps.ts@@ -9,12 +9,15 @@ import {buildAssemblyStepGroups,CURRENT_PLAN_VERSION} from "./plan";+import { joinTargets, stagedGroupNodeIds } from "./staging";export {assignStepPhases,buildAssemblyStepGroups,CURRENT_PLAN_VERSION,- indexAssemblyGraph+ indexAssemblyGraph,+ joinTargets,+ stagedGroupNodeIds};export type { AssemblyGraphIndex } from "./graph";export type { AssemblyPlan, AssemblyStepGroup, StepPhase } from "./plan";diff --git a/packages/viewer/src/types.ts b/packages/viewer/src/types.tsindex d01f402a03..0e8bebeafe 100644--- a/packages/viewer/src/types.ts+++ b/packages/viewer/src/types.ts@@ -115,12 +115,11 @@ export type AssemblyStep = {*/hiddenComponentNodeIds?: string[];/**- * Subassembly phase this step belongs to (baked at step generation from the- * plan's contact graph). `null`/absent = the main phase, built seated. A- * non-null phase builds staged off to the side and flies into the main body- * at its `join` step. See `@carbon/viewer` staging.+ * Built off to the side: the id of the later JOIN step where the group this+ * step builds is carried into the main assembly (DB `parentStepId`).+ * `null`/absent = built in place. See `staging.ts`.*/- phase?: { id: string; name: string; join: boolean } | null;+ joinStepId?: string | null;};/** One node of the assembly tree in graph.json. */