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(onshape): sync exact released part identity to Carbon items (#1630)

Brad Barbin4a1bc25c2eff
diff --git a/.ai/lessons.md b/.ai/lessons.md
index dd0add5f48..154117650c 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -6,6 +6,16 @@ Format: `Context → Problem → Rule → Applies to`
---
+## Onshape individual release assets need the complete source identity
+
+**Context:** Syncing a released part from a multi-part Part Studio to an existing Carbon item.
+
+**Problem:** Omitting `partIds` and `configuration` exports the whole studio; `getElementThumbnail` also depicts the entire element. Refreshing raw data under the same model ID leaves successful optimized artifacts in place and allows old background jobs to overwrite repaired assets.
+
+**Rule:** Resolve one exact released document/version/element/revision and propagate its part ID and configuration. Never fall back to a version-only match or unselected Part Studio export. Render the selected model's thumbnail after optimization. Give corrected individual-part sources deterministic immutable model generations, preserving item IDs and manufacturing records; repeat repairs reuse that generation. Repair existing items with explicit per-release events, not a company-wide backfill or new CAD releases.
+
+**Applies to:** Onshape revision sync, backfill, model export and attachment helpers in `packages/jobs/src/inngest/functions/integrations/`.
+
## Sales-order Paid Amount uses invoice-target principal
**Context:** Summarizing linked sales-invoice payments on a sales order.
diff --git a/packages/ee/src/onshape/lib/client.ts b/packages/ee/src/onshape/lib/client.ts
index 87df71c2c1..f1a4ead807 100644
--- a/packages/ee/src/onshape/lib/client.ts
+++ b/packages/ee/src/onshape/lib/client.ts
@@ -65,6 +65,7 @@ export interface OnshapeTranslation {
// 0 = Part Studio, 1 = Assembly, 2 = Drawing. Carries the released version's
// documentId/versionId/elementId — the join to a Carbon item is by partNumber.
export interface OnshapeRevision {
+ id?: string;
partNumber: string;
revision: string;
elementType: number;
@@ -72,6 +73,7 @@ export interface OnshapeRevision {
versionId: string;
elementId: string;
partId?: string | null;
+ configuration?: string | null;
mimeType?: string;
name?: string;
releaseId?: string;
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-attach.test.ts b/packages/jobs/src/inngest/functions/integrations/onshape-attach.test.ts
new file mode 100644
index 0000000000..2f5923b984
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-attach.test.ts
@@ -0,0 +1,381 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { attachOnshapeAssetsToItem } from "./onshape-attach";
+
+vi.mock("node:fs", () => ({
+ openAsBlob: vi.fn(async () => new Blob(["selected part geometry"]))
+}));
+vi.mock("../tasks/assembler-client", () => ({
+ resolveModelSourceBucket: vi.fn(async () => "temp-staging")
+}));
+
+type Row = Record<string, unknown>;
+type TableName = "company" | "item" | "modelUpload" | "document";
+type QueryError = { code?: string; message: string };
+type Call = { table: string; operation: string; filters: Row; values?: Row };
+
+// Stateful query/storage fake: exercise persisted state across redelivery,
+// partial failures and overlapping uploads, rather than asserting one payload.
+function database() {
+ const tables: Record<TableName, Row[]> = {
+ company: [{ id: "company", companyGroupId: "group" }],
+ item: [
+ {
+ id: "item",
+ companyId: "company",
+ modelUploadId: "onshape-legacy",
+ thumbnailPath: null
+ }
+ ],
+ // A fully-optimized prior Onshape generation: its "onshape-" id is what marks
+ // it as a superseded auto-generated artifact rather than user data.
+ modelUpload: [
+ {
+ id: "onshape-legacy",
+ companyId: "company",
+ name: "SADDLE.A.gltf",
+ modelPath: "company/models/onshape-legacy.gltf.zst",
+ size: 12880000,
+ optimizedModelPath: "company/models/onshape-legacy/optimized.glb",
+ optimizeStatus: "Success",
+ thumbnailPath: "company/thumbnails/onshape-legacy.png"
+ }
+ ],
+ document: []
+ };
+ const calls: Call[] = [];
+ const objects = new Map<string, Blob>();
+ const uploads: string[] = [];
+ const copies: string[] = [];
+ const failures: { table: string; operation: string; error: QueryError }[] =
+ [];
+ const client = {
+ from(table: TableName) {
+ let operation = "select";
+ let values: Row | undefined;
+ const filters: Row = {};
+ const execute = () => {
+ calls.push({ table, operation, filters: { ...filters }, values });
+ const index = failures.findIndex(
+ (f) => f.table === table && f.operation === operation
+ );
+ if (index >= 0)
+ return { data: null, error: failures.splice(index, 1)[0]!.error };
+ const rows = tables[table];
+ const matching = rows.filter((row) =>
+ Object.entries(filters).every(([key, value]) => row[key] === value)
+ );
+ if (operation === "insert") {
+ if (rows.some((row) => row.id === values?.id && values?.id)) {
+ return {
+ data: null,
+ error: { code: "23505", message: "duplicate key" }
+ };
+ }
+ const inserted = { id: `document-${rows.length}`, ...values };
+ rows.push(inserted);
+ return { data: inserted, error: null };
+ }
+ if (operation === "update") {
+ matching.forEach((row) => {
+ Object.assign(row, values);
+ });
+ }
+ return { data: matching[0] ?? null, error: null };
+ };
+ const query = {
+ select: (_fields?: string) => query,
+ eq: (key: string, value: unknown) => {
+ filters[key] = value;
+ return query;
+ },
+ limit: (_count: number) => query,
+ insert: (row: Row) => {
+ operation = "insert";
+ values = row;
+ return query;
+ },
+ update: (row: Row) => {
+ operation = "update";
+ values = row;
+ return query;
+ },
+ single: async () => execute(),
+ maybeSingle: async () => execute(),
+ then: (resolve: (result: ReturnType<typeof execute>) => unknown) =>
+ Promise.resolve(execute()).then(resolve)
+ };
+ return query;
+ },
+ storage: {
+ from(bucket: string) {
+ return {
+ upload: async (
+ path: string,
+ blob: Blob,
+ options: { upsert?: boolean }
+ ) => {
+ const key = `${bucket}/${path}`;
+ uploads.push(key);
+ if (objects.has(key) && !options.upsert) {
+ return {
+ error: {
+ statusCode: "409",
+ message: "The resource already exists"
+ }
+ };
+ }
+ objects.set(key, blob);
+ return { data: { path }, error: null };
+ },
+ copy: async (_source: string, target: string) => {
+ copies.push(target);
+ return { error: null };
+ },
+ remove: async (_paths: string[]) => ({ error: null })
+ };
+ }
+ }
+ };
+ return {
+ client: client as unknown as Parameters<
+ typeof attachOnshapeAssetsToItem
+ >[0],
+ tables,
+ calls,
+ objects,
+ uploads,
+ copies,
+ failures
+ };
+}
+
+const input = {
+ companyId: "company",
+ createdBy: "user",
+ itemId: "item",
+ sourceDocument: "Part" as const,
+ model: {
+ fileName: "SADDLE.A.gltf",
+ localPath: "/unused.gltf",
+ size: 22,
+ sourceId: "onshape-part-v2"
+ }
+};
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("immutable released-part attachments", () => {
+ it("replaces a bad generation while keeping item data and the prior model intact", async () => {
+ const db = database();
+ const prior = structuredClone(db.tables.modelUpload[0]);
+ const result = await attachOnshapeAssetsToItem(db.client, input);
+ expect(result.modelUploadId).toBe(input.model.sourceId);
+ expect(db.tables.item[0]).toEqual({
+ id: "item",
+ companyId: "company",
+ modelUploadId: input.model.sourceId,
+ thumbnailPath: null
+ });
+ expect(db.tables.modelUpload[0]).toEqual(prior);
+ expect(db.tables.modelUpload[1]).toMatchObject({
+ id: input.model.sourceId,
+ modelPath: "company/models/onshape-part-v2.gltf",
+ size: 22,
+ originalSize: 22
+ });
+ expect(db.copies).toEqual([]);
+ expect(db.tables.document).toEqual([]);
+ expect(result.preservedPriorModelAsDocument).toBe(false);
+ });
+
+ it("replays without overwriting a compacted raw, optimized preview or thumbnail", async () => {
+ const db = database();
+ await attachOnshapeAssetsToItem(db.client, input);
+ const current = db.tables.modelUpload.find(
+ (row) => row.id === input.model.sourceId
+ )!;
+ Object.assign(current, {
+ modelPath: "company/models/onshape-part-v2.gltf.zst",
+ optimizeStatus: "Success",
+ optimizedModelPath: "new.glb",
+ thumbnailPath: "new.png"
+ });
+ const snapshot = structuredClone(current);
+ const uploadCount = db.uploads.length;
+ await attachOnshapeAssetsToItem(db.client, input);
+ expect(db.tables.modelUpload).toHaveLength(2);
+ expect(current).toEqual(snapshot);
+ expect(db.uploads).toHaveLength(uploadCount);
+ });
+
+ it("recovers a failed item link using the already-created source model", async () => {
+ const db = database();
+ db.failures.push({
+ table: "item",
+ operation: "update",
+ error: { message: "link unavailable" }
+ });
+ await expect(attachOnshapeAssetsToItem(db.client, input)).rejects.toThrow(
+ /link/i
+ );
+ const result = await attachOnshapeAssetsToItem(db.client, input);
+ expect(result.modelUploadId).toBe(input.model.sourceId);
+ expect(db.tables.modelUpload).toHaveLength(2);
+ expect(db.uploads).toHaveLength(1);
+ });
+
+ it("allows concurrent redeliveries without duplicate model rows or overwriting bytes", async () => {
+ const db = database();
+ const results = await Promise.all([
+ attachOnshapeAssetsToItem(db.client, input),
+ attachOnshapeAssetsToItem(db.client, input)
+ ]);
+ expect(results.map((r) => r.modelUploadId)).toEqual([
+ input.model.sourceId,
+ input.model.sourceId
+ ]);
+ expect(db.tables.modelUpload).toHaveLength(2);
+ expect(db.objects.size).toBe(1);
+ });
+
+ // A non-"onshape-" id marks a manually uploaded model, which must be preserved.
+ function withManualPriorModel(db: ReturnType<typeof database>, name: string) {
+ db.tables.modelUpload[0]!.id = "manual-model";
+ db.tables.modelUpload[0]!.name = name;
+ db.tables.item[0]!.modelUploadId = "manual-model";
+ }
+
+ it("preserves a genuinely different manual model as a document", async () => {
+ const db = database();
+ withManualPriorModel(db, "manual-prototype.glb");
+ const result = await attachOnshapeAssetsToItem(db.client, input);
+ expect(result.preservedPriorModelAsDocument).toBe(true);
+ expect(db.copies).toEqual(["company/parts/item/manual-prototype.glb"]);
+ expect(db.tables.document).toHaveLength(1);
+ });
+
+ it("preserves a manual model sharing the released export's filename", async () => {
+ const db = database();
+ // Same filename as the incoming release — filename is not provenance, so the
+ // manual model must still be preserved rather than silently relinked away.
+ withManualPriorModel(db, input.model.fileName);
+ const result = await attachOnshapeAssetsToItem(db.client, input);
+ expect(result.modelUploadId).toBe(input.model.sourceId);
+ expect(result.preservedPriorModelAsDocument).toBe(true);
+ expect(db.copies).toEqual(["company/parts/item/SADDLE.A.gltf"]);
+ expect(db.tables.document).toHaveLength(1);
+ });
+
+ it("checks lookup failures instead of treating them as absent prior models", async () => {
+ const db = database();
+ db.failures.push({
+ table: "modelUpload",
+ operation: "select",
+ error: { message: "database unavailable" }
+ });
+ await expect(attachOnshapeAssetsToItem(db.client, input)).rejects.toThrow(
+ /lookup/i
+ );
+ expect(db.tables.item[0]!.modelUploadId).toBe("onshape-legacy");
+ expect(db.uploads).toEqual([]);
+ });
+
+ it("refuses a source ID belonging to another company", async () => {
+ const db = database();
+ db.tables.modelUpload.push({
+ id: input.model.sourceId,
+ companyId: "other-company",
+ name: input.model.fileName,
+ modelPath: "foreign.gltf"
+ });
+ await expect(attachOnshapeAssetsToItem(db.client, input)).rejects.toThrow();
+ expect(db.tables.item[0]!.modelUploadId).toBe("onshape-legacy");
+ expect(db.tables.modelUpload[1]!.modelPath).toBe("foreign.gltf");
+ });
+
+ it("recovers an upload completed before the model row insert failed", async () => {
+ const db = database();
+ db.failures.push({
+ table: "modelUpload",
+ operation: "insert",
+ error: { code: "08006", message: "connection lost" }
+ });
+ await expect(attachOnshapeAssetsToItem(db.client, input)).rejects.toThrow(
+ /insert/
+ );
+ expect(db.tables.item[0]!.modelUploadId).toBe("onshape-legacy");
+ const uploaded = db.objects.get(
+ "temp-staging/company/models/onshape-part-v2.gltf"
+ );
+ await attachOnshapeAssetsToItem(db.client, input);
+ expect(
+ db.objects.get("temp-staging/company/models/onshape-part-v2.gltf")
+ ).toBe(uploaded);
+ expect(db.tables.modelUpload).toHaveLength(2);
+ });
+
+ it("uses a separate model for a changed source and retains manual image overrides", async () => {
+ const db = database();
+ db.tables.item[0]!.thumbnailPath = "company/thumbnails/item/manual.png";
+ await attachOnshapeAssetsToItem(db.client, input);
+ const firstSource = structuredClone(db.tables.modelUpload[1]);
+ const result = await attachOnshapeAssetsToItem(db.client, {
+ ...input,
+ model: { ...input.model, sourceId: "onshape-another-part" }
+ });
+ expect(result.modelUploadId).toBe("onshape-another-part");
+ expect(db.tables.modelUpload).toHaveLength(3);
+ expect(db.tables.modelUpload[1]).toEqual(firstSource);
+ expect(db.tables.item[0]!.thumbnailPath).toBe(
+ "company/thumbnails/item/manual.png"
+ );
+ expect(db.copies).toEqual([]);
+ });
+
+ it("rejects an invalid or conflicting immutable identity", async () => {
+ const db = database();
+ await expect(
+ attachOnshapeAssetsToItem(db.client, {
+ ...input,
+ model: { ...input.model, sourceId: "../unsafe" }
+ })
+ ).rejects.toThrow(/invalid/);
+ db.tables.modelUpload.push({
+ id: input.model.sourceId,
+ companyId: "company",
+ name: "wrong-model.gltf",
+ modelPath: "wrong.gltf"
+ });
+ await expect(attachOnshapeAssetsToItem(db.client, input)).rejects.toThrow(
+ /identity/
+ );
+ expect(db.uploads).toEqual([]);
+ expect(db.tables.item[0]!.modelUploadId).toBe("onshape-legacy");
+ });
+
+ it("retains the existing no-source-ID attachment behavior", async () => {
+ const db = database();
+ const { sourceId: _sourceId, ...model } = input.model;
+ const result = await attachOnshapeAssetsToItem(db.client, {
+ ...input,
+ model
+ });
+ expect(result.modelUploadId).toBe("onshape-legacy");
+ expect(db.tables.modelUpload).toHaveLength(1);
+ expect(db.uploads).toEqual([
+ "temp-staging/company/models/onshape-legacy.gltf"
+ ]);
+ });
+
+ it("keeps every item/model read and update company-scoped", async () => {
+ const db = database();
+ await attachOnshapeAssetsToItem(db.client, input);
+ for (const call of db.calls.filter(
+ (call) =>
+ ["item", "modelUpload"].includes(call.table) &&
+ call.operation !== "insert"
+ )) {
+ expect(call.filters.companyId).toBe("company");
+ }
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts b/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts
index 486955208d..b6d25c80f4 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts
@@ -30,6 +30,9 @@ export interface OnshapeModelFile {
fileName: string;
localPath: string;
size: number;
+ // Stable ID derived by the exporter from the exact released source + its
+ // selection generation. An ID identifies immutable bytes, never a filename.
+ sourceId?: string;
}
export interface AttachOnshapeAssetsInput {
@@ -76,6 +79,90 @@ function documentTypeForFile(
return fileExtension(fileName) === "pdf" ? "PDF" : "Other";
}
+// A corrected part selection must not reuse the legacy modelUpload ID: active
+// optimize/compact/thumbnail jobs still own that ID and may finish later. New
+// sources get independent artifacts; exact-source retries reuse the existing
+// row including any compacted source path and completed viewer artifacts.
+async function ensureImmutableModel(
+ carbon: CarbonClient,
+ input: { companyId: string; createdBy: string; model: OnshapeModelFile },
+ modelId: string
+): Promise<string> {
+ if (!/^[a-zA-Z0-9_-]{1,128}$/.test(modelId)) {
+ throw new Error("attachOnshapeAssetsToItem: invalid model source ID");
+ }
+ const lookup = async () => {
+ const result = await carbon
+ .from("modelUpload")
+ .select("id, name, modelPath")
+ .eq("id", modelId)
+ .eq("companyId", input.companyId)
+ .maybeSingle();
+ if (result.error) {
+ throw new Error(
+ `attachOnshapeAssetsToItem: source model lookup failed: ${result.error.message}`
+ );
+ }
+ if (
+ result.data &&
+ (!result.data.modelPath || result.data.name !== input.model.fileName)
+ ) {
+ throw new Error(
+ "attachOnshapeAssetsToItem: source model identity mismatch"
+ );
+ }
+ return result.data;
+ };
+ if (await lookup()) return modelId;
+
+ const extension = fileExtension(input.model.fileName) || "gltf";
+ const modelPath = `${input.companyId}/models/${modelId}.${extension}`;
+ const contentType = modelContentType(extension);
+ const rawBlob = await openAsBlob(input.model.localPath, {
+ type: contentType
+ });
+ const uploaded = await carbon.storage
+ .from(STAGING_BUCKET)
+ .upload(modelPath, rawBlob, { upsert: false, contentType });
+ // A concurrent redelivery (or a retry after upload but before DB insert) can
+ // already own these immutable bytes. Never overwrite them. Both callers then
+ // converge through the modelUpload primary key below.
+ if (
+ uploaded.error &&
+ !(
+ "statusCode" in uploaded.error &&
+ String(uploaded.error.statusCode) === "409"
+ )
+ ) {
+ throw new Error(
+ `attachOnshapeAssetsToItem: model upload failed: ${uploaded.error.message}`
+ );
+ }
+ const inserted = await carbon
+ .from("modelUpload")
+ .insert({
+ id: modelId,
+ modelPath,
+ name: input.model.fileName,
+ size: input.model.size,
+ originalSize: input.model.size,
+ companyId: input.companyId,
+ createdBy: input.createdBy
+ })
+ .select("id")
+ .single();
+ if (inserted.error) {
+ // Do not turn a failed write into success unless another caller actually
+ // committed THIS model in THIS company. Other insert errors remain errors.
+ if (inserted.error.code !== "23505" || !(await lookup())) {
+ throw new Error(
+ `attachOnshapeAssetsToItem: modelUpload insert failed: ${inserted.error.message}`
+ );
+ }
+ }
+ return modelId;
+}
+
// "Replace rather than append": one document row per storage path, so re-running
// a sync (or an Inngest step retry) updates the existing row instead of
// accumulating duplicates. Returns the document id.
@@ -214,10 +301,8 @@ export async function attachOnshapeAssetsToItem(
if (input.model) {
const extension = fileExtension(input.model.fileName) || "gltf";
- // Resolve what the item currently points at first. This drives idempotency:
- // re-syncing the SAME model (identical filename — a step retry, webhook
- // redelivery, or backfill re-run) must replace it in place, not pile up new
- // modelUpload rows + duplicate "preserved" documents.
+ // Resolve the current model before linking a released source. Item identity
+ // and its manufacturing records are unchanged; only its model pointer moves.
const currentItem = await carbon
.from("item")
.select("modelUploadId")
@@ -232,107 +317,133 @@ export async function attachOnshapeAssetsToItem(
);
}
const priorModelId = currentItem.data?.modelUploadId ?? null;
- const priorModel = priorModelId
- ? (
- await carbon
- .from("modelUpload")
- .select("id, name, modelPath, size")
- .eq("id", priorModelId)
- .eq("companyId", companyId)
- .maybeSingle()
- ).data
+ const priorResult = priorModelId
+ ? await carbon
+ .from("modelUpload")
+ .select("id, name, modelPath, size")
+ .eq("id", priorModelId)
+ .eq("companyId", companyId)
+ .maybeSingle()
: null;
+ if (priorResult?.error) {
+ throw new Error(
+ `attachOnshapeAssetsToItem: prior model lookup failed: ${priorResult.error.message}`
+ );
+ }
+ const priorModel = priorResult?.data ?? null;
- // openAsBlob streams the file from disk on demand — the export is never
- // read into memory.
- const rawBlob = await openAsBlob(input.model.localPath, {
- type: modelContentType(extension)
- });
+ if (input.model.sourceId !== undefined) {
+ modelUploadId = await ensureImmutableModel(
+ carbon,
+ { companyId, createdBy, model: input.model },
+ input.model.sourceId
+ );
+ } else {
+ // Compatibility for callers that do not supply an immutable source identity.
+ // openAsBlob streams the file from disk on demand — the export is never
+ // read into memory.
+ const rawBlob = await openAsBlob(input.model.localPath, {
+ type: modelContentType(extension)
+ });
- if (priorModel?.modelPath && priorModel.name === input.model.fileName) {
- // Same model re-synced → refresh the raw + row in place. No new
- // modelUpload, no repoint, no preserve. The row's modelPath may point at
- // a zstd-compacted raw (model-optimize compacts after optimising), so
- // upload to the canonical staging path and repoint rather than
- // overwriting the stored object.
- const modelPath = `${companyId}/models/${priorModel.id}.${extension}`;
- const reupload = await carbon.storage
- .from(STAGING_BUCKET)
- .upload(modelPath, rawBlob, {
- upsert: true,
- contentType: modelContentType(extension)
- });
- if (reupload.error) {
- throw new Error(
- `attachOnshapeAssetsToItem: model re-upload failed: ${reupload.error.message}`
- );
- }
- if (priorModel.modelPath !== modelPath) {
- // Best-effort: drop the superseded object (e.g. the old .zst compact).
- await carbon.storage
+ if (priorModel?.modelPath && priorModel.name === input.model.fileName) {
+ // Same model re-synced → refresh the raw + row in place. No new
+ // modelUpload, no repoint, no preserve. The row's modelPath may point at
+ // a zstd-compacted raw (model-optimize compacts after optimising), so
+ // upload to the canonical staging path and repoint rather than
+ // overwriting the stored object.
+ const modelPath = `${companyId}/models/${priorModel.id}.${extension}`;
+ const reupload = await carbon.storage
.from(STAGING_BUCKET)
- .remove([priorModel.modelPath])
- .catch(() => {});
- }
- const refresh = await carbon
- .from("modelUpload")
- .update({
- modelPath,
- size: input.model.size,
- originalSize: input.model.size,
- updatedBy: createdBy,
- updatedAt: new Date().toISOString()
- })
- .eq("id", priorModel.id)
- .eq("companyId", companyId);
- if (refresh.error) {
- throw new Error(
- `attachOnshapeAssetsToItem: modelUpload refresh failed: ${refresh.error.message}`
- );
- }
- modelUploadId = priorModel.id;
- } else {
- // New model (or a genuinely different one). Upload + insert a fresh row.
- const modelId = nanoid();
- const modelPath = `${companyId}/models/${modelId}.${extension}`;
- const modelUpload = await carbon.storage
- .from(STAGING_BUCKET)
- .upload(modelPath, rawBlob, {
- upsert: true,
- contentType: modelContentType(extension)
- });
- if (modelUpload.error) {
- throw new Error(
- `attachOnshapeAssetsToItem: model upload failed: ${modelUpload.error.message}`
- );
- }
- const modelRecord = await carbon
- .from("modelUpload")
- .insert({
- id: modelId,
- modelPath,
- name: input.model.fileName,
- size: input.model.size,
- // Frozen as-uploaded bytes: `size` is later overwritten with the
- // compacted (.zst) stored size (model-optimize), but the viewer's
- // reduction badge compares the original.
- originalSize: input.model.size,
- companyId,
- createdBy
- })
- .select("id")
- .single();
- if (modelRecord.error) {
- throw new Error(
- `attachOnshapeAssetsToItem: modelUpload insert failed: ${modelRecord.error.message}`
- );
+ .upload(modelPath, rawBlob, {
+ upsert: true,
+ contentType: modelContentType(extension)
+ });
+ if (reupload.error) {
+ throw new Error(
+ `attachOnshapeAssetsToItem: model re-upload failed: ${reupload.error.message}`
+ );
+ }
+ if (priorModel.modelPath !== modelPath) {
+ // Best-effort: drop the superseded object (e.g. the old .zst compact).
+ await carbon.storage
+ .from(STAGING_BUCKET)
+ .remove([priorModel.modelPath])
+ .catch(() => {});
+ }
+ const refresh = await carbon
+ .from("modelUpload")
+ .update({
+ modelPath,
+ size: input.model.size,
+ originalSize: input.model.size,
+ updatedBy: createdBy,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", priorModel.id)
+ .eq("companyId", companyId);
+ if (refresh.error) {
+ throw new Error(
+ `attachOnshapeAssetsToItem: modelUpload refresh failed: ${refresh.error.message}`
+ );
+ }
+ modelUploadId = priorModel.id;
+ } else {
+ // New model (or a genuinely different one). Upload + insert a fresh row.
+ const modelId = nanoid();
+ const modelPath = `${companyId}/models/${modelId}.${extension}`;
+ const modelUpload = await carbon.storage
+ .from(STAGING_BUCKET)
+ .upload(modelPath, rawBlob, {
+ upsert: true,
+ contentType: modelContentType(extension)
+ });
+ if (modelUpload.error) {
+ throw new Error(
+ `attachOnshapeAssetsToItem: model upload failed: ${modelUpload.error.message}`
+ );
+ }
+ const modelRecord = await carbon
+ .from("modelUpload")
+ .insert({
+ id: modelId,
+ modelPath,
+ name: input.model.fileName,
+ size: input.model.size,
+ // Frozen as-uploaded bytes: `size` is later overwritten with the
+ // compacted (.zst) stored size (model-optimize), but the viewer's
+ // reduction badge compares the original.
+ originalSize: input.model.size,
+ companyId,
+ createdBy
+ })
+ .select("id")
+ .single();
+ if (modelRecord.error) {
+ throw new Error(
+ `attachOnshapeAssetsToItem: modelUpload insert failed: ${modelRecord.error.message}`
+ );
+ }
+ modelUploadId = modelId;
}
+ }
+ if (modelUploadId !== priorModelId) {
// Preserve a genuinely different prior model (e.g. a manual upload) as a
// document before repointing, so nothing is destroyed. The item's Documents
// tab lists objects under {companyId}/parts/{itemId} (items.service.ts), so
// copy the file there. Preserve failures are logged, never fatal.
- if (priorModel?.modelPath) {
+ // Filename equality is NOT provenance — a manual upload can share the
+ // released export's filename, and keying preservation off it silently
+ // dropped that manual model. Preserve unless the prior model is itself a
+ // prior Onshape immutable generation (its id carries the "onshape-" source
+ // prefix minted by ensureImmutableModel): those are superseded
+ // auto-generated artifacts, kept as a record for existing references but
+ // never re-attached as a misleading duplicate document.
+ const priorIsOnshapeGeneration = (priorModel?.id ?? "").startsWith(
+ "onshape-"
+ );
+ if (priorModel?.modelPath && !priorIsOnshapeGeneration) {
const preservedName = stripSpecialCharacters(
priorModel.name ?? `prior-model-${priorModel.id}`
);
@@ -379,7 +490,7 @@ export async function attachOnshapeAssetsToItem(
const itemLink = await carbon
.from("item")
- .update({ modelUploadId: modelId })
+ .update({ modelUploadId })
.eq("id", itemId)
.eq("companyId", companyId);
if (itemLink.error) {
@@ -387,7 +498,6 @@ export async function attachOnshapeAssetsToItem(
`attachOnshapeAssetsToItem: item model link failed: ${itemLink.error.message}`
);
}
- modelUploadId = modelId;
}
}
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-backfill.ts b/packages/jobs/src/inngest/functions/integrations/onshape-backfill.ts
index 9f555c23c0..ae2ce71604 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-backfill.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-backfill.ts
@@ -60,6 +60,8 @@ export interface OnshapeBackfillWorkItem {
versionId: string;
elementId: string;
modelElementKind?: "partstudio" | "assembly"; // kind === "model" only
+ partId?: string | null;
+ configuration?: string | null;
assetBaseName?: string;
}
@@ -250,13 +252,14 @@ export async function matchOnshapeBackfillPage(
);
const itemByKey = new Map<
string,
- { id: string; modelUploadId: string | null }
+ { id: string; modelUploadId: string | null } | null
>();
if (modelKeys.length > 0) {
const carbonItems = await carbon
.from("item")
.select("id, readableIdWithRevision, modelUploadId")
.eq("companyId", input.companyId)
+ .eq("type", "Part")
.in("readableIdWithRevision", modelKeys);
if (carbonItems.error) {
throw new Error(
@@ -265,10 +268,17 @@ export async function matchOnshapeBackfillPage(
}
for (const item of carbonItems.data ?? []) {
if (item.readableIdWithRevision) {
- itemByKey.set(item.readableIdWithRevision, {
- id: item.id,
- modelUploadId: item.modelUploadId
- });
+ // Generated display keys can collide (dots in numbers/revisions).
+ // Retain an ambiguous marker instead of silently taking the last row.
+ itemByKey.set(
+ item.readableIdWithRevision,
+ itemByKey.has(item.readableIdWithRevision)
+ ? null
+ : {
+ id: item.id,
+ modelUploadId: item.modelUploadId
+ }
+ );
}
}
}
@@ -288,6 +298,7 @@ export async function matchOnshapeBackfillPage(
.from("item")
.select("id, readableIdWithRevision")
.eq("companyId", input.companyId)
+ .eq("type", "Part")
.eq("revision", revision.revision)
.ilike("readableId", `%${escapeLikePattern(suffix)}`);
if (candidates.error) {
@@ -345,6 +356,8 @@ export async function matchOnshapeBackfillPage(
versionId: revision.versionId,
elementId: revision.elementId,
modelElementKind: revision.elementType === 1 ? "assembly" : "partstudio",
+ partId: revision.partId,
+ configuration: revision.configuration,
assetBaseName: releaseKey(revision.partNumber, revision.revision)
});
}
@@ -395,6 +408,8 @@ export async function syncOnshapeBackfillWorkItem(
versionId: workItem.versionId,
modelElementId: workItem.elementId,
modelElementKind: workItem.modelElementKind ?? "partstudio",
+ partId: workItem.partId,
+ configuration: workItem.configuration,
assetBaseName: workItem.assetBaseName
}),
workItem.label
@@ -516,8 +531,13 @@ export const onshapeBackfillFunction = inngest.createFunction(
optimizeModelUploadIds.push(attached.modelUploadId);
}
// Fallback only: models whose Onshape-rendered thumbnail was stored
- // during the sync don't need the screenshot pipeline.
- if (attached.modelUploadId && !attached.thumbnailAttached) {
+ // during the sync don't need the screenshot pipeline. Selected parts
+ // wait for the optimizer to produce the GLB and fire its thumbnail.
+ if (
+ attached.modelUploadId &&
+ !attached.thumbnailAttached &&
+ workItem.modelElementKind !== "partstudio"
+ ) {
syncedModelUploadIds.push(attached.modelUploadId);
}
} catch (syncError) {
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.test.ts b/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.test.ts
new file mode 100644
index 0000000000..ddfb36d30c
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.test.ts
@@ -0,0 +1,238 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ matchOnshapeBackfillPage,
+ syncOnshapeBackfillWorkItem
+} from "./onshape-backfill";
+import {
+ type OnshapeRevisionSyncInput,
+ runOnshapeRevisionSync
+} from "./onshape-revision-sync";
+
+const mocks = vi.hoisted(() => ({
+ getRevisions: vi.fn(),
+ getCompanyRevisions: vi.fn(),
+ sync: vi.fn(),
+ drawing: vi.fn()
+}));
+vi.mock("@carbon/ee/onshape", () => ({
+ getOnshapeClient: vi.fn(async () => ({ client: mocks })),
+ OnshapeAssetTooLargeError: class extends Error {},
+ OnshapeApiError: class extends Error {}
+}));
+vi.mock("@carbon/auth/client.server", () => ({
+ getCarbonServiceRole: vi.fn()
+}));
+vi.mock("../../client", () => ({
+ inngest: { createFunction: (...args: unknown[]) => args }
+}));
+vi.mock("./onshape-sync-element", () => ({
+ syncOnshapeElementAssetsToItem: mocks.sync,
+ syncOnshapeDrawingAssetsToItem: mocks.drawing
+}));
+
+const input: OnshapeRevisionSyncInput = {
+ companyId: "carbon-company",
+ onshapeCompanyId: "onshape-company",
+ userId: "user",
+ partNumber: "SADDLE",
+ documentId: "document",
+ versionId: "version",
+ elementId: "studio",
+ elementType: 0,
+ revisionId: "revision-id"
+};
+const released = {
+ id: "revision-id",
+ partNumber: "SADDLE",
+ revision: "A",
+ documentId: "document",
+ versionId: "version",
+ elementId: "studio",
+ elementType: 0,
+ partId: "saddle-part",
+ configuration: "Size=Large",
+ isObsolete: false
+};
+
+function database(
+ items = [
+ {
+ id: "existing-item",
+ readableIdWithRevision: "SADDLE.A",
+ modelUploadId: null as string | null
+ }
+ ]
+) {
+ const filters: [string, unknown][] = [];
+ const query = {
+ select: vi.fn().mockReturnThis(),
+ eq: vi.fn((key: string, value: unknown) => {
+ filters.push([key, value]);
+ return query;
+ }),
+ in: vi.fn().mockReturnThis(),
+ maybeSingle: vi.fn(async () => ({ error: null, data: items[0] ?? null })),
+ then: (resolve: (value: unknown) => unknown) =>
+ resolve({ error: null, data: items })
+ };
+ return {
+ client: { from: vi.fn(() => query) } as unknown as Parameters<
+ typeof runOnshapeRevisionSync
+ >[0],
+ filters
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getRevisions.mockResolvedValue({ items: [released] });
+ mocks.getCompanyRevisions.mockResolvedValue({ items: [released] });
+ mocks.sync.mockResolvedValue({
+ modelUploadId: "selected-model",
+ thumbnailAttached: false
+ });
+});
+
+describe("release identity", () => {
+ it("passes the exact released part/configuration to the existing item", async () => {
+ const db = database();
+ expect(await runOnshapeRevisionSync(db.client, input)).toMatchObject({
+ synced: true,
+ itemId: "existing-item"
+ });
+ expect(mocks.sync).toHaveBeenCalledWith(
+ db.client,
+ expect.objectContaining({
+ itemId: "existing-item",
+ documentId: "document",
+ versionId: "version",
+ modelElementId: "studio",
+ partId: "saddle-part",
+ configuration: "Size=Large"
+ })
+ );
+ expect(db.filters).toContainEqual(["companyId", "carbon-company"]);
+ expect(db.filters).toContainEqual(["readableIdWithRevision", "SADDLE.A"]);
+ expect(db.filters).toContainEqual(["type", "Part"]);
+ });
+
+ it.each([
+ { documentId: "wrong-document" },
+ { elementId: "wrong-element" },
+ { id: "wrong-revision-id" },
+ { partNumber: "wrong-number" },
+ { elementType: 1 },
+ { isObsolete: true }
+ ])("refuses a version-only fallback when identity differs: %j", async (mismatch) => {
+ mocks.getRevisions.mockResolvedValue({
+ items: [{ ...released, ...mismatch }]
+ });
+ expect(
+ await runOnshapeRevisionSync(database().client, input)
+ ).toMatchObject({
+ synced: false,
+ skippedReason: "revision-not-found"
+ });
+ expect(mocks.sync).not.toHaveBeenCalled();
+ });
+
+ it("refuses ambiguous revisions when the event has no revisionId", async () => {
+ mocks.getRevisions.mockResolvedValue({
+ items: [released, { ...released, id: "other", partId: "other-part" }]
+ });
+ expect(
+ await runOnshapeRevisionSync(database().client, {
+ ...input,
+ revisionId: undefined
+ })
+ ).toMatchObject({
+ synced: false,
+ skippedReason: "ambiguous-revision"
+ });
+ expect(mocks.sync).not.toHaveBeenCalled();
+ });
+
+ it("does not silently match an imported blank-revision item to revision A", async () => {
+ const db = database([]);
+ const result = await runOnshapeRevisionSync(db.client, input);
+ expect(result).toMatchObject({
+ synced: false,
+ skippedReason: "no-matching-item",
+ releaseKey: "SADDLE.A"
+ });
+ expect(db.filters).toContainEqual(["readableIdWithRevision", "SADDLE.A"]);
+ expect(mocks.sync).not.toHaveBeenCalled();
+ });
+});
+
+describe("backfill identity", () => {
+ it("refuses ambiguous Carbon display keys instead of picking the last row", async () => {
+ const page = await matchOnshapeBackfillPage(
+ database([
+ {
+ id: "item-one",
+ readableIdWithRevision: "SADDLE.A",
+ modelUploadId: null
+ },
+ {
+ id: "item-two",
+ readableIdWithRevision: "SADDLE.A",
+ modelUploadId: null
+ }
+ ]).client,
+ {
+ companyId: input.companyId,
+ userId: input.userId,
+ onshapeCompanyId: "onshape-company"
+ },
+ null
+ );
+ expect(page.workItems).toEqual([]);
+ expect(page.skippedNoItem).toBe(1);
+ });
+ it("retains selected part and configuration through page matching and export", async () => {
+ const db = database();
+ const page = await matchOnshapeBackfillPage(
+ db.client,
+ {
+ companyId: input.companyId,
+ userId: input.userId,
+ onshapeCompanyId: "onshape-company"
+ },
+ null
+ );
+ expect(page.workItems).toHaveLength(1);
+ expect(page.workItems[0]).toMatchObject({
+ partId: "saddle-part",
+ configuration: "Size=Large"
+ });
+ await syncOnshapeBackfillWorkItem(db.client, input, page.workItems[0]!);
+ expect(mocks.sync).toHaveBeenCalledWith(
+ db.client,
+ expect.objectContaining({
+ partId: "saddle-part",
+ configuration: "Size=Large"
+ })
+ );
+ });
+
+ it("does not use a full backfill to replace existing models", async () => {
+ const page = await matchOnshapeBackfillPage(
+ database([
+ {
+ id: "existing-item",
+ readableIdWithRevision: "SADDLE.A",
+ modelUploadId: "old-model"
+ }
+ ]).client,
+ {
+ companyId: input.companyId,
+ userId: input.userId,
+ onshapeCompanyId: "onshape-company"
+ },
+ null
+ );
+ expect(page.workItems).toEqual([]);
+ expect(page.skippedAlreadySynced).toBe(1);
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.ts b/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.ts
index 388b87673b..7ce0dc7478 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.ts
@@ -54,6 +54,7 @@ export interface OnshapeRevisionSyncResult {
| "no-matching-item"
| "ambiguous-item"
| "revision-not-found"
+ | "ambiguous-revision"
| "asset-too-large"; // export exceeds Carbon's upload limits — permanent skip
itemId?: string;
modelUploadId?: string | null;
@@ -87,21 +88,28 @@ export async function runOnshapeRevisionSync(
const onshapeCompanyId =
input.onshapeCompanyId ?? (await resolveOnshapeCompanyId(carbon, input));
- // Resolve the revision LETTER for this released element. Prefer the revision
- // whose version + element match this event exactly; fall back to version match.
+ // The webhook is only a hint. Resolve one exact released source from Onshape;
+ // never substitute another element in the same version or another document.
const revisions = await client.getRevisions(
onshapeCompanyId,
input.partNumber,
input.elementType
);
const revisionList = revisions.items ?? [];
- const releasedRevision =
- revisionList.find(
- (revision) =>
- revision.versionId === input.versionId &&
- revision.elementId === input.elementId
- ) ??
- revisionList.find((revision) => revision.versionId === input.versionId);
+ const matchingRevisions = revisionList.filter(
+ (revision) =>
+ !revision.isObsolete &&
+ revision.documentId === input.documentId &&
+ revision.versionId === input.versionId &&
+ revision.elementId === input.elementId &&
+ revision.elementType === input.elementType &&
+ revision.partNumber === input.partNumber &&
+ (!input.revisionId || revision.id === input.revisionId)
+ );
+ if (matchingRevisions.length > 1) {
+ return { synced: false, skippedReason: "ambiguous-revision" };
+ }
+ const releasedRevision = matchingRevisions[0];
if (!releasedRevision) {
return { synced: false, skippedReason: "revision-not-found" };
@@ -124,6 +132,7 @@ export async function runOnshapeRevisionSync(
.from("item")
.select("id, readableIdWithRevision")
.eq("companyId", input.companyId)
+ .eq("type", "Part")
.eq("revision", revision)
.ilike("readableId", `%${escapeLikePattern(suffix)}`);
if (candidates.error) {
@@ -189,6 +198,7 @@ export async function runOnshapeRevisionSync(
.from("item")
.select("id")
.eq("companyId", input.companyId)
+ .eq("type", "Part")
.eq("readableIdWithRevision", key)
.maybeSingle();
if (carbonItem.error) {
@@ -215,6 +225,8 @@ export async function runOnshapeRevisionSync(
versionId: input.versionId,
modelElementId: input.elementId,
modelElementKind,
+ partId: releasedRevision.partId,
+ configuration: releasedRevision.configuration,
assetBaseName: key
});
} catch (syncError) {
@@ -309,9 +321,16 @@ export const onshapeRevisionSyncFunction = inngest.createFunction(
});
}
- if (result.synced && result.modelUploadId && !result.thumbnailAttached) {
+ if (
+ result.synced &&
+ result.modelUploadId &&
+ !result.thumbnailAttached &&
+ payload.elementType !== 0
+ ) {
// Fallback only: the sync stores Onshape's server-rendered thumbnail
// itself; the screenshot pipeline runs just when that fetch failed.
+ // Selected parts wait for model-optimize's completion-chained thumbnail:
+ // their new immutable model IDs have no renderable GLB before that step.
await step.sendEvent("model-thumbnail", {
name: "carbon/model-thumbnail" as const,
data: { companyId: payload.companyId, modelId: result.modelUploadId }
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts
new file mode 100644
index 0000000000..a271bf5ef0
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts
@@ -0,0 +1,148 @@
+import { writeFile } from "node:fs/promises";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { SyncOnshapeElementInput } from "./onshape-sync-element";
+import { syncOnshapeElementAssetsToItem } from "./onshape-sync-element";
+
+const mocks = vi.hoisted(() => ({
+ client: {
+ createPartStudioTranslation: vi.fn(),
+ createAssemblyTranslation: vi.fn(),
+ getTranslation: vi.fn(),
+ downloadExternalDataToFile: vi.fn(),
+ getElementThumbnail: vi.fn()
+ },
+ attach: vi.fn(),
+ thumbnail: vi.fn()
+}));
+vi.mock("@carbon/ee/onshape", () => ({
+ getOnshapeClient: vi.fn(async () => ({ client: mocks.client }))
+}));
+vi.mock("@carbon/utils", () => ({
+ getFileSizeLimit: () => ({ bytes: 100000 })
+}));
+vi.mock("./onshape-attach", () => ({
+ attachOnshapeAssetsToItem: mocks.attach,
+ attachModelThumbnail: mocks.thumbnail
+}));
+
+const input = {
+ companyId: "company",
+ userId: "user",
+ itemId: "saddle-item",
+ sourceDocument: "Part",
+ documentId: "released-document",
+ versionId: "released-version",
+ modelElementId: "multi-part-studio",
+ modelElementKind: "partstudio",
+ partId: "saddle-only",
+ configuration: "Size=Large;Finish=Matte",
+ assetBaseName: "SADDLE.A"
+} as const;
+const carbon = {} as Parameters<typeof syncOnshapeElementAssetsToItem>[0];
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.client.createPartStudioTranslation.mockResolvedValue({
+ id: "translation"
+ });
+ mocks.client.createAssemblyTranslation.mockResolvedValue({
+ id: "translation"
+ });
+ mocks.client.getTranslation.mockResolvedValue({
+ id: "translation",
+ requestState: "DONE",
+ resultDocumentId: "export-document",
+ resultExternalDataIds: ["file"]
+ });
+ mocks.client.downloadExternalDataToFile.mockImplementation(
+ async (_document, _file, path) => writeFile(path, "selected geometry")
+ );
+ mocks.client.getElementThumbnail.mockResolvedValue(new ArrayBuffer(1));
+ mocks.attach.mockResolvedValue({
+ modelUploadId: "new-model",
+ documentIds: []
+ });
+});
+
+describe("released model exports", () => {
+ it("exports only the released part in its released configuration", async () => {
+ await syncOnshapeElementAssetsToItem(carbon, input);
+ expect(mocks.client.createPartStudioTranslation).toHaveBeenCalledWith(
+ input.documentId,
+ input.versionId,
+ input.modelElementId,
+ expect.objectContaining({
+ partIds: "saddle-only",
+ configuration: input.configuration
+ })
+ );
+ expect(mocks.client.createAssemblyTranslation).not.toHaveBeenCalled();
+ });
+
+ it("never attaches a whole-studio thumbnail to a part", async () => {
+ const result = await syncOnshapeElementAssetsToItem(carbon, input);
+ expect(mocks.client.getElementThumbnail).not.toHaveBeenCalled();
+ expect(mocks.thumbnail).not.toHaveBeenCalled();
+ expect(result.thumbnailAttached).toBe(false);
+ });
+
+ it.each([
+ undefined,
+ null,
+ "",
+ " ",
+ "part-one,part-two"
+ ])("refuses unsafe individual-part selection %s before any export or attach", async (partId) => {
+ const invalid = { ...input, partId } as unknown as SyncOnshapeElementInput;
+ await expect(
+ syncOnshapeElementAssetsToItem(carbon, invalid)
+ ).rejects.toThrow(/part/i);
+ expect(mocks.client.createPartStudioTranslation).not.toHaveBeenCalled();
+ expect(mocks.attach).not.toHaveBeenCalled();
+ });
+
+ it("keeps whole-assembly exports and forwards their configuration", async () => {
+ const assembly = {
+ ...input,
+ modelElementKind: "assembly" as const,
+ partId: undefined
+ };
+ const result = await syncOnshapeElementAssetsToItem(carbon, assembly);
+ expect(mocks.client.createAssemblyTranslation).toHaveBeenCalledWith(
+ input.documentId,
+ input.versionId,
+ input.modelElementId,
+ expect.objectContaining({ configuration: input.configuration })
+ );
+ expect(mocks.client.createPartStudioTranslation).not.toHaveBeenCalled();
+ // The element thumbnail cannot select a non-default assembly configuration.
+ expect(mocks.client.getElementThumbnail).not.toHaveBeenCalled();
+ expect(result.thumbnailAttached).toBe(false);
+ });
+
+ it("retains the inexpensive element thumbnail for an unconfigured assembly", async () => {
+ const result = await syncOnshapeElementAssetsToItem(carbon, {
+ ...input,
+ modelElementKind: "assembly",
+ partId: undefined,
+ configuration: undefined
+ });
+ expect(mocks.client.getElementThumbnail).toHaveBeenCalledOnce();
+ expect(result.thumbnailAttached).toBe(true);
+ });
+
+ it("gives exact-source replays a stable generation, distinct from another part/configuration", async () => {
+ for (const variation of [
+ input,
+ input,
+ { ...input, partId: "other-part" },
+ { ...input, configuration: "Size=Small" }
+ ]) {
+ await syncOnshapeElementAssetsToItem(carbon, variation);
+ }
+ const ids = mocks.attach.mock.calls.map(([, args]) => args.model.sourceId);
+ expect(ids[0]).toEqual(expect.any(String));
+ expect(ids[0]).toBe(ids[1]);
+ expect(new Set(ids).size).toBe(3);
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts
index 3b3b704f31..6aa636a30b 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts
@@ -1,3 +1,4 @@
+import { createHash } from "node:crypto";
import { mkdtemp, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -22,10 +23,9 @@ import {
// The caller (release-sync / backfill job) is responsible for turning a release
// event into these inputs: resolve itemId by part number (readableIdWithRevision,
// LINK-ONLY skip if none), and the documentId/versionId/elementId of the released
-// geometry. Thumbnails: the model sync stores Onshape's server-rendered element
-// thumbnail itself (thumbnailAttached: true); callers fire the
-// "carbon/model-thumbnail" screenshot job only as a fallback when that fetch
-// failed.
+// geometry, including the released partId and configuration. Individual-part
+// thumbnails come from that selected model after optimization; an element
+// thumbnail represents the entire Part Studio and must never be attached to it.
type CarbonClient = SupabaseClient<Database>;
type DocumentSourceType = Database["public"]["Enums"]["documentSourceType"];
@@ -39,6 +39,8 @@ export interface SyncOnshapeElementInput {
versionId: string; // the released version
modelElementId: string; // released Part Studio OR Assembly element to export
modelElementKind: "partstudio" | "assembly"; // from the revision's elementType (0/1)
+ partId?: string | null; // REQUIRED for individual Part Studio releases
+ configuration?: string | null; // exact released configuration, not the current workspace
drawingElementIds?: string[]; // optional PDF drawings (untested path — see client.ts)
assetBaseName?: string; // filename base (e.g. item part number); falls back to Onshape name
}
@@ -114,19 +116,40 @@ async function exportRawGltfModel(
input: SyncOnshapeElementInput,
scratchDir: string
): Promise<OnshapeModelFile> {
+ // Missing selection previously exported the entire studio. Fail closed:
+ // a release asset is one part, never an implicit list or whole-studio export.
+ if (
+ input.modelElementKind === "partstudio" &&
+ (typeof input.partId !== "string" ||
+ !input.partId.trim() ||
+ /[,\s]/.test(input.partId))
+ ) {
+ throw new Error(
+ "An individual Onshape release requires exactly one partId"
+ );
+ }
+ if (input.configuration != null && typeof input.configuration !== "string") {
+ throw new Error("Invalid released Onshape configuration");
+ }
+ const configuration = input.configuration ?? undefined;
const gltfTranslation =
input.modelElementKind === "assembly"
? await client.createAssemblyTranslation(
input.documentId,
input.versionId,
input.modelElementId,
- { formatName: "GLTF", storeInDocument: false }
+ { formatName: "GLTF", storeInDocument: false, configuration }
)
: await client.createPartStudioTranslation(
input.documentId,
input.versionId,
input.modelElementId,
- { formatName: "GLTF", storeInDocument: false }
+ {
+ formatName: "GLTF",
+ storeInDocument: false,
+ configuration,
+ partIds: input.partId!
+ }
);
const gltfDone = await waitForTranslation(client, gltfTranslation.id);
const baseName =
@@ -151,7 +174,29 @@ async function exportRawGltfModel(
return {
fileName: `${baseName}.gltf`,
localPath: gltfPath,
- size
+ size,
+ // Immutable generation: old optimizer/thumbnail/compact jobs can only
+ // finish against their old model ID. Replays of this exact released source
+ // share one ID; a different part/configuration cannot reuse its artifacts.
+ // Keep whole-assembly attachment behavior unchanged.
+ sourceId:
+ input.modelElementKind === "partstudio"
+ ? `onshape-${createHash("sha256")
+ .update(
+ JSON.stringify([
+ "selected-part-v1",
+ input.companyId,
+ input.itemId,
+ input.documentId,
+ input.versionId,
+ input.modelElementId,
+ input.partId,
+ configuration ?? ""
+ ])
+ )
+ .digest("hex")
+ .slice(0, 40)}`
+ : undefined
};
}
@@ -206,13 +251,15 @@ export async function syncOnshapeElementAssetsToItem(
documents
});
- // Thumbnail: prefer Onshape's server-rendered element thumbnail — one small
- // API call for an exact shaded render of the released geometry, instead of
- // the model-thumbnail pipeline screenshotting the full decoded mesh in a
- // headless browser (the very operation that struggles with big assemblies).
- // Best-effort: on failure the caller falls back to the model-thumbnail event.
+ // The element-thumbnail endpoint cannot select a part or configuration.
+ // Keep it only for unconfigured assemblies. All other thumbnails are
+ // generated from the selected model by the optimizer's completion event.
let thumbnailAttached = false;
- if (attached.modelUploadId) {
+ if (
+ attached.modelUploadId &&
+ input.modelElementKind === "assembly" &&
+ (!input.configuration || input.configuration.toLowerCase() === "default")
+ ) {
try {
const thumbnail = await client.getElementThumbnail(
input.documentId,