Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

(feat): see past already-installed parts in the 3D assembly viewer (#1660)

Anshul sharma95b4c31426f6
diff --git a/.ai/lessons.md b/.ai/lessons.md
index b0f4088662..47afd4de63 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -91,6 +91,16 @@ Format: `Context → Problem → Rule → Applies to`
**Applies to:** `packages/viewer/`, geometry planner (`crates/planner`).
+## "What is drawn" and "what blocks the view" must be derived from one predicate
+
+**Context:** Adding `installedMode` to the assembly viewer (`packages/viewer/src/visibility.ts`). Two pieces of code answered questions about the same timeline: `visualForComponent` decided how a component renders, while the camera's AABB view-direction scorer decided how much it counts as an obstacle. The scorer was written inline inside `AssemblyPlayer`, hundreds of lines away.
+
+**Problem:** They disagreed on one input. `visualForComponent` treats a component that **no step installs** exactly like a future-step one ("never already there"), so under the MES default `futureMode: "hidden"` it rendered hidden. The inline scorer computed `isFuture = stepIndex !== undefined && stepIndex > activeStepIndex` — `undefined` failed that test, so the same component kept full occluder weight. The camera picked view angles that dodged geometry it was not drawing. Silent: no error, nothing visibly broken, just subtly worse framing that no test covered because the logic was un-extractable inline.
+
+**Rule:** When one fact (here: a component's position relative to the active step) drives both what the user sees and what the system reasons about, derive both from a single exported predicate in the same module, and assert the invariant that links them — *anything invisible is never an obstacle* — over the full cross-product of modes, not over hand-picked cases. The cross-product test is what caught this; a case-by-case test would have encoded the bug. Extracting the inline logic is the fix, not adding a comment telling the next person to keep them in sync.
+
+**Applies to:** `packages/viewer/src/visibility.ts` (`visualForComponent` / `occluderWeight`), `packages/viewer/src/AssemblyPlayer.tsx`; any pair of render-vs-reason helpers over the same state.
+
## Posting-group-style matrices are a rejected pattern
**Context:** Designing multi-jurisdiction tax determination; the spec anchored on the customerType × itemPostingGroup posting-group matrix as "Carbon precedent."
diff --git a/.ai/plans/2026-09-17-viewer-installed-component-visibility.md b/.ai/plans/2026-09-17-viewer-installed-component-visibility.md
new file mode 100644
index 0000000000..b53e5a3253
--- /dev/null
+++ b/.ai/plans/2026-09-17-viewer-installed-component-visibility.md
@@ -0,0 +1,509 @@
+# Installed-component visibility in the assembly viewer — implementation plan
+
+**Spec:** .ai/specs/2026-09-17-viewer-installed-component-visibility.md
+**Research:** N/A — internal rendering change, no ERP-domain logic (see spec §Research)
+**Branch:** worktree-feat-hide-installed-parts
+
+## Progress
+- [x] Task 1: Add `InstalledComponentsMode` + 4th param to `visualForComponent`
+- [x] Task 2: Extend `visibility.test.ts` for the new parameter
+- [x] Task 3: Thread `installedMode` through `AssemblyPlayer` state and scene props
+- [x] Task 4: Make camera auto-framing respect `installedMode` — **shipped
+ differently**: extracted `occluderWeight` instead of an inline edit, and
+ fixed a pre-existing bug it exposed (see the note on Task 4)
+- [x] Task 5: Add the toolbar control — **shipped differently, twice.** The
+ six-button two-group design this plan describes was built, then rejected
+ by the user on sight. An MES-only Focus toggle was tried next and also
+ dropped, and so was a three-view version that had no way to show the
+ active part on its own. What shipped is four named views
+ (`Build`/`Focus`/`Isolate`/`Full`),
+ identical in ERP and MES, backed by `ASSEMBLY_VIEWS` / `VIEW_MODES` /
+ `viewForModes` in `visibility.ts` and `VIEW_LABELS` in
+ `AssemblyPlayer.tsx`. `FocusIcon`/`GhostIcon`/`HiddenIcon`/`SolidIcon`
+ were deleted as dead. `flex-wrap` on the row was kept; the "Next"/"Built"
+ labels went with the design that needed them. The two axes and every
+ pre-existing test are untouched — a view is a derived pair. See the spec
+ changelog for why each design was dropped.
+- [x] Task 6: Typecheck + full viewer test run — 120 tests pass (14 added for the
+ view table in the redesign); viewer, MES and ERP typecheck clean; biome
+ clean
+- [ ] Task 7: Browser verification in ERP and MES — **NOT DONE.** The local
+ `main.dev` dev stack was not running, and an ad-hoc server could not
+ complete the dev login ("User record not found"). Nothing in this change
+ has been seen rendering. Must be walked before merge.
+
+**Post-review follow-ups (not in the original plan):**
+- [x] Update `apps/erp/app/modules/production/AGENTS.md` — its playback-visibility
+ paragraph described only one visibility axis
+- [x] Add the two-predicates-must-agree invariant to `packages/viewer/AGENTS.md`
+- [x] Add a `.ai/lessons.md` entry for the render-vs-reason drift
+- [x] Correct the spec (occluder extraction, the incidental fix, the wrong
+ "already wraps" claim, verified vs unverified criteria)
+
+## Dependencies
+- Task 2 needs Task 1 (the new signature must exist).
+- Task 3 needs Task 1.
+- Tasks 4 and 5 both need Task 3 (they consume the `installedMode` state it introduces).
+- Task 6 needs Tasks 1–5.
+- Task 7 needs Task 6.
+- Tasks 4 and 5 are independent of each other and may run in parallel.
+
+## Context for the executor
+
+All work is in `packages/viewer` plus one comment-only touch in MES. There is **no**
+migration, no service, no route, no form, and no schema change — do not create any.
+
+`@carbon/viewer` is deliberately i18n-free (zero `@lingui` imports, no lingui
+dependency). New `aria-label` strings in this package stay plain English by
+decision — see the spec's Design Decisions. **Do not add Lingui macros to this
+package.**
+
+---
+
+## Task 1: Add `InstalledComponentsMode` + 4th param to `visualForComponent`
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/viewer/src/visibility.ts` — add the type and the parameter
+
+**Steps:**
+
+1. Open `packages/viewer/src/visibility.ts`. It is ~27 lines; read all of it first.
+2. Below the existing `FutureComponentsMode` type, add:
+
+```ts
+/** How components of steps BEFORE the active one are rendered. */
+export type InstalledComponentsMode = "solid" | "ghost" | "hidden";
+```
+
+3. Change the signature of `visualForComponent` to take a trailing, defaulted 4th
+ parameter, and replace the unconditional `return "solid"` for installed
+ components. The complete function body after the change:
+
+```ts
+export function visualForComponent(
+ stepIndex: number | undefined,
+ activeStepIndex: number,
+ futureMode: FutureComponentsMode,
+ installedMode: InstalledComponentsMode = "solid"
+): ComponentVisual {
+ if (stepIndex !== undefined) {
+ if (stepIndex < activeStepIndex) {
+ return installedMode === "ghost"
+ ? "ghost"
+ : installedMode === "hidden"
+ ? "hidden"
+ : "solid";
+ }
+ if (stepIndex === activeStepIndex) return "active";
+ }
+ return futureMode === "ghost"
+ ? "ghost"
+ : futureMode === "hidden"
+ ? "hidden"
+ : "solid";
+}
+```
+
+4. Update the function's existing doc comment to mention that installed
+ components now follow `installedMode`, which defaults to `"solid"` so
+ three-argument callers are unaffected.
+5. Export the new type from the package barrel: in `packages/viewer/src/index.ts`,
+ find the line that exports `FutureComponentsMode` from `./visibility` and add
+ `InstalledComponentsMode` to the same export.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/viewer
+# Expected: exits 0, no errors. The new param is optional, so no existing
+# call site needs changing yet.
+```
+
+**Out of scope:** Do not touch `AssemblyPlayer.tsx` in this task. Do not change
+the `active` branch or the future-mode branch — installed mode must never affect
+the active step or future components.
+
+---
+
+## Task 2: Extend `visibility.test.ts` for the new parameter
+
+**Depends on:** Task 1
+**Files:**
+- Modify: `packages/viewer/src/visibility.test.ts` — add cases, change nothing existing
+- Copy from (precedent): the same file's existing `describe`/`it` style
+
+**Steps:**
+
+1. Read `packages/viewer/src/visibility.test.ts` (37 lines, 6 `it` blocks).
+2. **Do not modify any existing assertion.** They encode the backward-compatible
+ three-argument behaviour and must keep passing untouched. If any existing test
+ fails after Task 1, STOP and report — the default is wrong.
+3. Append these cases inside the existing `describe("visualForComponent", ...)`:
+
+```ts
+ it("defaults installed components to solid when the 4th arg is omitted", () => {
+ expect(visualForComponent(0, 2, "ghost")).toBe("solid");
+ expect(visualForComponent(1, 2, "hidden")).toBe("solid");
+ });
+
+ it("renders installed components per the installed mode", () => {
+ expect(visualForComponent(0, 2, "ghost", "solid")).toBe("solid");
+ expect(visualForComponent(0, 2, "ghost", "ghost")).toBe("ghost");
+ expect(visualForComponent(0, 2, "ghost", "hidden")).toBe("hidden");
+ });
+
+ it("never lets the installed mode affect the active step", () => {
+ for (const mode of ["solid", "ghost", "hidden"] as const) {
+ expect(visualForComponent(2, 2, "ghost", mode)).toBe("active");
+ }
+ });
+
+ it("never lets the installed mode affect future components", () => {
+ expect(visualForComponent(3, 1, "ghost", "hidden")).toBe("ghost");
+ expect(visualForComponent(3, 1, "hidden", "ghost")).toBe("hidden");
+ expect(visualForComponent(3, 1, "solid", "hidden")).toBe("solid");
+ });
+
+ it("never lets the installed mode affect never-installed components", () => {
+ for (const mode of ["solid", "ghost", "hidden"] as const) {
+ expect(visualForComponent(undefined, 5, "hidden", mode)).toBe("hidden");
+ expect(visualForComponent(undefined, 5, "ghost", mode)).toBe("ghost");
+ }
+ });
+```
+
+4. Add the `InstalledComponentsMode` import if your assertions need it (they use
+ `as const` literals, so an import is likely unnecessary — do not add an unused one).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/viewer test -- visibility
+# Expected: all tests pass, including the 6 pre-existing ones, unmodified.
+```
+
+**Out of scope:** Do not change `graph.test.ts` — its `describeStep` tests are
+unrelated to visibility.
+
+---
+
+## Task 3: Thread `installedMode` through `AssemblyPlayer` state and scene props
+
+**Depends on:** Task 1
+**Files:**
+- Modify: `packages/viewer/src/AssemblyPlayer.tsx`
+- Copy from (precedent): the existing `futureMode` plumbing in the same file —
+ every change below mirrors it exactly
+
+**Steps:**
+
+Work through these in order. Each references the current line number, which will
+drift as you edit — locate by the quoted code, not the number.
+
+1. **Import the type.** Find the existing import of `FutureComponentsMode` from
+ `./visibility` and add `InstalledComponentsMode` alongside it.
+
+2. **Add the prop** (~line 112, next to `defaultFutureMode?: FutureComponentsMode;`):
+
+```ts
+ /**
+ * Initial state of the installed-components control. Defaults to "solid" —
+ * the historical behaviour, where everything already built renders opaque.
+ */
+ defaultInstalledMode?: InstalledComponentsMode;
+```
+
+3. **Destructure with the default** (~line 190, where `defaultFutureMode = "hidden"`
+ is destructured): add `defaultInstalledMode = "solid",`.
+ **The default MUST be `"solid"`** — it preserves existing behaviour for every
+ current user. If you find yourself writing `"ghost"` here, re-read the spec.
+
+4. **Add the state** (~line 219, next to the `futureMode` `useState`):
+
+```ts
+ const [installedMode, setInstalledMode] =
+ useState<InstalledComponentsMode>(defaultInstalledMode);
+```
+
+5. **Pass to the scene** (~line 491, the JSX block where `futureMode={futureMode}`
+ is passed): add `installedMode={installedMode}` directly beneath it.
+
+6. **Add to the scene's props type** (~line 856, where
+ `futureMode: FutureComponentsMode;` is declared): add
+ `installedMode: InstalledComponentsMode;`.
+
+7. **Destructure it in the scene component** (~line 825, the parameter
+ destructuring that includes `futureMode,`): add `installedMode,`.
+
+8. **Add the picker-mode guard and use it.** Immediately after the existing
+ `effectiveFutureMode` declaration (~line 1099), add:
+
+```ts
+ // A hidden component cannot be clicked, so component-picker mode forces the
+ // installed side back to solid — the mirror of the future side's ghost
+ // override above. Both stay pickable, and the two remain distinguishable.
+ const effectiveInstalledMode: InstalledComponentsMode = componentPickerActive
+ ? "solid"
+ : installedMode;
+```
+
+9. **Pass it into the call** (~line 1101, the `visualForComponent(...)` call): add
+ `effectiveInstalledMode` as the 4th argument, after `effectiveFutureMode`.
+
+10. **Add to the effect's dependency array** (~line 1221, the array containing
+ `futureMode,`): add `installedMode,`. Without this the scene will not
+ re-render when the operator changes the control.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/viewer
+# Expected: exits 0. A "declared but never read" error on setInstalledMode is
+# EXPECTED at this point — Task 5 adds the buttons that call it. Any OTHER
+# error means a step above was missed.
+```
+
+**Out of scope:** Do not add the toolbar buttons yet (Task 5). Do not touch the
+camera-framing code (Task 4). Do not change `defaultFutureMode` or any existing
+`futureMode` behaviour.
+
+**If** `installedMode` cannot be threaded because the scene component's props are
+built differently than described, STOP and report — do not improvise a context or
+a module-level variable.
+
+---
+
+## Task 4: Make camera auto-framing respect `installedMode`
+
+> **Superseded during execution — read this before the steps below.** The steps
+> specify an *inline* edit to the occluder loop. That is not what shipped. The
+> inline version duplicated `visualForComponent`'s reasoning about where a
+> component sits relative to the active step, so the logic was extracted into an
+> exported `occluderWeight()` helper in `visibility.ts` (returning `null` for
+> "not an occluder", else the weight; `GHOST_OCCLUDER_WEIGHT = 0.3`), and the
+> loop now calls it.
+>
+> Extracting it exposed a **pre-existing bug**: the inline `isFuture` required
+> `stepIndex !== undefined`, so a component no step installs kept full occluder
+> weight even though `visualForComponent` renders it hidden under the MES
+> default. The camera framed around invisible geometry. Fixed, and locked down
+> by a cross-product invariant test ("anything invisible is never an occluder").
+>
+> The steps below are kept as the original plan of record. See the spec's
+> "Incidental fix" section for what actually shipped.
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `packages/viewer/src/AssemblyPlayer.tsx` — the AABB fallback occluder loop
+- Modify (as shipped): `packages/viewer/src/visibility.ts` — new `occluderWeight`
+ helper + `GHOST_OCCLUDER_WEIGHT`
+
+**Why:** The live AABB framing fallback picks a view direction by scoring which
+components block the line of sight. It already skips future components when
+`futureMode === "hidden"` and half-weights them when `"ghost"`, but installed
+components are unconditionally weighted `1`. Without the symmetric treatment,
+"Hide installed components" would remove the parts visually while the camera still
+framed around them — the control would visibly half-work. This also follows the
+"occlusion-aware angles" rule in `.ai/lessons.md`.
+
+**Steps:**
+
+1. Find the occluder loop (~lines 1758–1769). It currently reads:
+
+```ts
+ for (const leaf of leafBounds ?? []) {
+ if (stepComponents.has(leaf.nodeId)) continue;
+ if (hiddenSet.has(leaf.nodeId)) continue;
+ const leafStep = stepIndexByNode.get(leaf.nodeId);
+ const isFuture = leafStep !== undefined && leafStep > activeStepIndex;
+ if (isFuture && futureMode === "hidden") continue;
+ occluders.push({
+ min: new Vector3(...(leaf.bbox.min as [number, number, number])),
+ max: new Vector3(...(leaf.bbox.max as [number, number, number])),
+ weight: isFuture && futureMode === "ghost" ? 0.3 : 1
+ });
+ }
+```
+
+2. Replace it with the version below. Note `isInstalled` is computed the same way
+ `visualForComponent` decides (`leafStep < activeStepIndex`), so the two stay
+ consistent:
+
+```ts
+ for (const leaf of leafBounds ?? []) {
+ if (stepComponents.has(leaf.nodeId)) continue;
+ if (hiddenSet.has(leaf.nodeId)) continue;
+ const leafStep = stepIndexByNode.get(leaf.nodeId);
+ const isFuture = leafStep !== undefined && leafStep > activeStepIndex;
+ const isInstalled = leafStep !== undefined && leafStep < activeStepIndex;
+ // An occluder the operator has hidden must not push the camera around,
+ // and a ghosted one should barely count — mirrored on both axes.
+ if (isFuture && futureMode === "hidden") continue;
+ if (isInstalled && installedMode === "hidden") continue;
+ const isGhosted =
+ (isFuture && futureMode === "ghost") ||
+ (isInstalled && installedMode === "ghost");
+ occluders.push({
+ min: new Vector3(...(leaf.bbox.min as [number, number, number])),
+ max: new Vector3(...(leaf.bbox.max as [number, number, number])),
+ weight: isGhosted ? 0.3 : 1
+ });
+ }
+```
+
+3. **Add `installedMode` to the framing key** (~line 1663). It is a `.join("|")`
+ string, not a dependency array. Find the entry `futureMode,` inside that array
+ literal and add `installedMode,` after it. Without this, the framing is cached
+ against a stale key and will not recompute when the mode changes.
+
+4. **Add `installedMode` to the framing effect's dependency array** (~line 1883,
+ the array ending `futureMode, cameraMode`): add `installedMode,`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/viewer
+# Expected: exits 0 (the setInstalledMode unused warning from Task 3 may persist
+# until Task 5).
+```
+
+**Out of scope:** Do not change the planner-baked-direction branch (the `if` side
+of this `else`). Steps carrying a baked view direction do not use AABB scoring and
+must keep their planner-chosen angle. Do not change the `0.3` ghost weight value.
+
+---
+
+## Task 5: Add the toolbar control group
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `packages/viewer/src/AssemblyPlayer.tsx` — toolbar JSX
+- Copy from (precedent): the existing future-components group in the same file
+ (~lines 668–692) — same `ControlButton`, same icons, same active pattern
+
+**Steps:**
+
+1. Find the existing group, which is wrapped in
+ `<div className="flex items-center rounded-md border border-border">` and holds
+ three `ControlButton`s writing `setFutureMode`.
+2. Immediately **after** that closing `</div>`, add a second group with the same
+ wrapper class. Order the buttons solid → ghost → hidden (least to most hiding),
+ and reuse the existing `SolidIcon`, `GhostIcon`, `HiddenIcon` components:
+
+```tsx
+ <div className="flex items-center rounded-md border border-border">
+ <ControlButton
+ aria-label="Show installed components solid"
+ aria-pressed={installedMode === "solid"}
+ isActive={installedMode === "solid"}
+ onClick={() => setInstalledMode("solid")}
+ >
+ <SolidIcon />
+ </ControlButton>
+ <ControlButton
+ aria-label="Show installed components ghosted"
+ aria-pressed={installedMode === "ghost"}
+ isActive={installedMode === "ghost"}
+ onClick={() => setInstalledMode("ghost")}
+ >
+ <GhostIcon />
+ </ControlButton>
+ <ControlButton
+ aria-label="Hide installed components"
+ aria-pressed={installedMode === "hidden"}
+ isActive={installedMode === "hidden"}
+ onClick={() => setInstalledMode("hidden")}
+ >
+ <HiddenIcon />
+ </ControlButton>
+ </div>
+```
+
+3. Add a brief comment above the new group explaining that the two groups are the
+ future and installed halves of the same timeline, so a future reader does not
+ mistake them for duplicates.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/viewer
+# Expected: exits 0 with NO unused-variable error — setInstalledMode is now used.
+```
+
+**Out of scope:** Do not add Lingui macros — this package is i18n-free by
+decision (spec Design Decisions). Do not create new icon components; reuse the
+three that exist. Do not restyle or reorder the existing future-components group.
+
+---
+
+## Task 6: Typecheck + full viewer test run
+
+**Depends on:** Tasks 1–5
+**Files:** none (verification only)
+
+**Steps:**
+
+1. Run the viewer's full test suite and typecheck.
+2. If anything fails, fix it before proceeding. A failure in a **pre-existing**
+ `visibility.test.ts` assertion means the default is not `"solid"` — recheck
+ Task 1 step 3 and Task 3 step 3.
+3. Also typecheck the two consuming apps, since the package's exported signature
+ changed (additively — these should pass without any app edits).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/viewer test
+# Expected: all suites pass, including camera, fallback, graph, motion, plan,
+# visibility. No skipped or failing tests.
+
+pnpm exec turbo run typecheck --filter=@carbon/viewer --filter=mes --filter=erp
+# Expected: exits 0 for all three.
+```
+
+**Out of scope:** Do not run a whole-repo `pnpm typecheck` — it OOMs.
+
+---
+
+## Task 7: Browser verification in ERP and MES
+
+**Depends on:** Task 6
+**Files:** none (verification only)
+
+**Prerequisite:** the local dev stack must be running and serving
+`erp.main.dev` / `mes.main.dev`. If it is not, start it (`crbn up`) or report that
+verification is blocked — do not mark this task done without running it.
+
+**Steps:**
+
+Use the `/test` skill (or `agent-browser` directly via the `/auth` skill for the
+session). Verify each of these and capture a screenshot for the ones marked 📸:
+
+1. **ERP, no-change baseline.** Open
+ `http://erp.main.dev/x/assembly/dahpsbnng0ghg1nrqup0`, click step 7 ("Fit the
+ cylinder heads and set valve clearance"). With no interaction, all installed
+ parts must render solid exactly as before this change. 📸
+2. **ERP, ghost.** Click "Show installed components ghosted". The five cylinder
+ barrels installed at steps 5–6 must become translucent and the five step-7
+ cylinder heads must become clearly visible. 📸
+3. **ERP, hidden.** Click "Hide installed components". The barrels must disappear
+ entirely, leaving the heads unobstructed. 📸
+4. **Two groups present and distinct.** Confirm via an accessibility snapshot that
+ six visibility buttons now exist, three labelled "…future components…" and
+ three labelled "…installed components…".
+5. **MES, control present + state survives navigation.** Open
+ `https://mes.main.dev/x/assembly/jo_4f8Tfqsy7WbQzVoAC9TzMo`, go to display step
+ 12, open the 3D view. Select "Show installed components ghosted", navigate to
+ step 13 and back to 12, and confirm the ghost selection is still active (the
+ player does not remount, so it must persist). 📸
+6. **Toolbar fits.** At the MES panel's real width, confirm both groups are
+ visible and not clipped or overlapping the transport controls.
+7. **Camera framing.** On a step using the live AABB fallback, confirm that with
+ "Hide installed components" the camera frames the active parts without treating
+ the hidden geometry as an occluder (the view should be no more obstructed than
+ with the mode off).
+
+**Verify:**
+```bash
+# Manual/agentic verification. Record the outcome of each of the 7 checks above
+# with its screenshot path. Every check must pass.
+```
+
+**Out of scope:** Do not author `assemblyUnit` rows or test sub-assembly naming —
+F2a is explicitly out of scope for this work (see spec §Non-goals). Do not commit
+without the user's explicit permission.
diff --git a/.ai/specs/2026-09-17-viewer-installed-component-visibility.md b/.ai/specs/2026-09-17-viewer-installed-component-visibility.md
new file mode 100644
index 0000000000..35fe37627d
--- /dev/null
+++ b/.ai/specs/2026-09-17-viewer-installed-component-visibility.md
@@ -0,0 +1,432 @@
+# Installed-component visibility in the assembly viewer
+
+> Status: approved / implemented (branch `feat/hide-installed-parts`, PR #1660; move to implemented/ after merge)
+> Author: Aashu
+> Date: 2026-09-17
+
+## TLDR
+
+The assembly viewer can ghost or hide components belonging to *future* steps, but
+components from *already-completed* steps are hard-coded solid and no control can
+change that. Deep into a build the parts an operator is being told to fit are
+visually buried inside everything installed before them. This spec adds
+`installedMode` — a `solid | ghost | hidden` sibling to the existing `futureMode`
+— surfaced as a named-view toolbar control and wired into both the ERP and MES
+players. Default stays `solid`, so nothing changes until an operator opts in.
+
+## Problem Statement
+
+`visualForComponent` (`packages/viewer/src/visibility.ts`) resolves a component's
+visual from its step index:
+
+```ts
+if (stepIndex !== undefined) {
+ if (stepIndex < activeStepIndex) return "solid"; // ← unconditional
+ if (stepIndex === activeStepIndex) return "active";
+}
+return futureMode === "ghost" ? "ghost" : futureMode === "hidden" ? "hidden" : "solid";
+```
+
+An installed component (`stepIndex < activeStepIndex`) returns `"solid"` with no
+path to any other value. The three toolbar buttons in `AssemblyPlayer.tsx`
+(~lines 669–692) all write `futureMode`, and their labels say so explicitly:
+"Show future components ghosted", "Hide future components", "Show all components
+solid". There is no installed-side equivalent.
+
+**Concrete repro** (live, local): ERP instruction `dahpsbnng0ghg1nrqup0` ("Radial
+Engine — Build Sequence"), step 7 "Fit the cylinder heads and set valve
+clearance". Five cylinder barrels are installed at steps 5–6 and form a solid
+star; step 7's five heads seat on their tips. With every component solid the
+heads are almost entirely occluded by the barrels — the operator cannot see the
+parts the instruction is naming. The same instruction is synced onto MES job
+J000001, operation `jo_4f8Tfqsy7WbQzVoAC9TzMo` (display step 12).
+
+The effect worsens monotonically with build depth: the further into an assembly,
+the more geometry stands between the camera and the active part — exactly when
+the instruction is hardest to read.
+
+MES compounds this by passing neither `hiddenNodeIds` nor `focusedNodeIds`
+(`apps/mes/app/components/AssemblyView.tsx` lines 1978–1991), so the two escape
+hatches ERP has are unavailable on the shop floor.
+
+## Proposed Solution
+
+Add a fourth parameter to `visualForComponent`, and a toolbar control over it.
+(The control shipped as four named views, not the second icon group described
+below — see UI Changes and the changelog.)
+
+### 1. `packages/viewer/src/visibility.ts`
+
+```ts
+/** How components of steps BEFORE the active one are rendered. */
+export type InstalledComponentsMode = "solid" | "ghost" | "hidden";
+
+export function visualForComponent(
+ stepIndex: number | undefined,
+ activeStepIndex: number,
+ futureMode: FutureComponentsMode,
+ installedMode: InstalledComponentsMode = "solid"
+): ComponentVisual {
+ if (stepIndex !== undefined) {
+ if (stepIndex < activeStepIndex) {
+ return installedMode === "ghost"
+ ? "ghost"
+ : installedMode === "hidden"
+ ? "hidden"
+ : "solid";
+ }
+ if (stepIndex === activeStepIndex) return "active";
+ }
+ return futureMode === "ghost"
+ ? "ghost"
+ : futureMode === "hidden"
+ ? "hidden"
+ : "solid";
+}
+```
+
+The parameter is trailing and defaults to `"solid"`, so the existing 3-argument
+call in `graph.test.ts`/`visibility.test.ts` and any other caller keeps its
+current behaviour verbatim.
+
+`InstalledComponentsMode` is declared as its own type rather than reusing
+`FutureComponentsMode`: the two are independent axes, and a future change to one
+should not silently widen the other. Both are structurally `"ghost" | "hidden" |
+"solid"` today.
+
+### 2. `packages/viewer/src/AssemblyPlayer.tsx`
+
+- New optional prop `defaultInstalledMode?: InstalledComponentsMode`, defaulting
+ to `"solid"` (mirrors `defaultFutureMode`, which defaults to `"hidden"`).
+- New state `const [installedMode, setInstalledMode] = useState(defaultInstalledMode)`
+ — plain `useState`, exactly like `futureMode`. No persistence.
+- Pass `installedMode` through to the scene component alongside `futureMode`
+ (same path as line 491; the scene's props type at ~line 856 gains the field),
+ and into the `visualForComponent` call (~line 1101).
+- Add `installedMode` to the dependency arrays of the effects that currently
+ list `futureMode` (~lines 1221, 1663, 1883) — otherwise the scene will not
+ re-render when the operator changes the mode. `futureMode` appears in three
+ such arrays; each must be checked, since they drive different effects
+ (visual application, ghost-weighted framing, and playback).
+- ~~Second `ControlButton` group beside the existing one, three buttons writing
+ `installedMode`.~~ **Superseded:** both axes are driven by a single named-view
+ control instead, so `AssemblyPlayer` holds one `view` state and derives the two
+ modes from `VIEW_MODES`. See UI Changes.
+
+**Camera auto-framing must respect the new mode.** The AABB fallback occluder
+scoring decides which view direction sees the active step with the least in the
+way. It skipped future components entirely when `futureMode === "hidden"` and
+half-weighted them (`0.3`) when `"ghost"`, but installed components were
+unconditionally weighted `1`. Left unchanged, an operator selecting "Hide
+installed components" would see the parts disappear while the camera still framed
+around geometry that is no longer drawn — the control would visibly half-work.
+
+Rather than bolt a second pair of conditionals onto the inline loop, the scoring
+moves into an exported `occluderWeight(stepIndex, activeStepIndex, futureMode,
+installedMode)` helper in `visibility.ts`, beside `visualForComponent`. It returns
+`null` for "not an occluder at all" and otherwise the weight
+(`GHOST_OCCLUDER_WEIGHT = 0.3` for a ghosted part, `1` for a solid one). The two
+functions now answer the same question — where does this component sit relative to
+the active step — from one place, and the test suite asserts the invariant that
+links them: **anything `visualForComponent` renders `"hidden"`, `occluderWeight`
+must score `null`**, across every mode combination.
+
+This applies only to the live AABB fallback branch. Steps carrying a planner-baked
+view direction take the other branch and are unaffected.
+
+### Incidental fix: never-installed components were phantom occluders
+
+Extracting the helper surfaced a **pre-existing bug**, fixed here. The inline code
+computed `isFuture = stepIndex !== undefined && stepIndex > activeStepIndex`, so a
+component that **no step installs** (`stepIndex === undefined`) failed the test and
+kept full occluder weight — even though `visualForComponent` renders exactly those
+components per the *future* mode, i.e. **hidden** under the MES default
+`futureMode: "hidden"`. The camera was framing around invisible geometry.
+
+`occluderWeight` uses `stepIndex === undefined || stepIndex > activeStepIndex`,
+matching `visualForComponent`'s documented contract that such a component "is
+treated exactly like a future-step component — it is never already there".
+
+**This changes existing behaviour at default settings**, independently of
+`installedMode`: any step that uses the live AABB fallback (no planner-baked view
+direction) and has unassigned geometry may now pick a different, less obstructed
+view angle. That is the intended correction, but it is not a no-op and reviewers
+should know it ships in this change.
+
+**Component-picker interaction.** `effectiveFutureMode` currently forces
+`"ghost"` while `componentPickerActive`, so not-yet-installed parts stay visible
+and clickable. The installed side needs the mirror-image guard: picker mode must
+force `installedMode` to a *pickable* value, because a hidden component cannot be
+clicked. Define `effectiveInstalledMode = componentPickerActive ? "solid" : installedMode`
+— picker mode already ghosts the future side, so leaving the installed side solid
+keeps the two visually distinguishable while both remain pickable.
+
+### 3. Call sites
+
+- **MES** (`apps/mes/app/components/AssemblyView.tsx` ~1978): no new prop needed
+ — the default `"solid"` preserves today's rendering and the operator gets the
+ toolbar control for free. (`hiddenNodeIds` remains unpassed; wiring it is not
+ in scope — see Non-goals.)
+- **ERP** (`apps/erp/app/routes/x+/assembly+/$id.tsx` ~598): unchanged; it keeps
+ passing `hiddenNodeIds` and inherits the new control.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Default installed mode | `"solid"` | Preserves today's behaviour exactly; no existing ERP or MES user sees a different scene after deploy. The fix is one click away when a part is actually buried. (User-resolved, Q1.) |
+| Where the choice lives | Component `useState`, no persistence | Mirrors `futureMode` precisely, keeping the two sibling controls symmetrical and adding no storage surface. Verified the MES player does **not** remount per step (no `key` prop, nothing resets the state), so the choice survives step navigation for the whole session — the case that actually matters. (User-resolved, Q2.) |
+| i18n of the new labels | Plain English `aria-label`s, exception documented | `@carbon/viewer` has zero `@lingui` imports and no lingui dependency; `packages/viewer/AGENTS.md` requires pure modules stay free of `@carbon/react` router/i18n peers. The six existing toolbar labels are already untranslated English — translating only the new three would produce a half-localized toolbar. Localizing the whole viewer is a separate ticket. (User-resolved, Q3.) |
+| API shape | Trailing 4th param with a default | Keeps every existing 3-arg call and all six existing `visibility.test.ts` assertions passing unchanged; no call-site churn. |
+| Type reuse | New `InstalledComponentsMode` type | Independent axis from `futureMode`; separate types stop a future change to one from silently widening the other. |
+| Picker-mode guard | Force `"solid"` when `componentPickerActive` | A hidden component cannot be clicked (three.js raycasting skips `visible === false`). Mirrors the existing `effectiveFutureMode` ghost-forcing guard, which exists for the same reason. Note `componentPickerActive` is set only by ERP authoring (`isAddingComponents`, `x+/assembly+/$id.tsx`) and never by MES, so the guard cannot interfere with the shop-floor case this feature targets. |
+| Occluder scoring | Extracted `occluderWeight` helper rather than inline conditionals | The inline loop and `visualForComponent` were answering the same question in two places and had already drifted (see the incidental fix above). One exported predicate plus a cross-product invariant test is what makes the drift impossible to reintroduce silently. |
+| Toolbar overflow | `flex-wrap` on the toolbar row | The row had no wrap and already carried transport controls, a scrubber and two timestamps; the visibility control pushes it past the width of the MES centre column. Wrapping to a second line beats a clipped control. Kept after the named-views redesign — four labelled segments are still wider than one icon triplet. |
+| Exposing the two axes | Three named views (`build` / `focus` / `full`), same in ERP and MES | The axes are the renderer's model, not the user's: nine combinations, most meaningless, asked through two identical icon triplets. A named view answers the operator's actual question directly and needs no glyph decoded. Costs reachability — an unnamed combination can no longer be built — accepted because the axes survive underneath, so finer control is a toolbar change away. Supersedes the "Next"/"Built" label row and the MES-only Focus toggle, both rejected on sight. |
+| Heuristics 1–7 | N/A | No new table, service function, route, form, or module; nothing touches multi-tenancy, RLS, permissions, or a FROZEN/STABLE surface. This is a pure view-layer change inside one package plus its two consumers. |
+
+## Data Model Changes
+
+N/A — no tables, columns, or migrations. The feature is entirely client-side
+render state; nothing is persisted (see Design Decisions, "Where the choice
+lives").
+
+## API / Service Changes
+
+N/A — no service functions, loaders, or actions change. Two changes to
+`@carbon/viewer`'s exported surface, neither a server-side or cross-service
+contract:
+
+- `visualForComponent` gains an optional trailing 4th parameter, so the exported
+ signature stays backward-compatible and no call site needed touching.
+- `occluderWeight` and `GHOST_OCCLUDER_WEIGHT` are new exports from
+ `visibility.ts`. They are additive; nothing consumed the inline logic before
+ because it had none.
+
+Note: `visibility.ts` is imported by `AssemblyPlayer.tsx` (a three.js module), not
+by `@carbon/viewer/steps`, so the three-free server import path is untouched.
+
+## UI Changes
+
+**Superseded — see changelog. The two-axis toolbar below was built, rejected on
+sight, and replaced by named views.** The axes remain exactly as specified in the
+sections above; only the control changed.
+
+The toolbar exposes **four named views**, not the two axes. `ASSEMBLY_VIEWS` and
+`VIEW_MODES` (`visibility.ts`) map each view to its axis pair; the UI never sets
+an axis directly:
+
+| Button | `aria-label` | Installed | Future | Answers |
+|--------|--------------|-----------|--------|---------|
+| `Build` | `Show the assembly as built so far, hiding later components` | `solid` | `hidden` | What is on my bench right now |
+| `Focus` | `Focus this step by fading the already-installed components to see-through` | `ghost` | `hidden` | My part, and where it mounts |
+| `Isolate` | `Show only this step's components, hiding everything else` | `hidden` | `hidden` | **Just my part, nothing else** |
+| `Full` | `Show every component solid` | `solid` | `solid` | The finished product |
+
+They are ordered by how much context they strip. The future side is `hidden` in
+all but `Full`: Build/Focus/Isolate are all "I am working this step" views, and a
+part that is not on the bench yet only adds clutter. `Focus` and `Isolate` differ
+in exactly one axis — the ghosted shell of what is already fitted is the whole
+distinction, and a test pins it so neither becomes a duplicate of the other.
+
+One segmented group, no icons, in **both ERP and MES** — the same control for both
+audiences. `Build` is the historical rendering, so the default is a no-op.
+Visible labels are single words to fit the MES centre column; the `aria-label`
+carries the fuller description, since "Build" alone does not say what changes.
+`VIEW_LABELS` in `AssemblyPlayer.tsx` holds both.
+
+Four of the nine axis combinations are reachable. The five that are not are
+future-side variations (`ghost`, or `solid` alongside a non-solid installed
+side), none of which answers a question an operator or an author was observed to
+ask. Adding one later is a row in `VIEW_MODES`, not a rendering change.
+
+`viewForModes` seats the initial view from the still-axis-shaped `default*Mode`
+props (neither call site overrides them today), falling back to `"build"` for a
+pair no view names rather than widening the type with an unselectable `"custom"`.
+
+### Why not the axes
+
+Two visually identical icon triplets side by side read as one duplicated control,
+and the underlying model — nine combinations, most meaningless — is not something
+an operator should have to learn to ask "what am I fitting right now?". A
+preceding-label variant ("Next" / "Built") and an audience split (one Focus toggle
+in MES, the raw axis in ERP) were both tried and rejected: the first still
+required decoding the glyphs, the second made the two screens disagree about what
+the toolbar means. Named views cost some reachability — an author can no longer
+build a combination we did not name — which was accepted as the price of a
+control that reads at a glance. The renderer keeps both axes, so restoring finer
+control later is a toolbar change only.
+
+## Acceptance Criteria
+
+Automated — **verified**, `pnpm --filter @carbon/viewer test` (120 passing):
+
+- [x] `visualForComponent(0, 2, "ghost")` returns `"solid"` when called with three
+ arguments (existing behaviour preserved; all six original
+ `visibility.test.ts` assertions pass unmodified).
+- [x] `visualForComponent(0, 2, "ghost", "ghost")` returns `"ghost"` and
+ `visualForComponent(0, 2, "ghost", "hidden")` returns `"hidden"`.
+- [x] `visualForComponent(2, 2, "ghost", "hidden")` returns `"active"` — the
+ active step is never affected by `installedMode`.
+- [x] `visualForComponent(3, 1, "ghost", "hidden")` returns `"ghost"` — future
+ components are never affected by `installedMode`.
+- [x] `visualForComponent(undefined, 5, "hidden", "solid")` returns `"hidden"` —
+ a never-installed component is still treated as future, not installed.
+- [x] `occluderWeight` returns `null` exactly when `visualForComponent` returns
+ `"hidden"`, across every (stepIndex × futureMode × installedMode)
+ combination — the invariant that keeps the two from drifting.
+- [x] `occluderWeight(undefined, 3, "hidden", "solid")` returns `null` — the
+ incidental fix; a never-installed component is no longer a phantom
+ occluder while rendering hidden.
+- [x] `pnpm --filter @carbon/viewer test`, `pnpm --filter @carbon/viewer
+ typecheck`, `pnpm --filter mes typecheck`, `pnpm --filter erp typecheck`
+ and `biome check` on the changed files all pass.
+
+Browser — **NOT verified** (the local `main.dev` dev stack was not running and an
+ad-hoc server could not complete the dev login; see Risks). These remain open and
+must be walked before merge:
+
+- [ ] Opening ERP instruction `dahpsbnng0ghg1nrqup0` at step 7 with no
+ interaction renders identically to before this change (all installed parts
+ solid).
+- [ ] On that same view, clicking "Show installed components ghosted" makes the
+ five cylinder barrels translucent and the five red cylinder heads clearly
+ visible; clicking "Hide installed components" removes the barrels entirely
+ and leaves the heads unobstructed.
+- [ ] On MES `jo_4f8Tfqsy7WbQzVoAC9TzMo` at display step 12, the new control
+ group is present, and a ghost selection persists when navigating to step 13
+ and back (player does not remount).
+- [ ] The toolbar fits the MES centre column — with `flex-wrap` it may occupy two
+ rows; confirm nothing is clipped and the second row looks deliberate.
+- [ ] With component-picker mode active (ERP "Add components"), installed
+ components remain clickable regardless of the `installedMode` selected
+ before entering picker mode.
+- [ ] On a step using the live AABB framing fallback (no planner-baked view
+ direction), selecting "Hide installed components" makes the camera frame
+ the active parts without treating the hidden geometry as an occluder —
+ i.e. the chosen view is at least as unobstructed as with the mode off.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| **Nothing has been verified in a browser** | **High** | Every browser acceptance criterion is still open. The automated suite covers the visibility/occlusion logic thoroughly, but no one has seen the toolbar render, and the two risks below it are exactly the kind only eyes catch. Must be walked before merge. |
+| Toolbar crowding — three labelled segments plus transport controls on a narrow MES panel | Med | Down from six buttons to three after the redesign, but words are wider than glyphs, so the risk stands. `flex-wrap` on the toolbar row means it wraps to a second line instead of clipping. (An earlier draft of this spec claimed the row already wrapped — it did not; `flex items-center gap-2` with no wrap.) Still needs a visual check at the MES panel's real width; `Build`/`Focus`/`Full` were chosen partly for being short. |
+| Operators confuse the two visually-identical icon groups | Med | Each group now carries an `aria-hidden` text label ("Next" / "Built") alongside the distinct `aria-label`s and separate bordered containers. Whether that reads clearly on the floor is a browser check. |
+| A hidden installed component becomes unclickable in component-picker mode | Low | `effectiveInstalledMode` forces `"solid"` while `componentPickerActive`, mirroring the existing `effectiveFutureMode` guard. Downgraded from Med: `componentPickerActive` is ERP-authoring-only and never set by MES. |
+| Ghost-on-ghost renders poorly when both modes are `"ghost"` (transparent-sorting artifacts) | Low | `applyVisual` already sets `renderOrder = 1` on ghosts specifically to limit sorting artifacts; the existing ghost path is reused unchanged. Verify visually during manual testing. |
+| The incidental occluder fix changes framing at default settings | Low | Intended correction (see "Incidental fix" above), but it is a real behaviour change independent of `installedMode` and is called out in the PR body rather than buried. Affects only fallback-framed steps with unassigned geometry. |
+| Default silently changes for someone relying on current rendering | Low | Default is `"solid"` = today's exact behaviour for the new axis; the first browser criterion asserts no-interaction parity. |
+
+## Non-goals
+
+- **Sub-assembly unit plumbing (F2a).** Investigated and found already built:
+ `apps/erp/app/modules/production/production.service.ts` (~8870–8895) resolves
+ `assemblyUnit` names through `describeStep(..., namedUnits)` and persists the
+ result as the step `title`; MES renders `step.name` from the DB
+ (`AssemblyView.tsx:2165`). A unit-named step already displays correctly in MES.
+ The flat-parts-list symptom is purely that **0 `assemblyUnit` rows exist** —
+ an authoring/data gap, not a code gap. Dropped from this work by the user.
+- **Nested instruction references (F2b)** — requires a new instruction→instruction
+ schema edge and a decision on how a nested build reports completion to its
+ parent. Out of scope.
+- **Wiring `hiddenNodeIds` into MES.** The generic mode covers the stated problem;
+ per-part hiding needs its own UI (a part list with visibility toggles) and is
+ not required to unbury the active step.
+- **Localizing the viewer toolbar.** See Design Decisions; the whole package is
+ currently i18n-free and localizing it is its own ticket.
+- **Persisting the operator's choice** across reloads or per work-center.
+
+## Research
+
+N/A — this is an internal rendering/UI change with no ERP-domain logic (no
+accounting, costing, tax, inventory, or planning semantics). Competitor research
+would not inform the design. The relevant prior art is in-repo: the existing
+`futureMode` control, which this deliberately mirrors.
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] **What should the default installed-part mode be?** — **Answer:** `"solid"`,
+ preserving today's behaviour exactly. Considered `"ghost"` everywhere (fixes
+ the problem out of the box but changes the look of every existing assembly
+ view and may read as "unbuilt") and `"solid"` in ERP / `"ghost"` in MES
+ (matches where the problem bites, at the cost of two defaults to reason
+ about). Chose no-behaviour-change: the burying problem is step-specific and
+ one click away, while a changed default would surprise every operator on
+ deploy.
+- [x] **Should the operator's choice persist beyond the current view?** —
+ **Answer:** component `useState` only, mirroring `futureMode`. Verified
+ first that the MES player does **not** remount per step (no `key` prop on
+ the `AssemblyPlayer`/`ClientOnly`, and nothing resets `futureMode`), so the
+ choice already survives step navigation — the scenario that actually
+ matters on the floor. `localStorage` persistence was considered and rejected
+ as unnecessary surface that would also make the two sibling toggles behave
+ inconsistently.
+- [x] **How do we satisfy the Lingui rule inside an i18n-free package?** —
+ **Answer:** plain English `aria-label`s, exception documented here.
+ Verified `@carbon/viewer` has zero `@lingui` imports and no lingui
+ dependency, and `packages/viewer/AGENTS.md` requires pure modules stay free
+ of `@carbon/react` router/i18n peers (`ModelPreview.tsx` is the sole
+ exception). The six existing toolbar labels are already untranslated
+ English, so translating only the new three would yield a half-localized
+ toolbar. Passing labels in as props from each app was considered (upholds
+ the rule without crossing the boundary) but rejected as prop-surface churn
+ for screen-reader-only strings; adding Lingui to the viewer crosses an
+ explicit Ask-First boundary and is much larger than this feature.
+
+## Changelog
+
+- 2026-09-17: Created. Three open questions resolved with the user before
+ writing. F2a (sub-assembly unit plumbing) investigated and dropped — found
+ already implemented; the observed symptom is missing data, not missing code.
+- 2026-09-17: Implemented, then revised after a strict self-review. Changes from
+ the as-designed spec:
+ - Occluder scoring was **extracted into `occluderWeight`** rather than added
+ inline as originally specced, after the inline version was found to duplicate
+ `visualForComponent`'s reasoning.
+ - Doing so surfaced a **pre-existing bug** (never-installed components were
+ phantom occluders while rendering hidden). Fixed here; documented as its own
+ subsection because it changes framing at default settings.
+ - Added `flex-wrap` to the toolbar row. The original Risks table wrongly stated
+ the row already wrapped; it did not.
+ - Added "Next" / "Built" labels to distinguish the two identical icon triplets.
+ - Acceptance criteria split into verified (automated) and **not verified**
+ (browser). Browser verification remains outstanding.
+- 2026-09-17: **Toolbar redesigned — named views.** The user rejected the
+ six-button two-group toolbar on sight ("wont work with 6 diff things right
+ upfront to the user with similar icons"). Two replacements were tried and
+ discarded before the third landed:
+ 1. "Next"/"Built" labels above the triplets — still six similar glyphs.
+ 2. An audience split: one Focus toggle in MES (`readOnly`), the raw future
+ axis in ERP. Rejected because it made the two screens disagree about what
+ the toolbar means, for no gain — neither call site overrides
+ `defaultFutureMode`, so the ERP triplet was moving an axis nobody set.
+ 3. Three named views — `Build` / `Focus` / `Full` — chosen from four variants
+ mocked up in `local-docs/viewer-visibility-variants.html`. **Rejected on
+ use:** the user asked "if am on a part (step 5) how can I just see that
+ part?" and there was no answer. `focus` ghosted everything, so on a
+ 15-step assembly the active part still sat under fourteen steps of
+ translucent geometry. The design had no state for "this part alone", and
+ four of the six axis states were unreachable.
+ 4. **Shipped:** four named views — `Build` / `Focus` / `Isolate` / `Full`,
+ chosen by the user from a second round of variants in the same doc, which
+ was rewritten to score each design on which of the six axis states it can
+ actually reach. `Isolate` (both sides hidden) is the state the three-view
+ design was missing. `focus` was also corrected: it hid the future side
+ rather than ghosting it, since a part not yet on the bench is clutter
+ during a working view. Identical in ERP and MES.
+
+ `ASSEMBLY_VIEWS`, `VIEW_MODES` and `viewForModes` were added to
+ `visibility.ts` — the view table lives beside the axes it derives from, so
+ the mapping is unit-testable without rendering. `VIEW_LABELS` (button text +
+ `aria-label`) stays in `AssemblyPlayer.tsx` as presentation. `FocusIcon`,
+ `GhostIcon`, `HiddenIcon` and `SolidIcon` were deleted — the named views use
+ no icons and nothing else referenced them.
+
+ The two axes, `occluderWeight`, the picker guard and every existing test are
+ untouched: a view is purely a derived pair. 14 tests added (120 total,
+ passing), covering the table's completeness, distinctness, the `build`
+ no-op-default invariant, the `viewForModes` round-trip and its fallback.
+ Browser verification is **still outstanding**.
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/mes.md b/apps/erp/app/modules/agent/kb/docs/reference/mes.md
index 77f7127fec..a236de65a4 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/mes.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/mes.md
@@ -50,6 +50,23 @@ Opening a job shows its operations as a directed graph (the routing DAG), so an
Open an operation and the station panel is where the shift actually happens. A big control starts and stops the clock: **"Start"** opens a production event, **"Pause"** closes it. A toggle picks which kind of time is being logged, matching the three production event types: **"Setup"**, **"Labor"**, or **"Machine"**. The panel is tabbed into **details**, **model** (the 3D part view), **procedure** (work instructions, with **attributes** and **parameters** sub-views), and **chat** (a per-operation note thread).
+### The guided assembly view
+
+An operation whose type is **Assembly** opens a guided 3D view instead of a plain part model: the assembly plays back one step at a time, and each step lights up the components it installs.
+
+Deep into a build this creates a problem. The parts already fitted sit between the camera and the ones the current step is naming, so the operator is looking at a finished-looking lump and guessing where the next piece goes. A view control in the player toolbar answers that directly:
+
+ - **Build**: The assembly as it stands on the bench right now: everything fitted so far is solid, and anything from a later step is not drawn. This is the default.
+ - **Focus**: The already-fitted parts fade to see-through, so the current step's components are visible in place without losing the shape around them.
+ - **Isolate**: Only the current step's components are drawn. The "just show me the part I am fitting" view.
+ - **Full**: Every component solid, the finished product.
+
+The view only changes what the operator sees. It never changes the step order, the components a step installs, or anything reported back.
+
+Picking a view that hides parts also stops the camera treating them as obstacles. On **Isolate** the view angle frames the current step's components directly, rather than angling around geometry that is no longer on screen.
+
+The same control appears in the ERP assembly editor, where an author checks that a step reads clearly before publishing. An author and an operator ask the model the same question, so the buttons mean the same thing on both screens.
+
### Reporting quantities
Good, bad, and reworked units are reported separately, so yield stays honest:
diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.json
index 2b47df93d0..0ced8a921d 100644
--- a/apps/erp/app/modules/agent/kb/manifest.json
+++ b/apps/erp/app/modules/agent/kb/manifest.json
@@ -965,6 +965,7 @@
"Focused lists",
"Open Jobs",
"Running an operation",
+ "The guided assembly view",
"Reporting quantities",
"Issuing material",
"Clocking in and out",
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 90d5d8e68c..4bac4836ae 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -70,7 +70,7 @@ pnpm --filter @carbon/erp test
| `productionQuantity` | Output: type (Production/Scrap/Rework), quantity, scrapReason |
| `jobOperationBatch` | Operation batch header (`BAT` sequence): process, work center, location, status (`Planned` = pre-floor, `Active` displayed "Released"). Members are `jobOperation` rows via nullable `jobOperationBatchId`. A Released batch's coalesced schedule slot is a `capacityReservation` row tagged `jobOperationBatchId` (spared by per-job regen deletes; visible in every snapshot regardless of the anchor job's status; deleted by a `jobOperationBatch` status trigger when the batch completes or is unreleased — the sparing rules make that trigger the only retirement path; dissolve self-heals via the FK's column-list SET NULL + the anchor job's next regen) |
| `procedure` / `procedureStep` / `procedureParameter` | Versioned work instructions |
-| `assemblyInstruction` / `assemblyInstructionStep` | 3D model-based assembly instructions (Draft/Published/Archived); steps carry `componentNodeIds` + `motion`/`camera` JSON for the viewer, a `buildWave` INTEGER (the step's longest-path level in the planner's precedence DAG — steps sharing a wave have no ordering constraint and can be built in parallel by different people/stations; NULL for cycle-affected or hand-authored steps; informational, `sortOrder` still governs playback), and `warnings.needsSupport` (a part in the step tips once placed — center of mass outside the support polygon of the parts below it — likely needs a fixture or a second hand; shown as a "Hold" badge) AND the typed-step fields mirrored from `jobOperationStep` (`type` `procedureStepType`, tiptap `description` with derived `instructionText`, `required`, UoM/min/max, `listValues`) for eventual copy into job operations. `motion`/`camera` are authored directly in the 3D viewer (drag the red waypoint path → relative `linear`/`L` motion; "Set view" captures the camera pose), autosaved via `updateAssemblyStepMotion` / the `steps/motion/$stepId` route — separate from the step form's `upsertAssemblyInstructionStep` (which rewrites `title`/typed fields). There is no numeric motion editor. **Step camera is a discriminated union**: a manual `{position,target,fov}` pose (applied verbatim), OR a planner hint `{source:"plan",direction}` — a mesh-precise view DIRECTION the Rust planner bakes per step (`crates/planner/src/view.rs` `best_view_direction`: sight lines against the real triangles of everything installed earlier, so it sees a hollow enclosure's open top where the viewer's AABB scoring can't). The viewer applies the hint with LIVE framing — target, standing distance, frustum fit at the real viewport aspect (`fitFraming`, `@carbon/viewer`). `null` = fully live AABB framing (fallback for hand-edited steps / old plans). Generated steps carry the plan hint (the TS-side camera bake was removed); re-motion refreshes it but never clobbers a manual pose. Playback visibility is presence-based (`@carbon/viewer` `visualForComponent`): a component exists on the canvas only once its step has run; components no step installs render like future-step ones (hidden during playback, future-components toggle while paused). AABB fallback motions for `"none"`-motion steps consider only PRIOR-step components as obstacles and fade in when no collision-free path exists or when the component interpenetrates a present component (mated parts — sliders on rails, fasteners in bores — never get fabricated paths; the planner is the only authority for those) |
+| `assemblyInstruction` / `assemblyInstructionStep` | 3D model-based assembly instructions (Draft/Published/Archived); steps carry `componentNodeIds` + `motion`/`camera` JSON for the viewer, a `buildWave` INTEGER (the step's longest-path level in the planner's precedence DAG — steps sharing a wave have no ordering constraint and can be built in parallel by different people/stations; NULL for cycle-affected or hand-authored steps; informational, `sortOrder` still governs playback), and `warnings.needsSupport` (a part in the step tips once placed — center of mass outside the support polygon of the parts below it — likely needs a fixture or a second hand; shown as a "Hold" badge) AND the typed-step fields mirrored from `jobOperationStep` (`type` `procedureStepType`, tiptap `description` with derived `instructionText`, `required`, UoM/min/max, `listValues`) for eventual copy into job operations. `motion`/`camera` are authored directly in the 3D viewer (drag the red waypoint path → relative `linear`/`L` motion; "Set view" captures the camera pose), autosaved via `updateAssemblyStepMotion` / the `steps/motion/$stepId` route — separate from the step form's `upsertAssemblyInstructionStep` (which rewrites `title`/typed fields). There is no numeric motion editor. **Step camera is a discriminated union**: a manual `{position,target,fov}` pose (applied verbatim), OR a planner hint `{source:"plan",direction}` — a mesh-precise view DIRECTION the Rust planner bakes per step (`crates/planner/src/view.rs` `best_view_direction`: sight lines against the real triangles of everything installed earlier, so it sees a hollow enclosure's open top where the viewer's AABB scoring can't). The viewer applies the hint with LIVE framing — target, standing distance, frustum fit at the real viewport aspect (`fitFraming`, `@carbon/viewer`). `null` = fully live AABB framing (fallback for hand-edited steps / old plans). Generated steps carry the plan hint (the TS-side camera bake was removed); re-motion refreshes it but never clobbers a manual pose. Playback visibility is presence-based (`@carbon/viewer` `visualForComponent`): a component exists on the canvas only once its step has run; components no step installs render like future-step ones (hidden during playback, future-components toggle while paused). Visibility has TWO independent axes — `futureMode` (not built yet) and `installedMode` (already built — `solid` default, so the historical rendering is unchanged; `ghost`/`hidden` let an operator see past an assembly that buries the active step's parts) — but the toolbar does NOT expose them as axes. It offers four NAMED views (`ASSEMBLY_VIEWS` / `VIEW_MODES` in `visibility.ts`), ordered by how much context they strip: **Build** (installed solid — the historical default), **Focus** (installed ghosted, so you see past what is already fitted but keep its shape), **Isolate** (installed hidden — the active step's parts alone, the "just show me my part" case) and **Full** (everything solid). The future side is hidden in all but Full: a step you are working is never helped by parts that are not on the bench yet. The same control renders in ERP and MES; nine combinations behind two icon triplets was the design that got rejected for being unreadable on a shop floor. The camera's AABB view-direction scoring honours both via `occluderWeight` — geometry the operator cannot see is never treated as an obstacle, or hiding it would clear the pixels while the framing still dodged it. AABB fallback motions for `"none"`-motion steps consider only PRIOR-step components as obstacles and fade in when no collision-free path exists or when the component interpenetrates a present component (mated parts — sliders on rails, fasteners in bores — never get fabricated paths; the planner is the only authority for those) |
| `assemblyInstructionStepMaterial` | BOM parts consumed at a step (`stepId` → `itemId` + optional quantity; stored by itemId so links survive make-method re-versioning; picker limited to the item's make-method BOM; UNIQUE `(stepId, itemId)`). Auto-populated from `assemblyComponentMapping` via `syncAssemblyStepMaterialsFromMappings` — additive only (manual quantities/deletions survive), triggered on step generation, component add, mapping create, and "Match BOM" |
| `assemblyInstructionStepSlide` | Per-step reference slides (image XOR 3D model via `modelUploadId`, caption, `size`, `annotations` JSONB pins), mirroring `methodOperationStepSlide`; authored in the step editor's Details tab and copied to `jobOperationStepSlide` by the BOP sync / get-method. The former `assemblyInstructionStepRequirement` / `assemblyStandardNote` tables (fixtures/consumables/notes/media) were dropped — a step definition is parts + tools + slides |
| `assemblyInstructionStepTool` | Tools used at a step (`stepId` → `itemId` of a tool-type item + `quantity`, UNIQUE `(stepId, itemId)`) — `itemId` is the same target `jobOperationTool.toolId` references, so the BOP sync maps rows 1:1 |
diff --git a/docs/content/docs/reference/mes.mdx b/docs/content/docs/reference/mes.mdx
index 87467bd063..ab4e9d9eb4 100644
--- a/docs/content/docs/reference/mes.mdx
+++ b/docs/content/docs/reference/mes.mdx
@@ -59,6 +59,27 @@ Opening a job shows its operations as a directed graph (the routing DAG), so an
Open an operation and the station panel is where the shift actually happens. A big control starts and stops the clock: **"Start"** opens a production event, **"Pause"** closes it. A toggle picks which kind of time is being logged, matching the three <Term id="production-event-type">production event types</Term>: **"Setup"**, **"Labor"**, or **"Machine"**. The panel is tabbed into **details**, **model** (the 3D part view), **procedure** (work instructions, with **attributes** and **parameters** sub-views), and **chat** (a per-operation note thread).
+### The guided assembly view
+
+An operation whose type is **Assembly** opens a guided 3D view instead of a plain part model: the assembly plays back one step at a time, and each step lights up the components it installs.
+
+Deep into a build this creates a problem. The parts already fitted sit between the camera and the ones the current step is naming, so the operator is looking at a finished-looking lump and guessing where the next piece goes. A view control in the player toolbar answers that directly:
+
+<FieldTable>
+ <Field name="Build">The assembly as it stands on the bench right now: everything fitted so far is solid, and anything from a later step is not drawn. This is the default.</Field>
+ <Field name="Focus">The already-fitted parts fade to see-through, so the current step's components are visible in place without losing the shape around them.</Field>
+ <Field name="Isolate">Only the current step's components are drawn. The "just show me the part I am fitting" view.</Field>
+ <Field name="Full">Every component solid, the finished product.</Field>
+</FieldTable>
+
+The view only changes what the operator sees. It never changes the step order, the components a step installs, or anything reported back.
+
+<Callout type="note" title="The camera follows what is drawn.">
+Picking a view that hides parts also stops the camera treating them as obstacles. On **Isolate** the view angle frames the current step's components directly, rather than angling around geometry that is no longer on screen.
+</Callout>
+
+The same control appears in the ERP assembly editor, where an author checks that a step reads clearly before publishing. An author and an operator ask the model the same question, so the buttons mean the same thing on both screens.
+
### Reporting quantities
Good, bad, and reworked units are reported separately, so yield stays honest:
diff --git a/packages/viewer/AGENTS.md b/packages/viewer/AGENTS.md
index f5ec2a81bc..43555ec85d 100644
--- a/packages/viewer/AGENTS.md
+++ b/packages/viewer/AGENTS.md
@@ -17,6 +17,8 @@
- MUST treat plans below `CURRENT_PLAN_VERSION` as absent (re-plan), never resurrect their motions.
- 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.
## Ask First
diff --git a/packages/viewer/src/AssemblyPlayer.tsx b/packages/viewer/src/AssemblyPlayer.tsx
index 35b229d026..b5a852190d 100644
--- a/packages/viewer/src/AssemblyPlayer.tsx
+++ b/packages/viewer/src/AssemblyPlayer.tsx
@@ -50,12 +50,22 @@ import type {
import { useAssembly } from "./useAssembly";
import { cn } from "./utils";
import {
+ ASSEMBLY_VIEWS,
+ type AssemblyView,
type ComponentVisual,
type FutureComponentsMode,
+ type InstalledComponentsMode,
+ occluderWeight,
+ VIEW_MODES,
+ viewForModes,
visualForComponent
} from "./visibility";
-export type { FutureComponentsMode } from "./visibility";
+export type {
+ AssemblyView,
+ FutureComponentsMode,
+ InstalledComponentsMode
+} from "./visibility";
/** Marquee rectangle in canvas-local CSS pixels while box-selecting. */
type BoxRect = { left: number; top: number; width: number; height: number };
@@ -110,6 +120,7 @@ export type AssemblyPlayerProps = {
/** Initial render mode for future-step components. Shared by step selection
* AND playback, so a ghosted default ghosts the animation too. */
defaultFutureMode?: FutureComponentsMode;
+ defaultInstalledMode?: InstalledComponentsMode;
/** Picking components to add to a step: ghost every not-yet-installed part so
* un-animated parts are visible and clickable (x-ray). */
componentPickerActive?: boolean;
@@ -188,6 +199,7 @@ export const AssemblyPlayer = forwardRef<
editMotion,
onMotionChange,
defaultFutureMode = "hidden",
+ defaultInstalledMode = "solid",
componentPickerActive = false,
autoPlay = true,
loop = false,
@@ -216,8 +228,12 @@ export const AssemblyPlayer = forwardRef<
const [cameraMode, setCameraMode] = useState<"auto" | "free">("auto");
// Stable identity — the scene re-subscribes its controls listener otherwise.
const handleFreeCamera = useCallback(() => setCameraMode("free"), []);
- const [futureMode, setFutureMode] =
- useState<FutureComponentsMode>(defaultFutureMode);
+ // Exposed as named views, not raw axes: six icon buttons made the reader
+ // learn a two-axis model to ask one question. A view is a derived pair.
+ const [view, setView] = useState<AssemblyView>(() =>
+ viewForModes(defaultInstalledMode, defaultFutureMode)
+ );
+ const { installedMode, futureMode } = VIEW_MODES[view];
// Live marquee rectangle while box-selecting (drawn as a DOM overlay).
const [boxRect, setBoxRect] = useState<BoxRect | null>(null);
@@ -489,6 +505,7 @@ export const AssemblyPlayer = forwardRef<
isPlaying={isPlaying}
loop={loop}
futureMode={futureMode}
+ installedMode={installedMode}
highlightedNodeIds={highlightedNodeIds}
hiddenNodeIds={hiddenNodeIds}
focusedNodeIds={isPlaying ? undefined : focusedNodeIds}
@@ -598,7 +615,8 @@ export const AssemblyPlayer = forwardRef<
)}
</div>
- <div className="flex items-center gap-2 border-t border-border bg-background px-3 py-2">
+ {/* Wraps rather than clipping on the narrow MES panel. */}
+ <div className="flex flex-wrap items-center gap-2 border-t border-border bg-background px-3 py-2">
<ControlButton
aria-label="Previous step"
disabled={clampedIndex <= 0}
@@ -659,37 +677,42 @@ export const AssemblyPlayer = forwardRef<
/>
<span className="whitespace-nowrap text-xs tabular-nums text-muted-foreground">
{stepCount > 0
- ? `${formatTime(Math.min(displayTime, totalSeconds))} / ${formatTime(totalSeconds)}`
+ ? `${formatTime(
+ Math.min(displayTime, totalSeconds)
+ )} / ${formatTime(totalSeconds)}`
: "–"}
</span>
<span className="whitespace-nowrap text-xs tabular-nums text-muted-foreground">
{stepCount > 0 ? `${clampedIndex + 1} / ${stepCount}` : ""}
</span>
- <div className="flex items-center rounded-md border border-border">
- <ControlButton
- aria-label="Show future components ghosted"
- aria-pressed={futureMode === "ghost"}
- isActive={futureMode === "ghost"}
- onClick={() => setFutureMode("ghost")}
- >
- <GhostIcon />
- </ControlButton>
- <ControlButton
- aria-label="Hide future components"
- aria-pressed={futureMode === "hidden"}
- isActive={futureMode === "hidden"}
- onClick={() => setFutureMode("hidden")}
- >
- <HiddenIcon />
- </ControlButton>
- <ControlButton
- aria-label="Show all components solid"
- aria-pressed={futureMode === "solid"}
- isActive={futureMode === "solid"}
- onClick={() => setFutureMode("solid")}
- >
- <SolidIcon />
- </ControlButton>
+ {/* Deliberately NOT gated on `readOnly`: an author and an operator ask
+ the same question of the model, so the control reads the same in
+ ERP and MES. Words over glyphs, and a bigger target for a glove. */}
+ <div
+ role="group"
+ aria-label="Component visibility"
+ className="flex shrink-0 items-center overflow-hidden rounded-md border border-border"
+ >
+ {ASSEMBLY_VIEWS.map((option) => (
+ <button
+ key={option}
+ type="button"
+ aria-label={VIEW_LABELS[option].description}
+ aria-pressed={view === option}
+ onClick={() => setView(option)}
+ className={cn(
+ "h-8 border-border px-2.5 text-xs font-medium transition-colors not-first:border-l",
+ // The selected view uses `primary`, not `accent`: `accent` is
+ // also the hover colour, so a selected-but-unhovered button was
+ // indistinguishable from an unselected one under the cursor.
+ view === option
+ ? "bg-primary text-primary-foreground"
+ : "text-foreground hover:bg-accent hover:text-accent-foreground"
+ )}
+ >
+ {VIEW_LABELS[option].label}
+ </button>
+ ))}
</div>
</div>
@@ -823,6 +846,7 @@ function AssemblyScene({
isPlaying,
loop,
futureMode,
+ installedMode,
highlightedNodeIds,
hiddenNodeIds,
focusedNodeIds,
@@ -854,6 +878,7 @@ function AssemblyScene({
/** Loop the active step's animation continuously (MES playback) */
loop: boolean;
futureMode: FutureComponentsMode;
+ installedMode: InstalledComponentsMode;
highlightedNodeIds?: string[];
hiddenNodeIds?: string[];
focusedNodeIds?: string[];
@@ -1099,6 +1124,9 @@ function AssemblyScene({
const effectiveFutureMode: FutureComponentsMode = componentPickerActive
? "ghost"
: futureMode;
+ // A hidden component cannot be clicked, so picking forces installed solid.
+ const effectiveInstalledMode: InstalledComponentsMode =
+ componentPickerActive ? "solid" : installedMode;
for (const [nodeId, stepIndex] of stepIndexByNode) {
const node = nodesById.get(nodeId);
@@ -1106,7 +1134,8 @@ function AssemblyScene({
const visual = visualForComponent(
stepIndex,
activeStepIndex,
- effectiveFutureMode
+ effectiveFutureMode,
+ effectiveInstalledMode
);
// The active step's blue tint is a "what's animating now" cue — only
// apply it during playback. Statically selecting/seating a step leaves
@@ -1219,6 +1248,7 @@ function AssemblyScene({
leafBounds,
activeStepIndex,
futureMode,
+ installedMode,
isPlaying,
componentPickerActive,
highlightedSet,
@@ -1661,6 +1691,7 @@ function AssemblyScene({
JSON.stringify(step.componentNodeIds),
JSON.stringify(step.motion),
futureMode,
+ installedMode,
[...hiddenSet].sort().join(",")
].join("|");
if (framingKey === lastFramedKeyRef.current) return;
@@ -1760,12 +1791,18 @@ function AssemblyScene({
if (stepComponents.has(leaf.nodeId)) continue;
if (hiddenSet.has(leaf.nodeId)) continue;
const leafStep = stepIndexByNode.get(leaf.nodeId);
- const isFuture = leafStep !== undefined && leafStep > activeStepIndex;
- if (isFuture && futureMode === "hidden") continue;
+ // Invisible geometry must not push the camera around.
+ const weight = occluderWeight(
+ leafStep,
+ activeStepIndex,
+ futureMode,
+ installedMode
+ );
+ if (weight === null) continue;
occluders.push({
min: new Vector3(...(leaf.bbox.min as [number, number, number])),
max: new Vector3(...(leaf.bbox.max as [number, number, number])),
- weight: isFuture && futureMode === "ghost" ? 0.3 : 1
+ weight
});
}
@@ -1881,6 +1918,7 @@ function AssemblyScene({
hiddenSet,
stepIndexByNode,
futureMode,
+ installedMode,
cameraMode
]);
@@ -2591,59 +2629,28 @@ function PauseIcon() {
);
}
-function GhostIcon() {
- return (
- <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" aria-hidden="true">
- <rect
- x="4"
- y="4"
- width="16"
- height="16"
- rx="2"
- stroke="currentColor"
- strokeWidth="2"
- strokeDasharray="3 2"
- />
- <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2" />
- </svg>
- );
-}
-
-function HiddenIcon() {
- return (
- <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" aria-hidden="true">
- <path
- d="M3 3l18 18M10.6 5.1A9.8 9.8 0 0112 5c7 0 10 7 10 7a16.7 16.7 0 01-3.2 4.2M6.6 6.6A16.4 16.4 0 002 12s3 7 10 7a9.9 9.9 0 004.3-1"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- <path
- d="M9.9 9.9a3 3 0 004.2 4.2"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- />
- </svg>
- );
-}
-
-function SolidIcon() {
- return (
- <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" aria-hidden="true">
- <path
- d="M12 3l8 4.5v9L12 21l-8-4.5v-9L12 3z"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinejoin="round"
- />
- <path
- d="M12 12l8-4.5M12 12L4 7.5M12 12v9"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinejoin="round"
- />
- </svg>
- );
-}
+/**
+ * One-word labels so they fit the narrow MES column; `description` is the
+ * screen-reader text, since "Build" alone does not say what changes.
+ * English lives here because `@carbon/viewer` is deliberately i18n-free
+ * (see `packages/viewer/AGENTS.md`); the apps translate around it.
+ */
+const VIEW_LABELS: Record<
+ AssemblyView,
+ { label: string; description: string }
+> = {
+ build: {
+ label: "Build",
+ description: "Show the assembly as built so far, hiding later components"
+ },
+ focus: {
+ label: "Focus",
+ description:
+ "Focus this step by fading the already-installed components to see-through"
+ },
+ isolate: {
+ label: "Isolate",
+ description: "Show only this step's components, hiding everything else"
+ },
+ full: { label: "Full", description: "Show every component solid" }
+};
diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.ts
index dff954954f..d9fab9d034 100644
--- a/packages/viewer/src/index.ts
+++ b/packages/viewer/src/index.ts
@@ -2,7 +2,9 @@ export {
AssemblyPlayer,
type AssemblyPlayerHandle,
type AssemblyPlayerProps,
- type FutureComponentsMode
+ type AssemblyView,
+ type FutureComponentsMode,
+ type InstalledComponentsMode
} from "./AssemblyPlayer";
export { AssemblyViewer, type AssemblyViewerProps } from "./AssemblyViewer";
export { type FramingFit, fitFraming } from "./camera";
@@ -60,4 +62,10 @@ export type {
Vec3
} from "./types";
export { type UseAssemblyResult, useAssembly } from "./useAssembly";
-export { type ComponentVisual, visualForComponent } from "./visibility";
+export {
+ ASSEMBLY_VIEWS,
+ type ComponentVisual,
+ VIEW_MODES,
+ viewForModes,
+ visualForComponent
+} from "./visibility";
diff --git a/packages/viewer/src/visibility.test.ts b/packages/viewer/src/visibility.test.ts
index 59bd67c319..fdc363e01a 100644
--- a/packages/viewer/src/visibility.test.ts
+++ b/packages/viewer/src/visibility.test.ts
@@ -1,5 +1,12 @@
import { describe, expect, it } from "vitest";
-import { visualForComponent } from "./visibility";
+import {
+ ASSEMBLY_VIEWS,
+ GHOST_OCCLUDER_WEIGHT,
+ occluderWeight,
+ VIEW_MODES,
+ viewForModes,
+ visualForComponent
+} from "./visibility";
describe("visualForComponent", () => {
it("shows earlier-step components solid", () => {
@@ -34,4 +41,225 @@ describe("visualForComponent", () => {
expect(visualForComponent(undefined, 10, "hidden")).toBe("hidden");
expect(visualForComponent(undefined, 10, "ghost")).toBe("ghost");
});
+
+ it("defaults installed components to solid when the 4th arg is omitted", () => {
+ expect(visualForComponent(0, 2, "ghost")).toBe("solid");
+ expect(visualForComponent(1, 2, "hidden")).toBe("solid");
+ });
+
+ it("renders installed components per the installed mode", () => {
+ expect(visualForComponent(0, 2, "ghost", "solid")).toBe("solid");
+ expect(visualForComponent(0, 2, "ghost", "ghost")).toBe("ghost");
+ expect(visualForComponent(0, 2, "ghost", "hidden")).toBe("hidden");
+ });
+
+ it("never lets the installed mode affect the active step", () => {
+ for (const mode of ["solid", "ghost", "hidden"] as const) {
+ expect(visualForComponent(2, 2, "ghost", mode)).toBe("active");
+ }
+ });
+
+ it("never lets the installed mode affect future components", () => {
+ expect(visualForComponent(3, 1, "ghost", "hidden")).toBe("ghost");
+ expect(visualForComponent(3, 1, "hidden", "ghost")).toBe("hidden");
+ expect(visualForComponent(3, 1, "solid", "hidden")).toBe("solid");
+ });
+
+ it("never lets the installed mode affect never-installed components", () => {
+ for (const mode of ["solid", "ghost", "hidden"] as const) {
+ expect(visualForComponent(undefined, 5, "hidden", mode)).toBe("hidden");
+ expect(visualForComponent(undefined, 5, "ghost", mode)).toBe("ghost");
+ }
+ });
+});
+
+describe("occluderWeight", () => {
+ it("counts a solid component fully, whichever side of the step it is on", () => {
+ expect(occluderWeight(0, 2, "solid", "solid")).toBe(1);
+ expect(occluderWeight(5, 2, "solid", "solid")).toBe(1);
+ });
+
+ it("drops a hidden component out of the scoring entirely", () => {
+ expect(occluderWeight(0, 2, "solid", "hidden")).toBeNull();
+ expect(occluderWeight(5, 2, "hidden", "solid")).toBeNull();
+ });
+
+ it("discounts a ghosted component instead of dropping it", () => {
+ expect(occluderWeight(0, 2, "solid", "ghost")).toBe(GHOST_OCCLUDER_WEIGHT);
+ expect(occluderWeight(5, 2, "ghost", "solid")).toBe(GHOST_OCCLUDER_WEIGHT);
+ expect(GHOST_OCCLUDER_WEIGHT).toBeGreaterThan(0);
+ expect(GHOST_OCCLUDER_WEIGHT).toBeLessThan(1);
+ });
+
+ it("applies each mode only to its own side of the active step", () => {
+ // Hiding the installed side must not drop a future occluder, and vice versa
+ expect(occluderWeight(5, 2, "solid", "hidden")).toBe(1);
+ expect(occluderWeight(0, 2, "hidden", "solid")).toBe(1);
+ });
+
+ it("treats the active step's own components as full occluders", () => {
+ // The caller filters these out by nodeId before asking; if one does reach
+ // here it must never be discounted away.
+ for (const mode of ["solid", "ghost", "hidden"] as const) {
+ expect(occluderWeight(2, 2, mode, mode)).toBe(1);
+ }
+ });
+
+ it("treats never-installed components exactly like future ones", () => {
+ // visualForComponent renders them per the FUTURE mode — they are never
+ // "already there" — so the occluder scoring must follow the same mode.
+ for (const mode of ["solid", "ghost", "hidden"] as const) {
+ expect(occluderWeight(undefined, 3, mode, "solid")).toBe(
+ occluderWeight(99, 3, mode, "solid")
+ );
+ }
+ expect(occluderWeight(undefined, 3, "hidden", "solid")).toBeNull();
+ expect(occluderWeight(undefined, 3, "ghost", "solid")).toBe(
+ GHOST_OCCLUDER_WEIGHT
+ );
+ // The installed mode must never touch them.
+ for (const mode of ["solid", "ghost", "hidden"] as const) {
+ expect(occluderWeight(undefined, 3, "solid", mode)).toBe(1);
+ }
+ });
+
+ it("stays consistent with visualForComponent: invisible implies not an occluder", () => {
+ const steps = [undefined, 0, 1, 2, 3, 4];
+ const modes = ["solid", "ghost", "hidden"] as const;
+ for (const stepIndex of steps) {
+ for (const future of modes) {
+ for (const installed of modes) {
+ const visual = visualForComponent(stepIndex, 2, future, installed);
+ const weight = occluderWeight(stepIndex, 2, future, installed);
+ if (visual === "hidden") {
+ expect(weight).toBeNull();
+ } else {
+ expect(weight).not.toBeNull();
+ }
+ }
+ }
+ }
+ });
+});
+
+describe("named views", () => {
+ it("names every view in VIEW_MODES", () => {
+ for (const view of ASSEMBLY_VIEWS) {
+ expect(VIEW_MODES[view]).toBeDefined();
+ }
+ expect(Object.keys(VIEW_MODES).sort()).toEqual([...ASSEMBLY_VIEWS].sort());
+ });
+
+ it("gives each view a distinct axis pair", () => {
+ const pairs = ASSEMBLY_VIEWS.map(
+ (view) =>
+ `${VIEW_MODES[view].installedMode}/${VIEW_MODES[view].futureMode}`
+ );
+ expect(new Set(pairs).size).toBe(pairs.length);
+ });
+
+ it("keeps 'build' the historical default (installed solid, future hidden)", () => {
+ // Three-argument callers rendered installed parts solid, and
+ // `defaultFutureMode` is "hidden" — so the default view must be a no-op.
+ expect(VIEW_MODES.build).toEqual({
+ installedMode: "solid",
+ futureMode: "hidden"
+ });
+ });
+
+ it("ghosts the built side in 'focus', keeping the future out of the way", () => {
+ expect(VIEW_MODES.focus).toEqual({
+ installedMode: "ghost",
+ futureMode: "hidden"
+ });
+ });
+
+ it("hides everything but the active step in 'isolate'", () => {
+ // The whole point of the view: "how do I just see the part I am fitting?"
+ expect(VIEW_MODES.isolate).toEqual({
+ installedMode: "hidden",
+ futureMode: "hidden"
+ });
+ });
+
+ it("draws nothing but the active step's components in 'isolate'", () => {
+ const { installedMode, futureMode } = VIEW_MODES.isolate;
+ expect(visualForComponent(0, 2, futureMode, installedMode)).toBe("hidden");
+ expect(visualForComponent(1, 2, futureMode, installedMode)).toBe("hidden");
+ expect(visualForComponent(2, 2, futureMode, installedMode)).toBe("active");
+ expect(visualForComponent(4, 2, futureMode, installedMode)).toBe("hidden");
+ // A component no step installs must vanish too, or "isolate" still leaves
+ // stray geometry on screen.
+ expect(visualForComponent(undefined, 2, futureMode, installedMode)).toBe(
+ "hidden"
+ );
+ });
+
+ it("leaves the camera nothing to dodge in 'isolate'", () => {
+ // Every non-active component is invisible, so none may score as an
+ // occluder — otherwise the camera frames around geometry it is not drawing.
+ const { installedMode, futureMode } = VIEW_MODES.isolate;
+ for (const stepIndex of [undefined, 0, 1, 3, 4]) {
+ expect(
+ occluderWeight(stepIndex, 2, futureMode, installedMode)
+ ).toBeNull();
+ }
+ });
+
+ it("hides the future side in every working view", () => {
+ // Build, Focus and Isolate are all "I am working this step" views; parts
+ // that are not on the bench yet only add clutter. Full is the exception.
+ for (const view of ["build", "focus", "isolate"] as const) {
+ expect(VIEW_MODES[view].futureMode).toBe("hidden");
+ }
+ expect(VIEW_MODES.full.futureMode).toBe("solid");
+ });
+
+ it("shows everything in 'full'", () => {
+ expect(VIEW_MODES.full).toEqual({
+ installedMode: "solid",
+ futureMode: "solid"
+ });
+ });
+
+ it("round-trips every view through viewForModes", () => {
+ for (const view of ASSEMBLY_VIEWS) {
+ const { installedMode, futureMode } = VIEW_MODES[view];
+ expect(viewForModes(installedMode, futureMode)).toBe(view);
+ }
+ });
+
+ it("falls back to 'build' for an axis pair no view names", () => {
+ // "hidden installed + solid future" is reachable from the props but is not
+ // a named view; it must seat a real button rather than none.
+ expect(viewForModes("hidden", "solid")).toBe("build");
+ });
+
+ it("renders the active step untouched in every view", () => {
+ for (const view of ASSEMBLY_VIEWS) {
+ const { installedMode, futureMode } = VIEW_MODES[view];
+ expect(visualForComponent(2, 2, futureMode, installedMode)).toBe(
+ "active"
+ );
+ }
+ });
+
+ it("ghosts rather than deletes the built side in 'focus'", () => {
+ // Focus is about seeing PAST what is already fitted while keeping its
+ // shape as context — that shell is the difference from Isolate.
+ const { installedMode, futureMode } = VIEW_MODES.focus;
+ expect(visualForComponent(0, 2, futureMode, installedMode)).toBe("ghost");
+ expect(occluderWeight(0, 2, futureMode, installedMode)).toBe(
+ GHOST_OCCLUDER_WEIGHT
+ );
+ });
+
+ it("separates 'focus' from 'isolate' on the built side only", () => {
+ // The two views differ in exactly one axis. If that ever collapses, one of
+ // the two buttons has become a duplicate.
+ expect(VIEW_MODES.focus.futureMode).toBe(VIEW_MODES.isolate.futureMode);
+ expect(VIEW_MODES.focus.installedMode).not.toBe(
+ VIEW_MODES.isolate.installedMode
+ );
+ });
});
diff --git a/packages/viewer/src/visibility.ts b/packages/viewer/src/visibility.ts
index b7e56a251a..14eedcd41b 100644
--- a/packages/viewer/src/visibility.ts
+++ b/packages/viewer/src/visibility.ts
@@ -1,22 +1,83 @@
/** How components of steps after the active one are rendered. */
export type FutureComponentsMode = "ghost" | "hidden" | "solid";
+/** How components of steps BEFORE the active one are rendered. */
+export type InstalledComponentsMode = "ghost" | "hidden" | "solid";
+
export type ComponentVisual = "solid" | "active" | "hidden" | "ghost";
+/**
+ * The named views the toolbar offers, in presentation order.
+ *
+ * The two modes are independent axes: the right model for the renderer, the
+ * wrong one for the screen (nine combinations, most meaningless). A view is a
+ * named point in that space, so the UI keeps one concept and the renderer both.
+ */
+export const ASSEMBLY_VIEWS = ["build", "focus", "isolate", "full"] as const;
+
+export type AssemblyView = (typeof ASSEMBLY_VIEWS)[number];
+
+/**
+ * Ordered by how much context they strip: Build keeps what is already there,
+ * Focus fades it, Isolate removes it, Full is the other extreme. The future
+ * side is hidden in all but Full: parts not yet on the bench only add clutter.
+ */
+export const VIEW_MODES: Record<
+ AssemblyView,
+ { installedMode: InstalledComponentsMode; futureMode: FutureComponentsMode }
+> = {
+ /** As it is on the bench right now: what is built is solid, the rest absent. */
+ build: { installedMode: "solid", futureMode: "hidden" },
+ /** This step, and where it mounts: what is built fades to a see-through shell. */
+ focus: { installedMode: "ghost", futureMode: "hidden" },
+ /** This step alone: nothing else is drawn at all. */
+ isolate: { installedMode: "hidden", futureMode: "hidden" },
+ /** The finished product: every component, solid. */
+ full: { installedMode: "solid", futureMode: "solid" }
+};
+
+/**
+ * The view for an axis pair, or "build" when the pair names none. Seats the
+ * initial view from the still-axis-shaped `default*Mode` props; an unnamed pair
+ * falls back rather than adding a "custom" member no button could select.
+ */
+export function viewForModes(
+ installedMode: InstalledComponentsMode,
+ futureMode: FutureComponentsMode
+): AssemblyView {
+ return (
+ ASSEMBLY_VIEWS.find(
+ (view) =>
+ VIEW_MODES[view].installedMode === installedMode &&
+ VIEW_MODES[view].futureMode === futureMode
+ ) ?? "build"
+ );
+}
+
/**
* The visual state of a component for the active step. `stepIndex` is the
* index of the first step that installs the component, or `undefined` when no
* step ever installs it. Presence is cumulative: a component exists on the
* canvas only once its step has run. A component no step installs is treated
* exactly like a future-step component — it is never "already there".
+ *
+ * `installedMode` defaults to "solid", so three-argument callers are
+ * unaffected. Neither mode ever touches the active step.
*/
export function visualForComponent(
stepIndex: number | undefined,
activeStepIndex: number,
- futureMode: FutureComponentsMode
+ futureMode: FutureComponentsMode,
+ installedMode: InstalledComponentsMode = "solid"
): ComponentVisual {
if (stepIndex !== undefined) {
- if (stepIndex < activeStepIndex) return "solid";
+ if (stepIndex < activeStepIndex) {
+ return installedMode === "ghost"
+ ? "ghost"
+ : installedMode === "hidden"
+ ? "hidden"
+ : "solid";
+ }
if (stepIndex === activeStepIndex) return "active";
}
return futureMode === "ghost"
@@ -25,3 +86,37 @@ export function visualForComponent(
? "hidden"
: "solid";
}
+
+/** A ghosted part is see-through, so it obstructs the view only slightly. */
+export const GHOST_OCCLUDER_WEIGHT = 0.3;
+
+/**
+ * How much a component counts as an obstacle when the camera picks a view
+ * direction. Mirrors `visualForComponent`: geometry the operator cannot see
+ * must not push the camera around, or "hide installed" would clear the pixels
+ * while the framing still dodged the parts that are no longer drawn.
+ *
+ * `null` means "not an occluder at all" (skip it); otherwise the weight the
+ * AABB scorer should use. Ghosted parts still block the view a little, so they
+ * keep a reduced weight rather than disappearing from the scoring entirely.
+ */
+export function occluderWeight(
+ stepIndex: number | undefined,
+ activeStepIndex: number,
+ futureMode: FutureComponentsMode,
+ installedMode: InstalledComponentsMode = "solid"
+): number | null {
+ // A component no step installs is never "already there" — it follows the
+ // future side, exactly as `visualForComponent` treats it. (The previous
+ // inline version required `stepIndex !== undefined`, so such a component
+ // kept full occluder weight while rendering hidden, and the camera framed
+ // around geometry it was not drawing.)
+ const isFuture = stepIndex === undefined || stepIndex > activeStepIndex;
+ const isInstalled = stepIndex !== undefined && stepIndex < activeStepIndex;
+ if (isFuture && futureMode === "hidden") return null;
+ if (isInstalled && installedMode === "hidden") return null;
+ const isGhosted =
+ (isFuture && futureMode === "ghost") ||
+ (isInstalled && installedMode === "ghost");
+ return isGhosted ? GHOST_OCCLUDER_WEIGHT : 1;
+}