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.

fix(mes): render Bill of Process step reference images on work instructions (#1277)

Sid8ee8e0267257
diff --git a/.ai/issues/2026-07-30-mes-step-image-cross-company-403.md b/.ai/issues/2026-07-30-mes-step-image-cross-company-403.md
new file mode 100644
index 0000000000..8f842872e0
--- /dev/null
+++ b/.ai/issues/2026-07-30-mes-step-image-cross-company-403.md
@@ -0,0 +1,82 @@
+# MES step reference images 403 (cross-company) + get-method annotations shape
+
+Filed: 2026-07-30 · Found while fixing "BOP step images not showing on MES work instructions".
+Status: OPEN (deferred — the rendering fix shipped separately in `Step.tsx`).
+
+## Issue 1 (primary): file-preview 403 for cross-company operations
+
+### Symptom
+On prod, a shop-floor operator opens an MES operation and the step reference
+images fail to load. The image request returns **403**:
+
+```
+GET https://mes.carbon.ms/file/preview/private/d0rlmp5l6de2s779lqi0/parts/<id>.png → 403
+```
+(referer: `/x/operation/jo_TGBpYrCw3oqQEGEjcbW9Qz`, active `companyId` cookie = `SMBHQP55H46bdEGV7acnir`.)
+
+### Root cause
+- The MES operation route loads via **service role**
+ (`getCarbonServiceRole()`, `apps/mes/app/routes/x+/operation.$operationId.tsx`),
+ so it renders an operation regardless of the session's active company.
+- The slide image is stored under the operation's company:
+ `private/<operationCompanyId>/parts/…` (path set at ERP upload time,
+ `apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx` → `${companyId}/parts/...`;
+ copied verbatim into `jobOperationStepSlide.imagePath` by the `get-method`
+ edge function).
+- The file-preview route authorizes **only against the session's active company**:
+
+ `apps/mes/app/routes/file+/preview+/$bucket.$.tsx:82` (identical in ERP
+ `apps/erp/app/routes/file+/preview+/$bucket.$.tsx`):
+ ```ts
+ const ownsPath =
+ decodedPath.startsWith(`${companyId}/`) ||
+ decodedPath.includes(`/${companyId}/`);
+ if (!ownsPath) return new Response(null, { status: 403 });
+ ```
+- When the viewed operation's company ≠ the active-company cookie
+ (`d0rlmp… ≠ SMBHQP…`, both companies the user belongs to), `ownsPath` is false → 403.
+ Same-company files are unaffected — this only bites cross-company viewing, which
+ the service-role operation page allows but the file route does not.
+
+### Recommended fix (needs multi-tenancy sign-off)
+Authorize the path against **every company the user is a member of**, not only the
+active one. Membership helper already exists:
+`getCompaniesForUser(client, userId)` → `string[]` (`packages/auth/src/services/users.ts`,
+reads `userToCompany`). The user genuinely has permissions in that company, so
+serving its private file is legitimate.
+
+Sketch (both file-preview routes):
+```ts
+const { client, companyId, userId } = await requirePermissions(request, {});
+const companies = new Set([companyId, ...(await getCompaniesForUser(client, userId))]);
+const ownsPath = [...companies].some(
+ (c) => decodedPath.startsWith(`${c}/`) || decodedPath.includes(`/${c}/`)
+);
+```
+Keep the full-segment match (never `.includes(companyId)` loose) to preserve the
+existing cross-tenant-substring protection.
+
+### Alternative
+Sync the MES active company to the operation's company when opening a
+cross-company operation (root-cause, but touches company-switch/session flow;
+`apps/mes/app/routes/x+/company.switch.$companyId.tsx`). Larger blast radius.
+
+## Issue 2 (secondary): get-method stores slide annotations as `{}` not `[]`
+
+`packages/database/supabase/functions/get-method/index.ts` copies method slides to
+`jobOperationStepSlide` with `annotations: JSON.stringify(slide.annotations ?? [])`.
+Observed result in the DB is a JSON **object** `{}` (`jsonb_typeof = object`), not an
+array — so any consumer doing `annotations.map(...)` crashes.
+
+- Reproduced locally: clicking a step image opened `ImageZoomViewer`, which does
+ `annotations.map` → `500 "annotations.map is not a function"`.
+- Worked around in the render fix (`Step.tsx` normalizes with `Array.isArray`), but
+ the serialization in `get-method` (and possibly the source `slide.annotations`
+ shape) should be corrected so job slides always persist an array. `AssemblyView`
+ passes the same field to `ImageZoomViewer` and is likely latently exposed too.
+
+## Related shipped change
+`apps/mes/app/components/JobOperation/components/Step.tsx` — `StepsListItem` now
+renders `jobOperationStepSlide` image slides (thumbnails + `ImageZoomViewer`),
+mirroring `AssemblyView`. This makes the images *render*; Issue 1 is why they still
+won't *load* for cross-company operations on prod.
diff --git a/.ai/playbooks/mes-step-reference-images.md b/.ai/playbooks/mes-step-reference-images.md
new file mode 100644
index 0000000000..53389322e2
--- /dev/null
+++ b/.ai/playbooks/mes-step-reference-images.md
@@ -0,0 +1,53 @@
+# MES Step Reference Images (shop-floor work instructions)
+
+Last tested: 2026-07-30
+App: MES
+Route: /x/operation/:operationId (standard, non-Assembly operation view)
+
+Verifies that reference images ("slides") attached to a Bill of Process step render
+as thumbnails on the MES operation Details/Procedure Steps list, and open in the
+fullscreen ImageZoomViewer on click. Component: `StepsListItem`
+(`apps/mes/app/components/JobOperation/components/Step.tsx`).
+
+## Prerequisites
+- A make part whose method has an operation with a **non-Assembly, non-Inspection**
+ process (so the standard operation view renders, not AssemblyView/InspectionView).
+- That operation's step has ≥1 `methodOperationStepSlide` with a real `imagePath`
+ in the `private` bucket.
+- A job created for that item (job creation runs the `get-method` edge function,
+ which copies method slides → `jobOperationStepSlide`).
+
+## Fast seed (when the dev DB is empty)
+1. ERP UI: create Make part; create a Process (processType **Process**); add a method
+ operation using that process; the step can be seeded directly.
+2. Upload a real PNG to the private bucket via storage REST (service role):
+ `POST {SUPABASE_URL}/storage/v1/object/private/{companyId}/parts/<name>.png`.
+3. DB: insert `methodOperationStep` (type `Task`) + `methodOperationStepSlide`
+ rows (`"imagePath"` = the uploaded path; `annotations` `'[]'::jsonb`).
+4. ERP UI: create a Job for the item (route /x/job/new) → materializes
+ `jobOperation` + `jobOperationStep` + `jobOperationStepSlide`.
+5. Get the job's operation id from `jobOperation` and open it in MES.
+
+## Steps
+### 1. Navigate — MES `/x/operation/<jobOperationId>`
+### 2. Verify thumbnails
+`[...document.querySelectorAll('img')].filter(i=>i.src.includes('/file/preview/private/'))`
+— expect one per image slide; each `naturalWidth > 0` (actually loaded, not broken).
+### 3. Click a thumbnail (button aria-label = slide caption or "Reference image N")
+→ ImageZoomViewer opens: an enlarged img + the caption + a Close (X) button.
+### 4. Close (X) → viewer dismisses.
+
+## Selector Notes
+- Thumbnail buttons carry `aria-label` = the slide `caption`.
+- Image URLs are `/file/preview/private/{companyId}/parts/...` (getPrivateUrl).
+- Viewer image is the same src rendered large (bounding width ≈ natural size).
+
+## Common Failures
+- **500 "annotations.map is not a function"**: `get-method` persists copied slide
+ `annotations` as a non-array JSON value (`{}`) on `jobOperationStepSlide`. Guarded
+ in `StepsListItem` by normalizing with `Array.isArray(...)` before passing to the
+ viewer. (Root-cause data bug in `get-method` still open — separate follow-up.)
+- Operation redirects to Assembly/Inspection view → the process type wasn't
+ `Process`; those op types use different components that already render slides.
+- Broken image (naturalWidth 0) → `imagePath` points at a missing object in the
+ `private` bucket.
diff --git a/apps/mes/app/components/JobOperation/components/Step.tsx b/apps/mes/app/components/JobOperation/components/Step.tsx
index 17c12d78a9..fe15098bdc 100644
--- a/apps/mes/app/components/JobOperation/components/Step.tsx
+++ b/apps/mes/app/components/JobOperation/components/Step.tsx
@@ -52,6 +52,7 @@ import {
} from "react-icons/lu";
import { useFetcher } from "react-router";
import { ProcedureStepTypeIcon } from "~/components/Icons";
+import { ImageZoomViewer } from "~/components/ImageZoomViewer";
import ItemThumbnail from "~/components/ItemThumbnail";
import { useDateFormatter, useUser } from "~/hooks";
import { stepRecordValidator } from "~/services/models";
@@ -60,6 +61,17 @@ import { useItems, usePeople } from "~/stores";
import { getPrivateUrl, path } from "~/utils/path";
import FileDropzone from "../../FileDropzone";
+// Reference-image annotation pins (mirrors ImageZoomViewer's Annotation shape). The
+// slide row stores these as JSON, so we cast when passing them to the viewer.
+type SlideAnnotation = {
+ id: string;
+ x: number;
+ y: number;
+ label?: string | null;
+ color?: string | null;
+ toolId?: string | null;
+};
+
// An empty step description is persisted by the ERP editors as
// JSON.stringify({}) === "{}" (and some legacy rows carry it as a tiptap doc
// whose only text is literally "{}"). Treat an empty object, empty doc, or
@@ -104,6 +116,26 @@ export function StepsListItem({
defaultIsOpen: hasDescription
});
+ // Reference images ("slides") attached to this step in the Bill of Process. A slide
+ // is image XOR model; only image slides (imagePath) render here — model slides need a
+ // modelUpload join the standard-view loader doesn't fetch, so they're skipped.
+ const imageSlides = (step.jobOperationStepSlide ?? [])
+ .filter((slide) => !!slide.imagePath)
+ .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))
+ .map((slide) => ({
+ id: slide.id,
+ url: getPrivateUrl(slide.imagePath as string),
+ caption: slide.caption,
+ // Slides copied from the method (get-method) can persist annotations as a
+ // non-array JSON value ({}), so normalize before the viewer calls .map().
+ annotations: Array.isArray(slide.annotations)
+ ? (slide.annotations as SlideAnnotation[])
+ : []
+ }));
+ const [viewerIndex, setViewerIndex] = useState<number | null>(null);
+ const activeSlide =
+ viewerIndex !== null ? (imageSlides[viewerIndex] ?? null) : null;
+
if (!operationId) return null;
const record = step.jobOperationStepRecord.find(
(r) => r.index === activeStep
@@ -244,6 +276,30 @@ export function StepsListItem({
)}
</div>
</div>
+ {imageSlides.length > 0 && (
+ <div className="mt-4 flex flex-wrap gap-2">
+ {imageSlides.map((slide, i) => (
+ <button
+ key={slide.id}
+ type="button"
+ aria-label={slide.caption || `Reference image ${i + 1}`}
+ title={slide.caption ?? undefined}
+ onClick={() => setViewerIndex(i)}
+ className={cn(
+ "relative flex h-24 w-32 shrink-0 items-center justify-center overflow-hidden rounded-lg border bg-muted/40",
+ "transition-transform active:scale-[0.96]"
+ )}
+ >
+ <img
+ src={slide.url}
+ alt={slide.caption || ""}
+ className="h-full w-full object-cover"
+ loading="lazy"
+ />
+ </button>
+ ))}
+ </div>
+ )}
{disclosure.isOpen && hasDescription && (
<div
className="my-4 text-sm prose prose-sm dark:prose-invert"
@@ -253,6 +309,13 @@ export function StepsListItem({
/>
)}
{mentionIds.length > 0 && <ItemsSummaryTable itemsIds={mentionIds} />}
+ <ImageZoomViewer
+ open={viewerIndex !== null}
+ src={activeSlide?.url ?? null}
+ caption={activeSlide?.caption}
+ annotations={activeSlide?.annotations ?? []}
+ onClose={() => setViewerIndex(null)}
+ />
</div>
);
}